card.php 121 KB

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