card.php 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617
  1. <?php
  2. /* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  5. * Copyright (C) 2005 Marc Barilley <marc@ocebo.fr>
  6. * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2010-2019 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2013-2015 Philippe Grand <philippe.grand@atoo-net.com>
  9. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  10. * Copyright (C) 2014-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2016-2021 Alexandre Spangaro <aspangaro@open-dsi.fr>
  12. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  13. * Copyright (C) 2019 Ferran Marcet <fmarcet@2byte.es>
  14. *
  15. * This program is free software; you can redistribute it and/or modify
  16. * it under the terms of the GNU General Public License as published by
  17. * the Free Software Foundation; either version 3 of the License, or
  18. * (at your option) any later version.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU General Public License
  26. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  27. */
  28. /**
  29. * \file htdocs/fourn/facture/card.php
  30. * \ingroup facture, fournisseur
  31. * \brief Page for supplier invoice card (view, edit, validate)
  32. */
  33. require '../../main.inc.php';
  34. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  35. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  36. require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
  37. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
  41. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  44. if (!empty($conf->product->enabled)) {
  45. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  46. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  47. }
  48. if (!empty($conf->projet->enabled)) {
  49. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  50. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  51. }
  52. if (!empty($conf->variants->enabled)) {
  53. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  54. }
  55. if (!empty($conf->accounting->enabled)) {
  56. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
  57. }
  58. $langs->loadLangs(array('bills', 'compta', 'suppliers', 'companies', 'products', 'banks', 'admin'));
  59. if (!empty($conf->incoterm->enabled)) {
  60. $langs->load('incoterm');
  61. }
  62. $id = (GETPOST('facid', 'int') ? GETPOST('facid', 'int') : GETPOST('id', 'int'));
  63. $socid = GETPOST('socid', 'int');
  64. $action = GETPOST('action', 'aZ09');
  65. $confirm = GETPOST("confirm");
  66. $ref = GETPOST('ref', 'alpha');
  67. $cancel = GETPOST('cancel', 'alpha');
  68. $lineid = GETPOST('lineid', 'int');
  69. $projectid = GETPOST('projectid', 'int');
  70. $origin = GETPOST('origin', 'alpha');
  71. $originid = GETPOST('originid', 'int');
  72. $fac_rec = GETPOST('fac_rec', 'int');
  73. // PDF
  74. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  75. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  76. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  77. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  78. $hookmanager->initHooks(array('invoicesuppliercard', 'globalcard'));
  79. $object = new FactureFournisseur($db);
  80. $extrafields = new ExtraFields($db);
  81. // fetch optionals attributes and labels
  82. $extrafields->fetch_name_optionals_label($object->table_element);
  83. // Load object
  84. if ($id > 0 || !empty($ref)) {
  85. $ret = $object->fetch($id, $ref);
  86. if ($ret < 0) {
  87. dol_print_error($db, $object->error);
  88. }
  89. $ret = $object->fetch_thirdparty();
  90. if ($ret < 0) {
  91. dol_print_error($db, $object->error);
  92. }
  93. }
  94. // Security check
  95. $socid = '';
  96. if (!empty($user->socid)) {
  97. $socid = $user->socid;
  98. }
  99. $isdraft = (($object->statut == FactureFournisseur::STATUS_DRAFT) ? 1 : 0);
  100. $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture', 'fk_soc', 'rowid', $isdraft);
  101. // Common permissions
  102. $usercanread = ($user->rights->fournisseur->facture->lire || $user->rights->supplier_invoice->lire);
  103. $usercancreate = ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer);
  104. $usercandelete = ($user->rights->fournisseur->facture->supprimer || $user->rights->supplier_invoice->supprimer);
  105. // Advanced permissions
  106. $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate)));
  107. $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->fournisseur->supplier_invoice_advance->send);
  108. // Permissions for includes
  109. $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
  110. $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
  111. $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdown.inc.php
  112. $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
  113. $error = 0;
  114. /*
  115. * Actions
  116. */
  117. $parameters = array('socid'=>$socid);
  118. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  119. if ($reshook < 0) {
  120. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  121. }
  122. if (empty($reshook)) {
  123. $backurlforlist = DOL_URL_ROOT.'/fourn/facture/list.php';
  124. if (empty($backtopage) || ($cancel && empty($id))) {
  125. if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
  126. if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
  127. $backtopage = $backurlforlist;
  128. } else {
  129. $backtopage = DOL_URL_ROOT.'/fourn/facture/card.php?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
  130. }
  131. }
  132. }
  133. if ($cancel) {
  134. if (!empty($backtopageforcancel)) {
  135. header("Location: ".$backtopageforcancel);
  136. exit;
  137. } elseif (!empty($backtopage)) {
  138. header("Location: ".$backtopage);
  139. exit;
  140. }
  141. $action = '';
  142. }
  143. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  144. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  145. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  146. // Link invoice to order
  147. if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) {
  148. $object->fetch($id);
  149. $object->fetch_thirdparty();
  150. $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder'));
  151. }
  152. // Action clone object
  153. if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
  154. $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid.
  155. if (GETPOST('newsupplierref', 'alphanohtml')) {
  156. $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml');
  157. }
  158. $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
  159. $result = $objectutil->createFromClone($user, $id);
  160. if ($result > 0) {
  161. header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
  162. exit;
  163. } else {
  164. $langs->load("errors");
  165. setEventMessages($objectutil->error, $objectutil->errors, 'errors');
  166. $action = '';
  167. }
  168. } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
  169. $idwarehouse = GETPOST('idwarehouse');
  170. $object->fetch($id);
  171. $object->fetch_thirdparty();
  172. $qualified_for_stock_change = 0;
  173. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  174. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  175. } else {
  176. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  177. }
  178. // Check parameters
  179. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  180. $langs->load("stocks");
  181. if (!$idwarehouse || $idwarehouse == -1) {
  182. $error++;
  183. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  184. $action = '';
  185. }
  186. }
  187. if (!$error) {
  188. $result = $object->validate($user, '', $idwarehouse);
  189. if ($result < 0) {
  190. setEventMessages($object->error, $object->errors, 'errors');
  191. } else {
  192. // Define output language
  193. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  194. $outputlangs = $langs;
  195. $newlang = '';
  196. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  197. $newlang = GETPOST('lang_id', 'aZ09');
  198. }
  199. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  200. $newlang = $object->thirdparty->default_lang;
  201. }
  202. if (!empty($newlang)) {
  203. $outputlangs = new Translate("", $conf);
  204. $outputlangs->setDefaultLang($newlang);
  205. }
  206. $model = $object->model_pdf;
  207. $ret = $object->fetch($id); // Reload to get new records
  208. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  209. if ($result < 0) {
  210. dol_print_error($db, $result);
  211. }
  212. }
  213. }
  214. }
  215. } elseif ($action == 'confirm_delete' && $confirm == 'yes') {
  216. $object->fetch($id);
  217. $object->fetch_thirdparty();
  218. $isErasable = $object->is_erasable();
  219. if (($usercandelete && $isErasable > 0) || ($usercancreate && $isErasable == 1)) {
  220. $result = $object->delete($user);
  221. if ($result > 0) {
  222. header('Location: list.php?restore_lastsearch_values=1');
  223. exit;
  224. } else {
  225. setEventMessages($object->error, $object->errors, 'errors');
  226. }
  227. }
  228. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
  229. // Remove a product line
  230. $result = $object->deleteline($lineid);
  231. if ($result > 0) {
  232. // Define output language
  233. /*$outputlangs = $langs;
  234. $newlang = '';
  235. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09'))
  236. $newlang = GETPOST('lang_id','aZ09');
  237. if ($conf->global->MAIN_MULTILANGS && empty($newlang))
  238. $newlang = $object->thirdparty->default_lang;
  239. if (! empty($newlang)) {
  240. $outputlangs = new Translate("", $conf);
  241. $outputlangs->setDefaultLang($newlang);
  242. }
  243. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  244. $ret = $object->fetch($object->id); // Reload to get new records
  245. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  246. }*/
  247. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id);
  248. exit;
  249. } else {
  250. setEventMessages($object->error, $object->errors, 'errors');
  251. /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */
  252. $action = '';
  253. }
  254. } elseif ($action == 'unlinkdiscount' && $usercancreate) {
  255. // Delete link of credit note to invoice
  256. $discount = new DiscountAbsolute($db);
  257. $result = $discount->fetch(GETPOST("discountid"));
  258. $discount->unlink_invoice();
  259. } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercancreate) {
  260. $object->fetch($id);
  261. $result = $object->setPaid($user);
  262. if ($result < 0) {
  263. setEventMessages($object->error, $object->errors, 'errors');
  264. }
  265. } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes') {
  266. // Classif "paid partialy"
  267. $object->fetch($id);
  268. $close_code = GETPOST("close_code", 'restricthtml');
  269. $close_note = GETPOST("close_note", 'restricthtml');
  270. if ($close_code) {
  271. $result = $object->setPaid($user, $close_code, $close_note);
  272. if ($result < 0) {
  273. setEventMessages($object->error, $object->errors, 'errors');
  274. }
  275. } else {
  276. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  277. }
  278. } elseif ($action == 'confirm_canceled' && $confirm == 'yes') {
  279. // Classify "abandoned"
  280. $object->fetch($id);
  281. $close_code = GETPOST("close_code", 'restricthtml');
  282. $close_note = GETPOST("close_note", 'restricthtml');
  283. if ($close_code) {
  284. $result = $object->setCanceled($user, $close_code, $close_note);
  285. if ($result < 0) {
  286. setEventMessages($object->error, $object->errors, 'errors');
  287. }
  288. } else {
  289. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  290. }
  291. }
  292. // Set supplier ref
  293. if ($action == 'setref_supplier' && $usercancreate) {
  294. $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
  295. if ($object->update($user) < 0) {
  296. setEventMessages($object->error, $object->errors, 'errors');
  297. } else {
  298. // Define output language
  299. $outputlangs = $langs;
  300. $newlang = '';
  301. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  302. $newlang = GETPOST('lang_id', 'aZ09');
  303. }
  304. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  305. $newlang = $object->thirdparty->default_lang;
  306. }
  307. if (!empty($newlang)) {
  308. $outputlangs = new Translate("", $conf);
  309. $outputlangs->setDefaultLang($newlang);
  310. }
  311. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  312. $ret = $object->fetch($object->id); // Reload to get new records
  313. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  314. }
  315. }
  316. }
  317. // payments conditions
  318. if ($action == 'setconditions' && $usercancreate) {
  319. $object->fetch($id);
  320. $object->cond_reglement_code = 0; // To clean property
  321. $object->cond_reglement_id = 0; // To clean property
  322. $error = 0;
  323. $db->begin();
  324. if (!$error) {
  325. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  326. if ($result < 0) {
  327. $error++;
  328. setEventMessages($object->error, $object->errors, 'errors');
  329. }
  330. }
  331. if (!$error) {
  332. $old_date_echeance = $object->date_echeance;
  333. $new_date_echeance = $object->calculate_date_lim_reglement();
  334. if ($new_date_echeance > $old_date_echeance) {
  335. $object->date_echeance = $new_date_echeance;
  336. }
  337. if ($object->date_echeance < $object->date) {
  338. $object->date_echeance = $object->date;
  339. }
  340. $result = $object->update($user);
  341. if ($result < 0) {
  342. $error++;
  343. setEventMessages($object->error, $object->errors, 'errors');
  344. }
  345. }
  346. if ($error) {
  347. $db->rollback();
  348. } else {
  349. $db->commit();
  350. }
  351. } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) {
  352. // Set incoterm
  353. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  354. } elseif ($action == 'setmode' && $usercancreate) {
  355. // payment mode
  356. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  357. } elseif ($action == 'setmulticurrencycode' && $usercancreate) {
  358. // Multicurrency Code
  359. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  360. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) {
  361. // Multicurrency rate
  362. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx', 'alpha')), GETPOST('calculation_mode', 'int'));
  363. } elseif ($action == 'setbankaccount' && $usercancreate) {
  364. // bank account
  365. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  366. }
  367. if ($action == 'settransportmode' && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)) {
  368. // transport mode
  369. $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int'));
  370. } elseif ($action == 'setlabel' && $usercancreate) {
  371. // Set label
  372. $object->fetch($id);
  373. $object->label = GETPOST('label');
  374. $result = $object->update($user);
  375. if ($result < 0) {
  376. dol_print_error($db);
  377. }
  378. } elseif ($action == 'setdatef' && $usercancreate) {
  379. $newdate = dol_mktime(0, 0, 0, GETPOST('datefmonth', 'int'), GETPOST('datefday', 'int'), GETPOST('datefyear', 'int'), 'tzserver');
  380. if ($newdate > (dol_now('tzuserrel') + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  381. if (empty($conf->global->INVOICE_MAX_FUTURE_DELAY)) {
  382. setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
  383. } else {
  384. setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
  385. }
  386. }
  387. $object->fetch($id);
  388. $object->date = $newdate;
  389. $date_echence_calc = $object->calculate_date_lim_reglement();
  390. if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) {
  391. $object->date_echeance = $date_echence_calc;
  392. }
  393. if ($object->date_echeance && $object->date_echeance < $object->date) {
  394. $object->date_echeance = $object->date;
  395. }
  396. $result = $object->update($user);
  397. if ($result < 0) {
  398. dol_print_error($db, $object->error);
  399. }
  400. } elseif ($action == 'setdate_lim_reglement' && $usercancreate) {
  401. $object->fetch($id);
  402. $object->date_echeance = dol_mktime(12, 0, 0, GETPOST('date_lim_reglementmonth', 'int'), GETPOST('date_lim_reglementday', 'int'), GETPOST('date_lim_reglementyear', 'int'));
  403. if (!empty($object->date_echeance) && $object->date_echeance < $object->date) {
  404. $object->date_echeance = $object->date;
  405. setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
  406. }
  407. $result = $object->update($user);
  408. if ($result < 0) {
  409. dol_print_error($db, $object->error);
  410. }
  411. } elseif ($action == "setabsolutediscount" && $usercancreate) {
  412. // We use the credit to reduce amount of invoice
  413. if (GETPOST("remise_id", "int")) {
  414. $ret = $object->fetch($id);
  415. if ($ret > 0) {
  416. $result = $object->insert_discount(GETPOST("remise_id", "int"));
  417. if ($result < 0) {
  418. setEventMessages($object->error, $object->errors, 'errors');
  419. }
  420. } else {
  421. dol_print_error($db, $object->error);
  422. }
  423. }
  424. // We use the credit to reduce remain to pay
  425. if (GETPOST("remise_id_for_payment", "int")) {
  426. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  427. $discount = new DiscountAbsolute($db);
  428. $discount->fetch(GETPOST("remise_id_for_payment", "int"));
  429. //var_dump($object->getRemainToPay(0));
  430. //var_dump($discount->amount_ttc);exit;
  431. if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) {
  432. // TODO Split the discount in 2 automatically
  433. $error++;
  434. setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
  435. }
  436. if (!$error) {
  437. $result = $discount->link_to_invoice(0, $id);
  438. if ($result < 0) {
  439. setEventMessages($discount->error, $discount->errors, 'errors');
  440. }
  441. }
  442. }
  443. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  444. $outputlangs = $langs;
  445. $newlang = '';
  446. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  447. $newlang = GETPOST('lang_id', 'aZ09');
  448. }
  449. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  450. $newlang = $object->thirdparty->default_lang;
  451. }
  452. if (!empty($newlang)) {
  453. $outputlangs = new Translate("", $conf);
  454. $outputlangs->setDefaultLang($newlang);
  455. }
  456. $ret = $object->fetch($id); // Reload to get new records
  457. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  458. if ($result < 0) {
  459. setEventMessages($object->error, $object->errors, 'errors');
  460. }
  461. }
  462. } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
  463. // Convertir en reduc
  464. $object->fetch($id);
  465. $object->fetch_thirdparty();
  466. //$object->fetch_lines(); // Already done into fetch
  467. // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
  468. $discountcheck = new DiscountAbsolute($db);
  469. $result = $discountcheck->fetch(0, 0, $object->id);
  470. $canconvert = 0;
  471. if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) {
  472. $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
  473. }
  474. if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) {
  475. $canconvert = 1; // we can convert credit note into discount if credit note is not refunded completely and not already converted and amount of payment is 0 (see also the real condition used as the condition to show button converttoreduc)
  476. }
  477. if ($canconvert) {
  478. $db->begin();
  479. $amount_ht = $amount_tva = $amount_ttc = array();
  480. $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
  481. // Loop on each vat rate
  482. $i = 0;
  483. foreach ($object->lines as $line) {
  484. if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 and no need to create discount if amount is null
  485. $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
  486. $amount_ht[$line->tva_tx] += $line->total_ht;
  487. $amount_tva[$line->tva_tx] += $line->total_tva;
  488. $amount_ttc[$line->tva_tx] += $line->total_ttc;
  489. $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
  490. $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
  491. $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
  492. $i++;
  493. }
  494. }
  495. // If some payments were already done, we change the amount to pay using same prorate
  496. if (!empty($conf->global->SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) && $object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  497. $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
  498. if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
  499. $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
  500. foreach ($amount_ht as $vatrate => $val) {
  501. $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
  502. $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
  503. $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
  504. $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
  505. $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
  506. $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
  507. }
  508. }
  509. }
  510. //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
  511. // Insert one discount by VAT rate category
  512. $discount = new DiscountAbsolute($db);
  513. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  514. $discount->description = '(CREDIT_NOTE)';
  515. } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) {
  516. $discount->description = '(DEPOSIT)';
  517. } elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) {
  518. $discount->description = '(EXCESS PAID)';
  519. } else {
  520. setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
  521. }
  522. $discount->discount_type = 1; // Supplier discount
  523. $discount->fk_soc = $object->socid;
  524. $discount->fk_invoice_supplier_source = $object->id;
  525. $error = 0;
  526. if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) {
  527. // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT
  528. // Total payments
  529. $sql = 'SELECT SUM(pf.amount) as total_paiements';
  530. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'paiementfourn as p';
  531. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id AND c.entity IN ('.getEntity('c_paiement').')';
  532. $sql .= ' WHERE pf.fk_facturefourn = '.((int) $object->id);
  533. $sql .= ' AND pf.fk_paiementfourn = p.rowid';
  534. $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
  535. $resql = $db->query($sql);
  536. if (!$resql) {
  537. dol_print_error($db);
  538. }
  539. $res = $db->fetch_object($resql);
  540. $total_paiements = $res->total_paiements;
  541. // Total credit note and deposit
  542. $total_creditnote_and_deposit = 0;
  543. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  544. $sql .= " re.description, re.fk_invoice_supplier_source";
  545. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  546. $sql .= " WHERE fk_invoice_supplier = ".((int) $object->id);
  547. $resql = $db->query($sql);
  548. if (!empty($resql)) {
  549. while ($obj = $db->fetch_object($resql)) {
  550. $total_creditnote_and_deposit += $obj->amount_ttc;
  551. }
  552. } else {
  553. dol_print_error($db);
  554. }
  555. $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
  556. $discount->amount_tva = 0;
  557. $discount->tva_tx = 0;
  558. $discount->vat_src_code = '';
  559. $result = $discount->create($user);
  560. if ($result < 0) {
  561. $error++;
  562. }
  563. }
  564. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
  565. foreach ($amount_ht as $tva_tx => $xxx) {
  566. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  567. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  568. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  569. $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
  570. $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
  571. $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
  572. // Clean vat code
  573. $reg = array();
  574. $vat_src_code = '';
  575. if (preg_match('/\((.*)\)/', $tva_tx, $reg)) {
  576. $vat_src_code = $reg[1];
  577. $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx); // Remove code into vatrate.
  578. }
  579. $discount->tva_tx = abs($tva_tx);
  580. $discount->vat_src_code = $vat_src_code;
  581. $result = $discount->create($user);
  582. if ($result < 0) {
  583. $error++;
  584. break;
  585. }
  586. }
  587. }
  588. if (empty($error)) {
  589. if ($object->type != FactureFournisseur::TYPE_DEPOSIT) {
  590. // Classe facture
  591. $result = $object->setPaid($user);
  592. if ($result >= 0) {
  593. $db->commit();
  594. } else {
  595. setEventMessages($object->error, $object->errors, 'errors');
  596. $db->rollback();
  597. }
  598. } else {
  599. $db->commit();
  600. }
  601. } else {
  602. setEventMessages($discount->error, $discount->errors, 'errors');
  603. $db->rollback();
  604. }
  605. }
  606. } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) {
  607. // Delete payment
  608. $object->fetch($id);
  609. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) {
  610. $paiementfourn = new PaiementFourn($db);
  611. $result = $paiementfourn->fetch(GETPOST('paiement_id'));
  612. if ($result > 0) {
  613. $result = $paiementfourn->delete(); // If fetch ok and found
  614. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  615. }
  616. if ($result < 0) {
  617. setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors');
  618. }
  619. }
  620. } elseif ($action == 'add' && $usercancreate) {
  621. // Insert new invoice in database
  622. if ($socid > 0) {
  623. $object->socid = GETPOST('socid', 'int');
  624. }
  625. $selectedLines = GETPOST('toselect', 'array');
  626. $db->begin();
  627. $error = 0;
  628. // Fill array 'array_options' with data from add form
  629. $ret = $extrafields->setOptionalsFromPost(null, $object);
  630. if ($ret < 0) {
  631. $error++;
  632. }
  633. $dateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver'); // If we enter the 02 january, we need to save the 02 january for server
  634. $datedue = dol_mktime(0, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int'), 'tzserver');
  635. /*var_dump($dateinvoice.' '.dol_print_date($dateinvoice, 'dayhour'));
  636. var_dump(dol_now('tzuserrel').' '.dol_get_last_hour(dol_now('tzuserrel')).' '.dol_print_date(dol_now('tzuserrel'),'dayhour').' '.dol_print_date(dol_get_last_hour(dol_now('tzuserrel')), 'dayhour'));
  637. var_dump($db->idate($dateinvoice));
  638. exit;*/
  639. // Replacement invoice
  640. if (GETPOST('type') == FactureFournisseur::TYPE_REPLACEMENT) {
  641. if (empty($dateinvoice)) {
  642. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  643. $action = 'create';
  644. $_GET['socid'] = $_POST['socid'];
  645. $error++;
  646. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  647. $error++;
  648. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  649. $action = 'create';
  650. }
  651. if (!(GETPOST('fac_replacement', 'int') > 0)) {
  652. $error++;
  653. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
  654. }
  655. if (!$error) {
  656. // This is a replacement invoice
  657. $result = $object->fetch(GETPOST('fac_replacement', 'int'));
  658. $object->fetch_thirdparty();
  659. $object->ref = GETPOST('ref', 'nohtml');
  660. $object->ref_supplier = GETPOST('ref_supplier', 'alpha');
  661. $object->socid = GETPOST('socid', 'int');
  662. $object->libelle = GETPOST('label', 'nohtml');
  663. $object->date = $dateinvoice;
  664. $object->date_echeance = $datedue;
  665. $object->note_public = GETPOST('note_public', 'restricthtml');
  666. $object->note_private = GETPOST('note_private', 'restricthtml');
  667. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  668. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  669. $object->fk_account = GETPOST('fk_account', 'int');
  670. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  671. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  672. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  673. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  674. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  675. $object->transport_mode_id = GETPOST('transport_mode_id', 'int');
  676. // Proprietes particulieres a facture de remplacement
  677. $object->fk_facture_source = GETPOST('fac_replacement', 'int');
  678. $object->type = FactureFournisseur::TYPE_REPLACEMENT;
  679. $id = $object->createFromCurrent($user);
  680. if ($id <= 0) {
  681. $error++;
  682. setEventMessages($object->error, $object->errors, 'errors');
  683. }
  684. }
  685. }
  686. // Credit note invoice
  687. if (GETPOST('type') == FactureFournisseur::TYPE_CREDIT_NOTE) {
  688. $sourceinvoice = GETPOST('fac_avoir', 'int');
  689. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  690. $error++;
  691. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  692. }
  693. if (GETPOST('socid', 'int') < 1) {
  694. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
  695. $action = 'create';
  696. $error++;
  697. }
  698. if (empty($dateinvoice)) {
  699. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  700. $action = 'create';
  701. $_GET['socid'] = $_POST['socid'];
  702. $error++;
  703. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  704. $error++;
  705. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  706. $action = 'create';
  707. }
  708. if (!GETPOST('ref_supplier')) {
  709. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors');
  710. $action = 'create';
  711. $_GET['socid'] = $_POST['socid'];
  712. $error++;
  713. }
  714. if (!$error) {
  715. $tmpproject = GETPOST('projectid', 'int');
  716. // Creation facture
  717. $object->ref = GETPOST('ref', 'nohtml');
  718. $object->ref_supplier = GETPOST('ref_supplier', 'nohtml');
  719. $object->socid = GETPOST('socid', 'int');
  720. $object->libelle = GETPOST('label', 'nohtml');
  721. $object->label = GETPOST('label', 'nohtml');
  722. $object->date = $dateinvoice;
  723. $object->date_echeance = $datedue;
  724. $object->note_public = GETPOST('note_public', 'restricthtml');
  725. $object->note_private = GETPOST('note_private', 'restricthtml');
  726. $object->cond_reglement_id = GETPOST('cond_reglement_id');
  727. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  728. $object->fk_account = GETPOST('fk_account', 'int');
  729. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  730. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  731. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  732. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  733. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  734. $object->transport_mode_id = GETPOST('transport_mode_id', 'int');
  735. // Proprietes particulieres a facture avoir
  736. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  737. $object->type = FactureFournisseur::TYPE_CREDIT_NOTE;
  738. $id = $object->create($user);
  739. if ($id <= 0) {
  740. $error++;
  741. }
  742. if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
  743. $facture_source = new FactureFournisseur($db); // fetch origin object
  744. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  745. $fk_parent_line = 0;
  746. foreach ($facture_source->lines as $line) {
  747. // Reset fk_parent_line for no child products and special product
  748. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  749. $fk_parent_line = 0;
  750. }
  751. $line->fk_facture_fourn = $object->id;
  752. $line->fk_parent_line = $fk_parent_line;
  753. $line->subprice = -$line->subprice; // invert price for object
  754. $line->pa_ht = -$line->pa_ht;
  755. $line->total_ht = -$line->total_ht;
  756. $line->total_tva = -$line->total_tva;
  757. $line->total_ttc = -$line->total_ttc;
  758. $line->total_localtax1 = -$line->total_localtax1;
  759. $line->total_localtax2 = -$line->total_localtax2;
  760. $result = $line->insert();
  761. $object->lines[] = $line; // insert new line in current object
  762. // Defined the new fk_parent_line
  763. if ($result > 0 && $line->product_type == 9) {
  764. $fk_parent_line = $result;
  765. }
  766. }
  767. $object->update_price(1);
  768. }
  769. }
  770. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  771. $facture_source = new FactureFournisseur($db); // fetch origin object if not previously defined
  772. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  773. $totalpaye = $facture_source->getSommePaiement();
  774. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  775. $totaldeposits = $facture_source->getSumDepositsUsed();
  776. $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits);
  777. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 0, 0, 0, 1, 0, 0, '', '', 'TTC');
  778. }
  779. }
  780. }
  781. }
  782. // Standard invoice or Deposit invoice, not from a Predefined template invoice
  783. if (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT) {
  784. if (GETPOST('socid', 'int') < 1) {
  785. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors');
  786. $action = 'create';
  787. $error++;
  788. }
  789. if (empty($dateinvoice)) {
  790. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors');
  791. $action = 'create';
  792. $_GET['socid'] = $_POST['socid'];
  793. $error++;
  794. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  795. $error++;
  796. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  797. $action = 'create';
  798. }
  799. if (!GETPOST('ref_supplier')) {
  800. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors');
  801. $action = 'create';
  802. $_GET['socid'] = $_POST['socid'];
  803. $error++;
  804. }
  805. if (!$error) {
  806. $tmpproject = GETPOST('projectid', 'int');
  807. // Creation invoice
  808. $object->socid = GETPOST('socid', 'int');
  809. $object->type = GETPOST('type');
  810. $object->ref = GETPOST('ref', 'nohtml');
  811. $object->ref_supplier = GETPOST('ref_supplier', 'nohtml');
  812. $object->socid = GETPOST('socid', 'int');
  813. $object->libelle = GETPOST('label', 'nohtml'); // deprecated
  814. $object->label = GETPOST('label', 'nohtml');
  815. $object->date = $dateinvoice;
  816. $object->date_echeance = $datedue;
  817. $object->note_public = GETPOST('note_public', 'restricthtml');
  818. $object->note_private = GETPOST('note_private', 'restricthtml');
  819. $object->cond_reglement_id = GETPOST('cond_reglement_id');
  820. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  821. $object->fk_account = GETPOST('fk_account', 'int');
  822. $object->fk_project = ($tmpproject > 0) ? $tmpproject : null;
  823. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  824. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  825. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  826. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  827. $object->transport_mode_id = GETPOST('transport_mode_id');
  828. // Auto calculation of date due if not filled by user
  829. if (empty($object->date_echeance)) {
  830. $object->date_echeance = $object->calculate_date_lim_reglement();
  831. }
  832. $object->fetch_thirdparty();
  833. // If creation from another object of another module
  834. if (!$error && GETPOST('origin', 'alpha') && GETPOST('originid')) {
  835. // Parse element/subelement (ex: project_task)
  836. $element = $subelement = GETPOST('origin', 'alpha');
  837. /*if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs))
  838. {
  839. $element = $regs[1];
  840. $subelement = $regs[2];
  841. }*/
  842. // For compatibility
  843. if ($element == 'order') {
  844. $element = $subelement = 'commande';
  845. }
  846. if ($element == 'propal') {
  847. $element = 'comm/propal'; $subelement = 'propal';
  848. }
  849. if ($element == 'contract') {
  850. $element = $subelement = 'contrat';
  851. }
  852. if ($element == 'order_supplier') {
  853. $element = 'fourn'; $subelement = 'fournisseur.commande';
  854. }
  855. if ($element == 'project') {
  856. $element = 'projet';
  857. }
  858. $object->origin = GETPOST('origin', 'alpha');
  859. $object->origin_id = GETPOST('originid', 'int');
  860. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  861. $classname = ucfirst($subelement);
  862. if ($classname == 'Fournisseur.commande') {
  863. $classname = 'CommandeFournisseur';
  864. }
  865. $objectsrc = new $classname($db);
  866. $objectsrc->fetch($originid);
  867. $objectsrc->fetch_thirdparty();
  868. if (!empty($object->origin) && !empty($object->origin_id)) {
  869. $object->linkedObjectsIds[$object->origin] = $object->origin_id;
  870. }
  871. // Add also link with order if object is reception
  872. if ($object->origin == 'reception') {
  873. $objectsrc->fetchObjectLinked();
  874. if (count($objectsrc->linkedObjectsIds['order_supplier']) > 0) {
  875. foreach ($objectsrc->linkedObjectsIds['order_supplier'] as $key => $value) {
  876. $object->linkedObjectsIds['order_supplier'] = $value;
  877. }
  878. }
  879. }
  880. $id = $object->create($user);
  881. // Add lines
  882. if ($id > 0) {
  883. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  884. $classname = ucfirst($subelement);
  885. if ($classname == 'Fournisseur.commande') {
  886. $classname = 'CommandeFournisseur';
  887. }
  888. $srcobject = new $classname($db);
  889. $result = $srcobject->fetch(GETPOST('originid', 'int'));
  890. // If deposit invoice - down payment with 1 line (fixed amount or percent)
  891. $typeamount = GETPOST('typedeposit', 'alpha');
  892. if (GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
  893. $valuedeposit = price2num(GETPOST('valuedeposit', 'alpha'), 'MU');
  894. // Define the array $amountdeposit
  895. $amountdeposit = array();
  896. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
  897. if ($typeamount == 'amount') {
  898. $amount = $valuedeposit;
  899. } else {
  900. $amount = $srcobject->total_ttc * ($valuedeposit / 100);
  901. }
  902. $TTotalByTva = array();
  903. foreach ($srcobject->lines as &$line) {
  904. if (!empty($line->special_code)) {
  905. continue;
  906. }
  907. $TTotalByTva[$line->tva_tx] += $line->total_ttc;
  908. }
  909. foreach ($TTotalByTva as $tva => &$total) {
  910. $coef = $total / $srcobject->total_ttc; // Calc coef
  911. $am = $amount * $coef;
  912. $amount_ttc_diff += $am;
  913. $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
  914. }
  915. } else {
  916. if ($typeamount == 'amount') {
  917. $amountdeposit[0] = $valuedeposit;
  918. } elseif ($typeamount == 'variable') {
  919. if ($result > 0) {
  920. $totalamount = 0;
  921. $lines = $srcobject->lines;
  922. $numlines = count($lines);
  923. for ($i = 0; $i < $numlines; $i++) {
  924. $qualified = 1;
  925. if (empty($lines[$i]->qty)) {
  926. $qualified = 0; // We discard qty=0, it is an option
  927. }
  928. if (!empty($lines[$i]->special_code)) {
  929. $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
  930. }
  931. if ($qualified) {
  932. $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
  933. $tva_tx = $lines[$i]->tva_tx;
  934. $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100;
  935. }
  936. }
  937. if ($totalamount == 0) {
  938. $amountdeposit[0] = 0;
  939. }
  940. } else {
  941. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  942. $error++;
  943. }
  944. }
  945. $amount_ttc_diff = $amountdeposit[0];
  946. }
  947. foreach ($amountdeposit as $tva => $amount) {
  948. if (empty($amount)) {
  949. continue;
  950. }
  951. $arraylist = array(
  952. 'amount' => 'FixAmount',
  953. 'variable' => 'VarAmount'
  954. );
  955. $descline = '(DEPOSIT)';
  956. //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
  957. if ($typeamount == 'amount') {
  958. $descline .= ' ('.price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')';
  959. } elseif ($typeamount == 'variable') {
  960. $descline .= ' ('.$valuedeposit.'%)';
  961. }
  962. $descline .= ' - '.$srcobject->ref;
  963. $result = $object->addline(
  964. $descline,
  965. $amount, // subprice
  966. $tva, // vat rate
  967. 0, // localtax1_tx
  968. 0, // localtax2_tx
  969. 1, // quantity
  970. (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
  971. 0, // remise_percent
  972. 0, // date_start
  973. 0, // date_end
  974. 0,
  975. $lines[$i]->info_bits, // info_bits
  976. 'HT',
  977. 0, // product_type
  978. 1,
  979. 0,
  980. 0,
  981. null,
  982. $object->origin,
  983. 0,
  984. '',
  985. $lines[$i]->special_code,
  986. 0,
  987. 0
  988. //,$langs->trans('Deposit') //Deprecated
  989. );
  990. }
  991. $diff = $object->total_ttc - $amount_ttc_diff;
  992. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
  993. $object->fetch_lines();
  994. $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
  995. $object->updateline($object->lines[0]->id, $object->lines[0]->desc, $subprice_diff, $object->lines[0]->qty, $object->lines[0]->remise_percent, $object->lines[0]->date_start, $object->lines[0]->date_end, $object->lines[0]->tva_tx, 0, 0, 'HT', $object->lines[0]->info_bits, $object->lines[0]->product_type, 0, 0, 0, $object->lines[0]->pa_ht, $object->lines[0]->label, 0, array(), 100);
  996. }
  997. } elseif ($result > 0) {
  998. $lines = $srcobject->lines;
  999. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1000. $srcobject->fetch_lines();
  1001. $lines = $srcobject->lines;
  1002. }
  1003. $num = count($lines);
  1004. for ($i = 0; $i < $num; $i++) { // TODO handle subprice < 0
  1005. if (!in_array($lines[$i]->id, $selectedLines)) {
  1006. continue; // Skip unselected lines
  1007. }
  1008. $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle);
  1009. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  1010. // Extrafields
  1011. if (method_exists($lines[$i], 'fetch_optionals')) {
  1012. $lines[$i]->fetch_optionals();
  1013. }
  1014. // Dates
  1015. // TODO mutualiser
  1016. $date_start = $lines[$i]->date_debut_prevue;
  1017. if ($lines[$i]->date_debut_reel) {
  1018. $date_start = $lines[$i]->date_debut_reel;
  1019. }
  1020. if ($lines[$i]->date_start) {
  1021. $date_start = $lines[$i]->date_start;
  1022. }
  1023. $date_end = $lines[$i]->date_fin_prevue;
  1024. if ($lines[$i]->date_fin_reel) {
  1025. $date_end = $lines[$i]->date_fin_reel;
  1026. }
  1027. if ($lines[$i]->date_end) {
  1028. $date_end = $lines[$i]->date_end;
  1029. }
  1030. // FIXME Missing special_code into addline and updateline methods
  1031. $object->special_code = $lines[$i]->special_code;
  1032. // FIXME If currency different from main currency, take multicurrency price
  1033. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  1034. $pu = 0;
  1035. $pu_currency = $lines[$i]->multicurrency_subprice;
  1036. } else {
  1037. $pu = $lines[$i]->subprice;
  1038. $pu_currency = 0;
  1039. }
  1040. // FIXME Missing $lines[$i]->ref_supplier and $lines[$i]->label into addline and updateline methods. They are filled when coming from order for example.
  1041. $result = $object->addline(
  1042. $desc,
  1043. $pu,
  1044. $lines[$i]->tva_tx,
  1045. $lines[$i]->localtax1_tx,
  1046. $lines[$i]->localtax2_tx,
  1047. $lines[$i]->qty,
  1048. $lines[$i]->fk_product,
  1049. $lines[$i]->remise_percent,
  1050. $date_start,
  1051. $date_end,
  1052. 0,
  1053. $lines[$i]->info_bits,
  1054. 'HT',
  1055. $product_type,
  1056. $lines[$i]->rang,
  1057. 0,
  1058. $lines[$i]->array_options,
  1059. $lines[$i]->fk_unit,
  1060. $lines[$i]->id,
  1061. $pu_currency,
  1062. $lines[$i]->ref_supplier,
  1063. $lines[$i]->special_code
  1064. );
  1065. if ($result < 0) {
  1066. $error++;
  1067. break;
  1068. }
  1069. }
  1070. // Now reload line
  1071. $object->fetch_lines();
  1072. } else {
  1073. $error++;
  1074. }
  1075. } else {
  1076. $error++;
  1077. }
  1078. } elseif (!$error) {
  1079. $id = $object->create($user);
  1080. if ($id < 0) {
  1081. $error++;
  1082. }
  1083. }
  1084. }
  1085. }
  1086. if ($error) {
  1087. $langs->load("errors");
  1088. $db->rollback();
  1089. setEventMessages($object->error, $object->errors, 'errors');
  1090. $action = 'create';
  1091. $_GET['socid'] = $_POST['socid'];
  1092. } else {
  1093. $db->commit();
  1094. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1095. $outputlangs = $langs;
  1096. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1097. if ($result < 0) {
  1098. dol_print_error($db, $object->error, $object->errors);
  1099. exit;
  1100. }
  1101. }
  1102. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  1103. exit;
  1104. }
  1105. } elseif ($action == 'updateline' && $usercancreate) {
  1106. // Edit line
  1107. $db->begin();
  1108. if (! $object->fetch($id) > 0) dol_print_error($db);
  1109. $object->fetch_thirdparty();
  1110. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  1111. if (GETPOST('price_ht') != '' || GETPOST('multicurrency_subprice') != '') {
  1112. $up = price2num(GETPOST('price_ht'), '', 2);
  1113. $price_base_type = 'HT';
  1114. } else {
  1115. $up = price2num(GETPOST('price_ttc'), '', 2);
  1116. $price_base_type = 'TTC';
  1117. }
  1118. if (GETPOST('productid') > 0) {
  1119. $productsupplier = new ProductFournisseur($db);
  1120. if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) {
  1121. if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty')), GETPOST('productid', 'int'), 'restricthtml', GETPOST('socid', 'int')) < 0) {
  1122. setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings');
  1123. }
  1124. }
  1125. $prod = new Product($db);
  1126. $prod->fetch(GETPOST('productid'));
  1127. $label = $prod->description;
  1128. if (trim(GETPOST('product_desc', 'restricthtml')) != trim($label)) {
  1129. $label = GETPOST('product_desc', 'restricthtml');
  1130. }
  1131. $type = $prod->type;
  1132. } else {
  1133. $label = GETPOST('product_desc', 'restricthtml');
  1134. $type = GETPOST("type") ? GETPOST("type") : 0;
  1135. }
  1136. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  1137. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  1138. // Define info_bits
  1139. $info_bits = 0;
  1140. if (preg_match('/\*/', $tva_tx)) {
  1141. $info_bits |= 0x01;
  1142. }
  1143. // Define vat_rate
  1144. $tva_tx = str_replace('*', '', $tva_tx);
  1145. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
  1146. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
  1147. $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1148. $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), 'MU', 2);
  1149. // Extrafields Lines
  1150. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  1151. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  1152. // Unset extrafield POST Data
  1153. if (is_array($extralabelsline)) {
  1154. foreach ($extralabelsline as $key => $value) {
  1155. unset($_POST["options_".$key]);
  1156. }
  1157. }
  1158. $result = $object->updateline(GETPOST('lineid', 'int'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, price2num(GETPOST('qty'), 'MS'), GETPOST('productid', 'int'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, GETPOST('units'), $pu_ht_devise, GETPOST('fourn_ref', 'alpha'));
  1159. if ($result >= 0) {
  1160. unset($_POST['label']);
  1161. unset($_POST['fourn_ref']);
  1162. unset($_POST['date_starthour']);
  1163. unset($_POST['date_startmin']);
  1164. unset($_POST['date_startsec']);
  1165. unset($_POST['date_startday']);
  1166. unset($_POST['date_startmonth']);
  1167. unset($_POST['date_startyear']);
  1168. unset($_POST['date_endhour']);
  1169. unset($_POST['date_endmin']);
  1170. unset($_POST['date_endsec']);
  1171. unset($_POST['date_endday']);
  1172. unset($_POST['date_endmonth']);
  1173. unset($_POST['date_endyear']);
  1174. $db->commit();
  1175. } else {
  1176. $db->rollback();
  1177. setEventMessages($object->error, $object->errors, 'errors');
  1178. }
  1179. } elseif ($action == 'addline' && $usercancreate) {
  1180. $db->begin();
  1181. $ret = $object->fetch($id);
  1182. if ($ret < 0) {
  1183. dol_print_error($db, $object->error);
  1184. exit;
  1185. }
  1186. $ret = $object->fetch_thirdparty();
  1187. $langs->load('errors');
  1188. $error = 0;
  1189. // Set if we used free entry or predefined product
  1190. $predef = '';
  1191. $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  1192. $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'));
  1193. $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'));
  1194. $prod_entry_mode = GETPOST('prod_entry_mode');
  1195. if ($prod_entry_mode == 'free') {
  1196. $idprod = 0;
  1197. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  1198. $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  1199. } else {
  1200. $idprod = GETPOST('idprod', 'int');
  1201. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  1202. $tva_tx = '';
  1203. }
  1204. $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS');
  1205. $remise_percent = price2num(GETPOST('remise_percent'.$predef), 2);
  1206. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'MU', 2);
  1207. // Extrafields
  1208. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  1209. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  1210. // Unset extrafield
  1211. if (is_array($extralabelsline)) {
  1212. // Get extra fields
  1213. foreach ($extralabelsline as $key => $value) {
  1214. unset($_POST["options_".$key]);
  1215. }
  1216. }
  1217. if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) {
  1218. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1219. $error++;
  1220. }
  1221. if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) {
  1222. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  1223. $error++;
  1224. }
  1225. if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not ''
  1226. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors');
  1227. $error++;
  1228. }
  1229. if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) {
  1230. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  1231. $error++;
  1232. }
  1233. if (!GETPOST('qty')) {
  1234. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1235. $error++;
  1236. }
  1237. if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') {
  1238. if ($combinations = GETPOST('combinations', 'array')) {
  1239. //Check if there is a product with the given combination
  1240. $prodcomb = new ProductCombination($db);
  1241. if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
  1242. $idprod = $res->fk_product_child;
  1243. } else {
  1244. setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
  1245. $error++;
  1246. }
  1247. }
  1248. }
  1249. if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
  1250. $productsupplier = new ProductFournisseur($db);
  1251. $idprod = 0;
  1252. if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') {
  1253. $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, ...)
  1254. }
  1255. $reg = array();
  1256. if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) {
  1257. $idprod = $reg[1];
  1258. $res = $productsupplier->fetch($idprod); // Load product from its id
  1259. // Call to init some price properties of $productsupplier
  1260. // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price
  1261. if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) {
  1262. $fksoctosearch = 0;
  1263. $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
  1264. if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price
  1265. $productsupplier->ref_supplier = '';
  1266. }
  1267. } else {
  1268. $fksoctosearch = $object->thirdparty->id;
  1269. $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist
  1270. }
  1271. } elseif (GETPOST('idprodfournprice', 'alpha') > 0) {
  1272. $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat.
  1273. //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist
  1274. $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch);
  1275. $res = $productsupplier->fetch($idprod);
  1276. }
  1277. if ($idprod > 0) {
  1278. $label = $productsupplier->label;
  1279. // if we use supplier description of the products
  1280. if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) {
  1281. $desc = $productsupplier->desc_supplier;
  1282. } else {
  1283. $desc = $productsupplier->description;
  1284. }
  1285. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  1286. if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  1287. $product_desc='';
  1288. }
  1289. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  1290. $desc = $product_desc;
  1291. }
  1292. if (!empty($product_desc) && trim($product_desc) != trim($desc)) {
  1293. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  1294. }
  1295. $type = $productsupplier->type;
  1296. if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') {
  1297. $price_base_type = 'HT';
  1298. $pu = price2num($price_ht, 'MU');
  1299. $pu_ht_devise = price2num($price_ht_devise, 'CU');
  1300. } else {
  1301. $price_base_type = ($productsupplier->fourn_price_base_type ? $productsupplier->fourn_price_base_type : 'HT');
  1302. 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
  1303. $pu = $productsupplier->fourn_pu;
  1304. $pu_ht_devise = 0;
  1305. } else {
  1306. $pu = $productsupplier->fourn_pu;
  1307. $pu_ht_devise = $productsupplier->fourn_multicurrency_unitprice;
  1308. }
  1309. }
  1310. $ref_supplier = $productsupplier->ref_supplier;
  1311. $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
  1312. $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha'));
  1313. if (empty($tva_tx)) {
  1314. $tva_npr = 0;
  1315. }
  1316. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr);
  1317. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr);
  1318. if (empty($pu)) {
  1319. $pu = 0; // If pu is '' or null, we force to have a numeric value
  1320. }
  1321. $result = $object->addline(
  1322. $desc,
  1323. $pu,
  1324. $tva_tx,
  1325. $localtax1_tx,
  1326. $localtax2_tx,
  1327. $qty,
  1328. $idprod,
  1329. $remise_percent,
  1330. $date_start,
  1331. $date_end,
  1332. 0,
  1333. $tva_npr,
  1334. $price_base_type,
  1335. $type,
  1336. -1,
  1337. 0,
  1338. $array_options,
  1339. $productsupplier->fk_unit,
  1340. 0,
  1341. $pu_ht_devise,
  1342. $ref_supplier,
  1343. ''
  1344. );
  1345. }
  1346. if ($idprod == -99 || $idprod == 0) {
  1347. // Product not selected
  1348. $error++;
  1349. $langs->load("errors");
  1350. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors');
  1351. }
  1352. if ($idprod == -1) {
  1353. // Quantity too low
  1354. $error++;
  1355. $langs->load("errors");
  1356. setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors');
  1357. }
  1358. } elseif (empty($error)) { // $price_ht is already set
  1359. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  1360. $tva_tx = str_replace('*', '', $tva_tx);
  1361. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1362. $desc = $product_desc;
  1363. $type = GETPOST('type');
  1364. $ref_supplier = GETPOST('fourn_ref', 'alpha');
  1365. $fk_unit = GETPOST('units', 'alpha');
  1366. if (!preg_match('/\((.*)\)/', $tva_tx)) {
  1367. $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'
  1368. }
  1369. // Local Taxes
  1370. $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty);
  1371. $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty);
  1372. if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') {
  1373. $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings
  1374. } else {
  1375. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  1376. $pu_ht = price2num($pu_ttc / (1 + ($tva_tx / 100)), 'MU'); // $pu_ht must be rounded according to settings
  1377. }
  1378. $price_base_type = 'HT';
  1379. $pu_ht_devise = price2num($price_ht_devise, 'CU');
  1380. $result = $object->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, 0, $remise_percent, $date_start, $date_end, 0, $tva_npr, $price_base_type, $type, -1, 0, $array_options, $fk_unit, 0, $pu_ht_devise, $ref_supplier);
  1381. }
  1382. //print "xx".$tva_tx; exit;
  1383. if (!$error && $result > 0) {
  1384. $db->commit();
  1385. // Define output language
  1386. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1387. $outputlangs = $langs;
  1388. $newlang = '';
  1389. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1390. $newlang = GETPOST('lang_id', 'aZ09');
  1391. }
  1392. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1393. $newlang = $object->thirdparty->default_lang;
  1394. }
  1395. if (!empty($newlang)) {
  1396. $outputlangs = new Translate("", $conf);
  1397. $outputlangs->setDefaultLang($newlang);
  1398. }
  1399. $model = $object->model_pdf;
  1400. $ret = $object->fetch($id); // Reload to get new records
  1401. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1402. if ($result < 0) {
  1403. dol_print_error($db, $result);
  1404. }
  1405. }
  1406. unset($_POST ['prod_entry_mode']);
  1407. unset($_POST['qty']);
  1408. unset($_POST['type']);
  1409. unset($_POST['remise_percent']);
  1410. unset($_POST['pu']);
  1411. unset($_POST['price_ht']);
  1412. unset($_POST['multicurrency_price_ht']);
  1413. unset($_POST['price_ttc']);
  1414. unset($_POST['fourn_ref']);
  1415. unset($_POST['tva_tx']);
  1416. unset($_POST['label']);
  1417. unset($localtax1_tx);
  1418. unset($localtax2_tx);
  1419. unset($_POST['np_marginRate']);
  1420. unset($_POST['np_markRate']);
  1421. unset($_POST['dp_desc']);
  1422. unset($_POST['idprodfournprice']);
  1423. unset($_POST['units']);
  1424. unset($_POST['date_starthour']);
  1425. unset($_POST['date_startmin']);
  1426. unset($_POST['date_startsec']);
  1427. unset($_POST['date_startday']);
  1428. unset($_POST['date_startmonth']);
  1429. unset($_POST['date_startyear']);
  1430. unset($_POST['date_endhour']);
  1431. unset($_POST['date_endmin']);
  1432. unset($_POST['date_endsec']);
  1433. unset($_POST['date_endday']);
  1434. unset($_POST['date_endmonth']);
  1435. unset($_POST['date_endyear']);
  1436. } else {
  1437. $db->rollback();
  1438. setEventMessages($object->error, $object->errors, 'errors');
  1439. }
  1440. $action = '';
  1441. } elseif ($action == 'classin' && $usercancreate) {
  1442. $object->fetch($id);
  1443. $result = $object->setProject($projectid);
  1444. } elseif ($action == 'confirm_edit' && $confirm == 'yes' && $usercancreate) {
  1445. // Set invoice to draft status
  1446. $object->fetch($id);
  1447. $totalpaye = $object->getSommePaiement();
  1448. $resteapayer = $object->total_ttc - $totalpaye;
  1449. // We check that lines of invoices are exported in accountancy
  1450. $ventilExportCompta = $object->getVentilExportCompta();
  1451. if (!$ventilExportCompta) {
  1452. // On verifie si aucun paiement n'a ete effectue
  1453. if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) {
  1454. $idwarehouse = GETPOST('idwarehouse');
  1455. $object->fetch_thirdparty();
  1456. $qualified_for_stock_change = 0;
  1457. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  1458. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  1459. } else {
  1460. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  1461. }
  1462. // Check parameters
  1463. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  1464. $langs->load("stocks");
  1465. if (!$idwarehouse || $idwarehouse == -1) {
  1466. $error++;
  1467. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  1468. $action = '';
  1469. }
  1470. }
  1471. $object->setDraft($user, $idwarehouse);
  1472. // Define output language
  1473. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1474. $outputlangs = $langs;
  1475. $newlang = '';
  1476. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1477. $newlang = GETPOST('lang_id', 'aZ09');
  1478. }
  1479. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1480. $newlang = $object->thirdparty->default_lang;
  1481. }
  1482. if (!empty($newlang)) {
  1483. $outputlangs = new Translate("", $conf);
  1484. $outputlangs->setDefaultLang($newlang);
  1485. }
  1486. $model = $object->model_pdf;
  1487. $ret = $object->fetch($id); // Reload to get new records
  1488. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1489. if ($result < 0) {
  1490. dol_print_error($db, $result);
  1491. }
  1492. }
  1493. $action = '';
  1494. }
  1495. }
  1496. } elseif ($action == 'reopen' && $usercancreate) {
  1497. // Set invoice to validated/unpaid status
  1498. $result = $object->fetch($id);
  1499. if ($object->statut == FactureFournisseur::STATUS_CLOSED
  1500. || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) {
  1501. $result = $object->setUnpaid($user);
  1502. if ($result > 0) {
  1503. header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
  1504. exit;
  1505. } else {
  1506. setEventMessages($object->error, $object->errors, 'errors');
  1507. }
  1508. }
  1509. }
  1510. // Actions when printing a doc from card
  1511. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  1512. // Actions to send emails
  1513. $triggersendname = 'BILL_SUPPLIER_SENTBYMAIL';
  1514. $paramname = 'id';
  1515. $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
  1516. $trackid = 'sinv'.$object->id;
  1517. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  1518. // Actions to build doc
  1519. $upload_dir = $conf->fournisseur->facture->dir_output;
  1520. $permissiontoadd = $usercancreate;
  1521. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  1522. // Make calculation according to calculationrule
  1523. if ($action == 'calculate') {
  1524. $calculationrule = GETPOST('calculationrule');
  1525. $object->fetch($id);
  1526. $object->fetch_thirdparty();
  1527. $result = $object->update_price(0, (($calculationrule == 'totalofround') ? '0' : '1'), 0, $object->thirdparty);
  1528. if ($result <= 0) {
  1529. dol_print_error($db, $result);
  1530. exit;
  1531. }
  1532. }
  1533. if ($action == 'update_extras') {
  1534. $object->oldcopy = dol_clone($object);
  1535. // Fill array 'array_options' with data from add form
  1536. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  1537. if ($ret < 0) {
  1538. $error++;
  1539. }
  1540. if (!$error) {
  1541. // Actions on extra fields
  1542. if (!$error) {
  1543. $result = $object->insertExtraFields('BILL_SUPPLIER_MODIFY');
  1544. if ($result < 0) {
  1545. $error++;
  1546. }
  1547. }
  1548. }
  1549. if ($error) {
  1550. $action = 'edit_extras';
  1551. }
  1552. }
  1553. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
  1554. if ($action == 'addcontact') {
  1555. $result = $object->fetch($id);
  1556. if ($result > 0 && $id > 0) {
  1557. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  1558. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  1559. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  1560. }
  1561. if ($result >= 0) {
  1562. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1563. exit;
  1564. } else {
  1565. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1566. $langs->load("errors");
  1567. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  1568. } else {
  1569. setEventMessages($object->error, $object->errors, 'errors');
  1570. }
  1571. }
  1572. } elseif ($action == 'swapstatut') {
  1573. // bascule du statut d'un contact
  1574. if ($object->fetch($id)) {
  1575. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  1576. } else {
  1577. dol_print_error($db);
  1578. }
  1579. } elseif ($action == 'deletecontact') {
  1580. // Efface un contact
  1581. $object->fetch($id);
  1582. $result = $object->delete_contact(GETPOST("lineid", 'int'));
  1583. if ($result >= 0) {
  1584. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  1585. exit;
  1586. } else {
  1587. dol_print_error($db);
  1588. }
  1589. }
  1590. }
  1591. }
  1592. /*
  1593. * View
  1594. */
  1595. $form = new Form($db);
  1596. $formfile = new FormFile($db);
  1597. $bankaccountstatic = new Account($db);
  1598. $paymentstatic = new PaiementFourn($db);
  1599. if (!empty($conf->projet->enabled)) {
  1600. $formproject = new FormProjets($db);
  1601. }
  1602. $now = dol_now();
  1603. $title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Card');
  1604. $help_url = 'EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores|DE:Modul_Lieferantenrechnungen';
  1605. llxHeader('', $title, $help_url);
  1606. // Mode creation
  1607. if ($action == 'create') {
  1608. $facturestatic = new FactureFournisseur($db);
  1609. print load_fiche_titre($langs->trans('NewBill'), '', 'supplier_invoice');
  1610. dol_htmloutput_events();
  1611. $currency_code = $conf->currency;
  1612. $societe = '';
  1613. if (GETPOST('socid') > 0) {
  1614. $societe = new Societe($db);
  1615. $societe->fetch(GETPOST('socid', 'int'));
  1616. if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) {
  1617. $currency_code = $societe->multicurrency_code;
  1618. }
  1619. }
  1620. if (!empty($origin) && !empty($originid)) {
  1621. // Parse element/subelement (ex: project_task)
  1622. $element = $subelement = $origin;
  1623. if ($element == 'project') {
  1624. $projectid = $originid;
  1625. $element = 'projet';
  1626. }
  1627. // For compatibility
  1628. if ($element == 'order') {
  1629. $element = $subelement = 'commande';
  1630. }
  1631. if ($element == 'propal') {
  1632. $element = 'comm/propal'; $subelement = 'propal';
  1633. }
  1634. if ($element == 'contract') {
  1635. $element = $subelement = 'contrat';
  1636. }
  1637. if ($element == 'order_supplier') {
  1638. $element = 'fourn'; $subelement = 'fournisseur.commande';
  1639. }
  1640. require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
  1641. $classname = ucfirst($subelement);
  1642. if ($classname == 'Fournisseur.commande') {
  1643. $classname = 'CommandeFournisseur';
  1644. }
  1645. $objectsrc = new $classname($db);
  1646. $objectsrc->fetch($originid);
  1647. $objectsrc->fetch_thirdparty();
  1648. $projectid = (!empty($objectsrc->fk_project) ? $objectsrc->fk_project : '');
  1649. //$ref_client = (!empty($objectsrc->ref_client)?$object->ref_client:'');
  1650. $soc = $objectsrc->thirdparty;
  1651. $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_supplier_id) ? $soc->cond_reglement_supplier_id : 0)); // TODO maybe add default value option
  1652. $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_supplier_id) ? $soc->mode_reglement_supplier_id : 0));
  1653. $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  1654. $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_supplier_percent) ? $soc->remise_supplier_percent : 0));
  1655. $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  1656. $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '';
  1657. $transport_mode_id = (!empty($objectsrc->transport_mode_id) ? $objectsrc->transport_mode_id : (!empty($soc->transport_mode_id) ? $soc->transport_mode_id : 0));
  1658. if (!empty($conf->multicurrency->enabled)) {
  1659. if (!empty($objectsrc->multicurrency_code)) {
  1660. $currency_code = $objectsrc->multicurrency_code;
  1661. }
  1662. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
  1663. $currency_tx = $objectsrc->multicurrency_tx;
  1664. }
  1665. }
  1666. $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  1667. $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp);
  1668. $datetmp = dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']);
  1669. $datedue = ($datetmp == '' ?-1 : $datetmp);
  1670. // Replicate extrafields
  1671. $objectsrc->fetch_optionals();
  1672. $object->array_options = $objectsrc->array_options;
  1673. } else {
  1674. $cond_reglement_id = $societe->cond_reglement_supplier_id;
  1675. $mode_reglement_id = $societe->mode_reglement_supplier_id;
  1676. $transport_mode_id = $societe->transport_mode_supplier_id;
  1677. $fk_account = $societe->fk_account;
  1678. $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
  1679. $dateinvoice = ($datetmp == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $datetmp);
  1680. $datetmp = dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']);
  1681. $datedue = ($datetmp == '' ?-1 : $datetmp);
  1682. if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) {
  1683. $currency_code = $soc->multicurrency_code;
  1684. }
  1685. }
  1686. // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
  1687. if (empty($cond_reglement_id)) {
  1688. $cond_reglement_id = GETPOST("cond_reglement_id");
  1689. }
  1690. // when payment mode is empty (means not override by payment condition form a other object, like third-party), try to use default value
  1691. if (empty($mode_reglement_id)) {
  1692. $mode_reglement_id = GETPOST("mode_reglement_id");
  1693. }
  1694. $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTUREFOURN_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null));
  1695. $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTUREFOURN_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null));
  1696. print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
  1697. print '<input type="hidden" name="token" value="'.newToken().'">';
  1698. print '<input type="hidden" name="action" value="add">';
  1699. if ($societe->id > 0) {
  1700. print '<input type="hidden" name="socid" value="'.$societe->id.'">'."\n";
  1701. }
  1702. print '<input type="hidden" name="origin" value="'.$origin.'">';
  1703. print '<input type="hidden" name="originid" value="'.$originid.'">';
  1704. if (!empty($currency_tx)) {
  1705. print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
  1706. }
  1707. print dol_get_fiche_head();
  1708. print '<table class="border centpercent">';
  1709. // Ref
  1710. print '<tr><td class="titlefieldcreate">'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
  1711. // Third party
  1712. print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
  1713. print '<td>';
  1714. if ($societe->id > 0) {
  1715. $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1);
  1716. print $societe->getNomUrl(1, 'supplier');
  1717. print '<input type="hidden" name="socid" value="'.$societe->id.'">';
  1718. } else {
  1719. print img_picto('', 'company').$form->select_company($societe->id, 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300 widthcentpercentminusxx');
  1720. // reload page to retrieve supplier informations
  1721. if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) {
  1722. print '<script type="text/javascript">
  1723. $(document).ready(function() {
  1724. $("#socid").change(function() {
  1725. var socid = $(this).val();
  1726. // reload page
  1727. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid;
  1728. });
  1729. });
  1730. </script>';
  1731. }
  1732. 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>';
  1733. }
  1734. print '</td></tr>';
  1735. // Ref supplier
  1736. print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="ref_supplier" value="'.(isset($_POST['ref_supplier']) ? $_POST['ref_supplier'] : $objectsrc->ref_supplier).'" type="text"';
  1737. if ($societe->id > 0) {
  1738. print ' autofocus';
  1739. }
  1740. print '></td>';
  1741. print '</tr>';
  1742. print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Type').'</td><td>';
  1743. print '<div class="tagtable">'."\n";
  1744. // Standard invoice
  1745. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1746. $tmp = '<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOST('type') == 0 ? ' checked' : '').'> ';
  1747. $desc = $form->textwithpicto($tmp.$langs->trans("InvoiceStandardAsk"), $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
  1748. print $desc;
  1749. print '</div></div>';
  1750. if (empty($origin) || ($origin == 'order_supplier' && !empty($originid))) {
  1751. // Deposit - Down payment
  1752. if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) {
  1753. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1754. $tmp='<input type="radio" id="radio_deposit" name="type" value="3"' . (GETPOST('type') == 3 ? ' checked' : '') . '> ';
  1755. print '<script type="text/javascript">
  1756. jQuery(document).ready(function() {
  1757. jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
  1758. jQuery("#radio_standard").prop("checked", true);
  1759. });
  1760. jQuery("#typedeposit, #valuedeposit").click(function() {
  1761. jQuery("#radio_deposit").prop("checked", true);
  1762. });
  1763. jQuery("#typedeposit").change(function() {
  1764. console.log("We change type of down payment");
  1765. jQuery("#radio_deposit").prop("checked", true);
  1766. setRadioForTypeOfInvoice();
  1767. });
  1768. jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_template").change(function() {
  1769. setRadioForTypeOfInvoice();
  1770. });
  1771. function setRadioForTypeOfInvoice() {
  1772. console.log("Change radio");
  1773. if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
  1774. jQuery(".checkforselect").prop("disabled", true);
  1775. jQuery(".checkforselect").prop("checked", false);
  1776. } else {
  1777. jQuery(".checkforselect").prop("disabled", false);
  1778. jQuery(".checkforselect").prop("checked", true);
  1779. }
  1780. };
  1781. });
  1782. </script>';
  1783. $tmp = $tmp.'<label for="radio_deposit" >'.$langs->trans("InvoiceDeposit").'</label>';
  1784. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
  1785. print '<table class="nobordernopadding"><tr>';
  1786. print '<td>';
  1787. print $desc;
  1788. print '</td>';
  1789. if ($origin == 'order_supplier') {
  1790. print '<td class="nowrap" style="padding-left: 15px">';
  1791. $arraylist = array(
  1792. 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  1793. 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  1794. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  1795. );
  1796. print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit', 'aZ09'), 0, 0, 0, '', 1);
  1797. print '</td>';
  1798. print '<td class="nowrap" style="padding-left: 5px">';
  1799. print '<span class="opacitymedium paddingleft">'.$langs->trans("AmountOrPercent").'</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="' . GETPOST('valuedeposit', 'int') . '"/>';
  1800. print '</td>';
  1801. }
  1802. print '</tr></table>';
  1803. print '</div></div>';
  1804. }
  1805. }
  1806. /* Not yet supported for supplier
  1807. if ($societe->id > 0)
  1808. {
  1809. // Replacement
  1810. if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT))
  1811. {
  1812. // Type invoice
  1813. $facids = $facturestatic->list_replacable_supplier_invoices($societe->id);
  1814. if ($facids < 0) {
  1815. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  1816. exit();
  1817. }
  1818. $options = "";
  1819. foreach ($facids as $facparam)
  1820. {
  1821. $options .= '<option value="' . $facparam ['id'] . '"';
  1822. if ($facparam ['id'] == $_POST['fac_replacement'])
  1823. $options .= ' selected';
  1824. $options .= '>' . $facparam ['ref'];
  1825. $options .= ' (' . $facturestatic->LibStatut(0, $facparam ['status']) . ')';
  1826. $options .= '</option>';
  1827. }
  1828. print '<!-- replacement line -->';
  1829. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1830. $tmp='<input type="radio" name="type" id="radio_replacement" value="1"' . (GETPOST('type') == 1 ? ' checked' : '');
  1831. if (! $options) $tmp.=' disabled';
  1832. $tmp.='> ';
  1833. print '<script type="text/javascript">
  1834. jQuery(document).ready(function() {
  1835. jQuery("#fac_replacement").change(function() {
  1836. jQuery("#radio_replacement").prop("checked", true);
  1837. });
  1838. });
  1839. </script>';
  1840. $text = $tmp.$langs->trans("InvoiceReplacementAsk") . ' ';
  1841. $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
  1842. if (! $options)
  1843. $text .= ' disabled';
  1844. $text .= '>';
  1845. if ($options) {
  1846. $text .= '<option value="-1">&nbsp;</option>';
  1847. $text .= $options;
  1848. } else {
  1849. $text .= '<option value="-1">' . $langs->trans("NoReplacableInvoice") . '</option>';
  1850. }
  1851. $text .= '</select>';
  1852. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  1853. print $desc;
  1854. print '</div></div>';
  1855. }
  1856. }
  1857. else
  1858. {
  1859. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1860. $tmp='<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
  1861. $text = $tmp.$langs->trans("InvoiceReplacement") . ' ';
  1862. $text.= '('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").') ';
  1863. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  1864. print $desc;
  1865. print '</div></div>';
  1866. }
  1867. */
  1868. if (empty($origin)) {
  1869. if ($societe->id > 0) {
  1870. // Credit note
  1871. if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) {
  1872. // Show link for credit note
  1873. $facids = $facturestatic->list_qualified_avoir_supplier_invoices($societe->id);
  1874. if ($facids < 0) {
  1875. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  1876. exit;
  1877. }
  1878. $optionsav = "";
  1879. $newinvoice_static = new FactureFournisseur($db);
  1880. foreach ($facids as $key => $valarray) {
  1881. $newinvoice_static->id = $key;
  1882. $newinvoice_static->ref = $valarray ['ref'];
  1883. $newinvoice_static->statut = $valarray ['status'];
  1884. $newinvoice_static->type = $valarray ['type'];
  1885. $newinvoice_static->paye = $valarray ['paye'];
  1886. $optionsav .= '<option value="'.$key.'"';
  1887. if ($key == GETPOST('fac_avoir', 'int')) {
  1888. $optionsav .= ' selected';
  1889. }
  1890. $optionsav .= '>';
  1891. $optionsav .= $newinvoice_static->ref;
  1892. $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')';
  1893. $optionsav .= '</option>';
  1894. }
  1895. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1896. $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST('type') == 2 ? ' checked' : '');
  1897. if (!$optionsav) {
  1898. $tmp .= ' disabled';
  1899. }
  1900. $tmp .= '> ';
  1901. // Show credit note options only if we checked credit note
  1902. print '<script type="text/javascript">
  1903. jQuery(document).ready(function() {
  1904. if (! jQuery("#radio_creditnote").is(":checked"))
  1905. {
  1906. jQuery("#credit_note_options").hide();
  1907. }
  1908. jQuery("#radio_creditnote").click(function() {
  1909. jQuery("#credit_note_options").show();
  1910. });
  1911. jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
  1912. jQuery("#credit_note_options").hide();
  1913. });
  1914. });
  1915. </script>';
  1916. $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk").' ';
  1917. // $text.='<input type="text" value="">';
  1918. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  1919. if (!$optionsav) {
  1920. $text .= ' disabled';
  1921. }
  1922. $text .= '>';
  1923. if ($optionsav) {
  1924. $text .= '<option value="-1"></option>';
  1925. $text .= $optionsav;
  1926. } else {
  1927. $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
  1928. }
  1929. $text .= '</select>';
  1930. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  1931. print $desc;
  1932. print '<div id="credit_note_options" class="clearboth">';
  1933. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithPaymentRestAmount\').removeAttr(\'checked\'); }" '.(GETPOST('invoiceAvoirWithLines', 'int') > 0 ? 'checked' : '').' /> ';
  1934. print '<label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
  1935. print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="if($(this).is(\':checked\') ) { $(\'#radio_creditnote\').prop(\'checked\', true); $(\'#invoiceAvoirWithLines\').removeAttr(\'checked\'); }" '.(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '').' /> ';
  1936. print '<label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  1937. print '</div>';
  1938. print '</div></div>';
  1939. }
  1940. } else {
  1941. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  1942. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
  1943. $text = $tmp.$langs->trans("InvoiceAvoir").' ';
  1944. $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromSupplierThird").')</span> ';
  1945. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  1946. print $desc;
  1947. print '</div></div>'."\n";
  1948. }
  1949. }
  1950. print '</div>';
  1951. print '</td></tr>';
  1952. if ($societe->id > 0) {
  1953. // Discounts for third party
  1954. print '<tr><td>'.$langs->trans('Discounts').'</td><td>';
  1955. $thirdparty = $societe;
  1956. $discount_type = 1;
  1957. $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$societe->id.'&action='.$action.'&origin='.GETPOST('origin').'&originid='.GETPOST('originid'));
  1958. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  1959. print '</td></tr>';
  1960. }
  1961. // Label
  1962. print '<tr><td>'.$langs->trans('Label').'</td><td><input class="minwidth200" name="label" value="'.dol_escape_htmltag(GETPOST('label')).'" type="text"></td></tr>';
  1963. // Date invoice
  1964. print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td>';
  1965. print $form->selectDate($dateinvoice, '', '', '', '', "add", 1, 1);
  1966. print '</td></tr>';
  1967. // Due date
  1968. print '<tr><td>'.$langs->trans('DateMaxPayment').'</td><td>';
  1969. print $form->selectDate($datedue, 'ech', '', '', '', "add", 1, 1);
  1970. print '</td></tr>';
  1971. // Payment term
  1972. print '<tr><td class="nowrap">'.$langs->trans('PaymentConditionsShort').'</td><td>';
  1973. $form->select_conditions_paiements(GETPOSTISSET('cond_reglement_id') ?GETPOST('cond_reglement_id', 'int') : $cond_reglement_id, 'cond_reglement_id');
  1974. print '</td></tr>';
  1975. // Payment mode
  1976. print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>';
  1977. print img_picto('', 'bank', 'class="pictofixedwidth"');
  1978. $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ?GETPOST('mode_reglement_id', 'int') : $mode_reglement_id, 'mode_reglement_id', 'DBIT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx');
  1979. print '</td></tr>';
  1980. // Bank Account
  1981. if (!empty($conf->banque->enabled)) {
  1982. print '<tr><td>'.$langs->trans('BankAccount').'</td><td>';
  1983. print img_picto('', 'bank_account', 'class="pictofixedwidth"').$form->select_comptes((GETPOSTISSET('fk_account') ?GETPOST('fk_account', 'alpha') : $fk_account), 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
  1984. print '</td></tr>';
  1985. }
  1986. // Project
  1987. if (!empty($conf->projet->enabled)) {
  1988. $formproject = new FormProjets($db);
  1989. $langs->load('projects');
  1990. print '<tr><td>'.$langs->trans('Project').'</td><td>';
  1991. print img_picto('', 'project', 'class="pictofixedwidth"').$formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $societe->id : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
  1992. print ' <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create&status=1&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create&socid='.$soc->id.($fac_rec ? '&fac_rec='.$fac_rec : '')).'"><span class="fa fa-plus-circle valignmiddle" title="'.$langs->trans("AddProject").'"></span></a>';
  1993. print '</td></tr>';
  1994. }
  1995. // Incoterms
  1996. if (!empty($conf->incoterm->enabled)) {
  1997. print '<tr>';
  1998. print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $objectsrc->label_incoterms, 1).'</label></td>';
  1999. print '<td colspan="3" class="maxwidthonsmartphone">';
  2000. print $form->select_incoterms(GETPOSTISSET('incoterm_id') ? GETPOST('incoterm_id', 'alphanohtml') : (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : ''), GETPOSTISSET('location_incoterms') ? GETPOST('location_incoterms', 'alphanohtml') : (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : ''));
  2001. print '</td></tr>';
  2002. }
  2003. // Multicurrency
  2004. if (!empty($conf->multicurrency->enabled)) {
  2005. print '<tr>';
  2006. print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
  2007. print '<td class="maxwidthonsmartphone">';
  2008. print $form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ?GETPOST('multicurrency_code', 'alpha') : $currency_code), 'multicurrency_code');
  2009. print '</td></tr>';
  2010. }
  2011. // Intracomm report
  2012. if (!empty($conf->intracommreport->enabled)) {
  2013. $langs->loadLangs(array("intracommreport"));
  2014. print '<tr><td>'.$langs->trans('IntracommReportTransportMode').'</td><td>';
  2015. $form->selectTransportMode(isset($_POST['transport_mode_id']) ? $_POST['transport_mode_id'] : $transport_mode_id, 'transport_mode_id');
  2016. print '</td></tr>';
  2017. }
  2018. if (empty($reshook)) {
  2019. print $object->showOptionals($extrafields, 'create');
  2020. }
  2021. // Public note
  2022. print '<tr><td>'.$langs->trans('NotePublic').'</td>';
  2023. print '<td>';
  2024. $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'restricthtml') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  2025. print $doleditor->Create(1);
  2026. print '</td>';
  2027. // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
  2028. print '</tr>';
  2029. // Private note
  2030. print '<tr><td>'.$langs->trans('NotePrivate').'</td>';
  2031. print '<td>';
  2032. $doleditor = new DolEditor('note_private', (GETPOSTISSET('note_private') ?GETPOST('note_private', 'restricthtml') : $note_private), '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  2033. print $doleditor->Create(1);
  2034. print '</td>';
  2035. // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
  2036. print '</tr>';
  2037. if (is_object($objectsrc)) {
  2038. print "\n<!-- ".$classname." info -->";
  2039. print "\n";
  2040. print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
  2041. print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
  2042. print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
  2043. print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  2044. print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  2045. $txt = $langs->trans($classname);
  2046. if ($classname == 'CommandeFournisseur') {
  2047. $langs->load('orders');
  2048. $txt = $langs->trans("SupplierOrder");
  2049. }
  2050. print '<tr><td>'.$txt.'</td><td>'.$objectsrc->getNomUrl(1);
  2051. // We check if Origin document (id and type is known) has already at least one invoice attached to it
  2052. $objectsrc->fetchObjectLinked($originid, $origin, '', 'invoice_supplier');
  2053. $invoice_supplier = $objectsrc->linkedObjects['invoice_supplier'];
  2054. // count function need a array as argument (Note: the array must implement Countable too)
  2055. if (is_array($invoice_supplier)) {
  2056. $cntinvoice = count($invoice_supplier);
  2057. if ($cntinvoice >= 1) {
  2058. setEventMessages('WarningBillExist', null, 'warnings');
  2059. echo ' ('.$langs->trans('LatestRelatedBill').end($invoice_supplier)->getNomUrl(1).')';
  2060. }
  2061. }
  2062. print '</td></tr>';
  2063. print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>';
  2064. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>";
  2065. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1
  2066. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>";
  2067. }
  2068. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2
  2069. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>";
  2070. }
  2071. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>";
  2072. if (!empty($conf->multicurrency->enabled)) {
  2073. print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
  2074. print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
  2075. print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
  2076. }
  2077. }
  2078. // Other options
  2079. $parameters = array();
  2080. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2081. print $hookmanager->resPrint;
  2082. print "</table>\n";
  2083. print dol_get_fiche_end();
  2084. print $form->buttonsSaveCancel("CreateDraft");
  2085. // Show origin lines
  2086. if (is_object($objectsrc)) {
  2087. print '<br>';
  2088. $title = $langs->trans('ProductsAndServices');
  2089. print load_fiche_titre($title);
  2090. print '<table class="noborder centpercent">';
  2091. $objectsrc->printOriginLinesList('', $selectedLines);
  2092. print '</table>';
  2093. }
  2094. print "</form>\n";
  2095. } else {
  2096. if ($id > 0 || !empty($ref)) {
  2097. //
  2098. // View or edit mode
  2099. //
  2100. $now = dol_now();
  2101. $productstatic = new Product($db);
  2102. $object->fetch($id, $ref);
  2103. $result = $object->fetch_thirdparty();
  2104. if ($result < 0) {
  2105. dol_print_error($db);
  2106. }
  2107. $societe = new Fournisseur($db);
  2108. $result = $societe->fetch($object->socid);
  2109. if ($result < 0) {
  2110. dol_print_error($db);
  2111. }
  2112. $totalpaye = $object->getSommePaiement();
  2113. $totalcreditnotes = $object->getSumCreditNotesUsed();
  2114. $totaldeposits = $object->getSumDepositsUsed();
  2115. // print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
  2116. // selleruserrevenuestamp=".$selleruserevenustamp;
  2117. // We can also use bcadd to avoid pb with floating points
  2118. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  2119. // $resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2120. // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  2121. $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
  2122. // Multicurrency
  2123. if (!empty($conf->multicurrency->enabled)) {
  2124. $multicurrency_totalpaye = $object->getSommePaiement(1);
  2125. $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
  2126. $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
  2127. $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaye - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
  2128. // Code to fix case of corrupted data
  2129. if ($resteapayer == 0 && $multicurrency_resteapayer != 0) {
  2130. $resteapayer = price2num($multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
  2131. }
  2132. }
  2133. if ($object->paye) {
  2134. $resteapayer = 0;
  2135. }
  2136. $resteapayeraffiche = $resteapayer;
  2137. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this
  2138. $filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  2139. $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
  2140. } else {
  2141. $filterabsolutediscount = "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')";
  2142. $filtercreditnote = "fk_invoice_supplier_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS PAID)%')";
  2143. }
  2144. $absolute_discount = $societe->getAvailableDiscounts('', $filterabsolutediscount, 0, 1);
  2145. $absolute_creditnote = $societe->getAvailableDiscounts('', $filtercreditnote, 0, 1);
  2146. $absolute_discount = price2num($absolute_discount, 'MT');
  2147. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  2148. /*
  2149. * View card
  2150. */
  2151. $head = facturefourn_prepare_head($object);
  2152. $titre = $langs->trans('SupplierInvoice');
  2153. print dol_get_fiche_head($head, 'card', $titre, -1, 'supplier_invoice');
  2154. $formconfirm = '';
  2155. // Confirmation de la conversion de l'avoir en reduc
  2156. if ($action == 'converttoreduc') {
  2157. if ($object->type == FactureFournisseur::TYPE_STANDARD) {
  2158. $type_fac = 'ExcessPaid';
  2159. } elseif ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2160. $type_fac = 'CreditNote';
  2161. } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) {
  2162. $type_fac = 'Deposit';
  2163. }
  2164. $text = $langs->trans('ConfirmConvertToReducSupplier', strtolower($langs->transnoentities($type_fac)));
  2165. $text .= '<br>'.$langs->trans('ConfirmConvertToReducSupplier2');
  2166. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
  2167. }
  2168. // Clone confirmation
  2169. if ($action == 'clone') {
  2170. // Create an array for form
  2171. $formquestion = array(
  2172. array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier),
  2173. array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
  2174. );
  2175. // Ask confirmation to clone
  2176. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250);
  2177. }
  2178. // Confirmation of validation
  2179. if ($action == 'valid') {
  2180. // We check if number is temporary number
  2181. if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) {
  2182. // empty should not happened, but when it occurs, the test save life
  2183. $numref = $object->getNextNumRef($societe);
  2184. } else {
  2185. $numref = $object->ref;
  2186. }
  2187. if ($numref < 0) {
  2188. setEventMessages($object->error, $object->errors, 'errors');
  2189. $action = '';
  2190. } else {
  2191. $text = $langs->trans('ConfirmValidateBill', $numref);
  2192. /*if (! empty($conf->notification->enabled))
  2193. {
  2194. require_once DOL_DOCUMENT_ROOT .'/core/class/notify.class.php';
  2195. $notify=new Notify($db);
  2196. $text.='<br>';
  2197. $text.=$notify->confirmMessage('BILL_SUPPLIER_VALIDATE',$object->socid, $object);
  2198. }*/
  2199. $formquestion = array();
  2200. $qualified_for_stock_change = 0;
  2201. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2202. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2203. } else {
  2204. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2205. }
  2206. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  2207. $langs->load("stocks");
  2208. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2209. $formproduct = new FormProduct($db);
  2210. $warehouse = new Entrepot($db);
  2211. $warehouse_array = $warehouse->list_array();
  2212. if (count($warehouse_array) == 1) {
  2213. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
  2214. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
  2215. } else {
  2216. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  2217. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  2218. }
  2219. $formquestion = array(
  2220. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  2221. );
  2222. }
  2223. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1);
  2224. }
  2225. }
  2226. // Confirmation edit (back to draft)
  2227. if ($action == 'edit') {
  2228. $formquestion = array();
  2229. $qualified_for_stock_change = 0;
  2230. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  2231. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  2232. } else {
  2233. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  2234. }
  2235. if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) {
  2236. $langs->load("stocks");
  2237. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  2238. $formproduct = new FormProduct($db);
  2239. $warehouse = new Entrepot($db);
  2240. $warehouse_array = $warehouse->list_array();
  2241. if (count($warehouse_array) == 1) {
  2242. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
  2243. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
  2244. } else {
  2245. $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
  2246. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  2247. }
  2248. $formquestion = array(
  2249. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value)
  2250. );
  2251. }
  2252. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1);
  2253. }
  2254. // Confirmation set paid
  2255. if ($action == 'paid' && ($resteapayer <= 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $resteapayer == $object->total_ttc))) {
  2256. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1);
  2257. }
  2258. if ($action == 'paid' && $resteapayer > 0 && (empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $resteapayer != $object->total_ttc)) {
  2259. $close = array();
  2260. // Code
  2261. $i = 0;
  2262. $close[$i]['code'] = 'discount_vat'; // escompte
  2263. $i++;
  2264. $close[$i]['code'] = 'badsupplier';
  2265. $i++;
  2266. $close[$i]['code'] = 'other';
  2267. $i++;
  2268. // Help
  2269. $i = 0;
  2270. $close[$i]['label'] = $langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
  2271. $i++;
  2272. $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadSupplierDesc");
  2273. $i++;
  2274. $close[$i]['label'] = $langs->trans("Other");
  2275. $i++;
  2276. // Text
  2277. $i = 0;
  2278. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
  2279. $i++;
  2280. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
  2281. $i++;
  2282. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
  2283. $i++;
  2284. // arrayreasons[code]=reason
  2285. foreach ($close as $key => $val) {
  2286. $arrayreasons[$close[$key]['code']] = $close[$key]['reason'];
  2287. }
  2288. // Create a form table
  2289. $formquestion = array('text' => $langs->trans("ConfirmClassifyPaidPartiallyQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
  2290. // Incomplete payment. We ask if the reason is discount or other
  2291. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 310);
  2292. }
  2293. // Confirmation of the abandoned classification
  2294. if ($action == 'canceled') {
  2295. // Code
  2296. $close[1]['code'] = 'badsupplier';
  2297. $close[2]['code'] = 'abandon';
  2298. // Help
  2299. $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadSupplierDesc");
  2300. $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
  2301. // Text
  2302. $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadSupplier", $object->ref), $close[1]['label'], 1);
  2303. $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
  2304. // arrayreasons
  2305. $arrayreasons[$close[1]['code']] = $close[1]['reason'];
  2306. $arrayreasons[$close[2]['code']] = $close[2]['reason'];
  2307. // Create a form table
  2308. $formquestion = array('text' => $langs->trans("ConfirmCancelBillQuestion"), array('type' => 'radio', 'name' => 'close_code', 'label' => $langs->trans("Reason"), 'values' => $arrayreasons), array('type' => 'text', 'name' => 'close_note', 'label' => $langs->trans("Comment"), 'value' => '', 'morecss' => 'minwidth300'));
  2309. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 250);
  2310. }
  2311. // Confirmation de la suppression de la facture fournisseur
  2312. if ($action == 'delete') {
  2313. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1);
  2314. }
  2315. if ($action == 'deletepayment') {
  2316. $payment_id = GETPOST('paiement_id');
  2317. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1);
  2318. }
  2319. // Confirmation to delete line
  2320. if ($action == 'ask_deleteline') {
  2321. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1);
  2322. }
  2323. if (!$formconfirm) {
  2324. $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid);
  2325. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2326. if (empty($reshook)) {
  2327. $formconfirm .= $hookmanager->resPrint;
  2328. } elseif ($reshook > 0) {
  2329. $formconfirm = $hookmanager->resPrint;
  2330. }
  2331. }
  2332. // Print form confirm
  2333. print $formconfirm;
  2334. // Supplier invoice card
  2335. $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  2336. $morehtmlref = '<div class="refidno">';
  2337. // Ref supplier
  2338. $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1);
  2339. $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1);
  2340. // Thirdparty
  2341. $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'supplier');
  2342. if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
  2343. $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
  2344. }
  2345. // Project
  2346. if (!empty($conf->projet->enabled)) {
  2347. $langs->load("projects");
  2348. $morehtmlref .= '<br>'.$langs->trans('Project').' ';
  2349. if ($usercancreate) {
  2350. if ($action != 'classify') {
  2351. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&token='.newToken().'&id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
  2352. }
  2353. if ($action == 'classify') {
  2354. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  2355. $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  2356. $morehtmlref .= '<input type="hidden" name="action" value="classin">';
  2357. $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
  2358. $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  2359. $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  2360. $morehtmlref .= '</form>';
  2361. } else {
  2362. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
  2363. }
  2364. } else {
  2365. if (!empty($object->fk_project)) {
  2366. $proj = new Project($db);
  2367. $proj->fetch($object->fk_project);
  2368. $morehtmlref .= ' : '.$proj->getNomUrl(1);
  2369. if ($proj->title) {
  2370. $morehtmlref .= ' - '.$proj->title;
  2371. }
  2372. } else {
  2373. $morehtmlref .= '';
  2374. }
  2375. }
  2376. }
  2377. $morehtmlref .= '</div>';
  2378. $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
  2379. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref);
  2380. print '<div class="fichecenter">';
  2381. print '<div class="fichehalfleft">';
  2382. print '<div class="underbanner clearboth"></div>';
  2383. print '<table class="border tableforfield" width="100%">';
  2384. // Type
  2385. print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>';
  2386. print '<span class="badgeneutral">';
  2387. print $object->getLibType();
  2388. print '</span>';
  2389. if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) {
  2390. $facreplaced = new FactureFournisseur($db);
  2391. $facreplaced->fetch($object->fk_facture_source);
  2392. print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')';
  2393. }
  2394. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2395. $facusing = new FactureFournisseur($db);
  2396. if ($object->fk_facture_source > 0) {
  2397. $facusing->fetch($object->fk_facture_source);
  2398. print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')';
  2399. } else {
  2400. print ' ('.$langs->transnoentities("CorrectedInvoiceNotFound").')';
  2401. }
  2402. }
  2403. $facidavoir = $object->getListIdAvoirFromInvoice();
  2404. if (count($facidavoir) > 0) {
  2405. $invoicecredits = array();
  2406. foreach ($facidavoir as $id) {
  2407. $facavoir = new FactureFournisseur($db);
  2408. $facavoir->fetch($id);
  2409. $invoicecredits[] = $facavoir->getNomUrl(1);
  2410. }
  2411. print ' ('.$langs->transnoentities("InvoiceHasAvoir") . (count($invoicecredits) ? ' ' : '') . implode(',', $invoicecredits) . ')';
  2412. }
  2413. if (isset($facidnext) && $facidnext > 0) {
  2414. $facthatreplace = new FactureFournisseur($db);
  2415. $facthatreplace->fetch($facidnext);
  2416. print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')';
  2417. }
  2418. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) {
  2419. $discount = new DiscountAbsolute($db);
  2420. $result = $discount->fetch(0, 0, $object->id);
  2421. if ($result > 0) {
  2422. print ' <span class="opacitymediumbycolor paddingleft">';
  2423. $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
  2424. $s = str_replace('{s1}', $object->getLibType(1), $s);
  2425. $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
  2426. print $s;
  2427. print '</span><br>';
  2428. }
  2429. }
  2430. print '</td></tr>';
  2431. // Relative and absolute discounts
  2432. print '<!-- Discounts --><tr><td>'.$langs->trans('Discounts');
  2433. print '</td><td>';
  2434. $thirdparty = $societe;
  2435. $discount_type = 1;
  2436. $backtopage = urlencode($_SERVER["PHP_SELF"].'?facid='.$object->id);
  2437. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  2438. print '</td></tr>';
  2439. // Label
  2440. print '<tr>';
  2441. print '<td>'.$form->editfieldkey("Label", 'label', $object->label, $object, $usercancreate).'</td>';
  2442. print '<td>'.$form->editfieldval("Label", 'label', $object->label, $object, $usercancreate).'</td>';
  2443. print '</tr>';
  2444. $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0);
  2445. $form_permission2 = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate;
  2446. // Date
  2447. print '<tr><td>';
  2448. print $form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker');
  2449. print '</td><td colspan="3">';
  2450. print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker');
  2451. print '</td>';
  2452. // Default terms of the settlement
  2453. $langs->load('bills');
  2454. print '<tr><td class="nowrap">';
  2455. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2456. print $langs->trans('PaymentConditions');
  2457. print '<td>';
  2458. if ($action != 'editconditions' && $form_permission) {
  2459. 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>';
  2460. }
  2461. print '</tr></table>';
  2462. print '</td><td>';
  2463. if ($action == 'editconditions') {
  2464. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  2465. } else {
  2466. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none');
  2467. }
  2468. print "</td>";
  2469. print '</tr>';
  2470. // Due date
  2471. print '<tr><td>';
  2472. print $form->editfieldkey("DateMaxPayment", 'date_lim_reglement', $object->date_echeance, $object, $form_permission2, 'datepicker');
  2473. print '</td><td>';
  2474. print $form->editfieldval("DateMaxPayment", 'date_lim_reglement', $object->date_echeance, $object, $form_permission2, 'datepicker');
  2475. if ($action != 'editdate_lim_reglement' && $object->hasDelay()) {
  2476. print img_warning($langs->trans('Late'));
  2477. }
  2478. print '</td>';
  2479. // Mode of payment
  2480. $langs->load('bills');
  2481. print '<tr><td class="nowrap">';
  2482. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2483. print $langs->trans('PaymentMode');
  2484. print '</td>';
  2485. if ($action != 'editmode' && $form_permission2) {
  2486. 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>';
  2487. }
  2488. print '</tr></table>';
  2489. print '</td><td>';
  2490. if ($action == 'editmode') {
  2491. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1);
  2492. } else {
  2493. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none');
  2494. }
  2495. print '</td></tr>';
  2496. // Multicurrency
  2497. if (!empty($conf->multicurrency->enabled)) {
  2498. // Multicurrency code
  2499. print '<tr>';
  2500. print '<td>';
  2501. print '<table class="nobordernopadding" width="100%"><tr><td>';
  2502. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  2503. print '</td>';
  2504. if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) {
  2505. 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>';
  2506. }
  2507. print '</tr></table>';
  2508. print '</td><td>';
  2509. if ($action == 'editmulticurrencycode') {
  2510. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'multicurrency_code');
  2511. } else {
  2512. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, 'none');
  2513. }
  2514. print '</td></tr>';
  2515. // Multicurrency rate
  2516. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  2517. print '<tr>';
  2518. print '<td>';
  2519. print '<table class="nobordernopadding centpercent"><tr><td>';
  2520. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  2521. print '</td>';
  2522. if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  2523. 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>';
  2524. }
  2525. print '</tr></table>';
  2526. print '</td><td>';
  2527. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  2528. if ($action == 'actualizemulticurrencyrate') {
  2529. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  2530. }
  2531. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'multicurrency_tx', $object->multicurrency_code);
  2532. } else {
  2533. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  2534. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  2535. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  2536. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  2537. print '</div>';
  2538. }
  2539. }
  2540. print '</td></tr>';
  2541. }
  2542. }
  2543. // Bank Account
  2544. if (!empty($conf->banque->enabled)) {
  2545. print '<tr><td class="nowrap">';
  2546. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  2547. print $langs->trans('BankAccount');
  2548. print '<td>';
  2549. if ($action != 'editbankaccount' && $usercancreate) {
  2550. 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>';
  2551. }
  2552. print '</tr></table>';
  2553. print '</td><td>';
  2554. if ($action == 'editbankaccount') {
  2555. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  2556. } else {
  2557. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  2558. }
  2559. print "</td>";
  2560. print '</tr>';
  2561. }
  2562. // Incoterms
  2563. if (!empty($conf->incoterm->enabled)) {
  2564. print '<tr><td>';
  2565. print '<table width="100%" class="nobordernopadding"><tr><td>';
  2566. print $langs->trans('IncotermLabel');
  2567. print '<td><td class="right">';
  2568. if ($usercancreate) {
  2569. print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm&token='.newToken().'">'.img_edit().'</a>';
  2570. } else {
  2571. print '&nbsp;';
  2572. }
  2573. print '</td></tr></table>';
  2574. print '</td>';
  2575. print '<td>';
  2576. if ($action != 'editincoterm') {
  2577. print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
  2578. } else {
  2579. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
  2580. }
  2581. print '</td></tr>';
  2582. }
  2583. // Intracomm report
  2584. if (!empty($conf->intracommreport->enabled)) {
  2585. $langs->loadLangs(array("intracommreport"));
  2586. print '<tr><td>';
  2587. print '<table width="100%" class="nobordernopadding"><tr><td>';
  2588. print $langs->trans('IntracommReportTransportMode');
  2589. print '</td>';
  2590. if ($action != 'editmode' && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)) {
  2591. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&token='.newToken().'&id='.$object->id.'">'.img_edit().'</a></td>';
  2592. }
  2593. print '</tr></table>';
  2594. print '</td>';
  2595. print '<td>';
  2596. if ($action == 'editmode') {
  2597. $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'transport_mode_id', 1, 1);
  2598. } else {
  2599. $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'none');
  2600. }
  2601. print '</td></tr>';
  2602. }
  2603. // Other attributes
  2604. $cols = 2;
  2605. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  2606. print '</table>';
  2607. print '</div>';
  2608. print '<div class="fichehalfright">';
  2609. print '<div class="underbanner clearboth"></div>';
  2610. print '<table class="border tableforfield centpercent">';
  2611. if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) {
  2612. // Multicurrency Amount HT
  2613. print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
  2614. print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2615. print '</tr>';
  2616. // Multicurrency Amount VAT
  2617. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
  2618. print '<td>'.price($object->multicurrency_total_tva, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2619. print '</tr>';
  2620. // Multicurrency Amount TTC
  2621. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
  2622. print '<td>'.price($object->multicurrency_total_ttc, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  2623. print '</tr>';
  2624. }
  2625. // Amount
  2626. print '<tr><td class="titlefield">'.$langs->trans('AmountHT').'</td><td>'.price($object->total_ht, 1, $langs, 0, -1, -1, $conf->currency).'</td></tr>';
  2627. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($object->total_tva, 1, $langs, 0, -1, -1, $conf->currency).'<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  2628. if (GETPOST('calculationrule')) {
  2629. $calculationrule = GETPOST('calculationrule', 'alpha');
  2630. } else {
  2631. $calculationrule = (empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND) ? 'totalofround' : 'roundoftotal');
  2632. }
  2633. if ($calculationrule == 'totalofround') {
  2634. $calculationrulenum = 1;
  2635. } else {
  2636. $calculationrulenum = 2;
  2637. }
  2638. // Show link for "recalculate"
  2639. if ($object->getVentilExportCompta() == 0) {
  2640. $s = $langs->trans("ReCalculate").' ';
  2641. $s .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=calculate&calculationrule=totalofround">'.$langs->trans("Mode1").'</a>';
  2642. $s .= ' / ';
  2643. $s .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=calculate&calculationrule=roundoftotal">'.$langs->trans("Mode2").'</a>';
  2644. print $form->textwithtooltip($s, $langs->trans("CalculationRuleDesc", $calculationrulenum).'<br>'.$langs->trans("CalculationRuleDescSupplier"), 2, 1, img_picto('', 'help'));
  2645. }
  2646. print '</div></td></tr>';
  2647. // Amount Local Taxes
  2648. //TODO: Place into a function to control showing by country or study better option
  2649. if ($societe->localtax1_assuj == "1") { //Localtax1
  2650. print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>';
  2651. print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>';
  2652. print '</tr>';
  2653. }
  2654. if ($societe->localtax2_assuj == "1") { //Localtax2
  2655. print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>';
  2656. print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>';
  2657. print '</tr>';
  2658. }
  2659. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="3">'.price($object->total_ttc, 1, $langs, 0, -1, -1, $conf->currency).'</td></tr>';
  2660. print '</table>';
  2661. // List of payments
  2662. $totalpaye = 0;
  2663. $sign = 1;
  2664. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2665. $sign = - 1;
  2666. }
  2667. $nbrows = 9; $nbcols = 3;
  2668. if (!empty($conf->projet->enabled)) {
  2669. $nbrows++;
  2670. }
  2671. if (!empty($conf->banque->enabled)) {
  2672. $nbrows++; $nbcols++;
  2673. }
  2674. if (!empty($conf->incoterm->enabled)) {
  2675. $nbrows++;
  2676. }
  2677. if (!empty($conf->multicurrency->enabled)) {
  2678. $nbrows += 5;
  2679. }
  2680. // Local taxes
  2681. if ($societe->localtax1_assuj == "1") {
  2682. $nbrows++;
  2683. }
  2684. if ($societe->localtax2_assuj == "1") {
  2685. $nbrows++;
  2686. }
  2687. $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
  2688. $sql .= ' c.id as paiement_type,';
  2689. $sql .= ' pf.amount,';
  2690. $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal';
  2691. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn as p';
  2692. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
  2693. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
  2694. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
  2695. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_paiementfourn = p.rowid';
  2696. $sql .= ' WHERE pf.fk_facturefourn = '.((int) $object->id);
  2697. $sql .= ' ORDER BY p.datep, p.tms';
  2698. $result = $db->query($sql);
  2699. if ($result) {
  2700. $num = $db->num_rows($result);
  2701. $i = 0;
  2702. print '<div class="div-table-responsive-no-min">';
  2703. print '<table class="noborder paymenttable" width="100%">';
  2704. print '<tr class="liste_titre">';
  2705. print '<td class="liste_titre">'.($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
  2706. print '<td>'.$langs->trans('Date').'</td>';
  2707. print '<td>'.$langs->trans('Type').'</td>';
  2708. if (!empty($conf->banque->enabled)) {
  2709. print '<td class="right">'.$langs->trans('BankAccount').'</td>';
  2710. }
  2711. print '<td class="right">'.$langs->trans('Amount').'</td>';
  2712. print '<td width="18">&nbsp;</td>';
  2713. print '</tr>';
  2714. if ($num > 0) {
  2715. while ($i < $num) {
  2716. $objp = $db->fetch_object($result);
  2717. $paymentstatic->id = $objp->rowid;
  2718. $paymentstatic->datepaye = $db->jdate($objp->dp);
  2719. $paymentstatic->ref = ($objp->ref ? $objp->ref : $objp->rowid);
  2720. $paymentstatic->num_payment = $objp->num_payment;
  2721. $paymentstatic->payment_code = $objp->payment_code;
  2722. print '<tr class="oddeven">';
  2723. print '<td>';
  2724. print $paymentstatic->getNomUrl(1);
  2725. print '</td>';
  2726. print '<td>'.dol_print_date($db->jdate($objp->dp), 'day').'</td>';
  2727. print '<td>';
  2728. print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_payment;
  2729. print '</td>';
  2730. if (!empty($conf->banque->enabled)) {
  2731. $bankaccountstatic->id = $objp->baid;
  2732. $bankaccountstatic->ref = $objp->baref;
  2733. $bankaccountstatic->label = $objp->baref;
  2734. $bankaccountstatic->number = $objp->banumber;
  2735. if (!empty($conf->accounting->enabled)) {
  2736. $bankaccountstatic->account_number = $objp->account_number;
  2737. $accountingjournal = new AccountingJournal($db);
  2738. $accountingjournal->fetch($objp->fk_accountancy_journal);
  2739. $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
  2740. }
  2741. print '<td class="right">';
  2742. if ($objp->baid > 0) {
  2743. print $bankaccountstatic->getNomUrl(1, 'transactions');
  2744. }
  2745. print '</td>';
  2746. }
  2747. print '<td class="right">'.price($sign * $objp->amount).'</td>';
  2748. print '<td class="center">';
  2749. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) {
  2750. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">';
  2751. print img_delete();
  2752. print '</a>';
  2753. }
  2754. print '</td>';
  2755. print '</tr>';
  2756. $totalpaye += $objp->amount;
  2757. $i++;
  2758. }
  2759. } else {
  2760. print '<tr class="oddeven"><td colspan="'.$nbcols.'"><span class="opacitymedium">'.$langs->trans("None").'</span></td><td></td><td></td></tr>';
  2761. }
  2762. /*
  2763. if ($object->paye == 0)
  2764. {
  2765. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('AlreadyPaid').' :</td><td class="right">'.price($totalpaye).'</td><td></td></tr>';
  2766. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>';
  2767. $resteapayer = $object->total_ttc - $totalpaye;
  2768. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('RemainderToPay').' :</td>';
  2769. print '<td class="right'.($resteapayer?' amountremaintopay':'').'">'.price($resteapayer).'</td><td></td></tr>';
  2770. }
  2771. */
  2772. $db->free($result);
  2773. } else {
  2774. dol_print_error($db);
  2775. }
  2776. if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) {
  2777. // Total already paid
  2778. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2779. print '<span class="opacitymedium">';
  2780. if ($object->type != FactureFournisseur::TYPE_DEPOSIT) {
  2781. print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
  2782. } else {
  2783. print $langs->trans('AlreadyPaid');
  2784. }
  2785. print '</span>';
  2786. print '</td><td class="right"'.(($totalpaye > 0) ? ' class="amountalreadypaid"' : '').'>'.price($totalpaye).'</td><td>&nbsp;</td></tr>';
  2787. //$resteapayer = $object->total_ttc - $totalpaye;
  2788. $resteapayeraffiche = $resteapayer;
  2789. $cssforamountpaymentcomplete = 'amountpaymentcomplete';
  2790. // Loop on each credit note or deposit amount applied
  2791. $creditnoteamount = 0;
  2792. $depositamount = 0;
  2793. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  2794. $sql .= " re.description, re.fk_invoice_supplier_source";
  2795. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  2796. $sql .= " WHERE fk_invoice_supplier = ".((int) $object->id);
  2797. $resql = $db->query($sql);
  2798. if ($resql) {
  2799. $num = $db->num_rows($resql);
  2800. $i = 0;
  2801. $invoice = new FactureFournisseur($db);
  2802. while ($i < $num) {
  2803. $obj = $db->fetch_object($resql);
  2804. $invoice->fetch($obj->fk_invoice_supplier_source);
  2805. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2806. if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2807. print $langs->trans("CreditNote").' ';
  2808. }
  2809. if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
  2810. print $langs->trans("Deposit").' ';
  2811. }
  2812. print $invoice->getNomUrl(0);
  2813. print ' :</td>';
  2814. print '<td class="right">'.price($obj->amount_ttc).'</td>';
  2815. print '<td class="right">';
  2816. print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>';
  2817. print '</td></tr>';
  2818. $i++;
  2819. if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) {
  2820. $creditnoteamount += $obj->amount_ttc;
  2821. }
  2822. if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) {
  2823. $depositamount += $obj->amount_ttc;
  2824. }
  2825. }
  2826. } else {
  2827. dol_print_error($db);
  2828. }
  2829. // Paye partiellement 'escompte'
  2830. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
  2831. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  2832. print '<span class="opacitymedium">';
  2833. print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), - 1);
  2834. print '</span>';
  2835. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
  2836. $resteapayeraffiche = 0;
  2837. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  2838. }
  2839. // Paye partiellement ou Abandon 'badsupplier'
  2840. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'badsupplier') {
  2841. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  2842. print '<span class="opacitymedium">';
  2843. print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), - 1);
  2844. print '</span>';
  2845. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
  2846. // $resteapayeraffiche=0;
  2847. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  2848. }
  2849. // Paye partiellement ou Abandon 'product_returned'
  2850. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
  2851. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  2852. print '<span class="opacitymedium">';
  2853. print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), - 1);
  2854. print '</span>';
  2855. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
  2856. $resteapayeraffiche = 0;
  2857. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  2858. }
  2859. // Paye partiellement ou Abandon 'abandon'
  2860. if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') {
  2861. print '<tr><td colspan="'.$nbcols.'" class="right nowrap">';
  2862. $text = $langs->trans("HelpAbandonOther");
  2863. if ($object->close_note) {
  2864. $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
  2865. }
  2866. print '<span class="opacitymedium">';
  2867. print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1);
  2868. print '</span>';
  2869. print '</td><td class="right">'.price($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye).'</td><td>&nbsp;</td></tr>';
  2870. $resteapayeraffiche = 0;
  2871. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  2872. }
  2873. // Billed
  2874. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2875. print '<span class="opacitymedium">';
  2876. print $langs->trans("Billed");
  2877. print '</span>';
  2878. print '</td><td class="right">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
  2879. // Remainder to pay
  2880. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2881. print '<span class="opacitymedium">';
  2882. if ($resteapayeraffiche >= 0) {
  2883. print $langs->trans('RemainderToPay');
  2884. } else {
  2885. print $langs->trans('ExcessPaid');
  2886. }
  2887. print '</span>';
  2888. print '</td>';
  2889. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td><td>&nbsp;</td></tr>';
  2890. // Remainder to pay Multicurrency
  2891. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  2892. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2893. print '<span class="opacitymedium">';
  2894. if ($resteapayeraffiche <= 0) {
  2895. print $langs->trans('RemainderToPayBackMulticurrency');
  2896. } else {
  2897. print $langs->trans('ExcessPaidMulticurrency');
  2898. }
  2899. print '</span>';
  2900. print '</td>';
  2901. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.(!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency).' '.price(price2num($object->multicurrency_tx*$resteapayeraffiche, 'MT')).'</td><td>&nbsp;</td></tr>';
  2902. }
  2903. } else // Credit note
  2904. {
  2905. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  2906. // Total already paid back
  2907. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2908. print $langs->trans('AlreadyPaidBack');
  2909. print ' :</td><td class="right">'.price($sign * $totalpaye).'</td><td>&nbsp;</td></tr>';
  2910. // Billed
  2911. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($sign * $object->total_ttc).'</td><td>&nbsp;</td></tr>';
  2912. // Remainder to pay back
  2913. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2914. print '<span class="opacitymedium">';
  2915. if ($resteapayeraffiche <= 0) {
  2916. print $langs->trans('RemainderToPayBack');
  2917. } else {
  2918. print $langs->trans('ExcessPaid');
  2919. }
  2920. print '</td>';
  2921. print '</span>';
  2922. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche).'</td><td>&nbsp;</td></tr>';
  2923. // Remainder to pay back Multicurrency
  2924. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  2925. print '<tr><td colspan="'.$nbcols.'" class="right">';
  2926. print '<span class="opacitymedium">';
  2927. if ($resteapayeraffiche <= 0) {
  2928. print $langs->trans('RemainderToPayBackMulticurrency');
  2929. } else {
  2930. print $langs->trans('ExcessPaidMulticurrency');
  2931. }
  2932. print '</span>';
  2933. print '</td>';
  2934. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.(!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency).' '.price(price2num($sign * $object->multicurrency_tx * $resteapayeraffiche, 'MT')).'</td><td>&nbsp;</td></tr>';
  2935. }
  2936. // Sold credit note
  2937. // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
  2938. // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
  2939. // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
  2940. }
  2941. print '</table>';
  2942. print '</div>';
  2943. print '</div>';
  2944. print '</div>';
  2945. print '<div class="clearboth"></div><br>';
  2946. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  2947. $blocname = 'contacts';
  2948. $title = $langs->trans('ContactsAddresses');
  2949. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  2950. }
  2951. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  2952. $colwidth = 20;
  2953. $blocname = 'notes';
  2954. $title = $langs->trans('Notes');
  2955. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  2956. }
  2957. /*
  2958. * Lines
  2959. */
  2960. print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">';
  2961. print '<input type="hidden" name="token" value="'.newToken().'">';
  2962. print '<input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">';
  2963. print '<input type="hidden" name="mode" value="">';
  2964. print '<input type="hidden" name="page_y" value="">';
  2965. print '<input type="hidden" name="id" value="'.$object->id.'">';
  2966. print '<input type="hidden" name="socid" value="'.$societe->id.'">';
  2967. if (!empty($conf->use_javascript_ajax) && $object->statut == FactureFournisseur::STATUS_DRAFT) {
  2968. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  2969. }
  2970. print '<div class="div-table-responsive-no-min">';
  2971. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  2972. global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax;
  2973. $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1;
  2974. $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum.
  2975. //if (! empty($conf->global->SUPPLIER_INVOICE_WITH_NOPRICEDEFINED)) $senderissupplier=2;
  2976. if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) {
  2977. $senderissupplier = 1;
  2978. }
  2979. // Show object lines
  2980. if (!empty($object->lines)) {
  2981. $ret = $object->printObjectLines($action, $societe, $mysoc, $lineid, 1);
  2982. }
  2983. $num = count($object->lines);
  2984. // Form to add new line
  2985. if ($object->statut == FactureFournisseur::STATUS_DRAFT && $usercancreate) {
  2986. if ($action != 'editline') {
  2987. // Add free products/services
  2988. $parameters = array();
  2989. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  2990. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  2991. if (empty($reshook))
  2992. $object->formAddObjectLine(1, $societe, $mysoc);
  2993. }
  2994. }
  2995. print '</table>';
  2996. print '</div>';
  2997. print '</form>';
  2998. print dol_get_fiche_end();
  2999. if ($action != 'presend') {
  3000. /*
  3001. * Buttons actions
  3002. */
  3003. print '<div class="tabsAction">';
  3004. $parameters = array();
  3005. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been
  3006. // modified by hook
  3007. if (empty($reshook)) {
  3008. // Modify a validated invoice with no payments
  3009. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) {
  3010. // We check if lines of invoice are not already transfered into accountancy
  3011. $ventilExportCompta = $object->getVentilExportCompta(); // Should be 0 since the sum of payments are zero. But we keep the protection.
  3012. if ($ventilExportCompta == 0) {
  3013. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=edit&token='.newToken().'">'.$langs->trans('Modify').'</a>';
  3014. } else {
  3015. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Modify').'</span>';
  3016. }
  3017. }
  3018. $discount = new DiscountAbsolute($db);
  3019. $result = $discount->fetch(0, 0, $object->id);
  3020. // Reopen a standard paid invoice
  3021. if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT
  3022. || ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && empty($discount->id))
  3023. || ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discount->id)))
  3024. && ($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED)) { // A paid invoice (partially or completely)
  3025. if (!$facidnext && $object->close_code != 'replaced' && $usercancreate) { // Not replaced by another invoice
  3026. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen&token='.newToken().'">'.$langs->trans('ReOpen').'</a>';
  3027. } else {
  3028. if ($usercancreate) {
  3029. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span>';
  3030. } elseif (empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
  3031. print '<span class="butActionRefused classfortooltip">'.$langs->trans('ReOpen').'</span>';
  3032. }
  3033. }
  3034. }
  3035. // Validate
  3036. if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) {
  3037. if (count($object->lines)) {
  3038. if ($usercanvalidate) {
  3039. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid"';
  3040. print '>'.$langs->trans('Validate').'</a>';
  3041. } else {
  3042. print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
  3043. print '>'.$langs->trans('Validate').'</a>';
  3044. }
  3045. }
  3046. }
  3047. // Send by mail
  3048. if (empty($user->socid)) {
  3049. if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) {
  3050. if ($usercansend) {
  3051. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>';
  3052. } else {
  3053. print '<span class="butActionRefused classfortooltip">'.$langs->trans('SendMail').'</span>';
  3054. }
  3055. }
  3056. }
  3057. // Create payment
  3058. if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) {
  3059. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.DOL_URL_ROOT.'/fourn/facture/paiement.php?facid='.$object->id.'&amp;action=create'.($object->fk_account > 0 ? '&amp;accountid='.$object->fk_account : '').'">'.$langs->trans('DoPayment').'</a>'; // must use facid because id is for payment id not invoice
  3060. }
  3061. // Reverse back money or convert to reduction
  3062. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) {
  3063. // For credit note only
  3064. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) {
  3065. if ($resteapayer == 0) {
  3066. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span>';
  3067. } else {
  3068. print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a>';
  3069. }
  3070. }
  3071. // For standard invoice with excess paid
  3072. if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $usercancreate && empty($discount->id)) {
  3073. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertExcessPaidToReduc').'</a>';
  3074. }
  3075. // For credit note
  3076. if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercancreate
  3077. && (!empty($conf->global->SUPPLIER_INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $object->getSommePaiement() == 0)
  3078. ) {
  3079. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReducSupplier2")).'">'.$langs->trans('ConvertToReduc').'</a>';
  3080. }
  3081. // For deposit invoice
  3082. if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $usercancreate && $object->statut > 0 && empty($discount->id)) {
  3083. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a>';
  3084. }
  3085. }
  3086. // Classify paid
  3087. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && (
  3088. ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $object->type != FactureFournisseur::TYPE_DEPOSIT && ($resteapayer <= 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $object->total_ttc == $resteapayer))) ||
  3089. ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $resteapayer >= 0) ||
  3090. ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->total_ttc > 0 && ($resteapayer == 0 || (!empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) && $object->total_ttc == $resteapayer)))
  3091. )
  3092. ) {
  3093. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a>';
  3094. }
  3095. // Classify 'closed not completely paid' (possible if validated and not yet filed paid)
  3096. if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && (empty($conf->global->SUPPLIER_INVOICE_CAN_SET_PAID_EVEN_IF_PARTIALLY_PAID) || $object->total_ttc != $resteapayer)) {
  3097. if ($totalpaye > 0 || $totalcreditnotes > 0) {
  3098. // If one payment or one credit note was linked to this invoice
  3099. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaidPartially').'</a>';
  3100. } else {
  3101. if (empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED)) {
  3102. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=canceled">'.$langs->trans('ClassifyCanceled').'</a>';
  3103. }
  3104. }
  3105. }
  3106. // Create event
  3107. /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page.
  3108. {
  3109. 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>';
  3110. }*/
  3111. // Create a credit note
  3112. if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $usercancreate) {
  3113. if (!$objectidnext) {
  3114. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&amp;action=create&amp;type=2'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').'">'.$langs->trans("CreateCreditNote").'</a>';
  3115. }
  3116. }
  3117. // Clone
  3118. if ($action != 'edit' && $usercancreate) {
  3119. print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=clone&amp;socid='.$object->socid.'">'.$langs->trans('ToClone').'</a>';
  3120. }
  3121. // Delete
  3122. $isErasable = $object->is_erasable();
  3123. if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($usercancreate && $isErasable == 1))) { // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions)
  3124. //var_dump($isErasable);
  3125. if ($isErasable == -4) {
  3126. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a>';
  3127. } elseif ($isErasable == -3) { // Should never happen with supplier invoice
  3128. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastSituationInvoice").'">'.$langs->trans('Delete').'</a>';
  3129. } elseif ($isErasable == -2) { // Should never happen with supplier invoice
  3130. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInvoice").'">'.$langs->trans('Delete').'</a>';
  3131. } elseif ($isErasable == -1) {
  3132. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Delete').'</a>';
  3133. } elseif ($isErasable <= 0) { // Any other cases
  3134. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a>';
  3135. } else {
  3136. print '<a class="butActionDelete'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken().'">'.$langs->trans('Delete').'</a>';
  3137. }
  3138. }
  3139. print '</div>';
  3140. if ($action != 'confirm_edit') {
  3141. print '<div class="fichecenter"><div class="fichehalfleft">';
  3142. /*
  3143. * Generated documents
  3144. */
  3145. $ref = dol_sanitizeFileName($object->ref);
  3146. $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref;
  3147. $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir;
  3148. $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id;
  3149. $genallowed = $usercanread;
  3150. $delallowed = $usercancreate;
  3151. $modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF) ? '' : $conf->global->INVOICE_SUPPLIER_ADDON_PDF));
  3152. print $formfile->showdocuments('facture_fournisseur', $subdir, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang);
  3153. $somethingshown = $formfile->numoffiles;
  3154. // Show links to link elements
  3155. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice_supplier'));
  3156. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem);
  3157. print '</div><div class="fichehalfright">';
  3158. // List of actions on element
  3159. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  3160. $formactions = new FormActions($db);
  3161. $somethingshown = $formactions->showactions($object, 'invoice_supplier', $socid, 1, 'listaction'.($genallowed ? 'largetitle' : ''));
  3162. print '</div></div>';
  3163. }
  3164. }
  3165. }
  3166. // Select mail models is same action as presend
  3167. if (GETPOST('modelselected')) {
  3168. $action = 'presend';
  3169. }
  3170. // Presend form
  3171. $modelmail = 'invoice_supplier_send';
  3172. $defaulttopic = 'SendBillRef';
  3173. $diroutput = $conf->fournisseur->facture->dir_output;
  3174. $autocopy = 'MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO';
  3175. $trackid = 'sinv'.$object->id;
  3176. include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
  3177. }
  3178. }
  3179. // End of page
  3180. llxFooter();
  3181. $db->close();