card.php 162 KB

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