card.php 119 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947
  1. <?php
  2. /* Copyright (C) 2004-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005 Eric Seigne <eric.seigne@ryxeo.com>
  5. * Copyright (C) 2005-2016 Regis Houssin <regis.houssin@inodbox.com>
  6. * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
  7. * Copyright (C) 2011-2022 Philippe Grand <philippe.grand@atoo-net.com>
  8. * Copyright (C) 2012-2016 Marcos García <marcosgdf@gmail.com>
  9. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  10. * Copyright (C) 2014 Ion Agorria <ion@agorria.com>
  11. * Copyright (C) 2018-2019 Frédéric France <frederic.france@netlogic.fr>
  12. * Copyright (C) 2022 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
  13. * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
  14. *
  15. * This program is free software; you can redistribute it and/or modify
  16. * it under the terms of the GNU General Public License as published by
  17. * the Free Software Foundation; either version 2 of the License, or
  18. * (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public License
  26. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  27. * or see https://www.gnu.org/
  28. */
  29. /**
  30. * \file htdocs/fourn/commande/card.php
  31. * \ingroup supplier, order
  32. * \brief Card supplier order
  33. */
  34. // Load Dolibarr environment
  35. require '../../main.inc.php';
  36. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formorder.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  40. require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
  41. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
  43. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  45. if (isModEnabled('supplier_proposal')) {
  46. require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
  47. }
  48. if (isModEnabled("product")) {
  49. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  50. }
  51. if (isModEnabled('project')) {
  52. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  53. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  54. }
  55. require_once NUSOAP_PATH.'/nusoap.php'; // Include SOAP
  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('admin', 'orders', 'sendings', 'companies', 'bills', 'propal', 'receptions', 'supplier_proposal', 'deliveries', 'products', 'stocks', 'productbatch'));
  61. if (isModEnabled('incoterm')) {
  62. $langs->load('incoterm');
  63. }
  64. // Get Parameters
  65. $id = GETPOST('id', 'int');
  66. $ref = GETPOST('ref', 'alpha');
  67. $action = GETPOST('action', 'alpha');
  68. $confirm = GETPOST('confirm', 'alpha');
  69. $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'purchaseordercard'; // To manage different context of search
  70. $backtopage = GETPOST('backtopage', 'alpha');
  71. $backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');
  72. $socid = GETPOST('socid', 'int');
  73. $projectid = GETPOST('projectid', 'int');
  74. $cancel = GETPOST('cancel', 'alpha');
  75. $lineid = GETPOST('lineid', 'int');
  76. $origin = GETPOST('origin', 'alpha');
  77. $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
  78. $rank = (GETPOST('rank', 'int') > 0) ? GETPOST('rank', 'int') : -1;
  79. // PDF
  80. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  81. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  82. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  83. $datelivraison = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), GETPOST('liv_sec', 'int'), GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int'));
  84. // Security check
  85. if (!empty($user->socid)) {
  86. $socid = $user->socid;
  87. }
  88. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  89. $hookmanager->initHooks(array('ordersuppliercard', 'globalcard'));
  90. $object = new CommandeFournisseur($db);
  91. $extrafields = new ExtraFields($db);
  92. // fetch optionals attributes and labels
  93. $extrafields->fetch_name_optionals_label($object->table_element);
  94. if ($user->socid) {
  95. $socid = $user->socid;
  96. }
  97. // Load object
  98. if ($id > 0 || !empty($ref)) {
  99. $ret = $object->fetch($id, $ref);
  100. if ($ret < 0) {
  101. dol_print_error($db, $object->error);
  102. }
  103. $ret = $object->fetch_thirdparty();
  104. if ($ret < 0) {
  105. dol_print_error($db, $object->error);
  106. }
  107. } elseif (!empty($socid) && $socid > 0) {
  108. $fourn = new Fournisseur($db);
  109. $ret = $fourn->fetch($socid);
  110. if ($ret < 0) {
  111. dol_print_error($db, $object->error);
  112. }
  113. $object->socid = $fourn->id;
  114. $ret = $object->fetch_thirdparty();
  115. if ($ret < 0) {
  116. dol_print_error($db, $object->error);
  117. }
  118. }
  119. // Security check
  120. $isdraft = (isset($object->statut) && ($object->statut == $object::STATUS_DRAFT) ? 1 : 0);
  121. $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande', 'fk_soc', 'rowid', $isdraft);
  122. // Common permissions
  123. $usercanread = ($user->rights->fournisseur->commande->lire || $user->rights->supplier_order->lire);
  124. $usercancreate = ($user->rights->fournisseur->commande->creer || $user->rights->supplier_order->creer);
  125. $usercandelete = (($user->rights->fournisseur->commande->supprimer || $user->rights->supplier_order->supprimer) || ($usercancreate && isset($object->statut) && $object->statut == $object::STATUS_DRAFT));
  126. // Advanced permissions
  127. $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate)));
  128. // Additional area permissions
  129. $usercanapprove = !empty($user->rights->fournisseur->commande->approuver) ? $user->rights->fournisseur->commande->approuver : 0;
  130. $usercanapprovesecond = !empty($user->rights->fournisseur->commande->approve2) ? $user->rights->fournisseur->commande->approve2 : 0;
  131. $usercanorder = !empty($user->rights->fournisseur->commande->commander) ? $user->rights->fournisseur->commande->commander : 0;
  132. if (empty($conf->reception->enabled)) {
  133. $usercanreceive = $user->rights->fournisseur->commande->receptionner;
  134. } else {
  135. $usercanreceive = $user->rights->reception->creer;
  136. }
  137. // Permissions for includes
  138. $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
  139. $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
  140. $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
  141. $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php
  142. // Project permission
  143. $caneditproject = false;
  144. if (isModEnabled('project')) {
  145. $caneditproject = empty($conf->global->SUPPLIER_ORDER_FORBID_EDIT_PROJECT) || ($object->statut == CommandeFournisseur::STATUS_DRAFT && preg_match('/^[\(]?PROV/i', $object->ref));
  146. }
  147. $error = 0;
  148. /*
  149. * Actions
  150. */
  151. $parameters = array('socid'=>$socid);
  152. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  153. if ($reshook < 0) {
  154. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  155. }
  156. if (empty($reshook)) {
  157. $backurlforlist = DOL_URL_ROOT.'/fourn/commande/list.php'.($socid > 0 ? '?socid='.((int) $socid) : '');
  158. if (empty($backtopage) || ($cancel && empty($id))) {
  159. if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
  160. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  161. $backtopage = $backurlforlist;
  162. } else {
  163. $backtopage = DOL_URL_ROOT.'/fourn/commande/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
  164. }
  165. }
  166. }
  167. if ($cancel) {
  168. if (!empty($backtopageforcancel)) {
  169. header("Location: ".$backtopageforcancel);
  170. exit;
  171. } elseif (!empty($backtopage)) {
  172. header("Location: ".$backtopage);
  173. exit;
  174. }
  175. $action = '';
  176. }
  177. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  178. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  179. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  180. if ($action == 'setref_supplier' && $usercancreate) {
  181. $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY');
  182. if ($result < 0) {
  183. setEventMessages($object->error, $object->errors, 'errors');
  184. }
  185. }
  186. // Set incoterm
  187. if ($action == 'set_incoterms' && $usercancreate) {
  188. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  189. if ($result < 0) {
  190. setEventMessages($object->error, $object->errors, 'errors');
  191. }
  192. }
  193. // payment conditions
  194. if ($action == 'setconditions' && $usercancreate) {
  195. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  196. if ($result < 0) {
  197. setEventMessages($object->error, $object->errors, 'errors');
  198. }
  199. }
  200. // payment mode
  201. if ($action == 'setmode' && $usercancreate) {
  202. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  203. if ($result < 0) {
  204. setEventMessages($object->error, $object->errors, 'errors');
  205. }
  206. } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
  207. // Multicurrency Code
  208. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  209. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
  210. // Multicurrency rate
  211. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
  212. }
  213. // bank account
  214. if ($action == 'setbankaccount' && $usercancreate) {
  215. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  216. if ($result < 0) {
  217. setEventMessages($object->error, $object->errors, 'errors');
  218. }
  219. }
  220. // date of delivery
  221. if ($action == 'setdate_livraison' && $usercancreate) {
  222. $result = $object->setDeliveryDate($user, $datelivraison);
  223. if ($result < 0) {
  224. setEventMessages($object->error, $object->errors, 'errors');
  225. }
  226. }
  227. // Set project
  228. if ($action == 'classin' && $usercancreate && $caneditproject) {
  229. $result = $object->setProject($projectid);
  230. if ($result < 0) {
  231. setEventMessages($object->error, $object->errors, 'errors');
  232. }
  233. }
  234. // Edit Thirdparty
  235. if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $action == 'set_thirdparty' && $usercancreate && $object->statut == CommandeFournisseur::STATUS_DRAFT) {
  236. $new_socid = GETPOST('new_socid', 'int');
  237. if (!empty($new_socid) && $new_socid != $object->thirdparty->id) {
  238. $db->begin();
  239. // Update supplier
  240. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
  241. $sql .= ' SET fk_soc = '.((int) $new_socid);
  242. $sql .= ' WHERE fk_soc = '.((int) $object->thirdparty->id);
  243. $sql .= ' AND rowid = '.((int) $object->id);
  244. $res = $db->query($sql);
  245. if (!$res) {
  246. $db->rollback();
  247. } else {
  248. $db->commit();
  249. // Replace prices for each lines by new supplier prices
  250. foreach ($object->lines as $l) {
  251. $sql = 'SELECT price, unitprice, tva_tx, ref_fourn';
  252. $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price';
  253. $sql .= ' WHERE fk_product = '.((int) $l->fk_product);
  254. $sql .= ' AND fk_soc = '.((int) $new_socid);
  255. $sql .= ' ORDER BY unitprice ASC';
  256. $resql = $db->query($sql);
  257. if ($resql) {
  258. $num_row = $db->num_rows($resql);
  259. if (empty($num_row)) {
  260. // No product price for this supplier !
  261. $l->subprice = 0;
  262. $l->total_ht = 0;
  263. $l->total_tva = 0;
  264. $l->total_ttc = 0;
  265. $l->ref_supplier = '';
  266. $l->update();
  267. } else {
  268. // No need for loop to keep best supplier price
  269. $obj = $db->fetch_object($resql);
  270. $l->subprice = $obj->unitprice;
  271. $l->total_ht = $obj->price;
  272. $l->tva_tx = $obj->tva_tx;
  273. $l->total_tva = $l->total_ht * ($obj->tva_tx / 100);
  274. $l->total_ttc = $l->total_ht + $l->total_tva;
  275. $l->ref_supplier = $obj->ref_fourn;
  276. $l->update();
  277. }
  278. } else {
  279. dol_print_error($db);
  280. }
  281. $db->free($resql);
  282. }
  283. $object->update_price();
  284. }
  285. }
  286. header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id);
  287. exit;
  288. }
  289. if ($action == 'setremisepercent' && $usercancreate) {
  290. $result = $object->set_remise($user, price2num(GETPOST('remise_percent')));
  291. if ($result < 0) {
  292. setEventMessages($object->error, $object->errors, 'errors');
  293. }
  294. }
  295. if ($action == 'reopen') { // no test on permission here, permission to use will depends on status
  296. if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) {
  297. if ($object->statut == 1) {
  298. $newstatus = 0; // Validated->Draft
  299. } elseif ($object->statut == 2) {
  300. $newstatus = 0; // Approved->Draft
  301. } elseif ($object->statut == 3) {
  302. $newstatus = 2; // Ordered->Approved
  303. } elseif ($object->statut == 4) {
  304. $newstatus = 3;
  305. } elseif ($object->statut == 5) {
  306. //$newstatus=2; // Ordered
  307. // TODO Can we set it to submited ?
  308. //$newstatus=3; // Submited
  309. // TODO If there is at least one reception, we can set to Received->Received partially
  310. $newstatus = 4; // Received partially
  311. } elseif ($object->statut == 6) {
  312. $newstatus = 2; // Canceled->Approved
  313. } elseif ($object->statut == 7) {
  314. $newstatus = 3; // Canceled->Process running
  315. } elseif ($object->statut == 9) {
  316. $newstatus = 1; // Refused->Validated
  317. } else {
  318. $newstatus = 2;
  319. }
  320. //print "old status = ".$object->statut.' new status = '.$newstatus;
  321. $db->begin();
  322. $result = $object->setStatus($user, $newstatus);
  323. if ($result > 0) {
  324. // Currently the "Re-open" also remove the billed flag because there is no button "Set unpaid" yet.
  325. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
  326. $sql .= ' SET billed = 0';
  327. $sql .= ' WHERE rowid = '.((int) $object->id);
  328. $resql = $db->query($sql);
  329. if ($newstatus == 0) {
  330. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur';
  331. $sql .= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null';
  332. $sql .= ' WHERE rowid = '.((int) $object->id);
  333. $resql = $db->query($sql);
  334. }
  335. $db->commit();
  336. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
  337. exit;
  338. } else {
  339. $db->rollback();
  340. setEventMessages($object->error, $object->errors, 'errors');
  341. }
  342. }
  343. }
  344. /*
  345. * Classify supplier order as billed
  346. */
  347. if ($action == 'classifybilled' && $usercancreate) {
  348. $ret = $object->classifyBilled($user);
  349. if ($ret < 0) {
  350. setEventMessages($object->error, $object->errors, 'errors');
  351. }
  352. }
  353. // Add a product line
  354. if ($action == 'addline' && GETPOST('submitforalllines', 'aZ09') && GETPOST('vatforalllines', 'alpha') && $usercancreate) {
  355. // Define new vat_rate for all lines
  356. $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
  357. $vat_rate = str_replace('*', '', $vat_rate);
  358. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
  359. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
  360. foreach ($object->lines as $line) {
  361. $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->product_type, 0, $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice, $line->ref_supplier);
  362. }
  363. } elseif ($action == 'addline' && $usercancreate) {
  364. $db->begin();
  365. $langs->load('errors');
  366. $error = 0;
  367. // Set if we used free entry or predefined product
  368. $predef = '';
  369. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  370. $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'));
  371. $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'));
  372. $prod_entry_mode = GETPOST('prod_entry_mode');
  373. if ($prod_entry_mode == 'free') {
  374. $idprod = 0;
  375. } else {
  376. $idprod = GETPOST('idprod', 'int');
  377. }
  378. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); // Can be '1.2' or '1.2 (CODE)'
  379. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  380. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  381. $price_ttc = price2num(GETPOST('price_ttc'), 'MU', 2);
  382. $price_ttc_devise = price2num(GETPOST('multicurrency_price_ttc'), 'CU', 2);
  383. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
  384. $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef, 'alpha'), '', 2) : 0);
  385. if (empty($remise_percent)) {
  386. $remise_percent = 0;
  387. }
  388. // Extrafields
  389. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  390. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  391. // Unset extrafield
  392. if (is_array($extralabelsline)) {
  393. // Get extra fields
  394. foreach ($extralabelsline as $key => $value) {
  395. unset($_POST["options_".$key]);
  396. }
  397. }
  398. if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) {
  399. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  400. $error++;
  401. }
  402. if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) {
  403. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  404. $error++;
  405. }
  406. if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not ''
  407. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors');
  408. $error++;
  409. }
  410. if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) {
  411. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  412. $error++;
  413. }
  414. if (GETPOST('qty', 'alpha') == '') { // 0 is allowed for order
  415. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  416. $error++;
  417. }
  418. if (!$error && isModEnabled('variants') && $prod_entry_mode != 'free') {
  419. if ($combinations = GETPOST('combinations', 'array')) {
  420. //Check if there is a product with the given combination
  421. $prodcomb = new ProductCombination($db);
  422. if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
  423. $idprod = $res->fk_product_child;
  424. } else {
  425. setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
  426. $error++;
  427. }
  428. }
  429. }
  430. if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
  431. $productsupplier = new ProductFournisseur($db);
  432. $idprod = 0;
  433. if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') {
  434. $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...)
  435. }
  436. $reg = array();
  437. if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) {
  438. $idprod = $reg[1];
  439. $res = $productsupplier->fetch($idprod); // Load product from its id
  440. // Call to init some price properties of $productsupplier
  441. // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
  442. if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) {
  443. $fksoctosearch = 0;
  444. $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
  445. if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price
  446. $productsupplier->ref_supplier = '';
  447. }
  448. } else {
  449. $fksoctosearch = $object->thirdparty->id;
  450. $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
  451. }
  452. } elseif (GETPOST('idprodfournprice', 'alpha') > 0) {
  453. $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat.
  454. //$qtytosearch = -1; // We force qty to -1 to be sure to find if a supplier price exist
  455. $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch);
  456. $res = $productsupplier->fetch($idprod);
  457. }
  458. if ($idprod > 0) {
  459. $label = $productsupplier->label;
  460. // Define output language
  461. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  462. $outputlangs = $langs;
  463. $newlang = '';
  464. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  465. $newlang = GETPOST('lang_id', 'aZ09');
  466. }
  467. if (empty($newlang)) {
  468. $newlang = $object->thirdparty->default_lang;
  469. }
  470. if (!empty($newlang)) {
  471. $outputlangs = new Translate("", $conf);
  472. $outputlangs->setDefaultLang($newlang);
  473. }
  474. $desc = (!empty($productsupplier->multilangs[$outputlangs->defaultlang]["description"])) ? $productsupplier->multilangs[$outputlangs->defaultlang]["description"] : $productsupplier->description;
  475. } else {
  476. $desc = $productsupplier->description;
  477. }
  478. // if we use supplier description of the products
  479. if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  480. $desc = $productsupplier->desc_supplier;
  481. }
  482. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  483. if (trim($product_desc) == trim($desc) && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  484. $product_desc='';
  485. }
  486. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  487. $desc = $product_desc;
  488. }
  489. if (!empty($product_desc) && trim($product_desc) != trim($desc)) {
  490. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  491. }
  492. $ref_supplier = $productsupplier->ref_supplier;
  493. // Get vat rate
  494. $tva_npr = 0;
  495. if (!GETPOSTISSET('tva_tx')) { // If vat rate not provided from the form (the form has the priority)
  496. $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
  497. $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
  498. if (empty($tva_tx)) {
  499. $tva_npr = 0;
  500. }
  501. }
  502. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
  503. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
  504. $type = $productsupplier->type;
  505. if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') {
  506. $price_base_type = 'HT';
  507. $pu = price2num($price_ht, 'MU');
  508. $pu_devise = price2num($price_ht_devise, 'CU');
  509. } elseif (GETPOST('price_ttc') != '' || GETPOST('price_ttc_devise') != '') {
  510. $price_base_type = 'TTC';
  511. $pu = price2num($price_ttc, 'MU');
  512. $pu_devise = price2num($price_ttc_devise, 'CU');
  513. } else {
  514. $price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT');
  515. if (empty($object->multicurrency_code) || ($productsupplier->fourn_multicurrency_code != $object->multicurrency_code)) { // If object is in a different currency and price not in this currency
  516. $pu = $productsupplier->fourn_pu;
  517. $pu_devise = 0;
  518. } else {
  519. $pu = $productsupplier->fourn_pu;
  520. $pu_devise = $productsupplier->fourn_multicurrency_unitprice;
  521. }
  522. }
  523. if (empty($pu)) {
  524. $pu = 0; // If pu is '' or null, we force to have a numeric value
  525. }
  526. $result = $object->addline(
  527. $desc,
  528. ($price_base_type == 'HT' ? $pu : 0),
  529. $qty,
  530. $tva_tx,
  531. $localtax1_tx,
  532. $localtax2_tx,
  533. $idprod,
  534. $productsupplier->product_fourn_price_id,
  535. $ref_supplier,
  536. $remise_percent,
  537. $price_base_type,
  538. ($price_base_type == 'TTC' ? $pu : 0),
  539. $type,
  540. $tva_npr,
  541. '',
  542. $date_start,
  543. $date_end,
  544. $array_options,
  545. $productsupplier->fk_unit,
  546. $pu_devise,
  547. '',
  548. 0,
  549. min($rank, count($object->lines) + 1)
  550. );
  551. }
  552. if ($idprod == -99 || $idprod == 0) {
  553. // Product not selected
  554. $error++;
  555. $langs->load("errors");
  556. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
  557. }
  558. if ($idprod == -1) {
  559. // Quantity too low
  560. $error++;
  561. $langs->load("errors");
  562. setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors');
  563. }
  564. } elseif (empty($error)) { // $price_ht is already set
  565. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  566. $tva_tx = str_replace('*', '', $tva_tx);
  567. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  568. $desc = $product_desc;
  569. $type = GETPOST('type');
  570. $ref_supplier = GETPOST('fourn_ref', 'alpha');
  571. $fk_unit = GETPOST('units', 'alpha');
  572. if (!preg_match('/\((.*)\)/', $tva_tx)) {
  573. $tva_tx = price2num($tva_tx); // $txtva can have format '5,1' or '5.1' or '5.1(XXX)', we must clean only if '5,1'
  574. }
  575. // Local Taxes
  576. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
  577. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
  578. if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') {
  579. $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings
  580. } else {
  581. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  582. $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); // $pu_ht must be rounded according to settings
  583. }
  584. $price_base_type = 'HT';
  585. $pu_ht_devise = price2num($price_ht_devise, 'CU');
  586. $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, 0, 0, $ref_supplier, $remise_percent, $price_base_type, $pu_ttc, $type, '', '', $date_start, $date_end, $array_options, $fk_unit, $pu_ht_devise);
  587. }
  588. //print "xx".$tva_tx; exit;
  589. if (!$error && $result > 0) {
  590. $db->commit();
  591. $ret = $object->fetch($object->id); // Reload to get new records
  592. // Define output language
  593. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  594. $outputlangs = $langs;
  595. $newlang = '';
  596. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  597. $newlang = $object->thirdparty->default_lang;
  598. if (GETPOST('lang_id', 'aZ09'))
  599. $newlang = GETPOST('lang_id', 'aZ09');
  600. }
  601. if (!empty($newlang)) {
  602. $outputlangs = new Translate("", $conf);
  603. $outputlangs->setDefaultLang($newlang);
  604. }
  605. $model = $object->model_pdf;
  606. $ret = $object->fetch($id); // Reload to get new records
  607. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  608. if ($result < 0) {
  609. dol_print_error($db, $result);
  610. }
  611. }
  612. unset($_POST ['prod_entry_mode']);
  613. unset($_POST['qty']);
  614. unset($_POST['type']);
  615. unset($_POST['remise_percent']);
  616. unset($_POST['pu']);
  617. unset($_POST['price_ht']);
  618. unset($_POST['multicurrency_price_ht']);
  619. unset($_POST['price_ttc']);
  620. unset($_POST['fourn_ref']);
  621. unset($_POST['tva_tx']);
  622. unset($_POST['label']);
  623. unset($localtax1_tx);
  624. unset($localtax2_tx);
  625. unset($_POST['np_marginRate']);
  626. unset($_POST['np_markRate']);
  627. unset($_POST['dp_desc']);
  628. unset($_POST['idprodfournprice']);
  629. unset($_POST['units']);
  630. unset($_POST['date_starthour']);
  631. unset($_POST['date_startmin']);
  632. unset($_POST['date_startsec']);
  633. unset($_POST['date_startday']);
  634. unset($_POST['date_startmonth']);
  635. unset($_POST['date_startyear']);
  636. unset($_POST['date_endhour']);
  637. unset($_POST['date_endmin']);
  638. unset($_POST['date_endsec']);
  639. unset($_POST['date_endday']);
  640. unset($_POST['date_endmonth']);
  641. unset($_POST['date_endyear']);
  642. } else {
  643. $db->rollback();
  644. setEventMessages($object->error, $object->errors, 'errors');
  645. }
  646. $action = '';
  647. }
  648. /*
  649. * Updating a line in the order
  650. */
  651. if ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) {
  652. $db->begin();
  653. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  654. if ($lineid) {
  655. $line = new CommandeFournisseurLigne($db);
  656. $res = $line->fetch($lineid);
  657. if (!$res) {
  658. dol_print_error($db);
  659. }
  660. }
  661. $productsupplier = new ProductFournisseur($db);
  662. if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) {
  663. if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty', 'int')), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0) {
  664. setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings');
  665. }
  666. }
  667. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  668. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  669. // Define info_bits
  670. $info_bits = 0;
  671. if (preg_match('/\*/', $vat_rate)) {
  672. $info_bits |= 0x01;
  673. }
  674. // Define vat_rate
  675. $vat_rate = str_replace('*', '', $vat_rate);
  676. $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty);
  677. $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty);
  678. if (GETPOST('price_ht') != '') {
  679. $price_base_type = 'HT';
  680. $ht = price2num(GETPOST('price_ht'), '', 2);
  681. } else {
  682. $reg = array();
  683. $vatratecleaned = $vat_rate;
  684. if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) { // If vat is "xx (yy)"
  685. $vatratecleaned = trim($reg[1]);
  686. $vatratecode = $reg[2];
  687. }
  688. $ttc = price2num(GETPOST('price_ttc'), '', 2);
  689. $ht = $ttc / (1 + ($vatratecleaned / 100));
  690. $price_base_type = 'HT';
  691. }
  692. $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), 'CU', 2);
  693. // Extrafields Lines
  694. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  695. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  696. // Unset extrafield POST Data
  697. if (is_array($extralabelsline)) {
  698. foreach ($extralabelsline as $key => $value) {
  699. unset($_POST["options_".$key]);
  700. }
  701. }
  702. $result = $object->updateline(
  703. $lineid,
  704. GETPOST('product_desc', 'restricthtml'),
  705. $ht,
  706. price2num(GETPOST('qty'), 'MS'),
  707. price2num(GETPOST('remise_percent'), '', 2),
  708. $vat_rate,
  709. $localtax1_rate,
  710. $localtax2_rate,
  711. $price_base_type,
  712. 0,
  713. GETPOSTISSET("type") ? GETPOST("type") : $line->product_type,
  714. false,
  715. $date_start,
  716. $date_end,
  717. $array_options,
  718. GETPOST('units'),
  719. $pu_ht_devise,
  720. GETPOST('fourn_ref', 'alpha')
  721. );
  722. unset($_POST['qty']);
  723. unset($_POST['type']);
  724. unset($_POST['idprodfournprice']);
  725. unset($_POST['remmise_percent']);
  726. unset($_POST['dp_desc']);
  727. unset($_POST['np_desc']);
  728. unset($_POST['pu']);
  729. unset($_POST['fourn_ref']);
  730. unset($_POST['tva_tx']);
  731. unset($_POST['date_start']);
  732. unset($_POST['date_end']);
  733. unset($_POST['units']);
  734. unset($localtax1_tx);
  735. unset($localtax2_tx);
  736. unset($_POST['date_starthour']);
  737. unset($_POST['date_startmin']);
  738. unset($_POST['date_startsec']);
  739. unset($_POST['date_startday']);
  740. unset($_POST['date_startmonth']);
  741. unset($_POST['date_startyear']);
  742. unset($_POST['date_endhour']);
  743. unset($_POST['date_endmin']);
  744. unset($_POST['date_endsec']);
  745. unset($_POST['date_endday']);
  746. unset($_POST['date_endmonth']);
  747. unset($_POST['date_endyear']);
  748. if ($result >= 0) {
  749. // Define output language
  750. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  751. $outputlangs = $langs;
  752. $newlang = '';
  753. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  754. $newlang = GETPOST('lang_id', 'aZ09');
  755. }
  756. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  757. $newlang = $object->thirdparty->default_lang;
  758. }
  759. if (!empty($newlang)) {
  760. $outputlangs = new Translate("", $conf);
  761. $outputlangs->setDefaultLang($newlang);
  762. }
  763. $model = $object->model_pdf;
  764. $ret = $object->fetch($id); // Reload to get new records
  765. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  766. if ($result < 0) {
  767. dol_print_error($db, $result);
  768. }
  769. }
  770. $db->commit();
  771. } else {
  772. $db->rollback();
  773. setEventMessages($object->error, $object->errors, 'errors');
  774. }
  775. }
  776. // Remove a product line
  777. if ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
  778. $db->begin();
  779. $result = $object->deleteline($lineid);
  780. if ($result > 0) {
  781. // reorder lines
  782. $object->line_order(true);
  783. // Define output language
  784. $outputlangs = $langs;
  785. $newlang = '';
  786. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  787. $newlang = GETPOST('lang_id', 'aZ09');
  788. }
  789. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  790. $newlang = $object->thirdparty->default_lang;
  791. }
  792. if (!empty($newlang)) {
  793. $outputlangs = new Translate("", $conf);
  794. $outputlangs->setDefaultLang($newlang);
  795. }
  796. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  797. $ret = $object->fetch($object->id); // Reload to get new records
  798. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  799. }
  800. } else {
  801. $error++;
  802. setEventMessages($object->error, $object->errors, 'errors');
  803. // Reset action to avoid asking again confirmation on failure
  804. $action = '';
  805. }
  806. if (!$error) {
  807. $db->commit();
  808. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
  809. exit;
  810. } else {
  811. $db->rollback();
  812. }
  813. }
  814. // Validate
  815. if ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
  816. $db->begin();
  817. $object->date_commande = dol_now();
  818. $result = $object->valid($user);
  819. if ($result >= 0) {
  820. // Define output language
  821. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  822. $outputlangs = $langs;
  823. $newlang = '';
  824. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  825. $newlang = GETPOST('lang_id', 'aZ09');
  826. }
  827. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  828. $newlang = $object->thirdparty->default_lang;
  829. }
  830. if (!empty($newlang)) {
  831. $outputlangs = new Translate("", $conf);
  832. $outputlangs->setDefaultLang($newlang);
  833. }
  834. $model = $object->model_pdf;
  835. $ret = $object->fetch($id); // Reload to get new records
  836. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  837. if ($result < 0) {
  838. $error++;
  839. dol_print_error($db, $result);
  840. }
  841. }
  842. } else {
  843. $error++;
  844. setEventMessages($object->error, $object->errors, 'errors');
  845. }
  846. // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step
  847. if (!$error && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $usercanapprove && !(!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) {
  848. $action = 'confirm_approve'; // can make standard or first level approval also if permission is set
  849. }
  850. if (!$error) {
  851. $db->commit();
  852. } else {
  853. $db->rollback();
  854. }
  855. }
  856. if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $usercanapprove) {
  857. $db->begin();
  858. $idwarehouse = GETPOST('idwarehouse', 'int');
  859. $qualified_for_stock_change = 0;
  860. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  861. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  862. } else {
  863. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  864. }
  865. // Check parameters
  866. if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) { // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER
  867. if (!$idwarehouse || $idwarehouse == -1) {
  868. $error++;
  869. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  870. $action = '';
  871. }
  872. }
  873. if (!$error) {
  874. $result = $object->approve($user, $idwarehouse, ($action == 'confirm_approve2' ? 1 : 0));
  875. if ($result > 0) {
  876. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  877. $outputlangs = $langs;
  878. $newlang = '';
  879. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  880. $newlang = GETPOST('lang_id', 'aZ09');
  881. }
  882. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  883. $newlang = $object->thirdparty->default_lang;
  884. }
  885. if (!empty($newlang)) {
  886. $outputlangs = new Translate("", $conf);
  887. $outputlangs->setDefaultLang($newlang);
  888. }
  889. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  890. }
  891. } else {
  892. $error++;
  893. setEventMessages($object->error, $object->errors, 'errors');
  894. }
  895. }
  896. if (!$error) {
  897. $db->commit();
  898. header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
  899. exit;
  900. } else {
  901. $db->rollback();
  902. }
  903. }
  904. if ($action == 'confirm_refuse' && $confirm == 'yes' && $usercanapprove) {
  905. if (GETPOST('refuse_note')) {
  906. $object->refuse_note = GETPOST('refuse_note');
  907. }
  908. $result = $object->refuse($user);
  909. if ($result > 0) {
  910. header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
  911. exit;
  912. } else {
  913. setEventMessages($object->error, $object->errors, 'errors');
  914. }
  915. }
  916. // Force mandatory order method
  917. if ($action == 'commande') {
  918. $methodecommande = GETPOST('methodecommande', 'int');
  919. if ($cancel) {
  920. $action = '';
  921. } elseif ($methodecommande <= 0) {
  922. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("OrderMode")), null, 'errors');
  923. $action = 'makeorder';
  924. }
  925. }
  926. if ($action == 'confirm_commande' && $confirm == 'yes' && $usercanorder) {
  927. $db->begin();
  928. $result = $object->commande($user, GETPOST("datecommande"), GETPOST("methode", 'int'), GETPOST('comment', 'alphanohtml'));
  929. if ($result > 0) {
  930. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  931. $outputlangs = $langs;
  932. $newlang = '';
  933. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  934. $newlang = GETPOST('lang_id', 'aZ09');
  935. }
  936. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  937. $newlang = $object->thirdparty->default_lang;
  938. }
  939. if (!empty($newlang)) {
  940. $outputlangs = new Translate("", $conf);
  941. $outputlangs->setDefaultLang($newlang);
  942. }
  943. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  944. }
  945. $action = '';
  946. } else {
  947. $error++;
  948. setEventMessages($object->error, $object->errors, 'errors');
  949. }
  950. if (!$error) {
  951. $db->commit();
  952. header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
  953. exit;
  954. } else {
  955. $db->rollback();
  956. }
  957. }
  958. if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) {
  959. $result = $object->delete($user);
  960. if ($result > 0) {
  961. header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php?restore_lastsearch_values=1');
  962. exit;
  963. } else {
  964. setEventMessages($object->error, $object->errors, 'errors');
  965. }
  966. }
  967. // Action clone object
  968. if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) {
  969. if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) {
  970. setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
  971. } else {
  972. if ($object->id > 0) {
  973. $orig = clone $object;
  974. $result = $object->createFromClone($user, $socid);
  975. if ($result > 0) {
  976. header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
  977. exit;
  978. } else {
  979. setEventMessages($object->error, $object->errors, 'errors');
  980. $object = $orig;
  981. $action = '';
  982. }
  983. }
  984. }
  985. }
  986. // Set status of reception (complete, partial, ...)
  987. if ($action == 'livraison' && $usercanreceive) {
  988. if ($cancel) {
  989. $action = '';
  990. } else {
  991. $db->begin();
  992. if (GETPOST("type") != '') {
  993. $date_liv = dol_mktime(GETPOST('rehour'), GETPOST('remin'), GETPOST('resec'), GETPOST("remonth"), GETPOST("reday"), GETPOST("reyear"));
  994. $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can'
  995. if ($result > 0) {
  996. $langs->load("deliveries");
  997. setEventMessages($langs->trans("DeliveryStateSaved"), null);
  998. $action = '';
  999. } elseif ($result == -3) {
  1000. $error++;
  1001. setEventMessages($object->error, $object->errors, 'errors');
  1002. } else {
  1003. $error++;
  1004. setEventMessages($object->error, $object->errors, 'errors');
  1005. }
  1006. } else {
  1007. $error++;
  1008. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Delivery")), null, 'errors');
  1009. }
  1010. if (!$error) {
  1011. $db->commit();
  1012. } else {
  1013. $db->rollback();
  1014. }
  1015. }
  1016. }
  1017. if ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanorder) {
  1018. if (GETPOST('cancel_note')) {
  1019. $object->cancel_note = GETPOST('cancel_note');
  1020. }
  1021. $result = $object->cancel($user);
  1022. if ($result > 0) {
  1023. header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id);
  1024. exit;
  1025. } else {
  1026. setEventMessages($object->error, $object->errors, 'errors');
  1027. }
  1028. }
  1029. // Actions when printing a doc from card
  1030. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  1031. // Actions to send emails
  1032. $triggersendname = 'ORDER_SUPPLIER_SENTBYMAIL';
  1033. $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO';
  1034. $trackid = 'sord'.$object->id;
  1035. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  1036. // Actions to build doc
  1037. $upload_dir = $conf->fournisseur->commande->dir_output;
  1038. $permissiontoadd = $usercancreate;
  1039. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  1040. if ($action == 'update_extras') {
  1041. $object->oldcopy = dol_clone($object);
  1042. // Fill array 'array_options' with data from add form
  1043. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  1044. if ($ret < 0) {
  1045. $error++;
  1046. }
  1047. if (!$error) {
  1048. // Actions on extra fields
  1049. if (!$error) {
  1050. $result = $object->insertExtraFields('ORDER_SUPPLIER_MODIFY');
  1051. if ($result < 0) {
  1052. $error++;
  1053. setEventMessages($object->error, $object->errors, 'errors');
  1054. }
  1055. }
  1056. }
  1057. if ($error) {
  1058. $action = 'edit_extras';
  1059. }
  1060. }
  1061. /*
  1062. * Create an order
  1063. */
  1064. if ($action == 'add' && $usercancreate) {
  1065. $error = 0;
  1066. $selectedLines = GETPOST('toselect', 'array');
  1067. if ($socid < 1) {
  1068. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
  1069. $action = 'create';
  1070. $error++;
  1071. }
  1072. if (!$error) {
  1073. $db->begin();
  1074. // Creation commande
  1075. $object->ref_supplier = GETPOST('refsupplier');
  1076. $object->socid = $socid;
  1077. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  1078. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1079. $object->fk_account = GETPOST('fk_account', 'int');
  1080. $object->note_private = GETPOST('note_private', 'restricthtml');
  1081. $object->note_public = GETPOST('note_public', 'restricthtml');
  1082. $object->date_livraison = $datelivraison; // deprecated
  1083. $object->delivery_date = $datelivraison;
  1084. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1085. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1086. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1087. $object->multicurrency_tx = price2num(GETPOST('originmulticurrency_tx', 'alpha'));
  1088. $object->fk_project = GETPOST('projectid', 'int');
  1089. // Fill array 'array_options' with data from add form
  1090. if (!$error) {
  1091. $ret = $extrafields->setOptionalsFromPost(null, $object);
  1092. if ($ret < 0) {
  1093. $error++;
  1094. }
  1095. }
  1096. if (!$error) {
  1097. // If creation from another object of another module (Example: origin=propal, originid=1)
  1098. if (!empty($origin) && !empty($originid)) {
  1099. $element = $subelement = $origin;
  1100. $classname = ucfirst($subelement);
  1101. if ($origin == 'propal' || $origin == 'proposal') {
  1102. $element = 'comm/propal'; $subelement = 'propal';
  1103. $classname = 'Propal';
  1104. }
  1105. if ($origin == 'order' || $origin == 'commande') {
  1106. $element = $subelement = 'commande';
  1107. $classname = 'Commande';
  1108. }
  1109. if ($origin == 'supplier_proposal') {
  1110. $classname = 'SupplierProposal';
  1111. $element = 'supplier_proposal';
  1112. $subelement = 'supplier_proposal';
  1113. }
  1114. $object->origin = $origin;
  1115. $object->origin_id = $originid;
  1116. // Possibility to add external linked objects with hooks
  1117. $object->linked_objects [$object->origin] = $object->origin_id;
  1118. $other_linked_objects = GETPOST('other_linked_objects', 'array');
  1119. if (!empty($other_linked_objects)) {
  1120. $object->linked_objects = array_merge($object->linked_objects, $other_linked_objects);
  1121. }
  1122. $id = $object->create($user);
  1123. if ($id > 0) {
  1124. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  1125. $srcobject = new $classname($db);
  1126. dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines");
  1127. $result = $srcobject->fetch($object->origin_id);
  1128. if ($result > 0) {
  1129. $tmpdate = ($srcobject->delivery_date ? $srcobject->delivery_date : $srcobject->date_livraison);
  1130. $object->setDeliveryDate($user, $tmpdate);
  1131. $object->set_id_projet($user, $srcobject->fk_project);
  1132. $lines = $srcobject->lines;
  1133. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1134. $srcobject->fetch_lines();
  1135. $lines = $srcobject->lines;
  1136. }
  1137. $fk_parent_line = 0;
  1138. $num = count($lines);
  1139. for ($i = 0; $i < $num; $i++) {
  1140. if (empty($lines[$i]->subprice) || $lines[$i]->qty <= 0 || !in_array($lines[$i]->id, $selectedLines)) {
  1141. continue;
  1142. }
  1143. $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
  1144. $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->product_desc);
  1145. $product_type = (!empty($lines[$i]->product_type) ? $lines[$i]->product_type : 0);
  1146. // Reset fk_parent_line for no child products and special product
  1147. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  1148. $fk_parent_line = 0;
  1149. }
  1150. // Extrafields
  1151. if (method_exists($lines[$i], 'fetch_optionals')) { // For avoid conflicts if
  1152. $lines[$i]->fetch_optionals();
  1153. $array_option = $lines[$i]->array_options;
  1154. }
  1155. $ref_supplier = '';
  1156. $product_fourn_price_id = 0;
  1157. if ($origin == "commande") {
  1158. $productsupplier = new ProductFournisseur($db);
  1159. $result = $productsupplier->find_min_price_product_fournisseur($lines[$i]->fk_product, $lines[$i]->qty, $srcobject->socid);
  1160. if ($result > 0) {
  1161. $ref_supplier = $productsupplier->ref_supplier;
  1162. $product_fourn_price_id = $productsupplier->product_fourn_price_id;
  1163. }
  1164. } else {
  1165. $ref_supplier = $lines[$i]->ref_fourn;
  1166. $product_fourn_price_id = 0;
  1167. }
  1168. $tva_tx = $lines[$i]->tva_tx;
  1169. if ($origin == "commande") {
  1170. $soc = new societe($db);
  1171. $soc->fetch($socid);
  1172. $tva_tx = get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $product_fourn_price_id);
  1173. }
  1174. $object->special_code = $lines[$i]->special_code;
  1175. $result = $object->addline(
  1176. $desc,
  1177. $lines[$i]->subprice,
  1178. $lines[$i]->qty,
  1179. $tva_tx,
  1180. $lines[$i]->localtax1_tx,
  1181. $lines[$i]->localtax2_tx,
  1182. $lines[$i]->fk_product > 0 ? $lines[$i]->fk_product : 0,
  1183. $product_fourn_price_id,
  1184. $ref_supplier,
  1185. $lines[$i]->remise_percent,
  1186. 'HT',
  1187. 0,
  1188. $lines[$i]->product_type,
  1189. '',
  1190. '',
  1191. null,
  1192. null,
  1193. $array_option,
  1194. $lines[$i]->fk_unit,
  1195. 0,
  1196. $element,
  1197. !empty($lines[$i]->id) ? $lines[$i]->id : $lines[$i]->rowid
  1198. );
  1199. if ($result < 0) {
  1200. $error++;
  1201. break;
  1202. }
  1203. // Defined the new fk_parent_line
  1204. if ($result > 0 && $lines[$i]->product_type == 9) {
  1205. $fk_parent_line = $result;
  1206. }
  1207. }
  1208. // Add link between elements
  1209. // Hooks
  1210. $parameters = array('objFrom' => $srcobject);
  1211. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
  1212. if ($reshook < 0) {
  1213. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1214. $error++;
  1215. }
  1216. } else {
  1217. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1218. $error++;
  1219. }
  1220. } else {
  1221. setEventMessages($object->error, $object->errors, 'errors');
  1222. $error++;
  1223. }
  1224. } else {
  1225. $id = $object->create($user);
  1226. if ($id < 0) {
  1227. $error++;
  1228. setEventMessages($object->error, $object->errors, 'errors');
  1229. }
  1230. }
  1231. }
  1232. if ($error) {
  1233. $langs->load("errors");
  1234. $db->rollback();
  1235. $action = 'create';
  1236. $_GET['socid'] = $_POST['socid'];
  1237. } else {
  1238. $db->commit();
  1239. header("Location: ".$_SERVER['PHP_SELF']."?id=".urlencode($id));
  1240. exit;
  1241. }
  1242. }
  1243. }
  1244. if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && !GETPOST('cancel', 'alpha')) {
  1245. $ws_url = $object->thirdparty->webservices_url;
  1246. $ws_key = $object->thirdparty->webservices_key;
  1247. $ws_user = GETPOST('ws_user', 'alpha');
  1248. $ws_password = GETPOST('ws_password', 'alpha');
  1249. $ws_entity = GETPOST('ws_entity', 'int');
  1250. $ws_thirdparty = GETPOST('ws_thirdparty', 'int');
  1251. // NS and Authentication parameters
  1252. $ws_ns = 'http://www.dolibarr.org/ns/';
  1253. $ws_authentication = array(
  1254. 'dolibarrkey'=>$ws_key,
  1255. 'sourceapplication'=>'DolibarrWebServiceClient',
  1256. 'login'=>$ws_user,
  1257. 'password'=>$ws_password,
  1258. 'entity'=>$ws_entity
  1259. );
  1260. //Is sync supplier web services module activated? and everything filled?
  1261. if (empty($conf->syncsupplierwebservices->enabled)) {
  1262. setEventMessages($langs->trans("WarningModuleNotActive", $langs->transnoentities("Module2650Name")), null, 'mesgs');
  1263. } elseif (empty($ws_url) || empty($ws_key)) {
  1264. setEventMessages($langs->trans("ErrorWebServicesFieldsRequired"), null, 'errors');
  1265. } elseif (empty($ws_user) || empty($ws_password) || empty($ws_thirdparty)) {
  1266. setEventMessages($langs->trans("ErrorFieldsRequired"), null, 'errors');
  1267. } else {
  1268. //Create SOAP client and connect it to order
  1269. $soapclient_order = new nusoap_client($ws_url."/webservices/server_order.php");
  1270. $soapclient_order->soap_defencoding = 'UTF-8';
  1271. $soapclient_order->decodeUTF8(false);
  1272. //Create SOAP client and connect it to product/service
  1273. $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php");
  1274. $soapclient_product->soap_defencoding = 'UTF-8';
  1275. $soapclient_product->decodeUTF8(false);
  1276. //Prepare the order lines from order
  1277. $order_lines = array();
  1278. foreach ($object->lines as $line) {
  1279. $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier);
  1280. $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, '');
  1281. if ($result_product["result"]["result_code"] == "OK") {
  1282. $order_lines[] = array(
  1283. 'desc' => $line->product_desc,
  1284. 'type' => $line->product_type,
  1285. 'product_id' => $result_product["product"]["id"],
  1286. 'vat_rate' => $line->tva_tx,
  1287. 'qty' => $line->qty,
  1288. 'price' => $line->price,
  1289. 'unitprice' => $line->subprice,
  1290. 'total_net' => $line->total_ht,
  1291. 'total_vat' => $line->total_tva,
  1292. 'total' => $line->total_ttc,
  1293. 'date_start' => $line->date_start,
  1294. 'date_end' => $line->date_end,
  1295. );
  1296. }
  1297. }
  1298. //Prepare the order header
  1299. $order = array(
  1300. 'thirdparty_id' => $ws_thirdparty,
  1301. 'date' => dol_print_date(dol_now(), 'dayrfc'),
  1302. 'total_net' => $object->total_ht,
  1303. 'total_var' => $object->total_tva,
  1304. 'total' => $object->total_ttc,
  1305. 'lines' => $order_lines
  1306. );
  1307. $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order);
  1308. $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, '');
  1309. if (empty($result_order["result"]["result_code"])) { //No result, check error str
  1310. setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors');
  1311. } elseif ($result_order["result"]["result_code"] != "OK") { //Something went wrong
  1312. setEventMessages($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", null, 'errors');
  1313. } else {
  1314. setEventMessages($langs->trans("RemoteOrderRef")." ".$result_order["ref"], null, 'mesgs');
  1315. }
  1316. }
  1317. }
  1318. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
  1319. if ($action == 'addcontact') {
  1320. if ($object->id > 0) {
  1321. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  1322. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  1323. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  1324. }
  1325. if ($result >= 0) {
  1326. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1327. exit;
  1328. } else {
  1329. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1330. $langs->load("errors");
  1331. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  1332. } else {
  1333. setEventMessages($object->error, $object->errors, 'errors');
  1334. }
  1335. }
  1336. } elseif ($action == 'swapstatut' && $object->id > 0) {
  1337. // bascule du statut d'un contact
  1338. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  1339. } elseif ($action == 'deletecontact' && $object->id > 0) {
  1340. // Efface un contact
  1341. $result = $object->delete_contact(GETPOST("lineid", 'int'));
  1342. if ($result >= 0) {
  1343. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1344. exit;
  1345. } else {
  1346. dol_print_error($db);
  1347. }
  1348. }
  1349. }
  1350. }
  1351. /*
  1352. * View
  1353. */
  1354. $form = new Form($db);
  1355. $formfile = new FormFile($db);
  1356. $formorder = new FormOrder($db);
  1357. $productstatic = new Product($db);
  1358. if (isModEnabled('project')) {
  1359. $formproject = new FormProjets($db);
  1360. }
  1361. $title = $object->ref." - ".$langs->trans('Card');
  1362. if ($action == 'create') {
  1363. $title = $langs->trans("NewOrderSupplier");
  1364. }
  1365. $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores';
  1366. llxHeader('', $title, $help_url);
  1367. $now = dol_now();
  1368. if ($action == 'create') {
  1369. print load_fiche_titre($langs->trans('NewOrderSupplier'), '', 'supplier_order');
  1370. dol_htmloutput_events();
  1371. $currency_code = $conf->currency;
  1372. $societe = '';
  1373. if ($socid > 0) {
  1374. $societe = new Societe($db);
  1375. $societe->fetch($socid);
  1376. }
  1377. if (!empty($origin) && !empty($originid)) {
  1378. // Parse element/subelement (ex: project_task)
  1379. $element = $subelement = $origin;
  1380. $classname = ucfirst($subelement);
  1381. $regs = array();
  1382. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  1383. $element = $regs[1];
  1384. $subelement = $regs[2];
  1385. }
  1386. if ($origin == 'propal' || $origin == 'proposal') {
  1387. $classname = 'Propal';
  1388. $element = 'comm/propal'; $subelement = 'propal';
  1389. }
  1390. if ($origin == 'order' || $origin == 'commande') {
  1391. $classname = 'Commande';
  1392. $element = $subelement = 'commande';
  1393. }
  1394. if ($origin == 'supplier_proposal') {
  1395. $classname = 'SupplierProposal';
  1396. $element = 'supplier_proposal';
  1397. $subelement = 'supplier_proposal';
  1398. }
  1399. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  1400. $objectsrc = new $classname($db);
  1401. $objectsrc->fetch($originid);
  1402. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
  1403. $objectsrc->fetch_lines();
  1404. }
  1405. $objectsrc->fetch_thirdparty();
  1406. // Replicate extrafields
  1407. $objectsrc->fetch_optionals();
  1408. $object->array_options = $objectsrc->array_options;
  1409. $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
  1410. $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : '');
  1411. $soc = $objectsrc->client;
  1412. $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0));
  1413. $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
  1414. $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  1415. $availability_id = (!empty($objectsrc->availability_id) ? $objectsrc->availability_id : (!empty($soc->availability_id) ? $soc->availability_id : 0));
  1416. $shipping_method_id = (!empty($objectsrc->shipping_method_id) ? $objectsrc->shipping_method_id : (!empty($soc->shipping_method_id) ? $soc->shipping_method_id : 0));
  1417. $demand_reason_id = (!empty($objectsrc->demand_reason_id) ? $objectsrc->demand_reason_id : (!empty($soc->demand_reason_id) ? $soc->demand_reason_id : 0));
  1418. $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_supplier_percent) ? $soc->remise_supplier_percent : 0));
  1419. $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  1420. $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '';
  1421. $datedelivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : (!empty($objectsrc->delivery_date) ? $objectsrc->delivery_date : ''));
  1422. if (isModEnabled("multicurrency")) {
  1423. if (!empty($objectsrc->multicurrency_code)) {
  1424. $currency_code = $objectsrc->multicurrency_code;
  1425. }
  1426. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
  1427. $currency_tx = $objectsrc->multicurrency_tx;
  1428. }
  1429. }
  1430. $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null));
  1431. $note_public = $object->getDefaultCreateValueFor('note_public', (!empty($objectsrc->note_public) ? $objectsrc->note_public : null));
  1432. // Object source contacts list
  1433. $srccontactslist = $objectsrc->liste_contact(-1, 'external', 1);
  1434. } else {
  1435. $cond_reglement_id = !empty($societe->cond_reglement_supplier_id) ? $societe->cond_reglement_supplier_id : 0;
  1436. $mode_reglement_id = !empty($societe->mode_reglement_supplier_id) ? $societe->mode_reglement_supplier_id : 0;
  1437. if (isModEnabled("multicurrency") && !empty($societe->multicurrency_code)) {
  1438. $currency_code = $societe->multicurrency_code;
  1439. }
  1440. $note_private = $object->getDefaultCreateValueFor('note_private');
  1441. $note_public = $object->getDefaultCreateValueFor('note_public');
  1442. }
  1443. // If not defined, set default value from constant
  1444. if (empty($cond_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID)) {
  1445. $cond_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID;
  1446. }
  1447. if (empty($mode_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID)) {
  1448. $mode_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID;
  1449. }
  1450. print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
  1451. print '<input type="hidden" name="token" value="'.newToken().'">';
  1452. print '<input type="hidden" name="action" value="add">';
  1453. print '<input type="hidden" name="remise_percent" value="'.(empty($soc->remise_supplier_percent) ? '' : $soc->remise_supplier_percent).'">';
  1454. print '<input type="hidden" name="origin" value="'.$origin.'">';
  1455. print '<input type="hidden" name="originid" value="'.$originid.'">';
  1456. if ($backtopage) {
  1457. print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
  1458. }
  1459. if ($backtopageforcancel) {
  1460. print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
  1461. }
  1462. if (!empty($currency_tx)) {
  1463. print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
  1464. }
  1465. print dol_get_fiche_head('');
  1466. print '<table class="border centpercent">';
  1467. // Ref
  1468. print '<tr><td class="titlefieldcreate">'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
  1469. // Third party
  1470. print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
  1471. print '<td>';
  1472. if (!empty($societe->id) && $societe->id > 0) {
  1473. print $societe->getNomUrl(1, 'supplier');
  1474. print '<input type="hidden" name="socid" value="'.$societe->id.'">';
  1475. } else {
  1476. print img_picto('', 'company').$form->select_company((empty($socid) ? '' : $socid), 'socid', '(s.fournisseur=1 AND s.status=1)', 'SelectThirdParty', 1, 0, null, 0, 'minwidth175 maxwidth500 widthcentpercentminusxx');
  1477. // reload page to retrieve customer informations
  1478. if (empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE_DISABLED)) {
  1479. print '<script>
  1480. $(document).ready(function() {
  1481. $("#socid").change(function() {
  1482. console.log("We have changed the company - Reload page");
  1483. // reload page
  1484. $("input[name=action]").val("create");
  1485. $("form[name=add]").submit();
  1486. });
  1487. });
  1488. </script>';
  1489. }
  1490. print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=0&fournisseur=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
  1491. }
  1492. print '</td>';
  1493. if (!empty($societe->id) && $societe->id > 0) {
  1494. // Discounts for third party
  1495. print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
  1496. $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1);
  1497. $thirdparty = $societe;
  1498. $discount_type = 1;
  1499. $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid'));
  1500. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  1501. print '</td></tr>';
  1502. }
  1503. // Ref supplier
  1504. print '<tr><td>'.$langs->trans('RefSupplier').'</td><td><input name="refsupplier" type="text"></td>';
  1505. print '</tr>';
  1506. // Payment term
  1507. print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
  1508. print $form->getSelectConditionsPaiements(GETPOSTISSET('cond_reglement_id') ? GETPOST('cond_reglement_id') : $cond_reglement_id, 'cond_reglement_id');
  1509. print '</td></tr>';
  1510. // Payment mode
  1511. print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
  1512. $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ? GETPOST('mode_reglement_id') : $mode_reglement_id, 'mode_reglement_id');
  1513. print '</td></tr>';
  1514. // Planned delivery date
  1515. print '<tr><td>';
  1516. print $langs->trans('DateDeliveryPlanned');
  1517. print '</td>';
  1518. print '<td>';
  1519. $usehourmin = 0;
  1520. if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) {
  1521. $usehourmin = 1;
  1522. }
  1523. print $form->selectDate($datelivraison ? $datelivraison : -1, 'liv_', $usehourmin, $usehourmin, '', "set");
  1524. print '</td></tr>';
  1525. // Bank Account
  1526. if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && isModEnabled("banque")) {
  1527. $langs->load("bank");
  1528. print '<tr><td>'.$langs->trans('BankAccount').'</td><td>';
  1529. print img_picto('', 'bank_account', 'class="paddingrightonly"');
  1530. $form->select_comptes($fk_account, 'fk_account', 0, '', 1);
  1531. print '</td></tr>';
  1532. }
  1533. // Project
  1534. if (isModEnabled('project')) {
  1535. $formproject = new FormProjets($db);
  1536. $langs->load('projects');
  1537. print '<tr><td>'.$langs->trans('Project').'</td><td>';
  1538. print img_picto('', 'project').$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500');
  1539. print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?action=create&status=1'.(!empty($societe->id) ? '&socid='.$societe->id : "").'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create'.(!empty($societe->id) ? '&socid='.$societe->id : "")).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
  1540. print '</td></tr>';
  1541. }
  1542. // Incoterms
  1543. if (isModEnabled('incoterm')) {
  1544. $fkincoterms = (!empty($object->fk_incoterms) ? $object->fk_incoterms : ($socid > 0 ? $societe->fk_incoterms : ''));
  1545. $locincoterms = (!empty($object->location_incoterms) ? $object->location_incoterms : ($socid > 0 ? $societe->location_incoterms : ''));
  1546. print '<tr>';
  1547. print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $object->label_incoterms, 1).'</label></td>';
  1548. print '<td class="maxwidthonsmartphone">';
  1549. print $form->select_incoterms($fkincoterms, $locincoterms);
  1550. print '</td></tr>';
  1551. }
  1552. // Multicurrency
  1553. if (isModEnabled("multicurrency")) {
  1554. print '<tr>';
  1555. print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
  1556. print '<td class="maxwidthonsmartphone">';
  1557. print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
  1558. print '</td></tr>';
  1559. }
  1560. print '<tr><td>'.$langs->trans('NotePublic').'</td>';
  1561. print '<td>';
  1562. $doleditor = new DolEditor('note_public', isset($note_public) ? $note_public : GETPOST('note_public', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  1563. print $doleditor->Create(1);
  1564. print '</td>';
  1565. //print '<textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea>';
  1566. print '</tr>';
  1567. print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
  1568. print '<td>';
  1569. $doleditor = new DolEditor('note_private', isset($note_private) ? $note_private : GETPOST('note_private', 'restricthtml'), '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  1570. print $doleditor->Create(1);
  1571. print '</td>';
  1572. //print '<td><textarea name="note_private" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
  1573. print '</tr>';
  1574. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  1575. print "\n<!-- ".$classname." info -->";
  1576. print "\n";
  1577. print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
  1578. print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
  1579. print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
  1580. print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  1581. print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  1582. $newclassname = $classname;
  1583. print '<tr><td>'.$langs->trans($newclassname).'</td><td>'.$objectsrc->getNomUrl(1, 'supplier').'</td></tr>';
  1584. print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>';
  1585. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>";
  1586. if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 RE
  1587. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>";
  1588. }
  1589. if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 IRPF
  1590. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>";
  1591. }
  1592. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>";
  1593. if (isModEnabled("multicurrency")) {
  1594. print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
  1595. print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva).'</td></tr>';
  1596. print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc).'</td></tr>';
  1597. }
  1598. }
  1599. // Other options
  1600. $parameters = array();
  1601. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1602. print $hookmanager->resPrint;
  1603. if (empty($reshook)) {
  1604. print $object->showOptionals($extrafields, 'create');
  1605. }
  1606. // Bouton "Create Draft"
  1607. print "</table>\n";
  1608. print dol_get_fiche_end();
  1609. print $form->buttonsSaveCancel("CreateDraft");
  1610. // Show origin lines
  1611. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  1612. $title = $langs->trans('ProductsAndServices');
  1613. print load_fiche_titre($title);
  1614. print '<div class="div-table-responsive-no-min">';
  1615. print '<table class="noborder centpercent">';
  1616. $objectsrc->printOriginLinesList('', $selectedLines);
  1617. print '</table>';
  1618. print '</div>';
  1619. }
  1620. print "</form>\n";
  1621. } elseif (!empty($object->id)) {
  1622. $result = $object->fetch($id, $ref);
  1623. $societe = new Fournisseur($db);
  1624. $result = $societe->fetch($object->socid);
  1625. if ($result < 0) {
  1626. dol_print_error($db);
  1627. }
  1628. $author = new User($db);
  1629. $author->fetch($object->user_author_id);
  1630. $res = $object->fetch_optionals();
  1631. $head = ordersupplier_prepare_head($object);
  1632. $title = $langs->trans("SupplierOrder");
  1633. print dol_get_fiche_head($head, 'card', $title, -1, 'order');
  1634. $formconfirm = '';
  1635. // Confirmation de la suppression de la commande
  1636. if ($action == 'delete') {
  1637. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 2);
  1638. }
  1639. // Clone confirmation
  1640. if ($action == 'clone') {
  1641. // Create an array for form
  1642. $formquestion = array(
  1643. array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.fournisseur=1)'))
  1644. );
  1645. // Paiement incomplet. On demande si motif = escompte ou autre
  1646. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneOrder', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
  1647. }
  1648. // Confirmation de la validation
  1649. if ($action == 'valid') {
  1650. $object->date_commande = dol_now();
  1651. // We check if number is temporary number
  1652. if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) { // empty should not happened, but when it occurs, the test save life
  1653. $newref = $object->getNextNumRef($object->thirdparty);
  1654. } else {
  1655. $newref = $object->ref;
  1656. }
  1657. if ($newref < 0) {
  1658. setEventMessages($object->error, $object->errors, 'errors');
  1659. $action = '';
  1660. } else {
  1661. $text = $langs->trans('ConfirmValidateOrder', $newref);
  1662. if (isModEnabled('notification')) {
  1663. require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
  1664. $notify = new Notify($db);
  1665. $text .= '<br>';
  1666. $text .= $notify->confirmMessage('ORDER_SUPPLIER_VALIDATE', $object->socid, $object);
  1667. }
  1668. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateOrder'), $text, 'confirm_valid', '', 0, 1);
  1669. }
  1670. }
  1671. // Confirm approval
  1672. if ($action == 'approve' || $action == 'approve2') {
  1673. $qualified_for_stock_change = 0;
  1674. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  1675. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  1676. } else {
  1677. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  1678. }
  1679. $formquestion = array();
  1680. if (isModEnabled('stock') && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) {
  1681. $langs->load("stocks");
  1682. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  1683. $formproduct = new FormProduct($db);
  1684. $forcecombo = 0;
  1685. if ($conf->browser->name == 'ie') {
  1686. $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
  1687. }
  1688. $formquestion = array(
  1689. //'text' => $langs->trans("ConfirmClone"),
  1690. //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
  1691. //array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
  1692. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockIncrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse', 'int'), 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo))
  1693. );
  1694. }
  1695. $text = $langs->trans("ConfirmApproveThisOrder", $object->ref);
  1696. if (isModEnabled('notification')) {
  1697. require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
  1698. $notify = new Notify($db);
  1699. $text .= '<br>';
  1700. $text .= $notify->confirmMessage('ORDER_SUPPLIER_APPROVE', $object->socid, $object);
  1701. }
  1702. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id, $langs->trans("ApproveThisOrder"), $text, "confirm_".$action, $formquestion, 1, 1, 240);
  1703. }
  1704. // Confirmation of disapproval
  1705. if ($action == 'refuse') {
  1706. $formquestion = array(
  1707. array(
  1708. 'type' => 'text',
  1709. 'name' => 'refuse_note',
  1710. 'label' => $langs->trans("Reason"),
  1711. 'value' => '',
  1712. 'morecss' => 'minwidth300'
  1713. )
  1714. );
  1715. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("DenyingThisOrder"), $langs->trans("ConfirmDenyingThisOrder", $object->ref), "confirm_refuse", $formquestion, 0, 1);
  1716. }
  1717. // Confirmation of cancellation
  1718. if ($action == 'cancel') {
  1719. $formquestion = array(
  1720. array(
  1721. 'type' => 'text',
  1722. 'name' => 'cancel_note',
  1723. 'label' => $langs->trans("Reason"),
  1724. 'value' => '',
  1725. 'morecss' => 'minwidth300'
  1726. )
  1727. );
  1728. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("Cancel"), $langs->trans("ConfirmCancelThisOrder", $object->ref), "confirm_cancel", $formquestion, 0, 1);
  1729. }
  1730. // Confirmation de l'envoi de la commande
  1731. if ($action == 'commande') {
  1732. $date_com = dol_mktime(GETPOST('rehour'), GETPOST('remin'), GETPOST('resec'), GETPOST("remonth"), GETPOST("reday"), GETPOST("reyear"));
  1733. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id."&datecommande=".$date_com."&methode=".GETPOST("methodecommande")."&comment=".urlencode(GETPOST("comment")), $langs->trans("MakeOrder"), $langs->trans("ConfirmMakeOrder", dol_print_date($date_com, 'day')), "confirm_commande", '', 0, 2);
  1734. }
  1735. // Confirmation to delete line
  1736. if ($action == 'ask_deleteline') {
  1737. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
  1738. }
  1739. $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid);
  1740. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  1741. if (empty($reshook)) {
  1742. $formconfirm .= $hookmanager->resPrint;
  1743. } elseif ($reshook > 0) {
  1744. $formconfirm = $hookmanager->resPrint;
  1745. }
  1746. // Print form confirm
  1747. print $formconfirm;
  1748. // Supplier order card
  1749. $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/commande/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  1750. $morehtmlref = '<div class="refidno">';
  1751. // Ref supplier
  1752. $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1);
  1753. $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string'.(isset($conf->global->THIRDPARTY_REF_INPUT_SIZE) ? ':'.$conf->global->THIRDPARTY_REF_INPUT_SIZE : ''), '', null, null, '', 1);
  1754. // Thirdparty
  1755. $morehtmlref .= '<br>';
  1756. if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && !empty($usercancreate) && $action == 'edit_thirdparty') {
  1757. $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  1758. $morehtmlref .= '<input type="hidden" name="action" value="set_thirdparty">';
  1759. $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
  1760. $morehtmlref .= $form->select_company($object->thirdparty->id, 'new_socid', 's.fournisseur=1', '', 0, 0, array(), 0, 'minwidth300');
  1761. $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  1762. $morehtmlref .= '</form>';
  1763. }
  1764. if (empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) || $action != 'edit_thirdparty') {
  1765. if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $object->statut == CommandeFournisseur::STATUS_DRAFT) {
  1766. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=edit_thirdparty&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).'</a>';
  1767. }
  1768. $morehtmlref .= $object->thirdparty->getNomUrl(1, 'supplier');
  1769. if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
  1770. $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)';
  1771. }
  1772. }
  1773. // Project
  1774. if (isModEnabled('project')) {
  1775. $langs->load("projects");
  1776. $morehtmlref .= '<br>';
  1777. if ($permissiontoadd) {
  1778. $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"');
  1779. if ($action != 'classify' && $caneditproject) {
  1780. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> ';
  1781. }
  1782. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, (empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300');
  1783. } else {
  1784. if (!empty($object->fk_project)) {
  1785. $proj = new Project($db);
  1786. $proj->fetch($object->fk_project);
  1787. $morehtmlref .= $proj->getNomUrl(1);
  1788. if ($proj->title) {
  1789. $morehtmlref .= '<span class="opacitymedium"> - '.dol_escape_htmltag($proj->title).'</span>';
  1790. }
  1791. }
  1792. }
  1793. }
  1794. $morehtmlref .= '</div>';
  1795. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
  1796. print '<div class="fichecenter">';
  1797. print '<div class="fichehalfleft">';
  1798. print '<div class="underbanner clearboth"></div>';
  1799. print '<table class="border tableforfield centpercent">';
  1800. // Date
  1801. if ($object->methode_commande_id > 0) {
  1802. $usehourmin = 0;
  1803. if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) {
  1804. $usehourmin = 1;
  1805. }
  1806. print '<tr><td class="titlefield">'.$langs->trans("Date").'</td><td>';
  1807. print $object->date_commande ? dol_print_date($object->date_commande, $usehourmin ? 'dayhour' : 'day') : '';
  1808. if ($object->hasDelay() && !empty($object->delivery_date) && !empty($object->date_commande)) {
  1809. print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
  1810. }
  1811. print "</td></tr>";
  1812. if ($object->methode_commande) {
  1813. print '<tr><td>'.$langs->trans("Method").'</td><td>'.$object->getInputMethod().'</td></tr>';
  1814. }
  1815. }
  1816. // Author
  1817. print '<tr><td class="titlefield">'.$langs->trans("AuthorRequest").'</td>';
  1818. print '<td>'.$author->getNomUrl(1, '', 0, 0, 0).'</td>';
  1819. print '</tr>';
  1820. // Relative and absolute discounts
  1821. if (!empty($conf->global->FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS)) {
  1822. $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  1823. $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  1824. } else {
  1825. $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')";
  1826. $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')";
  1827. }
  1828. $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1);
  1829. $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1);
  1830. $absolute_discount = price2num($absolute_discount, 'MT');
  1831. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  1832. print '<tr><td class="titlefield">'.$langs->trans('Discounts').'</td><td>';
  1833. $thirdparty = $societe;
  1834. $discount_type = 1;
  1835. $backtopage = urlencode($_SERVER["PHP_SELF"].'?id='.$object->id);
  1836. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  1837. print '</td></tr>';
  1838. // Default terms of the settlement
  1839. $langs->load('bills');
  1840. print '<tr><td class="nowrap">';
  1841. print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  1842. print $langs->trans('PaymentConditions');
  1843. print '<td>';
  1844. if ($action != 'editconditions') {
  1845. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
  1846. }
  1847. print '</tr></table>';
  1848. print '</td><td>';
  1849. if ($action == 'editconditions') {
  1850. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  1851. } else {
  1852. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none');
  1853. }
  1854. print "</td>";
  1855. print '</tr>';
  1856. // Mode of payment
  1857. $langs->load('bills');
  1858. print '<tr><td class="nowrap">';
  1859. print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  1860. print $langs->trans('PaymentMode');
  1861. print '</td>';
  1862. if ($action != 'editmode') {
  1863. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
  1864. }
  1865. print '</tr></table>';
  1866. print '</td><td>';
  1867. if ($action == 'editmode') {
  1868. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1);
  1869. } else {
  1870. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
  1871. }
  1872. print '</td></tr>';
  1873. // Multicurrency
  1874. if (isModEnabled("multicurrency")) {
  1875. // Multicurrency code
  1876. print '<tr>';
  1877. print '<td>';
  1878. print '<table class="nobordernopadding centpercent"><tr><td>';
  1879. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  1880. print '</td>';
  1881. if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) {
  1882. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
  1883. }
  1884. print '</tr></table>';
  1885. print '</td><td>';
  1886. if ($action == 'editmulticurrencycode') {
  1887. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code');
  1888. } else {
  1889. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none');
  1890. }
  1891. print '</td></tr>';
  1892. // Multicurrency rate
  1893. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  1894. print '<tr>';
  1895. print '<td>';
  1896. print '<table class="nobordernopadding centpercent"><tr>';
  1897. print '<td>';
  1898. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  1899. print '</td>';
  1900. if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  1901. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
  1902. }
  1903. print '</tr></table>';
  1904. print '</td><td>';
  1905. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  1906. if ($action == 'actualizemulticurrencyrate') {
  1907. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  1908. }
  1909. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
  1910. } else {
  1911. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  1912. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  1913. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  1914. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  1915. print '</div>';
  1916. }
  1917. }
  1918. print '</td></tr>';
  1919. }
  1920. }
  1921. // Bank Account
  1922. if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && isModEnabled("banque")) {
  1923. print '<tr><td class="nowrap">';
  1924. print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">';
  1925. print $langs->trans('BankAccount');
  1926. print '<td>';
  1927. if ($action != 'editbankaccount' && $usercancreate) {
  1928. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>';
  1929. }
  1930. print '</tr></table>';
  1931. print '</td><td>';
  1932. if ($action == 'editbankaccount') {
  1933. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  1934. } else {
  1935. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  1936. }
  1937. print '</td>';
  1938. print '</tr>';
  1939. }
  1940. // Delivery delay (in days)
  1941. print '<tr>';
  1942. print '<td>'.$langs->trans('NbDaysToDelivery').'&nbsp;'.img_picto($langs->trans('DescNbDaysToDelivery'), 'info', 'style="cursor:help"').'</td>';
  1943. print '<td>'.$object->getMaxDeliveryTimeDay($langs).'</td>';
  1944. print '</tr>';
  1945. // Delivery date planed
  1946. print '<tr><td>';
  1947. print '<table class="nobordernopadding centpercent"><tr><td>';
  1948. print $langs->trans('DateDeliveryPlanned');
  1949. print '</td>';
  1950. if ($action != 'editdate_livraison') {
  1951. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'</a></td>';
  1952. }
  1953. print '</tr></table>';
  1954. print '</td><td>';
  1955. if ($action == 'editdate_livraison') {
  1956. print '<form name="setdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
  1957. print '<input type="hidden" name="token" value="'.newToken().'">';
  1958. print '<input type="hidden" name="action" value="setdate_livraison">';
  1959. $usehourmin = 0;
  1960. if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) {
  1961. $usehourmin = 1;
  1962. }
  1963. print $form->selectDate($object->delivery_date ? $object->delivery_date : -1, 'liv_', $usehourmin, $usehourmin, '', "setdate_livraison");
  1964. print '<input type="submit" class="button button-edit smallpaddingimp valign middle" value="'.$langs->trans('Modify').'">';
  1965. print '</form>';
  1966. } else {
  1967. $usehourmin = 'day';
  1968. if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) {
  1969. $usehourmin = 'dayhour';
  1970. }
  1971. print $object->delivery_date ? dol_print_date($object->delivery_date, $usehourmin) : '&nbsp;';
  1972. if ($object->hasDelay() && !empty($object->delivery_date) && ($object->statut == $object::STATUS_ORDERSENT || $object->statut == $object::STATUS_RECEIVED_PARTIALLY)) {
  1973. print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning");
  1974. }
  1975. }
  1976. print '</td></tr>';
  1977. // Incoterms
  1978. if (isModEnabled('incoterm')) {
  1979. print '<tr><td>';
  1980. print '<table class="nobordernopadding centpercent"><tr><td>';
  1981. print $langs->trans('IncotermLabel');
  1982. print '<td><td class="right">';
  1983. if ($usercancreate) {
  1984. print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id.'&action=editincoterm&token='.newToken().'">'.img_edit().'</a>';
  1985. } else {
  1986. print '&nbsp;';
  1987. }
  1988. print '</td></tr></table>';
  1989. print '</td>';
  1990. print '<td>';
  1991. if ($action != 'editincoterm') {
  1992. print $form->textwithpicto(dol_escape_htmltag($object->display_incoterms()), $object->label_incoterms, 1);
  1993. } else {
  1994. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
  1995. }
  1996. print '</td></tr>';
  1997. }
  1998. // Other attributes
  1999. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  2000. print '</table>';
  2001. print '</div>';
  2002. print '<div class="fichehalfright">';
  2003. print '<div class="underbanner clearboth"></div>';
  2004. print '<table class="border tableforfield centpercent">';
  2005. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  2006. // Multicurrency Amount HT
  2007. print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
  2008. print '<td class="nowrap right amountcard">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2009. print '</tr>';
  2010. // Multicurrency Amount VAT
  2011. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
  2012. print '<td class="nowrap right amountcard">'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2013. print '</tr>';
  2014. // Multicurrency Amount TTC
  2015. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
  2016. print '<td class="nowrap right amountcard">'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2017. print '</tr>';
  2018. }
  2019. // Total
  2020. $alert = '';
  2021. if (!empty($conf->global->ORDER_MANAGE_MIN_AMOUNT) && $object->total_ht < $object->thirdparty->supplier_order_min_amount) {
  2022. $alert = ' '.img_warning($langs->trans('OrderMinAmount').': '.price($object->thirdparty->supplier_order_min_amount));
  2023. }
  2024. print '<tr><td class="titlefieldmiddle">'.$langs->trans("AmountHT").'</td>';
  2025. print '<td class="nowrap right amountcard">'.price($object->total_ht, '', $langs, 1, -1, -1, $conf->currency).$alert.'</td>';
  2026. print '</tr>';
  2027. // Total VAT
  2028. print '<tr><td>'.$langs->trans("AmountVAT").'</td>';
  2029. print '<td class="nowrap right amountcard">'.price($object->total_tva, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  2030. print '</tr>';
  2031. // Amount Local Taxes
  2032. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1
  2033. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
  2034. print '<td class="nowrap right amountcard">'.price($object->total_localtax1, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  2035. print '</tr>';
  2036. }
  2037. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2
  2038. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
  2039. print '<td class="nowrap right amountcard">'.price($object->total_localtax2, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  2040. print '</tr>';
  2041. }
  2042. // Total TTC
  2043. print '<tr><td>'.$langs->trans("AmountTTC").'</td>';
  2044. print '<td class="nowrap right amountcard">'.price($object->total_ttc, '', $langs, 1, -1, -1, $conf->currency).'</td>';
  2045. print '</tr>';
  2046. print '</table>';
  2047. // Margin Infos
  2048. /*if (isModEnabled('margin')) {
  2049. $formmargin->displayMarginInfos($object);
  2050. }*/
  2051. print '</div>';
  2052. print '</div>';
  2053. print '<div class="clearboth"></div><br>';
  2054. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  2055. $blocname = 'contacts';
  2056. $title = $langs->trans('ContactsAddresses');
  2057. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  2058. }
  2059. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  2060. $blocname = 'notes';
  2061. $title = $langs->trans('Notes');
  2062. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  2063. }
  2064. /*
  2065. * Lines
  2066. */
  2067. //$result = $object->getLinesArray();
  2068. print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
  2069. <input type="hidden" name="token" value="'.newToken().'">
  2070. <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
  2071. <input type="hidden" name="mode" value="">
  2072. <input type="hidden" name="page_y" value="">
  2073. <input type="hidden" name="id" value="'.$object->id.'">
  2074. <input type="hidden" name="socid" value="'.$societe->id.'">
  2075. ';
  2076. if (!empty($conf->use_javascript_ajax) && $object->statut == 0) {
  2077. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  2078. }
  2079. print '<div class="div-table-responsive-no-min">';
  2080. print '<table id="tablelines" class="noborder noshadow centpercent">';
  2081. // Add free products/services form
  2082. global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax;
  2083. $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1;
  2084. $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum.
  2085. if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) {
  2086. $senderissupplier = 1;
  2087. }
  2088. // Show object lines
  2089. if (!empty($object->lines)) {
  2090. $object->printObjectLines($action, $societe, $mysoc, $lineid, 1);
  2091. }
  2092. $num = count($object->lines);
  2093. // Form to add new line
  2094. if ($object->statut == CommandeFournisseur::STATUS_DRAFT && $usercancreate) {
  2095. if ($action != 'editline') {
  2096. // Add free products/services
  2097. $parameters = array();
  2098. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2099. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2100. if (empty($reshook))
  2101. $object->formAddObjectLine(1, $societe, $mysoc);
  2102. }
  2103. }
  2104. print '</table>';
  2105. print '</div>';
  2106. print '</form>';
  2107. print dol_get_fiche_end();
  2108. /**
  2109. * Buttons for actions
  2110. */
  2111. if ($user->socid == 0 && $action != 'delete') {
  2112. if ($action != 'makeorder' && $action != 'presend' && $action != 'editline') {
  2113. print '<div class="tabsAction">';
  2114. $parameters = array();
  2115. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
  2116. // modified by hook
  2117. if (empty($reshook)) {
  2118. $object->fetchObjectLinked(); // Links are used to show or not button, so we load them now.
  2119. // Validate
  2120. if ($object->statut == 0 && $num > 0) {
  2121. if ($usercanvalidate) {
  2122. $tmpbuttonlabel = $langs->trans('Validate');
  2123. if ($usercanapprove && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) {
  2124. $tmpbuttonlabel = $langs->trans("ValidateAndApprove");
  2125. }
  2126. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">';
  2127. print $tmpbuttonlabel;
  2128. print '</a>';
  2129. }
  2130. }
  2131. // Create event
  2132. /*if ($conf->agenda->enabled && !empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
  2133. {
  2134. print '<div class="inline-block divButAction"><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></div>';
  2135. }*/
  2136. // Modify
  2137. if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) {
  2138. if ($usercanorder) {
  2139. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen&token='.newToken().'">'.$langs->trans("Modify").'</a>';
  2140. }
  2141. }
  2142. // Approve
  2143. if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) {
  2144. if ($usercanapprove) {
  2145. if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED && !empty($object->user_approve_id)) {
  2146. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("FirstApprovalAlreadyDone")).'">'.$langs->trans("ApproveOrder").'</a>';
  2147. } else {
  2148. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=approve">'.$langs->trans("ApproveOrder").'</a>';
  2149. }
  2150. } else {
  2151. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("ApproveOrder").'</a>';
  2152. }
  2153. }
  2154. // Second approval (if option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set)
  2155. if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) {
  2156. if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) {
  2157. if ($usercanapprovesecond) {
  2158. if (!empty($object->user_approve_id2)) {
  2159. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("SecondApprovalAlreadyDone")).'">'.$langs->trans("Approve2Order").'</a>';
  2160. } else {
  2161. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=approve2">'.$langs->trans("Approve2Order").'</a>';
  2162. }
  2163. } else {
  2164. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("Approve2Order").'</a>';
  2165. }
  2166. }
  2167. }
  2168. // Refuse
  2169. if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) {
  2170. if ($usercanapprove || $usercanapprovesecond) {
  2171. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=refuse">'.$langs->trans("RefuseOrder").'</a>';
  2172. } else {
  2173. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("RefuseOrder").'</a>';
  2174. }
  2175. }
  2176. // Send
  2177. if (empty($user->socid)) {
  2178. if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED, 3, 4, 5)) || !empty($conf->global->SUPPLIER_ORDER_SENDBYEMAIL_FOR_ALL_STATUS)) {
  2179. if ($usercanorder) {
  2180. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>';
  2181. }
  2182. }
  2183. }
  2184. // Reopen
  2185. if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED))) {
  2186. $buttonshown = 0;
  2187. if (!$buttonshown && $usercanapprove) {
  2188. if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY)
  2189. || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) {
  2190. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen&token='.newToken().'">'.$langs->trans("Disapprove").'</a>';
  2191. $buttonshown++;
  2192. }
  2193. }
  2194. if (!$buttonshown && $usercanapprovesecond && !empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) {
  2195. if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY)
  2196. || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) {
  2197. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen&token='.newToken().'">'.$langs->trans("Disapprove").'</a>';
  2198. }
  2199. }
  2200. }
  2201. if (in_array($object->statut, array(3, 4, 5, 6, 7, 9))) {
  2202. if ($usercanorder) {
  2203. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen&token='.newToken().'">'.$langs->trans("ReOpen").'</a>';
  2204. }
  2205. }
  2206. // Ship
  2207. $hasreception = 0;
  2208. if (isModEnabled('stock') && (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE))) {
  2209. $labelofbutton = $langs->trans('ReceiveProducts');
  2210. if ($conf->reception->enabled) {
  2211. $labelofbutton = $langs->trans("CreateReception");
  2212. if (!empty($object->linkedObjects['reception'])) {
  2213. foreach ($object->linkedObjects['reception'] as $element) {
  2214. if ($element->statut >= 0) {
  2215. $hasreception = 1;
  2216. break;
  2217. }
  2218. }
  2219. }
  2220. }
  2221. if (in_array($object->statut, array(3, 4, 5))) {
  2222. if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order")) && $usercanreceive) {
  2223. print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/fourn/commande/dispatch.php?id='.$object->id.'">'.$labelofbutton.'</a></div>';
  2224. } else {
  2225. print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$labelofbutton.'</a></div>';
  2226. }
  2227. }
  2228. }
  2229. if ($object->statut == CommandeFournisseur::STATUS_ACCEPTED) {
  2230. if ($usercanorder) {
  2231. print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=makeorder#makeorder">'.$langs->trans("MakeOrder").'</a></div>';
  2232. } else {
  2233. print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("MakeOrder").'</a></div>';
  2234. }
  2235. }
  2236. // Classify received (this does not record reception)
  2237. if ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) {
  2238. if ($usercanreceive) {
  2239. print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&token='.newToken().'&action=classifyreception#classifyreception">'.$langs->trans("ClassifyReception").'</a></div>';
  2240. }
  2241. }
  2242. // Create bill
  2243. //if (isModEnabled('facture'))
  2244. //{
  2245. if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_invoice")) && ($object->statut >= 2 && $object->statut != 7 && $object->billed != 1)) { // statut 2 means approved, 7 means canceled
  2246. if ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer) {
  2247. print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("CreateBill").'</a>';
  2248. }
  2249. }
  2250. //}
  2251. // Classify billed manually (need one invoice if module invoice is on, no condition on invoice if not)
  2252. if ($usercancreate && $object->statut >= 2 && $object->statut != 7 && $object->billed != 1) { // statut 2 means approved
  2253. if (!isModEnabled('facture')) {
  2254. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=classifybilled&token='.newToken().'">'.$langs->trans("ClassifyBilled").'</a>';
  2255. } else {
  2256. if (!empty($object->linkedObjectsIds['invoice_supplier'])) {
  2257. if ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer) {
  2258. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=classifybilled&token='.newToken().'">'.$langs->trans("ClassifyBilled").'</a>';
  2259. }
  2260. } else {
  2261. print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NeedAtLeastOneInvoice")).'">'.$langs->trans("ClassifyBilled").'</a>';
  2262. }
  2263. }
  2264. }
  2265. // Create a remote order using WebService only if module is activated
  2266. if (!empty($conf->syncsupplierwebservices->enabled) && $object->statut >= 2) { // 2 means accepted
  2267. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=webservice&token='.newToken().'&mode=init">'.$langs->trans('CreateRemoteOrder').'</a>';
  2268. }
  2269. // Clone
  2270. if ($usercancreate) {
  2271. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object=order">'.$langs->trans("ToClone").'</a>';
  2272. }
  2273. // Cancel
  2274. if ($object->statut == CommandeFournisseur::STATUS_ACCEPTED) {
  2275. if ($usercanorder) {
  2276. print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=cancel">'.$langs->trans("CancelOrder").'</a>';
  2277. }
  2278. }
  2279. // Delete
  2280. if (!empty($usercandelete)) {
  2281. if ($hasreception) {
  2282. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("ReceptionExist").'">'.$langs->trans("Delete").'</a>';
  2283. } else {
  2284. print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans("Delete").'</a>';
  2285. }
  2286. }
  2287. }
  2288. print "</div>";
  2289. }
  2290. if ($usercanorder && $object->statut == CommandeFournisseur::STATUS_ACCEPTED && $action == 'makeorder') {
  2291. // Set status to ordered (action=commande)
  2292. print '<!-- form to record supplier order -->'."\n";
  2293. print '<form name="commande" id="makeorder" action="card.php?id='.$object->id.'&amp;action=commande" method="POST">';
  2294. print '<input type="hidden" name="token" value="'.newToken().'">';
  2295. print '<input type="hidden" name="action" value="commande">';
  2296. print load_fiche_titre($langs->trans("ToOrder"), '', '');
  2297. print '<table class="noborder centpercent">';
  2298. //print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("ToOrder").'</td></tr>';
  2299. print '<tr><td class="fieldrequired">'.$langs->trans("OrderDate").'</td><td>';
  2300. $date_com = dol_mktime(GETPOST('rehour', 'int'), GETPOST('remin', 'int'), GETPOST('resec', 'int'), GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  2301. if (empty($date_com)) {
  2302. $date_com = dol_now();
  2303. }
  2304. print $form->selectDate($date_com, '', 1, 1, '', "commande", 1, 1);
  2305. print '</td></tr>';
  2306. // Force mandatory order method
  2307. print '<tr><td class="fieldrequired">'.$langs->trans("OrderMode").'</td><td>';
  2308. $formorder->selectInputMethod(GETPOST('methodecommande'), "methodecommande", 1);
  2309. print '</td></tr>';
  2310. print '<tr><td>'.$langs->trans("Comment").'</td><td><input size="40" type="text" name="comment" value="'.GETPOST('comment').'"></td></tr>';
  2311. print '<tr><td class="center" colspan="2">';
  2312. print '<input type="submit" name="makeorder" class="button" value="'.$langs->trans("ToOrder").'">';
  2313. print ' &nbsp; &nbsp; ';
  2314. print '<input type="submit" name="cancel" class="button button-cancel" value="'.$langs->trans("Cancel").'">';
  2315. print '</td></tr>';
  2316. print '</table>';
  2317. print '</form>';
  2318. print "<br>";
  2319. }
  2320. // Select mail models is same action as presend
  2321. if (GETPOST('modelselected')) {
  2322. $action = 'presend';
  2323. }
  2324. if ($action != 'makeorder' && $action != 'presend' ) {
  2325. print '<div class="fichecenter"><div class="fichehalfleft">';
  2326. // Generated documents
  2327. $objref = dol_sanitizeFileName($object->ref);
  2328. $file = $conf->fournisseur->dir_output.'/commande/'.$objref.'/'.$objref.'.pdf';
  2329. $relativepath = $objref.'/'.$objref.'.pdf';
  2330. $filedir = $conf->fournisseur->dir_output.'/commande/'.$objref;
  2331. $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id;
  2332. $genallowed = $usercanread;
  2333. $delallowed = $usercancreate;
  2334. $modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->COMMANDE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->COMMANDE_SUPPLIER_ADDON_PDF));
  2335. print $formfile->showdocuments('commande_fournisseur', $objref, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 0, 0, '', '', '', $object->thirdparty->default_lang, '', $object);
  2336. $somethingshown = $formfile->numoffiles;
  2337. // Show links to link elements
  2338. $linktoelem = $form->showLinkToObjectBlock($object, null, array('supplier_order', 'order_supplier'));
  2339. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  2340. print '</div><div class="fichehalfright">';
  2341. if ($action == 'classifyreception') {
  2342. if ($usercanreceive && ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY)) {
  2343. // Set status to received (action=livraison)
  2344. print '<!-- form to record purchase order received -->'."\n";
  2345. print '<form id="classifyreception" action="card.php?id='.$object->id.'" method="post">';
  2346. print '<input type="hidden" name="token" value="'.newToken().'">';
  2347. print '<input type="hidden" name="action" value="livraison">';
  2348. print load_fiche_titre($langs->trans("Receive"), '', '');
  2349. print '<table class="noborder centpercent">';
  2350. //print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("Receive").'</td></tr>';
  2351. print '<tr><td>'.$langs->trans("DeliveryDate").'</td><td>';
  2352. $datepreselected = dol_now();
  2353. print $form->selectDate($datepreselected, '', 1, 1, '', "commande", 1, 1);
  2354. print "</td></tr>\n";
  2355. print '<tr><td class="fieldrequired">'.$langs->trans("Delivery")."</td><td>\n";
  2356. $liv = array();
  2357. $liv[''] = '&nbsp;';
  2358. $liv['tot'] = $langs->trans("CompleteOrNoMoreReceptionExpected");
  2359. $liv['par'] = $langs->trans("PartialWoman");
  2360. $liv['nev'] = $langs->trans("NeverReceived");
  2361. $liv['can'] = $langs->trans("Canceled");
  2362. print $form->selectarray("type", $liv);
  2363. print '</td></tr>';
  2364. print '<tr><td>'.$langs->trans("Comment").'</td><td><input size="40" type="text" name="comment"></td></tr>';
  2365. print '<tr><td class="center" colspan="2">';
  2366. print '<input type="submit" name="receive" class="button" value="'.$langs->trans("Receive").'">';
  2367. print ' &nbsp; &nbsp; ';
  2368. print '<input type="submit" name="cancel" class="button button-cancel" value="'.$langs->trans("Cancel").'">';
  2369. print '</td></tr>';
  2370. print "</table>\n";
  2371. print "</form>\n";
  2372. print "<br>";
  2373. }
  2374. }
  2375. // List of actions on element
  2376. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  2377. $formactions = new FormActions($db);
  2378. $somethingshown = $formactions->showactions($object, 'order_supplier', $socid, 1, 'listaction'.($genallowed ? 'largetitle' : ''));
  2379. print '</div></div>';
  2380. }
  2381. /*
  2382. * Action webservice
  2383. */
  2384. if ($action == 'webservice' && GETPOST('mode', 'alpha') != "send" && !GETPOST('cancel', 'alpha')) {
  2385. $mode = GETPOST('mode', 'alpha');
  2386. $ws_url = $object->thirdparty->webservices_url;
  2387. $ws_key = $object->thirdparty->webservices_key;
  2388. $ws_user = GETPOST('ws_user', 'alpha');
  2389. $ws_password = GETPOST('ws_password', 'alpha');
  2390. // NS and Authentication parameters
  2391. $ws_ns = 'http://www.dolibarr.org/ns/';
  2392. $ws_authentication = array(
  2393. 'dolibarrkey'=>$ws_key,
  2394. 'sourceapplication'=>'DolibarrWebServiceClient',
  2395. 'login'=>$ws_user,
  2396. 'password'=>$ws_password,
  2397. 'entity'=>''
  2398. );
  2399. print load_fiche_titre($langs->trans('CreateRemoteOrder'), '');
  2400. //Is everything filled?
  2401. if (empty($ws_url) || empty($ws_key)) {
  2402. setEventMessages($langs->trans("ErrorWebServicesFieldsRequired"), null, 'errors');
  2403. $mode = "init";
  2404. $error_occurred = true; //Don't allow to set the user/pass if thirdparty fields are not filled
  2405. } elseif ($mode != "init" && (empty($ws_user) || empty($ws_password))) {
  2406. setEventMessages($langs->trans("ErrorFieldsRequired"), null, 'errors');
  2407. $mode = "init";
  2408. }
  2409. if ($mode == "init") {
  2410. //Table/form header
  2411. print '<table class="border centpercent">';
  2412. print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
  2413. print '<input type="hidden" name="token" value="'.newToken().'">';
  2414. print '<input type="hidden" name="action" value="webservice">';
  2415. print '<input type="hidden" name="mode" value="check">';
  2416. if ($error_occurred) {
  2417. print "<br>".$langs->trans("ErrorOccurredReviseAndRetry")."<br>";
  2418. print '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
  2419. } else {
  2420. $textinput_size = "50";
  2421. // Webservice url
  2422. print '<tr><td>'.$langs->trans("WebServiceURL").'</td><td colspan="3">'.dol_print_url($ws_url).'</td></tr>';
  2423. //Remote User
  2424. print '<tr><td>'.$langs->trans("User").'</td><td><input size="'.$textinput_size.'" type="text" name="ws_user"></td></tr>';
  2425. //Remote Password
  2426. print '<tr><td>'.$langs->trans("Password").'</td><td><input size="'.$textinput_size.'" type="text" name="ws_password"></td></tr>';
  2427. //Submit button
  2428. print '<tr><td class="center" colspan="2">';
  2429. print '<input type="submit" class="button" id="ws_submit" name="ws_submit" value="'.$langs->trans("CreateRemoteOrder").'">';
  2430. print ' &nbsp; &nbsp; ';
  2431. //Cancel button
  2432. print '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
  2433. print '</td></tr>';
  2434. }
  2435. //End table/form
  2436. print '</form>';
  2437. print '</table>';
  2438. } elseif ($mode == "check") {
  2439. $ws_entity = '';
  2440. $ws_thirdparty = '';
  2441. $error_occurred = false;
  2442. //Create SOAP client and connect it to user
  2443. $soapclient_user = new nusoap_client($ws_url."/webservices/server_user.php");
  2444. $soapclient_user->soap_defencoding = 'UTF-8';
  2445. $soapclient_user->decodeUTF8(false);
  2446. //Get the thirdparty associated to user
  2447. $ws_parameters = array('authentication'=>$ws_authentication, 'id' => '', 'ref'=>$ws_user);
  2448. $result_user = $soapclient_user->call("getUser", $ws_parameters, $ws_ns, '');
  2449. $user_status_code = $result_user["result"]["result_code"];
  2450. if ($user_status_code == "OK") {
  2451. //Fill the variables
  2452. $ws_entity = $result_user["user"]["entity"];
  2453. $ws_authentication['entity'] = $ws_entity;
  2454. $ws_thirdparty = $result_user["user"]["fk_thirdparty"];
  2455. if (empty($ws_thirdparty)) {
  2456. setEventMessages($langs->trans("RemoteUserMissingAssociatedSoc"), null, 'errors');
  2457. $error_occurred = true;
  2458. } else {
  2459. //Create SOAP client and connect it to product/service
  2460. $soapclient_product = new nusoap_client($ws_url."/webservices/server_productorservice.php");
  2461. $soapclient_product->soap_defencoding = 'UTF-8';
  2462. $soapclient_product->decodeUTF8(false);
  2463. // Iterate each line and get the reference that uses the supplier of that product/service
  2464. $i = 0;
  2465. foreach ($object->lines as $line) {
  2466. $i = $i + 1;
  2467. $ref_supplier = $line->ref_supplier;
  2468. $line_id = $i."º) ".$line->product_ref.": ";
  2469. if (empty($ref_supplier)) {
  2470. continue;
  2471. }
  2472. $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $ref_supplier);
  2473. $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, '');
  2474. if (!$result_product) {
  2475. setEventMessages($line_id.$langs->trans("SOAPError")." ".$soapclient_product->error_str." - ".$soapclient_product->response, null, 'errors');
  2476. $error_occurred = true;
  2477. break;
  2478. }
  2479. // Check the result code
  2480. $status_code = $result_product["result"]["result_code"];
  2481. if (empty($status_code)) { //No result, check error str
  2482. setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors');
  2483. } elseif ($status_code != "OK") { //Something went wrong
  2484. if ($status_code == "NOT_FOUND") {
  2485. setEventMessages($line_id.$langs->trans("SupplierMissingRef")." '".$ref_supplier."'", null, 'warnings');
  2486. } else {
  2487. setEventMessages($line_id.$langs->trans("ResponseNonOK")." '".$status_code."' - '".$result_product["result"]["result_label"]."'", null, 'errors');
  2488. $error_occurred = true;
  2489. break;
  2490. }
  2491. }
  2492. // Ensure that price is equal and warn user if it's not
  2493. $supplier_price = price($result_product["product"]["price_net"]); //Price of client tab in supplier dolibarr
  2494. $local_price = null; //Price of supplier as stated in product suppliers tab on this dolibarr, NULL if not found
  2495. $product_fourn = new ProductFournisseur($db);
  2496. $product_fourn_list = $product_fourn->list_product_fournisseur_price($line->fk_product);
  2497. if (count($product_fourn_list) > 0) {
  2498. foreach ($product_fourn_list as $product_fourn_line) {
  2499. //Only accept the line where the supplier is the same at this order and has the same ref
  2500. if ($product_fourn_line->fourn_id == $object->socid && $product_fourn_line->fourn_ref == $ref_supplier) {
  2501. $local_price = price($product_fourn_line->fourn_price);
  2502. }
  2503. }
  2504. }
  2505. if ($local_price != null && $local_price != $supplier_price) {
  2506. setEventMessages($line_id.$langs->trans("RemotePriceMismatch")." ".$supplier_price." - ".$local_price, null, 'warnings');
  2507. }
  2508. // Check if is in sale
  2509. if (empty($result_product["product"]["status_tosell"])) {
  2510. setEventMessages($line_id.$langs->trans("ProductStatusNotOnSellShort")." '".$ref_supplier."'", null, 'warnings');
  2511. }
  2512. }
  2513. }
  2514. } elseif ($user_status_code == "PERMISSION_DENIED") {
  2515. setEventMessages($langs->trans("RemoteUserNotPermission"), null, 'errors');
  2516. $error_occurred = true;
  2517. } elseif ($user_status_code == "BAD_CREDENTIALS") {
  2518. setEventMessages($langs->trans("RemoteUserBadCredentials"), null, 'errors');
  2519. $error_occurred = true;
  2520. } else {
  2521. setEventMessages($langs->trans("ResponseNonOK")." '".$user_status_code."'", null, 'errors');
  2522. $error_occurred = true;
  2523. }
  2524. //Form
  2525. print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
  2526. print '<input type="hidden" name="token" value="'.newToken().'">';
  2527. print '<input type="hidden" name="action" value="webservice">';
  2528. print '<input type="hidden" name="mode" value="send">';
  2529. print '<input type="hidden" name="ws_user" value="'.$ws_user.'">';
  2530. print '<input type="hidden" name="ws_password" value="'.$ws_password.'">';
  2531. print '<input type="hidden" name="ws_entity" value="'.$ws_entity.'">';
  2532. print '<input type="hidden" name="ws_thirdparty" value="'.$ws_thirdparty.'">';
  2533. if ($error_occurred) {
  2534. print "<br>".$langs->trans("ErrorOccurredReviseAndRetry")."<br>";
  2535. } else {
  2536. print '<input type="submit" class="button" id="ws_submit" name="ws_submit" value="'.$langs->trans("Confirm").'">';
  2537. print ' &nbsp; &nbsp; ';
  2538. }
  2539. print '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
  2540. print '</form>';
  2541. }
  2542. }
  2543. // Presend form
  2544. $modelmail = 'order_supplier_send';
  2545. $defaulttopic = 'SendOrderRef';
  2546. $diroutput = $conf->fournisseur->commande->dir_output;
  2547. $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO';
  2548. $trackid = 'sord'.$object->id;
  2549. include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
  2550. }
  2551. }
  2552. // End of page
  2553. llxFooter();
  2554. $db->close();