card.php 243 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588
  1. <?php
  2. /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  4. * Copyright (C) 2004-2020 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  6. * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  8. * Copyright (C) 2010-2015 Juanjo Menent <jmenent@2byte.es>
  9. * Copyright (C) 2012-2013 Christophe Battarel <christophe.battarel@altairis.fr>
  10. * Copyright (C) 2012-2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  11. * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  12. * Copyright (C) 2013 Jean-Francois FERRY <jfefe@aternatik.fr>
  13. * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
  14. * Copyright (C) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
  15. * Copyright (C) 2014-2019 Ferran Marcet <fmarcet@2byte.es>
  16. * Copyright (C) 2015-2016 Marcos García <marcosgdf@gmail.com>
  17. * Copyright (C) 2018-2021 Frédéric France <frederic.france@netlogic.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/compta/facture/card.php
  34. * \ingroup facture
  35. * \brief Page to create/see an invoice
  36. */
  37. require '../../main.inc.php';
  38. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  45. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
  46. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php';
  47. require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php';
  48. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  49. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  50. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  51. if (!empty($conf->commande->enabled)) {
  52. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  53. }
  54. if (!empty($conf->projet->enabled)) {
  55. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  56. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
  57. }
  58. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  59. if (!empty($conf->variants->enabled)) {
  60. require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  61. }
  62. if (!empty($conf->accounting->enabled)) {
  63. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
  64. }
  65. // Load translation files required by the page
  66. $langs->loadLangs(array('bills', 'companies', 'compta', 'products', 'banks', 'main', 'withdrawals'));
  67. if (!empty($conf->incoterm->enabled)) {
  68. $langs->load('incoterm');
  69. }
  70. if (!empty($conf->margin->enabled)) {
  71. $langs->load('margins');
  72. }
  73. $projectid = (GETPOST('projectid', 'int') ? GETPOST('projectid', 'int') : 0);
  74. $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('facid', 'int')); // For backward compatibility
  75. $ref = GETPOST('ref', 'alpha');
  76. $socid = GETPOST('socid', 'int');
  77. $action = GETPOST('action', 'aZ09');
  78. $confirm = GETPOST('confirm', 'alpha');
  79. $cancel = GETPOST('cancel', 'alpha');
  80. $lineid = GETPOST('lineid', 'int');
  81. $userid = GETPOST('userid', 'int');
  82. $search_ref = GETPOST('sf_ref', 'alpha') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha');
  83. $search_societe = GETPOST('search_societe', 'alpha');
  84. $search_montant_ht = GETPOST('search_montant_ht', 'alpha');
  85. $search_montant_ttc = GETPOST('search_montant_ttc', 'alpha');
  86. $origin = GETPOST('origin', 'alpha');
  87. $originid = (GETPOST('originid', 'int') ? GETPOST('originid', 'int') : GETPOST('origin_id', 'int')); // For backward compatibility
  88. $fac_rec = GETPOST('fac_rec', 'int');
  89. // PDF
  90. $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  91. $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
  92. $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  93. // Nombre de ligne pour choix de produit/service predefinis
  94. $NBLINES = 4;
  95. $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0);
  96. $object = new Facture($db);
  97. $extrafields = new ExtraFields($db);
  98. // Fetch optionals attributes and labels
  99. $extrafields->fetch_name_optionals_label($object->table_element);
  100. // Load object
  101. if ($id > 0 || !empty($ref)) {
  102. if ($action != 'add') {
  103. if (empty($conf->global->INVOICE_USE_SITUATION)) {
  104. $fetch_situation = false;
  105. } else {
  106. $fetch_situation = true;
  107. }
  108. $ret = $object->fetch($id, $ref, '', '', $fetch_situation);
  109. }
  110. }
  111. // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
  112. $hookmanager->initHooks(array('invoicecard', 'globalcard'));
  113. $usercanread = $user->rights->facture->lire;
  114. $usercancreate = $user->rights->facture->creer;
  115. $usercanissuepayment = $user->rights->facture->paiement;
  116. $usercandelete = $user->rights->facture->supprimer;
  117. $usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->validate)));
  118. $usercansend = (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->send)));
  119. $usercanreopen = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->reopen)));
  120. if (!empty($conf->global->INVOICE_DISALLOW_REOPEN)) {
  121. $usercanreopen = false;
  122. }
  123. $usercanunvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->facture->invoice_advance->unvalidate)));
  124. $usercanproductignorepricemin = ((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS));
  125. $usercancreatemargin = $user->rights->margins->creer;
  126. $usercanreadallmargin = $user->rights->margins->liretous;
  127. $usercancreatewithdrarequest = $user->rights->prelevement->bons->creer;
  128. $permissionnote = $usercancreate; // Used by the include of actions_setnotes.inc.php
  129. $permissiondellink = $usercancreate; // Used by the include of actions_dellink.inc.php
  130. $permissiontoedit = $usercancreate; // Used by the include of actions_lineupdonw.inc.php
  131. $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatedelete.inc.php
  132. // retained warranty invoice available type
  133. $retainedWarrantyInvoiceAvailableType = array();
  134. if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  135. $retainedWarrantyInvoiceAvailableType = explode('+', $conf->global->INVOICE_USE_RETAINED_WARRANTY);
  136. }
  137. // Security check
  138. $fieldid = (!empty($ref) ? 'ref' : 'rowid');
  139. if ($user->socid) {
  140. $socid = $user->socid;
  141. }
  142. $isdraft = (($object->statut == Facture::STATUS_DRAFT) ? 1 : 0);
  143. $result = restrictedArea($user, 'facture', $object->id, '', '', 'fk_soc', $fieldid, $isdraft);
  144. /*
  145. * Actions
  146. */
  147. $parameters = array('socid' => $socid);
  148. $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  149. if ($reshook < 0) {
  150. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  151. }
  152. if (empty($reshook)) {
  153. if ($cancel) {
  154. if (!empty($backtopage)) {
  155. header("Location: ".$backtopage);
  156. exit;
  157. }
  158. $action = '';
  159. }
  160. include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not include_once
  161. include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once
  162. include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once
  163. // Action clone object
  164. if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) {
  165. $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.
  166. $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int'));
  167. $objectutil->socid = $socid;
  168. $result = $objectutil->createFromClone($user, $id);
  169. if ($result > 0) {
  170. header("Location: ".$_SERVER['PHP_SELF'].'?facid='.$result);
  171. exit();
  172. } else {
  173. $langs->load("errors");
  174. setEventMessages($objectutil->error, $objectutil->errors, 'errors');
  175. $action = '';
  176. }
  177. } elseif ($action == 'reopen' && $usercanreopen) {
  178. $result = $object->fetch($id);
  179. if ($object->statut == Facture::STATUS_CLOSED || ($object->statut == Facture::STATUS_ABANDONED && ($object->close_code != 'replaced' || $object->getIdReplacingInvoice() == 0)) || ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 1)) { // ($object->statut == 1 && $object->paye == 1) should not happened but can be found when data are corrupted
  180. $result = $object->setUnpaid($user);
  181. if ($result > 0) {
  182. header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
  183. exit();
  184. } else {
  185. setEventMessages($object->error, $object->errors, 'errors');
  186. }
  187. }
  188. } elseif ($action == 'confirm_delete' && $confirm == 'yes') {
  189. // Delete invoice
  190. $result = $object->fetch($id);
  191. $object->fetch_thirdparty();
  192. $idwarehouse = GETPOST('idwarehouse');
  193. $qualified_for_stock_change = 0;
  194. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  195. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  196. } else {
  197. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  198. }
  199. $isErasable = $object->is_erasable();
  200. if (($usercandelete && $isErasable > 0)
  201. || ($usercancreate && $isErasable == 1)) {
  202. $result = $object->delete($user, 0, $idwarehouse);
  203. if ($result > 0) {
  204. header('Location: '.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1');
  205. exit();
  206. } else {
  207. setEventMessages($object->error, $object->errors, 'errors');
  208. $action = '';
  209. }
  210. }
  211. } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) {
  212. // Delete line
  213. $object->fetch($id);
  214. $object->fetch_thirdparty();
  215. $result = $object->deleteline(GETPOST('lineid', 'int'));
  216. if ($result > 0) {
  217. // Define output language
  218. $outputlangs = $langs;
  219. $newlang = '';
  220. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id')) {
  221. $newlang = GETPOST('lang_id');
  222. }
  223. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  224. $newlang = $object->thirdparty->default_lang;
  225. }
  226. if (!empty($newlang)) {
  227. $outputlangs = new Translate("", $conf);
  228. $outputlangs->setDefaultLang($newlang);
  229. $outputlangs->load('products');
  230. }
  231. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  232. $ret = $object->fetch($id); // Reload to get new records
  233. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  234. }
  235. if ($result >= 0) {
  236. header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
  237. exit();
  238. }
  239. } else {
  240. setEventMessages($object->error, $object->errors, 'errors');
  241. $action = '';
  242. }
  243. } elseif ($action == 'unlinkdiscount' && $usercancreate) {
  244. // Delete link of credit note to invoice
  245. $discount = new DiscountAbsolute($db);
  246. $result = $discount->fetch(GETPOST("discountid"));
  247. $discount->unlink_invoice();
  248. } elseif ($action == 'valid' && $usercancreate) {
  249. // Validation
  250. $object->fetch($id);
  251. // On verifie signe facture
  252. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  253. // Si avoir, le signe doit etre negatif
  254. if ($object->total_ht >= 0) {
  255. setEventMessages($langs->trans("ErrorInvoiceAvoirMustBeNegative"), null, 'errors');
  256. $action = '';
  257. }
  258. } else {
  259. // If not a credit note, amount with tax must be positive or nul.
  260. // Note that amount excluding tax can be negative because you can have a invoice of 100 with vat of 20 that
  261. // consumes a credit note of 100 with vat 0 (total with tax is 0 but without tax is -20).
  262. // For some cases, credit notes can have a vat of 0 (for example when selling goods in France).
  263. if (empty($conf->global->FACTURE_ENABLE_NEGATIVE) && $object->total_ttc < 0) {
  264. setEventMessages($langs->trans("ErrorInvoiceOfThisTypeMustBePositive"), null, 'errors');
  265. $action = '';
  266. }
  267. // Also negative lines should not be allowed on 'non Credit notes' invoices. A test is done when adding or updating lines but we must
  268. // do it again in validation to avoid cases where invoice is created from another object that allow negative lines.
  269. // Note that we can accept the negative line if sum with other lines with same vat makes total positive: Because all the lines will be merged together
  270. // when converted into 'available credit' and we will get a positive available credit line.
  271. // Note: Other solution if you want to add a negative line on invoice, is to create a discount for customer and consumme it (but this is possible on standard invoice only).
  272. $array_of_total_ht_per_vat_rate = array();
  273. $array_of_total_ht_devise_per_vat_rate = array();
  274. foreach ($object->lines as $line) {
  275. //$vat_src_code_for_line = $line->vat_src_code; // TODO We chek sign of total per vat without taking into account the vat code because for the moment the vat code is lost/unknown when we add a down payment.
  276. $vat_src_code_for_line = '';
  277. if (empty($array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) {
  278. $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0;
  279. }
  280. if (empty($array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line])) {
  281. $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] = 0;
  282. }
  283. $array_of_total_ht_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] += $line->total_ht;
  284. $array_of_total_ht_devise_per_vat_rate[$line->tva_tx.'_'.$vat_src_code_for_line] += $line->multicurrency_total_ht;
  285. }
  286. //var_dump($array_of_total_ht_per_vat_rate);exit;
  287. foreach ($array_of_total_ht_per_vat_rate as $vatrate => $tmpvalue) {
  288. $tmp_total_ht = price2num($array_of_total_ht_per_vat_rate[$vatrate]);
  289. $tmp_total_ht_devise = price2num($array_of_total_ht_devise_per_vat_rate[$vatrate]);
  290. if (($tmp_total_ht < 0 || $tmp_total_ht_devise < 0) && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  291. if ($object->type == $object::TYPE_DEPOSIT) {
  292. $langs->load("errors");
  293. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  294. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  295. $error++;
  296. $action = '';
  297. } else {
  298. $tmpvatratetoshow = explode('_', $vatrate);
  299. $tmpvatratetoshow[0] = round($tmpvatratetoshow[0], 2);
  300. if ($tmpvatratetoshow[0] != 0) {
  301. $langs->load("errors");
  302. setEventMessages($langs->trans("ErrorLinesCantBeNegativeForOneVATRate", $tmpvatratetoshow[0]), null, 'errors');
  303. $error++;
  304. $action = '';
  305. }
  306. }
  307. }
  308. }
  309. }
  310. } elseif ($action == 'classin' && $usercancreate) {
  311. $object->fetch($id);
  312. $object->setProject($_POST['projectid']);
  313. } elseif ($action == 'setmode' && $usercancreate) {
  314. $object->fetch($id);
  315. $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int'));
  316. if ($result < 0) {
  317. dol_print_error($db, $object->error);
  318. }
  319. } elseif ($action == 'setretainedwarrantyconditions' && $user->rights->facture->creer) {
  320. $object->fetch($id);
  321. $object->retained_warranty_fk_cond_reglement = 0; // To clean property
  322. $result = $object->setRetainedWarrantyPaymentTerms(GETPOST('retained_warranty_fk_cond_reglement', 'int'));
  323. if ($result < 0) {
  324. dol_print_error($db, $object->error);
  325. }
  326. $old_rw_date_lim_reglement = $object->retained_warranty_date_limit;
  327. $new_rw_date_lim_reglement = $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  328. if ($new_rw_date_lim_reglement > $old_rw_date_lim_reglement) {
  329. $object->retained_warranty_date_limit = $new_rw_date_lim_reglement;
  330. }
  331. if ($object->retained_warranty_date_limit < $object->date) {
  332. $object->retained_warranty_date_limit = $object->date;
  333. }
  334. $result = $object->update($user);
  335. if ($result < 0) {
  336. dol_print_error($db, $object->error);
  337. }
  338. } elseif ($action == 'setretainedwarranty' && $user->rights->facture->creer) {
  339. $object->fetch($id);
  340. $result = $object->setRetainedWarranty(GETPOST('retained_warranty', 'float'));
  341. if ($result < 0) {
  342. dol_print_error($db, $object->error);
  343. }
  344. } elseif ($action == 'setretainedwarrantydatelimit' && $user->rights->facture->creer) {
  345. $object->fetch($id);
  346. $result = $object->setRetainedWarrantyDateLimit(GETPOST('retained_warranty_date_limit', 'float'));
  347. if ($result < 0) {
  348. dol_print_error($db, $object->error);
  349. }
  350. } elseif ($action == 'setmulticurrencycode' && $usercancreate) { // Multicurrency Code
  351. $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha'));
  352. } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { // Multicurrency rate
  353. $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx')), GETPOST('calculation_mode', 'int'));
  354. } elseif ($action == 'setinvoicedate' && $usercancreate) {
  355. $object->fetch($id);
  356. $old_date_lim_reglement = $object->date_lim_reglement;
  357. $newdate = dol_mktime(0, 0, 0, GETPOST('invoicedatemonth', 'int'), GETPOST('invoicedateday', 'int'), GETPOST('invoicedateyear', 'int'), 'tzserver');
  358. if (empty($newdate)) {
  359. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  360. header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id.'&action=editinvoicedate&token='.newToken());
  361. exit;
  362. }
  363. if ($newdate > (dol_now('tzuserrel') + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  364. if (empty($conf->global->INVOICE_MAX_FUTURE_DELAY)) {
  365. setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings');
  366. } else {
  367. setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings');
  368. }
  369. }
  370. $object->date = $newdate;
  371. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  372. if ($new_date_lim_reglement > $old_date_lim_reglement) {
  373. $object->date_lim_reglement = $new_date_lim_reglement;
  374. }
  375. if ($object->date_lim_reglement < $object->date) {
  376. $object->date_lim_reglement = $object->date;
  377. }
  378. $result = $object->update($user);
  379. if ($result < 0) {
  380. dol_print_error($db, $object->error);
  381. }
  382. } elseif ($action == 'setdate_pointoftax' && $usercancreate) {
  383. $object->fetch($id);
  384. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  385. $object->date_pointoftax = $date_pointoftax;
  386. $result = $object->update($user);
  387. if ($result < 0) {
  388. dol_print_error($db, $object->error);
  389. }
  390. } elseif ($action == 'setconditions' && $usercancreate) {
  391. $object->fetch($id);
  392. $object->cond_reglement_code = 0; // To clean property
  393. $object->cond_reglement_id = 0; // To clean property
  394. $error = 0;
  395. $db->begin();
  396. if (!$error) {
  397. $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int'));
  398. if ($result < 0) {
  399. $error++;
  400. setEventMessages($object->error, $object->errors, 'errors');
  401. }
  402. }
  403. if (!$error) {
  404. $old_date_lim_reglement = $object->date_lim_reglement;
  405. $new_date_lim_reglement = $object->calculate_date_lim_reglement();
  406. if ($new_date_lim_reglement > $old_date_lim_reglement) {
  407. $object->date_lim_reglement = $new_date_lim_reglement;
  408. }
  409. if ($object->date_lim_reglement < $object->date) {
  410. $object->date_lim_reglement = $object->date;
  411. }
  412. $result = $object->update($user);
  413. if ($result < 0) {
  414. $error++;
  415. setEventMessages($object->error, $object->errors, 'errors');
  416. }
  417. }
  418. if ($error) {
  419. $db->rollback();
  420. } else {
  421. $db->commit();
  422. }
  423. } elseif ($action == 'setpaymentterm' && $usercancreate) {
  424. $object->fetch($id);
  425. $object->date_lim_reglement = dol_mktime(12, 0, 0, $_POST['paymenttermmonth'], $_POST['paymenttermday'], $_POST['paymenttermyear']);
  426. if ($object->date_lim_reglement < $object->date) {
  427. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  428. setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings');
  429. }
  430. $result = $object->update($user);
  431. if ($result < 0) {
  432. dol_print_error($db, $object->error);
  433. }
  434. } elseif ($action == 'setrevenuestamp' && $usercancreate) {
  435. $object->fetch($id);
  436. $object->revenuestamp = GETPOST('revenuestamp');
  437. $result = $object->update($user);
  438. $object->update_price(1);
  439. if ($result < 0) {
  440. dol_print_error($db, $object->error);
  441. } else {
  442. // Define output language
  443. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  444. $outputlangs = $langs;
  445. $newlang = '';
  446. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  447. $newlang = GETPOST('lang_id', 'aZ09');
  448. }
  449. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  450. $newlang = $object->thirdparty->default_lang;
  451. }
  452. if (!empty($newlang)) {
  453. $outputlangs = new Translate("", $conf);
  454. $outputlangs->setDefaultLang($newlang);
  455. $outputlangs->load('products');
  456. }
  457. $model = $object->model_pdf;
  458. $ret = $object->fetch($id); // Reload to get new records
  459. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  460. if ($result < 0) {
  461. setEventMessages($object->error, $object->errors, 'errors');
  462. }
  463. }
  464. }
  465. } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { // Set incoterm
  466. $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha'));
  467. } elseif ($action == 'setbankaccount' && $usercancreate) { // bank account
  468. $result = $object->setBankAccount(GETPOST('fk_account', 'int'));
  469. } elseif ($action == 'setremisepercent' && $usercancreate) {
  470. $object->fetch($id);
  471. $result = $object->setDiscount($user, price2num(GETPOST('remise_percent'), '', 2));
  472. } elseif ($action == "setabsolutediscount" && $usercancreate) {
  473. // POST[remise_id] or POST[remise_id_for_payment]
  474. // We use the credit to reduce amount of invoice
  475. if (GETPOST("remise_id", 'int') > 0) {
  476. $ret = $object->fetch($id);
  477. if ($ret > 0) {
  478. $result = $object->insert_discount(GETPOST("remise_id", 'int'));
  479. if ($result < 0) {
  480. setEventMessages($object->error, $object->errors, 'errors');
  481. }
  482. } else {
  483. dol_print_error($db, $object->error);
  484. }
  485. }
  486. // We use the credit to reduce remain to pay
  487. if (GETPOST("remise_id_for_payment", 'int') > 0) {
  488. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  489. $discount = new DiscountAbsolute($db);
  490. $discount->fetch(GETPOST("remise_id_for_payment", 'int'));
  491. //var_dump($object->getRemainToPay(0));
  492. //var_dump($discount->amount_ttc);exit;
  493. if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) {
  494. // TODO Split the discount in 2 automatically
  495. $error++;
  496. setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors');
  497. }
  498. if (!$error) {
  499. $result = $discount->link_to_invoice(0, $id);
  500. if ($result < 0) {
  501. setEventMessages($discount->error, $discount->errors, 'errors');
  502. }
  503. }
  504. }
  505. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  506. $outputlangs = $langs;
  507. $newlang = '';
  508. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  509. $newlang = GETPOST('lang_id', 'aZ09');
  510. }
  511. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  512. $newlang = $object->thirdparty->default_lang;
  513. }
  514. if (!empty($newlang)) {
  515. $outputlangs = new Translate("", $conf);
  516. $outputlangs->setDefaultLang($newlang);
  517. }
  518. $ret = $object->fetch($id); // Reload to get new records
  519. $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  520. if ($result < 0) {
  521. setEventMessages($object->error, $object->errors, 'errors');
  522. }
  523. }
  524. } elseif ($action == 'setref' && $usercancreate) {
  525. $object->fetch($id);
  526. $object->setValueFrom('ref', GETPOST('ref'), '', null, '', '', $user, 'BILL_MODIFY');
  527. } elseif ($action == 'setref_client' && $usercancreate) {
  528. $object->fetch($id);
  529. $object->set_ref_client(GETPOST('ref_client'));
  530. } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) {
  531. // Classify to validated
  532. $idwarehouse = GETPOST('idwarehouse', 'int');
  533. $object->fetch($id);
  534. $object->fetch_thirdparty();
  535. // Check parameters
  536. // Check for mandatory fields in thirdparty (defined into setup)
  537. $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL');
  538. foreach ($array_to_check as $key) {
  539. $keymin = strtolower($key);
  540. $i = (int) preg_replace('/[^0-9]/', '', $key);
  541. $vallabel = $object->thirdparty->$keymin;
  542. if ($i > 0) {
  543. if ($object->thirdparty->isACompany()) {
  544. // Check for mandatory prof id (but only if country is other than ours)
  545. if ($mysoc->country_id > 0 && $object->thirdparty->country_id == $mysoc->country_id) {
  546. $idprof_mandatory = 'SOCIETE_'.$key.'_INVOICE_MANDATORY';
  547. if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
  548. $langs->load("errors");
  549. $error++;
  550. setEventMessages($langs->trans('ErrorProdIdIsMandatory', $langs->transcountry('ProfId'.$i, $object->thirdparty->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')', null, 'errors');
  551. }
  552. }
  553. }
  554. } else {
  555. //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
  556. if ($key == 'EMAIL') {
  557. // Check for mandatory
  558. if (!empty($conf->global->SOCIETE_EMAIL_INVOICE_MANDATORY) && !isValidEMail($object->thirdparty->email)) {
  559. $langs->load("errors");
  560. $error++;
  561. setEventMessages($langs->trans("ErrorBadEMail", $object->thirdparty->email).' ('.$langs->trans("ForbiddenBySetupRules").')', null, 'errors');
  562. }
  563. }
  564. }
  565. }
  566. // Check for mandatory fields in invoice
  567. $array_to_check = array('REF_CLIENT'=>'RefCustomer');
  568. foreach ($array_to_check as $key => $val) {
  569. $keymin = strtolower($key);
  570. $vallabel = $object->$keymin;
  571. // Check for mandatory
  572. $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION';
  573. if (!$vallabel && !empty($conf->global->$keymandatory)) {
  574. $langs->load("errors");
  575. $error++;
  576. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val)), null, 'errors');
  577. }
  578. }
  579. // Check for warehouse
  580. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  581. $qualified_for_stock_change = 0;
  582. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  583. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  584. } else {
  585. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  586. }
  587. if ($qualified_for_stock_change) {
  588. if (!$idwarehouse || $idwarehouse == - 1) {
  589. $error++;
  590. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  591. $action = '';
  592. }
  593. }
  594. }
  595. if (!$error) {
  596. $result = $object->validate($user, '', $idwarehouse);
  597. if ($result >= 0) {
  598. // Define output language
  599. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  600. $outputlangs = $langs;
  601. $newlang = '';
  602. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  603. $newlang = GETPOST('lang_id', 'aZ09');
  604. }
  605. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  606. $newlang = $object->thirdparty->default_lang;
  607. }
  608. if (!empty($newlang)) {
  609. $outputlangs = new Translate("", $conf);
  610. $outputlangs->setDefaultLang($newlang);
  611. $outputlangs->load('products');
  612. }
  613. $model = $object->model_pdf;
  614. $ret = $object->fetch($id); // Reload to get new records
  615. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  616. if ($result < 0) {
  617. setEventMessages($object->error, $object->errors, 'errors');
  618. }
  619. }
  620. } else {
  621. if (count($object->errors)) {
  622. setEventMessages(null, $object->errors, 'errors');
  623. } else {
  624. setEventMessages($object->error, $object->errors, 'errors');
  625. }
  626. }
  627. }
  628. } elseif ($action == 'confirm_modif' && $usercanunvalidate) {
  629. // Go back to draft status (unvalidate)
  630. $idwarehouse = GETPOST('idwarehouse', 'int');
  631. $object->fetch($id);
  632. $object->fetch_thirdparty();
  633. // Check parameters
  634. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  635. $qualified_for_stock_change = 0;
  636. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  637. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  638. } else {
  639. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  640. }
  641. if ($qualified_for_stock_change) {
  642. if (!$idwarehouse || $idwarehouse == - 1) {
  643. $error++;
  644. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors');
  645. $action = '';
  646. }
  647. }
  648. }
  649. if (!$error) {
  650. // On verifie si la facture a des paiements
  651. $sql = 'SELECT pf.amount';
  652. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf';
  653. $sql .= ' WHERE pf.fk_facture = '.$object->id;
  654. $result = $db->query($sql);
  655. if ($result) {
  656. $i = 0;
  657. $num = $db->num_rows($result);
  658. while ($i < $num) {
  659. $objp = $db->fetch_object($result);
  660. $totalpaye += $objp->amount;
  661. $i++;
  662. }
  663. } else {
  664. dol_print_error($db, '');
  665. }
  666. $resteapayer = $object->total_ttc - $totalpaye;
  667. // We check that invlice lines are transferred into accountancy
  668. $ventilExportCompta = $object->getVentilExportCompta();
  669. // On verifie si aucun paiement n'a ete effectue
  670. if ($ventilExportCompta == 0) {
  671. if (!empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == $object->total_ttc && empty($object->paye))) {
  672. $result = $object->setDraft($user, $idwarehouse);
  673. if ($result < 0) {
  674. setEventMessages($object->error, $object->errors, 'errors');
  675. }
  676. // Define output language
  677. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  678. $outputlangs = $langs;
  679. $newlang = '';
  680. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  681. $newlang = GETPOST('lang_id', 'aZ09');
  682. }
  683. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  684. $newlang = $object->thirdparty->default_lang;
  685. }
  686. if (!empty($newlang)) {
  687. $outputlangs = new Translate("", $conf);
  688. $outputlangs->setDefaultLang($newlang);
  689. $outputlangs->load('products');
  690. }
  691. $model = $object->model_pdf;
  692. $ret = $object->fetch($id); // Reload to get new records
  693. $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  694. }
  695. }
  696. }
  697. }
  698. } elseif ($action == 'confirm_paid' && $confirm == 'yes' && $usercanissuepayment) {
  699. // Classify "paid"
  700. $object->fetch($id);
  701. $result = $object->setPaid($user);
  702. if ($result < 0) {
  703. setEventMessages($object->error, $object->errors, 'errors');
  704. }
  705. } elseif ($action == 'confirm_paid_partially' && $confirm == 'yes' && $usercanissuepayment) {
  706. // Classif "paid partialy"
  707. $object->fetch($id);
  708. $close_code = GETPOST("close_code", 'restricthtml');
  709. $close_note = GETPOST("close_note", 'restricthtml');
  710. if ($close_code) {
  711. $result = $object->setPaid($user, $close_code, $close_note);
  712. if ($result < 0) {
  713. setEventMessages($object->error, $object->errors, 'errors');
  714. }
  715. } else {
  716. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  717. }
  718. } elseif ($action == 'confirm_canceled' && $confirm == 'yes') {
  719. // Classify "abandoned"
  720. $object->fetch($id);
  721. $close_code = GETPOST("close_code", 'restricthtml');
  722. $close_note = GETPOST("close_note", 'restricthtml');
  723. if ($close_code) {
  724. $result = $object->setCanceled($user, $close_code, $close_note);
  725. if ($result < 0) {
  726. setEventMessages($object->error, $object->errors, 'errors');
  727. }
  728. } else {
  729. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Reason")), null, 'errors');
  730. }
  731. } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) {
  732. // Convertir en reduc
  733. $object->fetch($id);
  734. $object->fetch_thirdparty();
  735. //$object->fetch_lines(); // Already done into fetch
  736. // Check if there is already a discount (protection to avoid duplicate creation when resubmit post)
  737. $discountcheck = new DiscountAbsolute($db);
  738. $result = $discountcheck->fetch(0, $object->id);
  739. $canconvert = 0;
  740. if ($object->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) {
  741. $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc)
  742. }
  743. if (($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->paye == 0 && empty($discountcheck->id)) {
  744. $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc)
  745. }
  746. if ($canconvert) {
  747. $db->begin();
  748. $amount_ht = $amount_tva = $amount_ttc = array();
  749. $multicurrency_amount_ht = $multicurrency_amount_tva = $multicurrency_amount_ttc = array();
  750. // Loop on each vat rate
  751. $i = 0;
  752. foreach ($object->lines as $line) {
  753. 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
  754. $keyforvatrate = $line->tva_tx.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : '');
  755. $amount_ht[$keyforvatrate] += $line->total_ht;
  756. $amount_tva[$keyforvatrate] += $line->total_tva;
  757. $amount_ttc[$keyforvatrate] += $line->total_ttc;
  758. $multicurrency_amount_ht[$keyforvatrate] += $line->multicurrency_total_ht;
  759. $multicurrency_amount_tva[$keyforvatrate] += $line->multicurrency_total_tva;
  760. $multicurrency_amount_ttc[$keyforvatrate] += $line->multicurrency_total_ttc;
  761. $i++;
  762. }
  763. }
  764. // If some payments were already done, we change the amount to pay using same prorate
  765. if (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) && $object->type == Facture::TYPE_CREDIT_NOTE) {
  766. $alreadypaid = $object->getSommePaiement(); // This can be not 0 if we allow to create credit to reuse from credit notes partially refunded.
  767. if ($alreadypaid && abs($alreadypaid) < abs($object->total_ttc)) {
  768. $ratio = abs(($object->total_ttc - $alreadypaid) / $object->total_ttc);
  769. foreach ($amount_ht as $vatrate => $val) {
  770. $amount_ht[$vatrate] = price2num($amount_ht[$vatrate] * $ratio, 'MU');
  771. $amount_tva[$vatrate] = price2num($amount_tva[$vatrate] * $ratio, 'MU');
  772. $amount_ttc[$vatrate] = price2num($amount_ttc[$vatrate] * $ratio, 'MU');
  773. $multicurrency_amount_ht[$vatrate] = price2num($multicurrency_amount_ht[$vatrate] * $ratio, 'MU');
  774. $multicurrency_amount_tva[$vatrate] = price2num($multicurrency_amount_tva[$vatrate] * $ratio, 'MU');
  775. $multicurrency_amount_ttc[$vatrate] = price2num($multicurrency_amount_ttc[$vatrate] * $ratio, 'MU');
  776. }
  777. }
  778. }
  779. //var_dump($amount_ht);var_dump($amount_tva);var_dump($amount_ttc);exit;
  780. // Insert one discount by VAT rate category
  781. $discount = new DiscountAbsolute($db);
  782. if ($object->type == Facture::TYPE_CREDIT_NOTE) {
  783. $discount->description = '(CREDIT_NOTE)';
  784. } elseif ($object->type == Facture::TYPE_DEPOSIT) {
  785. $discount->description = '(DEPOSIT)';
  786. } elseif ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) {
  787. $discount->description = '(EXCESS RECEIVED)';
  788. } else {
  789. setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors');
  790. }
  791. $discount->fk_soc = $object->socid;
  792. $discount->fk_facture_source = $object->id;
  793. $error = 0;
  794. if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_SITUATION) {
  795. // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT
  796. // Total payments
  797. $sql = 'SELECT SUM(pf.amount) as total_paiements';
  798. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
  799. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
  800. $sql .= ' WHERE pf.fk_facture = '.$object->id;
  801. $sql .= ' AND pf.fk_paiement = p.rowid';
  802. $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
  803. $resql = $db->query($sql);
  804. if (!$resql) {
  805. dol_print_error($db);
  806. }
  807. $res = $db->fetch_object($resql);
  808. $total_paiements = $res->total_paiements;
  809. // Total credit note and deposit
  810. $total_creditnote_and_deposit = 0;
  811. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  812. $sql .= " re.description, re.fk_facture_source";
  813. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  814. $sql .= " WHERE fk_facture = ".$object->id;
  815. $resql = $db->query($sql);
  816. if (!empty($resql)) {
  817. while ($obj = $db->fetch_object($resql)) {
  818. $total_creditnote_and_deposit += $obj->amount_ttc;
  819. }
  820. } else {
  821. dol_print_error($db);
  822. }
  823. $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc;
  824. $discount->amount_tva = 0;
  825. $discount->tva_tx = 0;
  826. $discount->vat_src_code = '';
  827. $result = $discount->create($user);
  828. if ($result < 0) {
  829. $error++;
  830. }
  831. }
  832. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  833. foreach ($amount_ht as $tva_tx => $xxx) {
  834. $discount->amount_ht = abs($amount_ht[$tva_tx]);
  835. $discount->amount_tva = abs($amount_tva[$tva_tx]);
  836. $discount->amount_ttc = abs($amount_ttc[$tva_tx]);
  837. $discount->multicurrency_amount_ht = abs($multicurrency_amount_ht[$tva_tx]);
  838. $discount->multicurrency_amount_tva = abs($multicurrency_amount_tva[$tva_tx]);
  839. $discount->multicurrency_amount_ttc = abs($multicurrency_amount_ttc[$tva_tx]);
  840. // Clean vat code
  841. $reg = array();
  842. $vat_src_code = '';
  843. if (preg_match('/\((.*)\)/', $tva_tx, $reg)) {
  844. $vat_src_code = $reg[1];
  845. $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx); // Remove code into vatrate.
  846. }
  847. $discount->tva_tx = abs($tva_tx);
  848. $discount->vat_src_code = $vat_src_code;
  849. $result = $discount->create($user);
  850. if ($result < 0) {
  851. $error++;
  852. break;
  853. }
  854. }
  855. }
  856. if (empty($error)) {
  857. if ($object->type != Facture::TYPE_DEPOSIT) {
  858. // Classe facture
  859. $result = $object->setPaid($user);
  860. if ($result >= 0) {
  861. $db->commit();
  862. } else {
  863. setEventMessages($object->error, $object->errors, 'errors');
  864. $db->rollback();
  865. }
  866. } else {
  867. $db->commit();
  868. }
  869. } else {
  870. setEventMessages($discount->error, $discount->errors, 'errors');
  871. $db->rollback();
  872. }
  873. }
  874. } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) {
  875. // Delete payment
  876. $object->fetch($id);
  877. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0) {
  878. $paiement = new Paiement($db);
  879. $result = $paiement->fetch(GETPOST('paiement_id'));
  880. if ($result > 0) {
  881. $result = $paiement->delete(); // If fetch ok and found
  882. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  883. }
  884. if ($result < 0) {
  885. setEventMessages($paiement->error, $paiement->errors, 'errors');
  886. }
  887. }
  888. } elseif ($action == 'add' && $usercancreate) {
  889. // Insert new invoice in database
  890. if ($socid > 0) {
  891. $object->socid = GETPOST('socid', 'int');
  892. }
  893. $selectedLines = GETPOST('toselect', 'array');
  894. $db->begin();
  895. $error = 0;
  896. $originentity = GETPOST('originentity');
  897. // Fill array 'array_options' with data from add form
  898. $ret = $extrafields->setOptionalsFromPost(null, $object);
  899. if ($ret < 0) {
  900. $error++;
  901. }
  902. $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
  903. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  904. // Replacement invoice
  905. if (GETPOST('type') == Facture::TYPE_REPLACEMENT) {
  906. if (empty($dateinvoice)) {
  907. $error++;
  908. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  909. $action = 'create';
  910. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  911. $error++;
  912. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  913. $action = 'create';
  914. }
  915. if (!(GETPOST('fac_replacement', 'int') > 0)) {
  916. $error++;
  917. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ReplaceInvoice")), null, 'errors');
  918. $action = 'create';
  919. }
  920. if (!$error) {
  921. // This is a replacement invoice
  922. $result = $object->fetch(GETPOST('fac_replacement', 'int'));
  923. $object->fetch_thirdparty();
  924. $object->date = $dateinvoice;
  925. $object->date_pointoftax = $date_pointoftax;
  926. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  927. // We do not copy the private note
  928. $object->ref_client = GETPOST('ref_client', 'alphanohtml');
  929. $object->model_pdf = GETPOST('model', 'alphanohtml');
  930. $object->fk_project = GETPOST('projectid', 'int');
  931. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  932. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  933. $object->fk_account = GETPOST('fk_account', 'int');
  934. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU', 2);
  935. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  936. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  937. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  938. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  939. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  940. // Proprietes particulieres a facture de remplacement
  941. $object->fk_facture_source = GETPOST('fac_replacement', 'int');
  942. $object->type = Facture::TYPE_REPLACEMENT;
  943. $id = $object->createFromCurrent($user);
  944. if ($id <= 0) {
  945. setEventMessages($object->error, $object->errors, 'errors');
  946. }
  947. }
  948. }
  949. // Credit note invoice
  950. if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) {
  951. $sourceinvoice = GETPOST('fac_avoir', 'int');
  952. if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  953. $error++;
  954. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors');
  955. $action = 'create';
  956. }
  957. if (empty($dateinvoice)) {
  958. $error++;
  959. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  960. $action = 'create';
  961. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  962. $error++;
  963. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  964. $action = 'create';
  965. }
  966. if (!$error) {
  967. if (!empty($originentity)) {
  968. $object->entity = $originentity;
  969. }
  970. $object->socid = GETPOST('socid', 'int');
  971. $object->ref = GETPOST('ref');
  972. $object->date = $dateinvoice;
  973. $object->date_pointoftax = $date_pointoftax;
  974. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  975. // We do not copy the private note
  976. $object->ref_client = GETPOST('ref_client');
  977. $object->model_pdf = GETPOST('model');
  978. $object->fk_project = GETPOST('projectid', 'int');
  979. $object->cond_reglement_id = 0; // No payment term for a credit note
  980. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  981. $object->fk_account = GETPOST('fk_account', 'int');
  982. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  983. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  984. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  985. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  986. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  987. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  988. // Proprietes particulieres a facture avoir
  989. $object->fk_facture_source = $sourceinvoice > 0 ? $sourceinvoice : '';
  990. $object->type = Facture::TYPE_CREDIT_NOTE;
  991. $facture_source = new Facture($db); // fetch origin object
  992. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  993. if ($facture_source->type == Facture::TYPE_SITUATION) {
  994. $object->situation_counter = $facture_source->situation_counter;
  995. $object->situation_cycle_ref = $facture_source->situation_cycle_ref;
  996. $facture_source->fetchPreviousNextSituationInvoice();
  997. }
  998. }
  999. $id = $object->create($user);
  1000. if ($id < 0) {
  1001. $error++;
  1002. } else {
  1003. // copy internal contacts
  1004. if ($object->copy_linked_contact($facture_source, 'internal') < 0) {
  1005. $error++;
  1006. } elseif ($facture_source->socid == $object->socid) {
  1007. // copy external contacts if same company
  1008. if ($object->copy_linked_contact($facture_source, 'external') < 0) {
  1009. $error++;
  1010. }
  1011. }
  1012. }
  1013. // NOTE: Pb with situation invoice
  1014. // NOTE: fields total on situation invoice are stored as cumulative values on total of lines (bad) but delta on invoice total
  1015. // NOTE: fields total on credit note are stored as delta both on total of lines and on invoice total (good)
  1016. // NOTE: fields situation_percent on situation invoice are stored as cumulative values on lines (bad)
  1017. // NOTE: fields situation_percent on credit note are stored as delta on lines (good)
  1018. if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) {
  1019. if (!empty($facture_source->lines)) {
  1020. $fk_parent_line = 0;
  1021. foreach ($facture_source->lines as $line) {
  1022. // Extrafields
  1023. if (method_exists($line, 'fetch_optionals')) {
  1024. // load extrafields
  1025. $line->fetch_optionals();
  1026. }
  1027. // Reset fk_parent_line for no child products and special product
  1028. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  1029. $fk_parent_line = 0;
  1030. }
  1031. if ($facture_source->type == Facture::TYPE_SITUATION) {
  1032. $source_fk_prev_id = $line->fk_prev_id; // temporary storing situation invoice fk_prev_id
  1033. $line->fk_prev_id = $line->id; // The new line of the new credit note we are creating must be linked to the situation invoice line it is created from
  1034. if (!empty($facture_source->tab_previous_situation_invoice)) {
  1035. // search the last standard invoice in cycle and the possible credit note between this last and facture_source
  1036. // TODO Move this out of loop of $facture_source->lines
  1037. $tab_jumped_credit_notes = array();
  1038. $lineIndex = count($facture_source->tab_previous_situation_invoice) - 1;
  1039. $searchPreviousInvoice = true;
  1040. while ($searchPreviousInvoice) {
  1041. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  1042. $searchPreviousInvoice = false; // find, exit;
  1043. break;
  1044. } else {
  1045. if ($facture_source->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_CREDIT_NOTE) {
  1046. $tab_jumped_credit_notes[$lineIndex] = $facture_source->tab_previous_situation_invoice[$lineIndex]->id;
  1047. }
  1048. $lineIndex--; // go to previous invoice in cycle
  1049. }
  1050. }
  1051. $maxPrevSituationPercent = 0;
  1052. foreach ($facture_source->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  1053. if ($prevLine->id == $source_fk_prev_id) {
  1054. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  1055. //$line->subprice = $line->subprice - $prevLine->subprice;
  1056. $line->total_ht = $line->total_ht - $prevLine->total_ht;
  1057. $line->total_tva = $line->total_tva - $prevLine->total_tva;
  1058. $line->total_ttc = $line->total_ttc - $prevLine->total_ttc;
  1059. $line->total_localtax1 = $line->total_localtax1 - $prevLine->total_localtax1;
  1060. $line->total_localtax2 = $line->total_localtax2 - $prevLine->total_localtax2;
  1061. $line->multicurrency_subprice = $line->multicurrency_subprice - $prevLine->multicurrency_subprice;
  1062. $line->multicurrency_total_ht = $line->multicurrency_total_ht - $prevLine->multicurrency_total_ht;
  1063. $line->multicurrency_total_tva = $line->multicurrency_total_tva - $prevLine->multicurrency_total_tva;
  1064. $line->multicurrency_total_ttc = $line->multicurrency_total_ttc - $prevLine->multicurrency_total_ttc;
  1065. }
  1066. }
  1067. // prorata
  1068. $line->situation_percent = $maxPrevSituationPercent - $line->situation_percent;
  1069. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1070. // If there is some credit note between last situation invoice and invoice used for credit note generation (note: credit notes are stored as delta)
  1071. $maxPrevSituationPercent = 0;
  1072. foreach ($tab_jumped_credit_notes as $index => $creditnoteid) {
  1073. foreach ($facture_source->tab_previous_situation_invoice[$index]->lines as $prevLine) {
  1074. if ($prevLine->fk_prev_id == $source_fk_prev_id) {
  1075. $maxPrevSituationPercent = $prevLine->situation_percent;
  1076. $line->total_ht -= $prevLine->total_ht;
  1077. $line->total_tva -= $prevLine->total_tva;
  1078. $line->total_ttc -= $prevLine->total_ttc;
  1079. $line->total_localtax1 -= $prevLine->total_localtax1;
  1080. $line->total_localtax2 -= $prevLine->total_localtax2;
  1081. $line->multicurrency_subprice -= $prevLine->multicurrency_subprice;
  1082. $line->multicurrency_total_ht -= $prevLine->multicurrency_total_ht;
  1083. $line->multicurrency_total_tva -= $prevLine->multicurrency_total_tva;
  1084. $line->multicurrency_total_ttc -= $prevLine->multicurrency_total_ttc;
  1085. }
  1086. }
  1087. }
  1088. // prorata
  1089. $line->situation_percent += $maxPrevSituationPercent;
  1090. //print 'New line based on invoice id '.$facture_source->tab_previous_situation_invoice[$lineIndex]->id.' fk_prev_id='.$source_fk_prev_id.' will be fk_prev_id='.$line->fk_prev_id.' '.$line->total_ht.' '.$line->situation_percent.'<br>';
  1091. }
  1092. }
  1093. $line->fk_facture = $object->id;
  1094. $line->fk_parent_line = $fk_parent_line;
  1095. $line->subprice = -$line->subprice; // invert price for object
  1096. $line->pa_ht = $line->pa_ht; // we choosed to have buy/cost price always positive, so no revert of sign here
  1097. $line->total_ht = -$line->total_ht;
  1098. $line->total_tva = -$line->total_tva;
  1099. $line->total_ttc = -$line->total_ttc;
  1100. $line->total_localtax1 = -$line->total_localtax1;
  1101. $line->total_localtax2 = -$line->total_localtax2;
  1102. $line->multicurrency_subprice = -$line->multicurrency_subprice;
  1103. $line->multicurrency_total_ht = -$line->multicurrency_total_ht;
  1104. $line->multicurrency_total_tva = -$line->multicurrency_total_tva;
  1105. $line->multicurrency_total_ttc = -$line->multicurrency_total_ttc;
  1106. $result = $line->insert(0, 1); // When creating credit note with same lines than source, we must ignore error if discount alreayd linked
  1107. $object->lines[] = $line; // insert new line in current object
  1108. // Defined the new fk_parent_line
  1109. if ($result > 0 && $line->product_type == 9) {
  1110. $fk_parent_line = $result;
  1111. }
  1112. }
  1113. $object->update_price(1);
  1114. }
  1115. }
  1116. if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) {
  1117. if ($facture_source->fetch($object->fk_facture_source) > 0) {
  1118. $totalpaye = $facture_source->getSommePaiement();
  1119. $totalcreditnotes = $facture_source->getSumCreditNotesUsed();
  1120. $totaldeposits = $facture_source->getSumDepositsUsed();
  1121. $remain_to_pay = abs($facture_source->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits);
  1122. $object->addline($langs->trans('invoiceAvoirLineWithPaymentRestAmount'), $remain_to_pay, 1, 0, 0, 0, 0, 0, '', '', 'TTC');
  1123. }
  1124. }
  1125. // Add link between credit note and origin
  1126. if (!empty($object->fk_facture_source) && $id > 0) {
  1127. $facture_source->fetch($object->fk_facture_source);
  1128. $facture_source->fetchObjectLinked();
  1129. if (!empty($facture_source->linkedObjectsIds)) {
  1130. foreach ($facture_source->linkedObjectsIds as $sourcetype => $TIds) {
  1131. $object->add_object_linked($sourcetype, current($TIds));
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. // Standard invoice or Deposit invoice, created from a Predefined template invoice
  1138. if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT) && GETPOST('fac_rec', 'int') > 0) {
  1139. if (empty($dateinvoice)) {
  1140. $error++;
  1141. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1142. $action = 'create';
  1143. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1144. $error++;
  1145. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1146. $action = 'create';
  1147. }
  1148. if (!$error) {
  1149. $object->socid = GETPOST('socid', 'int');
  1150. $object->type = GETPOST('type');
  1151. $object->ref = GETPOST('ref');
  1152. $object->date = $dateinvoice;
  1153. $object->date_pointoftax = $date_pointoftax;
  1154. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1155. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1156. $object->ref_client = GETPOST('ref_client');
  1157. $object->model_pdf = GETPOST('model');
  1158. $object->fk_project = GETPOST('projectid', 'int');
  1159. $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  1160. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1161. $object->fk_account = GETPOST('fk_account', 'int');
  1162. $object->amount = price2num(GETPOST('amount'));
  1163. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1164. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1165. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1166. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1167. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1168. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1169. // Source facture
  1170. $object->fac_rec = GETPOST('fac_rec', 'int');
  1171. $id = $object->create($user); // This include recopy of links from recurring invoice and recurring invoice lines
  1172. }
  1173. }
  1174. // Standard or deposit invoice, not from a Predefined template invoice
  1175. if ((GETPOST('type') == Facture::TYPE_STANDARD || GETPOST('type') == Facture::TYPE_DEPOSIT || GETPOST('type') == Facture::TYPE_PROFORMA || (GETPOST('type') == Facture::TYPE_SITUATION && !GETPOST('situations'))) && GETPOST('fac_rec') <= 0) {
  1176. $typeamount = GETPOST('typedeposit', 'aZ09');
  1177. $valuestandardinvoice = price2num(str_replace('%', '', GETPOST('valuestandardinvoice', 'alpha')), 'MU');
  1178. $valuedeposit = price2num(str_replace('%', '', GETPOST('valuedeposit', 'alpha')), 'MU');
  1179. if (GETPOST('socid', 'int') < 1) {
  1180. $error++;
  1181. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Customer")), null, 'errors');
  1182. $action = 'create';
  1183. }
  1184. if (empty($dateinvoice)) {
  1185. $error++;
  1186. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
  1187. $action = 'create';
  1188. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1189. $error++;
  1190. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1191. $action = 'create';
  1192. }
  1193. if (GETPOST('type') == Facture::TYPE_STANDARD) {
  1194. if ($valuestandardinvoice < 0 || $valuestandardinvoice > 100) {
  1195. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1196. $error++;
  1197. $action = 'create';
  1198. }
  1199. } elseif (GETPOST('type') == Facture::TYPE_DEPOSIT) {
  1200. if ($typeamount && !empty($origin) && !empty($originid)) {
  1201. if ($typeamount == 'amount' && $valuedeposit <= 0) {
  1202. setEventMessages($langs->trans("ErrorAnAmountWithoutTaxIsRequired"), null, 'errors');
  1203. $error++;
  1204. $action = 'create';
  1205. }
  1206. if ($typeamount == 'variable' && $valuedeposit <= 0) {
  1207. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1208. $error++;
  1209. $action = 'create';
  1210. }
  1211. if ($typeamount == 'variablealllines' && $valuedeposit <= 0) {
  1212. setEventMessages($langs->trans("ErrorAPercentIsRequired"), null, 'errors');
  1213. $error++;
  1214. $action = 'create';
  1215. }
  1216. }
  1217. }
  1218. if (!$error) {
  1219. // Si facture standard
  1220. $object->socid = GETPOST('socid', 'int');
  1221. $object->type = GETPOST('type');
  1222. $object->ref = GETPOST('ref');
  1223. $object->date = $dateinvoice;
  1224. $object->date_pointoftax = $date_pointoftax;
  1225. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1226. $object->note_private = trim(GETPOST('note_private', 'restricthtml'));
  1227. $object->ref_client = GETPOST('ref_client');
  1228. $object->model_pdf = GETPOST('model');
  1229. $object->fk_project = GETPOST('projectid', 'int');
  1230. $object->cond_reglement_id = (GETPOST('type') == 3 ? 1 : GETPOST('cond_reglement_id'));
  1231. $object->mode_reglement_id = GETPOST('mode_reglement_id');
  1232. $object->fk_account = GETPOST('fk_account', 'int');
  1233. $object->amount = price2num(GETPOST('amount'));
  1234. $object->remise_absolue = price2num(GETPOST('remise_absolue'), 'MU');
  1235. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1236. $object->fk_incoterms = GETPOST('incoterm_id', 'int');
  1237. $object->location_incoterms = GETPOST('location_incoterms', 'alpha');
  1238. $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha');
  1239. $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int');
  1240. if (GETPOST('type') == Facture::TYPE_SITUATION) {
  1241. $object->situation_counter = 1;
  1242. $object->situation_final = 0;
  1243. $object->situation_cycle_ref = $object->newCycle();
  1244. }
  1245. if (in_array($object->type, $retainedWarrantyInvoiceAvailableType)) {
  1246. $object->retained_warranty = GETPOST('retained_warranty', 'int');
  1247. $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  1248. } else {
  1249. $object->retained_warranty = 0;
  1250. $object->retained_warranty_fk_cond_reglement = 0;
  1251. }
  1252. $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
  1253. if (!empty($retained_warranty_date_limit) && dol_stringtotime($retained_warranty_date_limit)) {
  1254. $object->retained_warranty_date_limit = dol_stringtotime($retained_warranty_date_limit);
  1255. }
  1256. $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  1257. $object->fetch_thirdparty();
  1258. // If creation from another object of another module (Example: origin=propal, originid=1)
  1259. if (!empty($origin) && !empty($originid)) {
  1260. $regs = array();
  1261. // Parse element/subelement (ex: project_task)
  1262. $element = $subelement = $origin;
  1263. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  1264. $element = $regs[1];
  1265. $subelement = $regs[2];
  1266. }
  1267. // For compatibility
  1268. if ($element == 'order') {
  1269. $element = $subelement = 'commande';
  1270. }
  1271. if ($element == 'propal') {
  1272. $element = 'comm/propal';
  1273. $subelement = 'propal';
  1274. }
  1275. if ($element == 'contract') {
  1276. $element = $subelement = 'contrat';
  1277. }
  1278. if ($element == 'inter') {
  1279. $element = $subelement = 'ficheinter';
  1280. }
  1281. if ($element == 'shipping') {
  1282. $element = $subelement = 'expedition';
  1283. }
  1284. $object->origin = $origin;
  1285. $object->origin_id = $originid;
  1286. // Possibility to add external linked objects with hooks
  1287. $object->linked_objects[$object->origin] = $object->origin_id;
  1288. // link with order if it is a shipping invoice
  1289. if ($object->origin == 'shipping') {
  1290. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  1291. $exp = new Expedition($db);
  1292. $exp->fetch($object->origin_id);
  1293. $exp->fetchObjectLinked();
  1294. if (is_array($exp->linkedObjectsIds['commande']) && count($exp->linkedObjectsIds['commande']) > 0) {
  1295. foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
  1296. $object->linked_objects['commande'] = $value;
  1297. }
  1298. }
  1299. }
  1300. if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) {
  1301. $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']);
  1302. }
  1303. $id = $object->create($user); // This include class to add_object_linked() and add add_contact()
  1304. if ($id > 0) {
  1305. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  1306. $classname = ucfirst($subelement);
  1307. $srcobject = new $classname($db);
  1308. dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines or deposit lines");
  1309. $result = $srcobject->fetch($object->origin_id);
  1310. // If deposit invoice - down payment with 1 line (fixed amount or percent)
  1311. if (GETPOST('type') == Facture::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable'))) {
  1312. // Define the array $amountdeposit
  1313. $amountdeposit = array();
  1314. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA)) {
  1315. if ($typeamount == 'amount') {
  1316. $amount = $valuedeposit;
  1317. } else {
  1318. $amount = $srcobject->total_ttc * ($valuedeposit / 100);
  1319. }
  1320. $TTotalByTva = array();
  1321. foreach ($srcobject->lines as &$line) {
  1322. if (!empty($line->special_code)) {
  1323. continue;
  1324. }
  1325. $TTotalByTva[$line->tva_tx] += $line->total_ttc;
  1326. }
  1327. foreach ($TTotalByTva as $tva => &$total) {
  1328. $coef = $total / $srcobject->total_ttc; // Calc coef
  1329. $am = $amount * $coef;
  1330. $amount_ttc_diff += $am;
  1331. $amountdeposit[$tva] += $am / (1 + $tva / 100); // Convert into HT for the addline
  1332. }
  1333. } else {
  1334. if ($typeamount == 'amount') {
  1335. $amountdeposit[0] = $valuedeposit;
  1336. } elseif ($typeamount == 'variable') {
  1337. if ($result > 0) {
  1338. $totalamount = 0;
  1339. $lines = $srcobject->lines;
  1340. $numlines = count($lines);
  1341. for ($i = 0; $i < $numlines; $i++) {
  1342. $qualified = 1;
  1343. if (empty($lines[$i]->qty)) {
  1344. $qualified = 0; // We discard qty=0, it is an option
  1345. }
  1346. if (!empty($lines[$i]->special_code)) {
  1347. $qualified = 0; // We discard special_code (frais port, ecotaxe, option, ...)
  1348. }
  1349. if ($qualified) {
  1350. $totalamount += $lines[$i]->total_ht; // Fixme : is it not for the customer ? Shouldn't we take total_ttc ?
  1351. $tva_tx = $lines[$i]->tva_tx;
  1352. $amountdeposit[$tva_tx] += ($lines[$i]->total_ht * $valuedeposit) / 100;
  1353. }
  1354. }
  1355. if ($totalamount == 0) {
  1356. $amountdeposit[0] = 0;
  1357. }
  1358. } else {
  1359. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1360. $error++;
  1361. }
  1362. }
  1363. $amount_ttc_diff = $amountdeposit[0];
  1364. }
  1365. foreach ($amountdeposit as $tva => $amount) {
  1366. if (empty($amount)) {
  1367. continue;
  1368. }
  1369. $arraylist = array(
  1370. 'amount' => 'FixAmount',
  1371. 'variable' => 'VarAmount'
  1372. );
  1373. $descline = '(DEPOSIT)';
  1374. //$descline.= ' - '.$langs->trans($arraylist[$typeamount]);
  1375. if ($typeamount == 'amount') {
  1376. $descline .= ' ('.price($valuedeposit, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).')';
  1377. } elseif ($typeamount == 'variable') {
  1378. $descline .= ' ('.$valuedeposit.'%)';
  1379. }
  1380. $descline .= ' - '.$srcobject->ref;
  1381. $result = $object->addline(
  1382. $descline,
  1383. $amount, // subprice
  1384. 1, // quantity
  1385. $tva, // vat rate
  1386. 0, // localtax1_tx
  1387. 0, // localtax2_tx
  1388. (empty($conf->global->INVOICE_PRODUCTID_DEPOSIT) ? 0 : $conf->global->INVOICE_PRODUCTID_DEPOSIT), // fk_product
  1389. 0, // remise_percent
  1390. 0, // date_start
  1391. 0, // date_end
  1392. 0,
  1393. $lines[$i]->info_bits, // info_bits
  1394. 0,
  1395. 'HT',
  1396. 0,
  1397. 0, // product_type
  1398. 1,
  1399. $lines[$i]->special_code,
  1400. $object->origin,
  1401. 0,
  1402. 0,
  1403. 0,
  1404. 0
  1405. //,$langs->trans('Deposit') //Deprecated
  1406. );
  1407. }
  1408. $diff = $object->total_ttc - $amount_ttc_diff;
  1409. if (!empty($conf->global->MAIN_DEPOSIT_MULTI_TVA) && $diff != 0) {
  1410. $object->fetch_lines();
  1411. $subprice_diff = $object->lines[0]->subprice - $diff / (1 + $object->lines[0]->tva_tx / 100);
  1412. $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);
  1413. }
  1414. }
  1415. // standard invoice, credit note, or down payment from a percent of all lines
  1416. if (GETPOST('type') != Facture::TYPE_DEPOSIT || (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines')) {
  1417. if ($result > 0) {
  1418. $lines = $srcobject->lines;
  1419. if (empty($lines) && method_exists($srcobject, 'fetch_lines')) {
  1420. $srcobject->fetch_lines();
  1421. $lines = $srcobject->lines;
  1422. }
  1423. // If we create a standard invoice with a percent, we change amount by changing the qty
  1424. if (GETPOST('type') == Facture::TYPE_STANDARD && $valuestandardinvoice > 0 && $valuestandardinvoice < 100) {
  1425. if (is_array($lines)) {
  1426. foreach ($lines as $line) {
  1427. // We keep ->subprice and ->pa_ht, but we change the qty
  1428. $line->qty = price2num($line->qty * $valuestandardinvoice / 100, 'MS');
  1429. }
  1430. }
  1431. }
  1432. // If we create a down payment with a percent on all lines, we change amount by changing the qty
  1433. if (GETPOST('type') == Facture::TYPE_DEPOSIT && $typeamount == 'variablealllines') {
  1434. if (is_array($lines)) {
  1435. foreach ($lines as $line) {
  1436. // We keep ->subprice and ->pa_ht, but we change the qty
  1437. $line->qty = price2num($line->qty * $valuedeposit / 100, 'MS');
  1438. }
  1439. }
  1440. }
  1441. $fk_parent_line = 0;
  1442. $num = count($lines);
  1443. for ($i = 0; $i < $num; $i++) {
  1444. if (!in_array($lines[$i]->id, $selectedLines)) {
  1445. continue; // Skip unselected lines
  1446. }
  1447. // Don't add lines with qty 0 when coming from a shipment including all order lines
  1448. if ($srcobject->element == 'shipping' && $conf->global->SHIPMENT_GETS_ALL_ORDER_PRODUCTS && $lines[$i]->qty == 0) {
  1449. continue;
  1450. }
  1451. // Don't add closed lines when coming from a contract (Set constant to '0,5' to exclude also inactive lines)
  1452. if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) {
  1453. $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5';
  1454. }
  1455. if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE))) {
  1456. continue;
  1457. }
  1458. $label = (!empty($lines[$i]->label) ? $lines[$i]->label : '');
  1459. $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->libelle);
  1460. if ($object->situation_counter == 1) {
  1461. $lines[$i]->situation_percent = 0;
  1462. }
  1463. if ($lines[$i]->subprice < 0 && empty($conf->global->INVOICE_KEEP_DISCOUNT_LINES_AS_IN_ORIGIN)) {
  1464. // Negative line, we create a discount line
  1465. $discount = new DiscountAbsolute($db);
  1466. $discount->fk_soc = $object->socid;
  1467. $discount->amount_ht = abs($lines[$i]->total_ht);
  1468. $discount->amount_tva = abs($lines[$i]->total_tva);
  1469. $discount->amount_ttc = abs($lines[$i]->total_ttc);
  1470. $discount->tva_tx = $lines[$i]->tva_tx;
  1471. $discount->fk_user = $user->id;
  1472. $discount->description = $desc;
  1473. $discountid = $discount->create($user);
  1474. if ($discountid > 0) {
  1475. $result = $object->insert_discount($discountid); // This include link_to_invoice
  1476. } else {
  1477. setEventMessages($discount->error, $discount->errors, 'errors');
  1478. $error++;
  1479. break;
  1480. }
  1481. } else {
  1482. // Positive line
  1483. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
  1484. // Date start
  1485. $date_start = false;
  1486. if ($lines[$i]->date_debut_prevue) {
  1487. $date_start = $lines[$i]->date_debut_prevue;
  1488. }
  1489. if ($lines[$i]->date_debut_reel) {
  1490. $date_start = $lines[$i]->date_debut_reel;
  1491. }
  1492. if ($lines[$i]->date_start) {
  1493. $date_start = $lines[$i]->date_start;
  1494. }
  1495. // Date end
  1496. $date_end = false;
  1497. if ($lines[$i]->date_fin_prevue) {
  1498. $date_end = $lines[$i]->date_fin_prevue;
  1499. }
  1500. if ($lines[$i]->date_fin_reel) {
  1501. $date_end = $lines[$i]->date_fin_reel;
  1502. }
  1503. if ($lines[$i]->date_end) {
  1504. $date_end = $lines[$i]->date_end;
  1505. }
  1506. // Reset fk_parent_line for no child products and special product
  1507. if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) {
  1508. $fk_parent_line = 0;
  1509. }
  1510. // Extrafields
  1511. if (method_exists($lines[$i], 'fetch_optionals')) {
  1512. $lines[$i]->fetch_optionals();
  1513. $array_options = $lines[$i]->array_options;
  1514. }
  1515. $tva_tx = $lines[$i]->tva_tx;
  1516. if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) {
  1517. $tva_tx .= ' ('.$lines[$i]->vat_src_code.')';
  1518. }
  1519. // View third's localtaxes for NOW and do not use value from origin.
  1520. // TODO Is this really what we want ? Yes if source is template invoice but what if proposal or order ?
  1521. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty);
  1522. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty);
  1523. $result = $object->addline(
  1524. $desc,
  1525. $lines[$i]->subprice,
  1526. $lines[$i]->qty,
  1527. $tva_tx,
  1528. $localtax1_tx,
  1529. $localtax2_tx,
  1530. $lines[$i]->fk_product,
  1531. $lines[$i]->remise_percent,
  1532. $date_start,
  1533. $date_end,
  1534. 0,
  1535. $lines[$i]->info_bits,
  1536. $lines[$i]->fk_remise_except,
  1537. 'HT',
  1538. 0,
  1539. $product_type,
  1540. $lines[$i]->rang,
  1541. $lines[$i]->special_code,
  1542. $object->origin,
  1543. $lines[$i]->rowid,
  1544. $fk_parent_line,
  1545. $lines[$i]->fk_fournprice,
  1546. $lines[$i]->pa_ht,
  1547. $label,
  1548. $array_options,
  1549. $lines[$i]->situation_percent,
  1550. $lines[$i]->fk_prev_id,
  1551. $lines[$i]->fk_unit
  1552. );
  1553. if ($result > 0) {
  1554. $lineid = $result;
  1555. } else {
  1556. $lineid = 0;
  1557. $error++;
  1558. break;
  1559. }
  1560. // Defined the new fk_parent_line
  1561. if ($result > 0 && $lines[$i]->product_type == 9) {
  1562. $fk_parent_line = $result;
  1563. }
  1564. }
  1565. }
  1566. } else {
  1567. setEventMessages($srcobject->error, $srcobject->errors, 'errors');
  1568. $error++;
  1569. }
  1570. }
  1571. // Now we create same links to contact than the ones found on origin object
  1572. /* Useless, already into the create
  1573. if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
  1574. {
  1575. $originforcontact = $object->origin;
  1576. $originidforcontact = $object->origin_id;
  1577. if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order
  1578. {
  1579. $originforcontact=$srcobject->origin;
  1580. $originidforcontact=$srcobject->origin_id;
  1581. }
  1582. $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  1583. $sqlcontact.= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'";
  1584. $resqlcontact = $db->query($sqlcontact);
  1585. if ($resqlcontact)
  1586. {
  1587. while($objcontact = $db->fetch_object($resqlcontact))
  1588. {
  1589. //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n";
  1590. $object->add_contact($objcontact->fk_socpeople, $objcontact->code);
  1591. }
  1592. }
  1593. else dol_print_error($resqlcontact);
  1594. }*/
  1595. // Hooks
  1596. $parameters = array('objFrom' => $srcobject);
  1597. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been
  1598. // modified by hook
  1599. if ($reshook < 0) {
  1600. setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  1601. $error++;
  1602. }
  1603. } else {
  1604. setEventMessages($object->error, $object->errors, 'errors');
  1605. $error++;
  1606. }
  1607. } else { // If some invoice's lines coming from page
  1608. $id = $object->create($user);
  1609. for ($i = 1; $i <= $NBLINES; $i++) {
  1610. if (GETPOST('idprod'.$i, 'int')) {
  1611. $product = new Product($db);
  1612. $product->fetch(GETPOST('idprod'.$i, 'int'));
  1613. $startday = dol_mktime(12, 0, 0, GETPOST('date_start'.$i.'month'), GETPOST('date_start'.$i.'day'), GETPOST('date_start'.$i.'year'));
  1614. $endday = dol_mktime(12, 0, 0, GETPOST('date_end'.$i.'month'), GETPOST('date_end'.$i.'day'), GETPOST('date_end'.$i.'year'));
  1615. $result = $object->addline($product->description, $product->price, price2num(GETPOST('qty'.$i), 'MS'), $product->tva_tx, $product->localtax1_tx, $product->localtax2_tx, GETPOST('idprod'.$i, 'int'), price2num(GETPOST('remise_percent'.$i), '', 2), $startday, $endday, 0, 0, '', $product->price_base_type, $product->price_ttc, $product->type, -1, 0, '', 0, 0, null, 0, '', 0, 100, '', $product->fk_unit);
  1616. }
  1617. }
  1618. }
  1619. }
  1620. }
  1621. // Situation invoices
  1622. if (GETPOST('type') == Facture::TYPE_SITUATION && GETPOST('situations')) {
  1623. if (empty($dateinvoice)) {
  1624. $error++;
  1625. $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date"));
  1626. setEventMessages($mesg, null, 'errors');
  1627. } elseif ($dateinvoice > (dol_get_last_hour(dol_now('tzuserrel')) + (empty($conf->global->INVOICE_MAX_FUTURE_DELAY) ? 0 : $conf->global->INVOICE_MAX_FUTURE_DELAY))) {
  1628. $error++;
  1629. setEventMessages($langs->trans("ErrorDateIsInFuture"), null, 'errors');
  1630. $action = 'create';
  1631. }
  1632. if (!(GETPOST('situations', 'int') > 0)) {
  1633. $error++;
  1634. $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceSituation"));
  1635. setEventMessages($mesg, null, 'errors');
  1636. $action = 'create';
  1637. }
  1638. if (!$error) {
  1639. $result = $object->fetch(GETPOST('situations', 'int'));
  1640. $object->fk_facture_source = GETPOST('situations', 'int');
  1641. $object->type = Facture::TYPE_SITUATION;
  1642. if (!empty($origin) && !empty($originid)) {
  1643. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1644. $object->origin = $origin;
  1645. $object->origin_id = $originid;
  1646. // retained warranty
  1647. if (!empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  1648. $retained_warranty = GETPOST('retained_warranty', 'int');
  1649. if (price2num($retained_warranty) > 0) {
  1650. $object->retained_warranty = price2num($retained_warranty);
  1651. }
  1652. if (GETPOST('retained_warranty_fk_cond_reglement', 'int') > 0) {
  1653. $object->retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  1654. }
  1655. $retained_warranty_date_limit = GETPOST('retained_warranty_date_limit');
  1656. if (!empty($retained_warranty_date_limit) && $db->jdate($retained_warranty_date_limit)) {
  1657. $object->retained_warranty_date_limit = $db->jdate($retained_warranty_date_limit);
  1658. }
  1659. $object->retained_warranty_date_limit = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : $object->calculate_date_lim_reglement($object->retained_warranty_fk_cond_reglement);
  1660. }
  1661. foreach ($object->lines as $i => &$line) {
  1662. $line->origin = $object->origin;
  1663. $line->origin_id = $line->id;
  1664. $line->fk_prev_id = $line->id;
  1665. $line->fetch_optionals();
  1666. $line->situation_percent = $line->get_prev_progress($object->id); // get good progress including credit note
  1667. // The $line->situation_percent has been modified, so we must recalculate all amounts
  1668. $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, '', $line->situation_percent);
  1669. $line->total_ht = $tabprice[0];
  1670. $line->total_tva = $tabprice[1];
  1671. $line->total_ttc = $tabprice[2];
  1672. $line->total_localtax1 = $tabprice[9];
  1673. $line->total_localtax2 = $tabprice[10];
  1674. $line->multicurrency_total_ht = $tabprice[16];
  1675. $line->multicurrency_total_tva = $tabprice[17];
  1676. $line->multicurrency_total_ttc = $tabprice[18];
  1677. // Si fk_remise_except defini on vérifie si la réduction à déjà été appliquée
  1678. if ($line->fk_remise_except) {
  1679. $discount = new DiscountAbsolute($line->db);
  1680. $result = $discount->fetch($line->fk_remise_except);
  1681. if ($result > 0) {
  1682. // Check if discount not already affected to another invoice
  1683. if ($discount->fk_facture_line > 0) {
  1684. $line->fk_remise_except = 0;
  1685. }
  1686. }
  1687. }
  1688. }
  1689. }
  1690. $object->fetch_thirdparty();
  1691. $object->date = $dateinvoice;
  1692. $object->date_pointoftax = $date_pointoftax;
  1693. $object->note_public = trim(GETPOST('note_public', 'restricthtml'));
  1694. $object->note = trim(GETPOST('note', 'restricthtml'));
  1695. $object->note_private = trim(GETPOST('note', 'restricthtml'));
  1696. $object->ref_client = GETPOST('ref_client', 'alpha');
  1697. $object->model_pdf = GETPOST('model', 'alpha');
  1698. $object->fk_project = GETPOST('projectid', 'int');
  1699. $object->cond_reglement_id = GETPOST('cond_reglement_id', 'int');
  1700. $object->mode_reglement_id = GETPOST('mode_reglement_id', 'int');
  1701. $object->remise_absolue =price2num(GETPOST('remise_absolue'), 'MU', 2);
  1702. $object->remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  1703. // Proprietes particulieres a facture de remplacement
  1704. $object->situation_counter = $object->situation_counter + 1;
  1705. $id = $object->createFromCurrent($user);
  1706. if ($id <= 0) {
  1707. $mesg = $object->error;
  1708. } else {
  1709. $nextSituationInvoice = new Facture($db);
  1710. $nextSituationInvoice->fetch($id);
  1711. // create extrafields with data from create form
  1712. $extrafields->fetch_name_optionals_label($nextSituationInvoice->table_element);
  1713. $ret = $extrafields->setOptionalsFromPost(null, $nextSituationInvoice);
  1714. if ($ret > 0) {
  1715. $nextSituationInvoice->insertExtraFields();
  1716. }
  1717. }
  1718. }
  1719. }
  1720. // End of object creation, we show it
  1721. if ($id > 0 && !$error) {
  1722. $db->commit();
  1723. // Define output language
  1724. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && count($object->lines)) {
  1725. $outputlangs = $langs;
  1726. $newlang = '';
  1727. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1728. $newlang = GETPOST('lang_id', 'aZ09');
  1729. }
  1730. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  1731. $newlang = $object->thirdparty->default_lang;
  1732. }
  1733. if (!empty($newlang)) {
  1734. $outputlangs = new Translate("", $conf);
  1735. $outputlangs->setDefaultLang($newlang);
  1736. $outputlangs->load('products');
  1737. }
  1738. $model = $object->model_pdf;
  1739. $ret = $object->fetch($id); // Reload to get new records
  1740. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1741. if ($result < 0) {
  1742. setEventMessages($object->error, $object->errors, 'errors');
  1743. }
  1744. }
  1745. header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id);
  1746. exit();
  1747. } else {
  1748. $db->rollback();
  1749. $action = 'create';
  1750. $_GET["origin"] = $_POST["origin"];
  1751. $_GET["originid"] = $_POST["originid"];
  1752. setEventMessages($object->error, $object->errors, 'errors');
  1753. }
  1754. } elseif ($action == 'addline' && GETPOST('submitforalllines', 'alpha') && GETPOST('vatforalllines', 'alpha') !== '') {
  1755. // Define vat_rate
  1756. $vat_rate = (GETPOST('vatforalllines') ? GETPOST('vatforalllines') : 0);
  1757. $vat_rate = str_replace('*', '', $vat_rate);
  1758. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty, $mysoc);
  1759. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty, $mysoc);
  1760. foreach ($object->lines as $line) {
  1761. $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $line->date_start, $line->date_end, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice);
  1762. }
  1763. } elseif ($action == 'addline' && $usercancreate) { // Add a new line
  1764. $langs->load('errors');
  1765. $error = 0;
  1766. // Set if we used free entry or predefined product
  1767. $predef = '';
  1768. $product_desc =(GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : '');
  1769. $price_ht = price2num(GETPOST('price_ht'), 'MU', 2);
  1770. $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU', 2);
  1771. $prod_entry_mode = GETPOST('prod_entry_mode', 'alpha');
  1772. if ($prod_entry_mode == 'free') {
  1773. $idprod = 0;
  1774. $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0);
  1775. } else {
  1776. $idprod = GETPOST('idprod', 'int');
  1777. $tva_tx = '';
  1778. }
  1779. $qty = price2num(GETPOST('qty'.$predef), 'MS', 2);
  1780. $remise_percent = price2num(GETPOST('remise_percent'.$predef), '', 2);
  1781. // Extrafields
  1782. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  1783. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line, $predef);
  1784. // Unset extrafield
  1785. if (is_array($extralabelsline)) {
  1786. // Get extra fields
  1787. foreach ($extralabelsline as $key => $value) {
  1788. unset($_POST["options_".$key.$predef]);
  1789. }
  1790. }
  1791. if ((empty($idprod) || $idprod < 0) && ($price_ht < 0) && ($qty < 0)) {
  1792. setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPriceHT'), $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1793. $error++;
  1794. }
  1795. if (!$prod_entry_mode) {
  1796. if (GETPOST('type') < 0 && !GETPOST('search_idprod')) {
  1797. setEventMessages($langs->trans('ErrorChooseBetweenFreeEntryOrPredefinedProduct'), null, 'errors');
  1798. $error++;
  1799. }
  1800. }
  1801. if ($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && GETPOST('type') < 0) {
  1802. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors');
  1803. $error++;
  1804. }
  1805. if (($prod_entry_mode == 'free' && (empty($idprod) || $idprod < 0) && (($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $price_ht == '') && $price_ht_devise == '') && $object->type != Facture::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not ''
  1806. if ($price_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  1807. $langs->load("errors");
  1808. if ($object->type == $object::TYPE_DEPOSIT) {
  1809. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  1810. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  1811. } else {
  1812. setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
  1813. }
  1814. $error++;
  1815. } else {
  1816. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  1817. $error++;
  1818. }
  1819. }
  1820. if ($qty == '') {
  1821. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors');
  1822. $error++;
  1823. }
  1824. if ($prod_entry_mode == 'free' && empty($idprod) && empty($product_desc)) {
  1825. setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors');
  1826. $error++;
  1827. }
  1828. if ($qty < 0) {
  1829. $langs->load("errors");
  1830. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  1831. $error++;
  1832. }
  1833. if (!$error && !empty($conf->variants->enabled) && $prod_entry_mode != 'free') {
  1834. if ($combinations = GETPOST('combinations', 'array')) {
  1835. //Check if there is a product with the given combination
  1836. $prodcomb = new ProductCombination($db);
  1837. if ($res = $prodcomb->fetchByProductCombination2ValuePairs($idprod, $combinations)) {
  1838. $idprod = $res->fk_product_child;
  1839. } else {
  1840. setEventMessages($langs->trans('ErrorProductCombinationNotFound'), null, 'errors');
  1841. $error++;
  1842. }
  1843. }
  1844. }
  1845. if (!$error && ($qty >= 0) && (!empty($product_desc) || (!empty($idprod) && $idprod > 0))) {
  1846. $ret = $object->fetch($id);
  1847. if ($ret < 0) {
  1848. dol_print_error($db, $object->error);
  1849. exit();
  1850. }
  1851. $ret = $object->fetch_thirdparty();
  1852. // Clean parameters
  1853. $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'));
  1854. $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'));
  1855. $price_base_type = (GETPOST('price_base_type', 'alpha') ? GETPOST('price_base_type', 'alpha') : 'HT');
  1856. // Define special_code for special lines
  1857. $special_code = 0;
  1858. // if (empty($_POST['qty'])) $special_code=3; // Options should not exists on invoices
  1859. // Ecrase $pu par celui du produit
  1860. // Ecrase $desc par celui du produit
  1861. // Ecrase $tva_tx par celui du produit
  1862. // Ecrase $base_price_type par celui du produit
  1863. // Replaces $fk_unit with the product's
  1864. if (!empty($idprod) && $idprod > 0) {
  1865. $prod = new Product($db);
  1866. $prod->fetch($idprod);
  1867. $label = ((GETPOST('product_label') && GETPOST('product_label') != $prod->label) ? GETPOST('product_label') : '');
  1868. // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp'].
  1869. $pqp = (GETPOST('pbq', 'int') ? GETPOST('pbq', 'int') : 0);
  1870. $datapriceofproduct = $prod->getSellPrice($mysoc, $object->thirdparty, $pqp);
  1871. $pu_ht = $datapriceofproduct['pu_ht'];
  1872. $pu_ttc = $datapriceofproduct['pu_ttc'];
  1873. $price_min = $datapriceofproduct['price_min'];
  1874. $price_base_type = $datapriceofproduct['price_base_type'];
  1875. $tva_tx = $datapriceofproduct['tva_tx'];
  1876. $tva_npr = $datapriceofproduct['tva_npr'];
  1877. $tmpvat = price2num(preg_replace('/\s*\(.*\)/', '', $tva_tx));
  1878. $tmpprodvat = price2num(preg_replace('/\s*\(.*\)/', '', $prod->tva_tx));
  1879. // if price ht was forced (ie: from gui when calculated by margin rate and cost price). TODO Why this ?
  1880. if (!empty($price_ht) || $price_ht === '0') {
  1881. $pu_ht = price2num($price_ht, 'MU');
  1882. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  1883. } elseif ($tmpvat != $tmpprodvat) {
  1884. // On reevalue prix selon taux tva car taux tva transaction peut etre different
  1885. // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur).
  1886. if ($price_base_type != 'HT') {
  1887. $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU');
  1888. } else {
  1889. $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU');
  1890. }
  1891. }
  1892. $desc = '';
  1893. // Define output language
  1894. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  1895. $outputlangs = $langs;
  1896. $newlang = '';
  1897. if (empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1898. $newlang = GETPOST('lang_id', 'aZ09');
  1899. }
  1900. if (empty($newlang)) {
  1901. $newlang = $object->thirdparty->default_lang;
  1902. }
  1903. if (!empty($newlang)) {
  1904. $outputlangs = new Translate("", $conf);
  1905. $outputlangs->setDefaultLang($newlang);
  1906. $outputlangs->load('products');
  1907. }
  1908. $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description;
  1909. } else {
  1910. $desc = $prod->description;
  1911. }
  1912. //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time
  1913. if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) {
  1914. $product_desc='';
  1915. }
  1916. if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) {
  1917. $desc = $product_desc;
  1918. } else {
  1919. $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION));
  1920. }
  1921. // Add custom code and origin country into description
  1922. if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) {
  1923. $tmptxt = '(';
  1924. // Define output language
  1925. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) {
  1926. $outputlangs = $langs;
  1927. $newlang = '';
  1928. if (empty($newlang) && GETPOST('lang_id', 'alpha')) {
  1929. $newlang = GETPOST('lang_id', 'alpha');
  1930. }
  1931. if (empty($newlang)) {
  1932. $newlang = $object->thirdparty->default_lang;
  1933. }
  1934. if (!empty($newlang)) {
  1935. $outputlangs = new Translate("", $conf);
  1936. $outputlangs->setDefaultLang($newlang);
  1937. $outputlangs->load('products');
  1938. }
  1939. if (!empty($prod->customcode)) {
  1940. $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
  1941. }
  1942. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  1943. $tmptxt .= ' - ';
  1944. }
  1945. if (!empty($prod->country_code)) {
  1946. $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0);
  1947. }
  1948. } else {
  1949. if (!empty($prod->customcode)) {
  1950. $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode;
  1951. }
  1952. if (!empty($prod->customcode) && !empty($prod->country_code)) {
  1953. $tmptxt .= ' - ';
  1954. }
  1955. if (!empty($prod->country_code)) {
  1956. $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0);
  1957. }
  1958. }
  1959. $tmptxt .= ')';
  1960. $desc = dol_concatdesc($desc, $tmptxt);
  1961. }
  1962. $type = $prod->type;
  1963. $fk_unit = $prod->fk_unit;
  1964. } else {
  1965. $pu_ht = price2num($price_ht, 'MU');
  1966. $pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
  1967. $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
  1968. $tva_tx = str_replace('*', '', $tva_tx);
  1969. if (empty($tva_tx)) {
  1970. $tva_npr = 0;
  1971. }
  1972. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  1973. $desc = $product_desc;
  1974. $type = GETPOST('type');
  1975. $fk_unit = GETPOST('units', 'alpha');
  1976. $pu_ht_devise = price2num($price_ht_devise, 'MU');
  1977. }
  1978. // Margin
  1979. $fournprice = price2num(GETPOST('fournprice'.$predef) ? GETPOST('fournprice'.$predef) : '');
  1980. $buyingprice = price2num(GETPOST('buying_price'.$predef) != '' ? GETPOST('buying_price'.$predef) : ''); // If buying_price is '0', we must keep this value
  1981. // Local Taxes
  1982. $localtax1_tx = get_localtax($tva_tx, 1, $object->thirdparty, $mysoc, $tva_npr);
  1983. $localtax2_tx = get_localtax($tva_tx, 2, $object->thirdparty, $mysoc, $tva_npr);
  1984. $info_bits = 0;
  1985. if ($tva_npr) {
  1986. $info_bits |= 0x01;
  1987. }
  1988. $price2num_pu_ht = price2num($pu_ht);
  1989. $price2num_remise_percent = price2num($remise_percent);
  1990. $price2num_price_min = price2num($price_min);
  1991. if (empty($price2num_pu_ht)) {
  1992. $price2num_pu_ht = 0;
  1993. }
  1994. if (empty($price2num_remise_percent)) {
  1995. $price2num_remise_percent = 0;
  1996. }
  1997. if (empty($price2num_price_min)) {
  1998. $price2num_price_min = 0;
  1999. }
  2000. if ($usercanproductignorepricemin && (!empty($price_min) && ($price2num_pu_ht * (1 - $price2num_remise_percent / 100) < $price2num_price_min))) {
  2001. $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency));
  2002. setEventMessages($mesg, null, 'errors');
  2003. } else {
  2004. // Add batchinfo if the detail_batch array is defined
  2005. if (!empty($conf->productbatch->enabled) && !empty($lines[$i]->detail_batch) && is_array($lines[$i]->detail_batch) && !empty($conf->global->INVOICE_INCUDE_DETAILS_OF_LOTS_SERIALS)) {
  2006. $langs->load('productbatch');
  2007. foreach ($lines[$i]->detail_batch as $batchline) {
  2008. $desc .= ' '.$langs->trans('Batch').' '.$batchline->batch.' '.$langs->trans('printQty', $batchline->qty).' ';
  2009. }
  2010. }
  2011. // Insert line
  2012. $result = $object->addline($desc, $pu_ht, $qty, $tva_tx, $localtax1_tx, $localtax2_tx, $idprod, $remise_percent, $date_start, $date_end, 0, $info_bits, '', $price_base_type, $pu_ttc, $type, - 1, $special_code, '', 0, GETPOST('fk_parent_line'), $fournprice, $buyingprice, $label, $array_options, $_POST['progress'], '', $fk_unit, $pu_ht_devise);
  2013. if ($result > 0) {
  2014. // Define output language and generate document
  2015. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  2016. $outputlangs = $langs;
  2017. $newlang = '';
  2018. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  2019. $newlang = GETPOST('lang_id', 'aZ09');
  2020. }
  2021. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  2022. $newlang = $object->thirdparty->default_lang;
  2023. }
  2024. if (!empty($newlang)) {
  2025. $outputlangs = new Translate("", $conf);
  2026. $outputlangs->setDefaultLang($newlang);
  2027. $outputlangs->load('products');
  2028. }
  2029. $model = $object->model_pdf;
  2030. $ret = $object->fetch($id); // Reload to get new records
  2031. $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  2032. if ($result < 0) {
  2033. setEventMessages($object->error, $object->errors, 'errors');
  2034. }
  2035. }
  2036. unset($_POST['prod_entry_mode']);
  2037. unset($_POST['qty']);
  2038. unset($_POST['type']);
  2039. unset($_POST['remise_percent']);
  2040. unset($_POST['price_ht']);
  2041. unset($_POST['multicurrency_price_ht']);
  2042. unset($_POST['price_ttc']);
  2043. unset($_POST['tva_tx']);
  2044. unset($_POST['product_ref']);
  2045. unset($_POST['product_label']);
  2046. unset($_POST['product_desc']);
  2047. unset($_POST['fournprice']);
  2048. unset($_POST['buying_price']);
  2049. unset($_POST['np_marginRate']);
  2050. unset($_POST['np_markRate']);
  2051. unset($_POST['dp_desc']);
  2052. unset($_POST['idprod']);
  2053. unset($_POST['units']);
  2054. unset($_POST['date_starthour']);
  2055. unset($_POST['date_startmin']);
  2056. unset($_POST['date_startsec']);
  2057. unset($_POST['date_startday']);
  2058. unset($_POST['date_startmonth']);
  2059. unset($_POST['date_startyear']);
  2060. unset($_POST['date_endhour']);
  2061. unset($_POST['date_endmin']);
  2062. unset($_POST['date_endsec']);
  2063. unset($_POST['date_endday']);
  2064. unset($_POST['date_endmonth']);
  2065. unset($_POST['date_endyear']);
  2066. unset($_POST['situations']);
  2067. unset($_POST['progress']);
  2068. } else {
  2069. setEventMessages($object->error, $object->errors, 'errors');
  2070. }
  2071. $action = '';
  2072. }
  2073. }
  2074. } elseif ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) {
  2075. if (!$object->fetch($id) > 0) {
  2076. dol_print_error($db);
  2077. }
  2078. $object->fetch_thirdparty();
  2079. // Clean parameters
  2080. $date_start = '';
  2081. $date_end = '';
  2082. $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear'));
  2083. $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear'));
  2084. $description = dol_htmlcleanlastbr(GETPOST('product_desc', 'restricthtml') ? GETPOST('product_desc', 'restricthtml') : GETPOST('desc', 'restricthtml'));
  2085. $pu_ht = price2num(GETPOST('price_ht'), '', 2);
  2086. $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
  2087. $qty = GETPOST('qty');
  2088. $pu_ht_devise = price2num(GETPOST('multicurrency_subprice'), '', 2);
  2089. // Define info_bits
  2090. $info_bits = 0;
  2091. if (preg_match('/\*/', $vat_rate)) {
  2092. $info_bits |= 0x01;
  2093. }
  2094. // Define vat_rate
  2095. $vat_rate = str_replace('*', '', $vat_rate);
  2096. $localtax1_rate = get_localtax($vat_rate, 1, $object->thirdparty);
  2097. $localtax2_rate = get_localtax($vat_rate, 2, $object->thirdparty);
  2098. // Add buying price
  2099. $fournprice = price2num(GETPOST('fournprice') ? GETPOST('fournprice') : '');
  2100. $buyingprice = price2num(GETPOST('buying_price') != '' ? GETPOST('buying_price') : ''); // If buying_price is '0', we muste keep this value
  2101. // Extrafields
  2102. $extralabelsline = $extrafields->fetch_name_optionals_label($object->table_element_line);
  2103. $array_options = $extrafields->getOptionalsFromPost($object->table_element_line);
  2104. // Unset extrafield
  2105. if (is_array($extralabelsline)) {
  2106. // Get extra fields
  2107. foreach ($extralabelsline as $key => $value) {
  2108. unset($_POST["options_".$key]);
  2109. }
  2110. }
  2111. // Define special_code for special lines
  2112. $special_code = GETPOST('special_code');
  2113. if (!GETPOST('qty')) {
  2114. $special_code = 3;
  2115. }
  2116. $line = new FactureLigne($db);
  2117. $line->fetch(GETPOST('lineid', 'int'));
  2118. $percent = $line->get_prev_progress($object->id);
  2119. $progress = price2num(GETPOST('progress', 'alpha'));
  2120. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->situation_cycle_ref > 0) {
  2121. // in case of situation credit note
  2122. if ($progress >= 0) {
  2123. $mesg = $langs->trans("CantBeNullOrPositive");
  2124. setEventMessages($mesg, null, 'warnings');
  2125. $error++;
  2126. $result = -1;
  2127. } elseif ($progress < $line->situation_percent) { // TODO : use a modified $line->get_prev_progress($object->id) result
  2128. $mesg = $langs->trans("CantBeLessThanMinPercent");
  2129. setEventMessages($mesg, null, 'warnings');
  2130. $error++;
  2131. $result = -1;
  2132. } elseif ($progress < $percent) {
  2133. $mesg = '<div class="warning">'.$langs->trans("CantBeLessThanMinPercent").'</div>';
  2134. setEventMessages($mesg, null, 'warnings');
  2135. $error++;
  2136. $result = -1;
  2137. }
  2138. }
  2139. $remise_percent = price2num(GETPOST('remise_percent'), '', 2);
  2140. // Check minimum price
  2141. $productid = GETPOST('productid', 'int');
  2142. if (!empty($productid)) {
  2143. $product = new Product($db);
  2144. $product->fetch($productid);
  2145. $type = $product->type;
  2146. $price_min = $product->price_min;
  2147. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) {
  2148. $price_min = $product->multiprices_min [$object->thirdparty->price_level];
  2149. }
  2150. $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : '');
  2151. // Check price is not lower than minimum (check is done only for standard or replacement invoices)
  2152. if ($usercanproductignorepricemin && (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT) && $price_min && (price2num($pu_ht) * (1 - $remise_percent / 100) < price2num($price_min)))) {
  2153. setEventMessages($langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)), null, 'errors');
  2154. $error++;
  2155. }
  2156. } else {
  2157. $type = GETPOST('type');
  2158. $label = (GETPOST('product_label') ? GETPOST('product_label') : '');
  2159. // Check parameters
  2160. if (GETPOST('type') < 0) {
  2161. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors');
  2162. $error++;
  2163. }
  2164. }
  2165. if ($qty < 0) {
  2166. $langs->load("errors");
  2167. setEventMessages($langs->trans('ErrorQtyForCustomerInvoiceCantBeNegative'), null, 'errors');
  2168. $error++;
  2169. }
  2170. if ((empty($productid) && (($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) || $pu_ht == '') && $pu_ht_devise == '') && $object->type != Facture::TYPE_CREDIT_NOTE) { // Unit price can be 0 but not ''
  2171. if ($pu_ht < 0 && empty($conf->global->FACTURE_ENABLE_NEGATIVE_LINES)) {
  2172. $langs->load("errors");
  2173. if ($object->type == $object::TYPE_DEPOSIT) {
  2174. // Using negative lines on deposit lead to headach and blocking problems when you want to consume them.
  2175. setEventMessages($langs->trans("ErrorLinesCantBeNegativeOnDeposits"), null, 'errors');
  2176. } else {
  2177. setEventMessages($langs->trans("ErrorFieldCantBeNegativeOnInvoice", $langs->transnoentitiesnoconv("UnitPriceHT"), $langs->transnoentitiesnoconv("CustomerAbsoluteDiscountShort")), null, 'errors');
  2178. }
  2179. $error++;
  2180. } else {
  2181. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors');
  2182. $error++;
  2183. }
  2184. }
  2185. // Update line
  2186. if (!$error) {
  2187. if (empty($usercancreatemargin)) {
  2188. foreach ($object->lines as &$line) {
  2189. if ($line->id == GETPOST('lineid', 'int')) {
  2190. $fournprice = $line->fk_fournprice;
  2191. $buyingprice = $line->pa_ht;
  2192. break;
  2193. }
  2194. }
  2195. }
  2196. $result = $object->updateline(
  2197. GETPOST('lineid', 'int'),
  2198. $description,
  2199. $pu_ht,
  2200. $qty,
  2201. $remise_percent,
  2202. $date_start,
  2203. $date_end,
  2204. $vat_rate,
  2205. $localtax1_rate,
  2206. $localtax2_rate,
  2207. 'HT',
  2208. $info_bits,
  2209. $type,
  2210. GETPOST('fk_parent_line', 'int'),
  2211. 0,
  2212. $fournprice,
  2213. $buyingprice,
  2214. $label,
  2215. $special_code,
  2216. $array_options,
  2217. price2num(GETPOST('progress', 'alpha')),
  2218. GETPOST('units', 'alpha'),
  2219. $pu_ht_devise
  2220. );
  2221. if ($result >= 0) {
  2222. if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  2223. // Define output language
  2224. $outputlangs = $langs;
  2225. $newlang = '';
  2226. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  2227. $newlang = GETPOST('lang_id', 'aZ09');
  2228. }
  2229. if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
  2230. $newlang = $object->thirdparty->default_lang;
  2231. }
  2232. if (!empty($newlang)) {
  2233. $outputlangs = new Translate("", $conf);
  2234. $outputlangs->setDefaultLang($newlang);
  2235. $outputlangs->load('products');
  2236. }
  2237. $ret = $object->fetch($id); // Reload to get new records
  2238. $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref);
  2239. }
  2240. unset($_POST['qty']);
  2241. unset($_POST['type']);
  2242. unset($_POST['productid']);
  2243. unset($_POST['remise_percent']);
  2244. unset($_POST['price_ht']);
  2245. unset($_POST['multicurrency_price_ht']);
  2246. unset($_POST['price_ttc']);
  2247. unset($_POST['tva_tx']);
  2248. unset($_POST['product_ref']);
  2249. unset($_POST['product_label']);
  2250. unset($_POST['product_desc']);
  2251. unset($_POST['fournprice']);
  2252. unset($_POST['buying_price']);
  2253. unset($_POST['np_marginRate']);
  2254. unset($_POST['np_markRate']);
  2255. unset($_POST['dp_desc']);
  2256. unset($_POST['idprod']);
  2257. unset($_POST['units']);
  2258. unset($_POST['date_starthour']);
  2259. unset($_POST['date_startmin']);
  2260. unset($_POST['date_startsec']);
  2261. unset($_POST['date_startday']);
  2262. unset($_POST['date_startmonth']);
  2263. unset($_POST['date_startyear']);
  2264. unset($_POST['date_endhour']);
  2265. unset($_POST['date_endmin']);
  2266. unset($_POST['date_endsec']);
  2267. unset($_POST['date_endday']);
  2268. unset($_POST['date_endmonth']);
  2269. unset($_POST['date_endyear']);
  2270. unset($_POST['situations']);
  2271. unset($_POST['progress']);
  2272. } else {
  2273. setEventMessages($object->error, $object->errors, 'errors');
  2274. }
  2275. }
  2276. } elseif ($action == 'updatealllines' && $usercancreate && $_POST['all_percent'] == $langs->trans('Modifier')) { // Update all lines of situation invoice
  2277. if (!$object->fetch($id) > 0) {
  2278. dol_print_error($db);
  2279. }
  2280. if (GETPOST('all_progress') != "") {
  2281. $all_progress = GETPOST('all_progress', 'int');
  2282. foreach ($object->lines as $line) {
  2283. $percent = $line->get_prev_progress($object->id);
  2284. if (floatval($all_progress) < floatval($percent)) {
  2285. $mesg = $langs->trans("Line").' '.$i.' : '.$langs->trans("CantBeLessThanMinPercent");
  2286. setEventMessages($mesg, null, 'warnings');
  2287. $result = -1;
  2288. } else {
  2289. $object->update_percent($line, $_POST['all_progress']);
  2290. }
  2291. }
  2292. }
  2293. } elseif ($action == 'updateline' && $usercancreate && $_POST['cancel'] == $langs->trans("Cancel")) {
  2294. header('Location: '.$_SERVER["PHP_SELF"].'?facid='.$id); // To show again edited page
  2295. exit();
  2296. } elseif ($action == 'confirm_situationout' && $confirm == 'yes' && $usercancreate) {
  2297. // Outing situation invoice from cycle
  2298. $object->fetch($id, '', '', '', true);
  2299. if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  2300. && $object->type == Facture::TYPE_SITUATION
  2301. && $usercancreate
  2302. && !$objectidnext
  2303. && $object->is_last_in_cycle()
  2304. && $usercanunvalidate
  2305. ) {
  2306. $outingError = 0;
  2307. $newCycle = $object->newCycle(); // we need to keep the "situation behavior" so we place it on a new situation cycle
  2308. if ($newCycle > 1) {
  2309. // Search credit notes
  2310. $lastCycle = $object->situation_cycle_ref;
  2311. $lastSituationCounter = $object->situation_counter;
  2312. $linkedCreditNotesList = array();
  2313. if (count($object->tab_next_situation_invoice) > 0) {
  2314. foreach ($object->tab_next_situation_invoice as $next_invoice) {
  2315. if ($next_invoice->type == Facture::TYPE_CREDIT_NOTE
  2316. && $next_invoice->situation_counter == $object->situation_counter
  2317. && $next_invoice->fk_facture_source == $object->id
  2318. ) {
  2319. $linkedCreditNotesList[] = $next_invoice->id;
  2320. }
  2321. }
  2322. }
  2323. $object->situation_cycle_ref = $newCycle;
  2324. $object->situation_counter = 1;
  2325. $object->situation_final = 0;
  2326. if ($object->update($user) > 0) {
  2327. $errors = 0;
  2328. if (count($linkedCreditNotesList) > 0) {
  2329. // now, credit note must follow
  2330. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture ';
  2331. $sql .= ' SET situation_cycle_ref='.$newCycle;
  2332. $sql .= ' , situation_final=0';
  2333. $sql .= ' , situation_counter='.$object->situation_counter;
  2334. $sql .= ' WHERE rowid IN ('.$db->sanitize(implode(',', $linkedCreditNotesList)).')';
  2335. $resql = $db->query($sql);
  2336. if (!$resql) {
  2337. $errors++;
  2338. }
  2339. // Change each progression persent on each lines
  2340. foreach ($object->lines as $line) {
  2341. // no traitement for special product
  2342. if ($line->product_type == 9) {
  2343. continue;
  2344. }
  2345. if (!empty($object->tab_previous_situation_invoice)) {
  2346. // search the last invoice in cycle
  2347. $lineIndex = count($object->tab_previous_situation_invoice) - 1;
  2348. $searchPreviousInvoice = true;
  2349. while ($searchPreviousInvoice) {
  2350. if ($object->tab_previous_situation_invoice[$lineIndex]->type == Facture::TYPE_SITUATION || $lineIndex < 1) {
  2351. $searchPreviousInvoice = false; // find, exit;
  2352. break;
  2353. } else {
  2354. $lineIndex--; // go to previous invoice in cycle
  2355. }
  2356. }
  2357. $maxPrevSituationPercent = 0;
  2358. foreach ($object->tab_previous_situation_invoice[$lineIndex]->lines as $prevLine) {
  2359. if ($prevLine->id == $line->fk_prev_id) {
  2360. $maxPrevSituationPercent = max($maxPrevSituationPercent, $prevLine->situation_percent);
  2361. }
  2362. }
  2363. $line->situation_percent = $line->situation_percent - $maxPrevSituationPercent;
  2364. if ($line->update() < 0) {
  2365. $errors++;
  2366. }
  2367. }
  2368. }
  2369. }
  2370. if (!$errors) {
  2371. setEventMessages($langs->trans('Updated'), '', 'mesgs');
  2372. header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
  2373. } else {
  2374. setEventMessages($langs->trans('ErrorOutingSituationInvoiceCreditNote'), array(), 'errors');
  2375. }
  2376. } else {
  2377. setEventMessages($langs->trans('ErrorOutingSituationInvoiceOnUpdate'), array(), 'errors');
  2378. }
  2379. } else {
  2380. setEventMessages($langs->trans('ErrorFindNextSituationInvoice'), array(), 'errors');
  2381. }
  2382. }
  2383. } elseif ($action == 'import_lines_from_object'
  2384. && $usercancreate
  2385. && $object->statut == Facture::STATUS_DRAFT
  2386. && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION)) {
  2387. // add lines from objectlinked
  2388. $fromElement = GETPOST('fromelement');
  2389. $fromElementid = GETPOST('fromelementid');
  2390. $importLines = GETPOST('line_checkbox');
  2391. if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) {
  2392. if ($fromElement == 'commande') {
  2393. dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php');
  2394. $lineClassName = 'OrderLine';
  2395. } elseif ($fromElement == 'propal') {
  2396. dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php');
  2397. $lineClassName = 'PropaleLigne';
  2398. }
  2399. $nextRang = count($object->lines) + 1;
  2400. $importCount = 0;
  2401. $error = 0;
  2402. foreach ($importLines as $lineId) {
  2403. $lineId = intval($lineId);
  2404. $originLine = new $lineClassName($db);
  2405. if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) {
  2406. $originLine->fetch_optionals();
  2407. $desc = $originLine->desc;
  2408. $pu_ht = $originLine->subprice;
  2409. $qty = $originLine->qty;
  2410. $txtva = $originLine->tva_tx;
  2411. $txlocaltax1 = $originLine->localtax1_tx;
  2412. $txlocaltax2 = $originLine->localtax2_tx;
  2413. $fk_product = $originLine->fk_product;
  2414. $remise_percent = $originLine->remise_percent;
  2415. $date_start = $originLine->date_start;
  2416. $date_end = $originLine->date_end;
  2417. $ventil = 0;
  2418. $info_bits = $originLine->info_bits;
  2419. $fk_remise_except = $originLine->fk_remise_except;
  2420. $price_base_type = 'HT';
  2421. $pu_ttc = 0;
  2422. $type = $originLine->product_type;
  2423. $rang = $nextRang++;
  2424. $special_code = $originLine->special_code;
  2425. $origin = $originLine->element;
  2426. $origin_id = $originLine->id;
  2427. $fk_parent_line = 0;
  2428. $fk_fournprice = $originLine->fk_fournprice;
  2429. $pa_ht = $originLine->pa_ht;
  2430. $label = $originLine->label;
  2431. $array_options = $originLine->array_options;
  2432. if ($object->type == Facture::TYPE_SITUATION) {
  2433. $situation_percent = 0;
  2434. } else {
  2435. $situation_percent = 100;
  2436. }
  2437. $fk_prev_id = '';
  2438. $fk_unit = $originLine->fk_unit;
  2439. $pu_ht_devise = $originLine->multicurrency_subprice;
  2440. $res = $object->addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $ventil, $info_bits, $fk_remise_except, $price_base_type, $pu_ttc, $type, $rang, $special_code, $origin, $origin_id, $fk_parent_line, $fk_fournprice, $pa_ht, $label, $array_options, $situation_percent, $fk_prev_id, $fk_unit, $pu_ht_devise);
  2441. if ($res > 0) {
  2442. $importCount++;
  2443. } else {
  2444. $error++;
  2445. }
  2446. } else {
  2447. $error++;
  2448. }
  2449. }
  2450. if ($error) {
  2451. setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors');
  2452. }
  2453. }
  2454. }
  2455. // Actions when printing a doc from card
  2456. include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
  2457. // Actions to send emails
  2458. if (empty($id)) {
  2459. $id = $facid;
  2460. }
  2461. $triggersendname = 'BILL_SENTBYMAIL';
  2462. $paramname = 'id';
  2463. $autocopy = 'MAIN_MAIL_AUTOCOPY_INVOICE_TO';
  2464. $trackid = 'inv'.$object->id;
  2465. include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php';
  2466. // Actions to build doc
  2467. $upload_dir = $conf->facture->multidir_output[$object->entity];
  2468. $permissiontoadd = $usercancreate;
  2469. include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
  2470. if ($action == 'update_extras') {
  2471. $object->oldcopy = dol_clone($object);
  2472. // Fill array 'array_options' with data from add form
  2473. $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml'));
  2474. if ($ret < 0) {
  2475. $error++;
  2476. }
  2477. if (!$error) {
  2478. // Actions on extra fields
  2479. $result = $object->insertExtraFields('BILL_MODIFY');
  2480. if ($result < 0) {
  2481. setEventMessages($object->error, $object->errors, 'errors');
  2482. $error++;
  2483. }
  2484. }
  2485. if ($error) {
  2486. $action = 'edit_extras';
  2487. }
  2488. }
  2489. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) {
  2490. if ($action == 'addcontact') {
  2491. $result = $object->fetch($id);
  2492. if ($result > 0 && $id > 0) {
  2493. $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
  2494. $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type'));
  2495. $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09'));
  2496. }
  2497. if ($result >= 0) {
  2498. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  2499. exit();
  2500. } else {
  2501. if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  2502. $langs->load("errors");
  2503. setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors');
  2504. } else {
  2505. setEventMessages($object->error, $object->errors, 'errors');
  2506. }
  2507. }
  2508. } elseif ($action == 'swapstatut') {
  2509. // bascule du statut d'un contact
  2510. if ($object->fetch($id)) {
  2511. $result = $object->swapContactStatus(GETPOST('ligne', 'int'));
  2512. } else {
  2513. dol_print_error($db);
  2514. }
  2515. } elseif ($action == 'deletecontact') {
  2516. // Efface un contact
  2517. $object->fetch($id);
  2518. $result = $object->delete_contact($lineid);
  2519. if ($result >= 0) {
  2520. header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
  2521. exit();
  2522. } else {
  2523. dol_print_error($db);
  2524. }
  2525. }
  2526. if ($error) {
  2527. $action = 'edit_extras';
  2528. }
  2529. }
  2530. }
  2531. /*
  2532. * View
  2533. */
  2534. if (empty($object->id)) {
  2535. llxHeader();
  2536. $head = facture_prepare_head($object);
  2537. $langs->load('errors');
  2538. echo dol_get_fiche_head($head, 'compta', $langs->trans("InvoiceCustomer"), -1, 'bill'),
  2539. '<div class="error">' . $langs->trans("ErrorRecordNotFound") . '</div>';
  2540. llxFooter();
  2541. exit;
  2542. }
  2543. $form = new Form($db);
  2544. $formother = new FormOther($db);
  2545. $formfile = new FormFile($db);
  2546. $formmargin = new FormMargin($db);
  2547. $soc = new Societe($db);
  2548. $paymentstatic = new Paiement($db);
  2549. $bankaccountstatic = new Account($db);
  2550. if (!empty($conf->projet->enabled)) {
  2551. $formproject = new FormProjets($db);
  2552. }
  2553. $now = dol_now();
  2554. $title = $langs->trans('InvoiceCustomer')." - ".$langs->trans('Card');
  2555. $help_url = "EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes";
  2556. llxHeader('', $title, $help_url);
  2557. // Mode creation
  2558. if ($action == 'create') {
  2559. $facturestatic = new Facture($db);
  2560. $extrafields->fetch_name_optionals_label($facturestatic->table_element);
  2561. print load_fiche_titre($langs->trans('NewBill'), '', 'bill');
  2562. if ($socid > 0) {
  2563. $res = $soc->fetch($socid);
  2564. }
  2565. $currency_code = $conf->currency;
  2566. // Load objectsrc
  2567. $remise_absolue = 0;
  2568. if (!empty($origin) && !empty($originid)) {
  2569. // Parse element/subelement (ex: project_task)
  2570. $element = $subelement = $origin;
  2571. $regs = array();
  2572. if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) {
  2573. $element = $regs[1];
  2574. $subelement = $regs[2];
  2575. }
  2576. if ($element == 'project') {
  2577. $projectid = $originid;
  2578. if (empty($cond_reglement_id)) {
  2579. $cond_reglement_id = $soc->cond_reglement_id;
  2580. }
  2581. if (empty($mode_reglement_id)) {
  2582. $mode_reglement_id = $soc->mode_reglement_id;
  2583. }
  2584. if (!$remise_percent) {
  2585. $remise_percent = $soc->remise_percent;
  2586. }
  2587. if (!$dateinvoice) {
  2588. // Do not set 0 here (0 for a date is 1970)
  2589. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice);
  2590. }
  2591. } else {
  2592. // For compatibility
  2593. if ($element == 'order' || $element == 'commande') {
  2594. $element = $subelement = 'commande';
  2595. }
  2596. if ($element == 'propal') {
  2597. $element = 'comm/propal';
  2598. $subelement = 'propal';
  2599. }
  2600. if ($element == 'contract') {
  2601. $element = $subelement = 'contrat';
  2602. }
  2603. if ($element == 'shipping') {
  2604. $element = $subelement = 'expedition';
  2605. }
  2606. dol_include_once('/'.$element.'/class/'.$subelement.'.class.php');
  2607. $classname = ucfirst($subelement);
  2608. $objectsrc = new $classname($db);
  2609. $objectsrc->fetch($originid);
  2610. if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) {
  2611. $objectsrc->fetch_lines();
  2612. }
  2613. $objectsrc->fetch_thirdparty();
  2614. $projectid = (!empty($projectid) ? $projectid : $objectsrc->fk_project);
  2615. $ref_client = (!empty($objectsrc->ref_client) ? $objectsrc->ref_client : (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : ''));
  2616. // only if socid not filled else it's allready done upper
  2617. if (empty($socid)) {
  2618. $soc = $objectsrc->thirdparty;
  2619. }
  2620. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice);
  2621. if ($element == 'expedition') {
  2622. $ref_client = (!empty($objectsrc->ref_customer) ? $objectsrc->ref_customer : '');
  2623. $elem = $subelem = $objectsrc->origin;
  2624. $expeoriginid = $objectsrc->origin_id;
  2625. dol_include_once('/'.$elem.'/class/'.$subelem.'.class.php');
  2626. $classname = ucfirst($subelem);
  2627. $expesrc = new $classname($db);
  2628. $expesrc->fetch($expeoriginid);
  2629. $cond_reglement_id = (!empty($expesrc->cond_reglement_id) ? $expesrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 1));
  2630. $mode_reglement_id = (!empty($expesrc->mode_reglement_id) ? $expesrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
  2631. $fk_account = (!empty($expesrc->fk_account) ? $expesrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  2632. $remise_percent = (!empty($expesrc->remise_percent) ? $expesrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
  2633. $remise_absolue = (!empty($expesrc->remise_absolue) ? $expesrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  2634. //Replicate extrafields
  2635. $expesrc->fetch_optionals();
  2636. $object->array_options = $expesrc->array_options;
  2637. } else {
  2638. $cond_reglement_id = (!empty($objectsrc->cond_reglement_id) ? $objectsrc->cond_reglement_id : (!empty($soc->cond_reglement_id) ? $soc->cond_reglement_id : 0));
  2639. $mode_reglement_id = (!empty($objectsrc->mode_reglement_id) ? $objectsrc->mode_reglement_id : (!empty($soc->mode_reglement_id) ? $soc->mode_reglement_id : 0));
  2640. $fk_account = (!empty($objectsrc->fk_account) ? $objectsrc->fk_account : (!empty($soc->fk_account) ? $soc->fk_account : 0));
  2641. $remise_percent = (!empty($objectsrc->remise_percent) ? $objectsrc->remise_percent : (!empty($soc->remise_percent) ? $soc->remise_percent : 0));
  2642. $remise_absolue = (!empty($objectsrc->remise_absolue) ? $objectsrc->remise_absolue : (!empty($soc->remise_absolue) ? $soc->remise_absolue : 0));
  2643. if (!empty($conf->multicurrency->enabled)) {
  2644. if (!empty($objectsrc->multicurrency_code)) {
  2645. $currency_code = $objectsrc->multicurrency_code;
  2646. }
  2647. if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) {
  2648. $currency_tx = $objectsrc->multicurrency_tx;
  2649. }
  2650. }
  2651. // Replicate extrafields
  2652. $objectsrc->fetch_optionals();
  2653. $object->array_options = $objectsrc->array_options;
  2654. }
  2655. }
  2656. } else {
  2657. $cond_reglement_id = $soc->cond_reglement_id;
  2658. $mode_reglement_id = $soc->mode_reglement_id;
  2659. $fk_account = $soc->fk_account;
  2660. $remise_percent = $soc->remise_percent;
  2661. $remise_absolue = 0;
  2662. $dateinvoice = (empty($dateinvoice) ? (empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : '') : $dateinvoice); // Do not set 0 here (0 for a date is 1970)
  2663. if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) {
  2664. $currency_code = $soc->multicurrency_code;
  2665. }
  2666. }
  2667. // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value
  2668. if (empty($cond_reglement_id)) {
  2669. $cond_reglement_id = GETPOST("cond_reglement_id", 'int');
  2670. }
  2671. // when payment mode is empty (means not override by payment mode form a other object, like third-party), try to use default value
  2672. if (empty($mode_reglement_id)) {
  2673. $mode_reglement_id = GETPOST("mode_reglement_id", 'int');
  2674. }
  2675. if (!empty($soc->id)) {
  2676. $absolute_discount = $soc->getAvailableDiscounts();
  2677. }
  2678. $note_public = $object->getDefaultCreateValueFor('note_public', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_public : null));
  2679. $note_private = $object->getDefaultCreateValueFor('note_private', ((!empty($origin) && !empty($originid) && is_object($objectsrc) && !empty($conf->global->FACTURE_REUSE_NOTES_ON_CREATE_FROM)) ? $objectsrc->note_private : null));
  2680. if (!empty($conf->use_javascript_ajax)) {
  2681. require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
  2682. print ajax_combobox('fac_replacement');
  2683. print ajax_combobox('fac_avoir');
  2684. print ajax_combobox('situations');
  2685. }
  2686. if ($origin == 'contrat') {
  2687. $langs->load("admin");
  2688. $text = $langs->trans("ToCreateARecurringInvoice");
  2689. $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGene", $langs->transnoentitiesnoconv("MenuFinancial"), $langs->transnoentitiesnoconv("BillsCustomers"), $langs->transnoentitiesnoconv("ListOfTemplates"));
  2690. if (empty($conf->global->INVOICE_DISABLE_AUTOMATIC_RECURRING_INVOICE)) {
  2691. $text .= ' '.$langs->trans("ToCreateARecurringInvoiceGeneAuto", $langs->transnoentitiesnoconv('Module2300Name'));
  2692. }
  2693. print info_admin($text, 0, 0, 0).'<br>';
  2694. }
  2695. print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="POST" id="formtocreate" name="formtocreate">';
  2696. print '<input type="hidden" name="token" value="'.newToken().'">';
  2697. print '<input type="hidden" name="action" value="add">';
  2698. if ($soc->id > 0) {
  2699. print '<input type="hidden" name="socid" value="'.$soc->id.'">'."\n";
  2700. }
  2701. print '<input name="ref" type="hidden" value="provisoire">';
  2702. print '<input name="ref_client" type="hidden" value="'.$ref_client.'">';
  2703. print '<input name="force_cond_reglement_id" type="hidden" value="0">';
  2704. print '<input name="force_mode_reglement_id" type="hidden" value="0">';
  2705. print '<input name="force_fk_account" type="hidden" value="0">';
  2706. print '<input type="hidden" name="origin" value="'.$origin.'">';
  2707. print '<input type="hidden" name="originid" value="'.$originid.'">';
  2708. print '<input type="hidden" name="originentity" value="'.GETPOST('originentity').'">';
  2709. if (!empty($currency_tx)) {
  2710. print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">';
  2711. }
  2712. print dol_get_fiche_head('');
  2713. print '<table class="border centpercent">';
  2714. // Ref
  2715. //print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans('Ref').'</td><td colspan="2">'.$langs->trans('Draft').'</td></tr>';
  2716. $exampletemplateinvoice = new FactureRec($db);
  2717. $invoice_predefined = new FactureRec($db);
  2718. if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) {
  2719. $invoice_predefined->fetch(GETPOST('fac_rec', 'int'));
  2720. }
  2721. // Thirdparty
  2722. if ($soc->id > 0 && (!GETPOST('fac_rec', 'int') || !empty($invoice_predefined->frequency))) {
  2723. // If thirdparty known and not a predefined invoiced without a recurring rule
  2724. print '<tr><td class="fieldrequired">'.$langs->trans('Customer').'</td>';
  2725. print '<td colspan="2">';
  2726. print $soc->getNomUrl(1);
  2727. print '<input type="hidden" name="socid" value="'.$soc->id.'">';
  2728. // Outstanding Bill
  2729. $arrayoutstandingbills = $soc->getOutstandingBills();
  2730. $outstandingBills = $arrayoutstandingbills['opened'];
  2731. print ' - <span class="opacitymedium">'.$langs->trans('CurrentOutstandingBill').':</span> ';
  2732. print price($outstandingBills, '', $langs, 0, 0, -1, $conf->currency);
  2733. if ($soc->outstanding_limit != '') {
  2734. if ($outstandingBills > $soc->outstanding_limit) {
  2735. print img_warning($langs->trans("OutstandingBillReached"));
  2736. }
  2737. print ' / '.price($soc->outstanding_limit, '', $langs, 0, 0, -1, $conf->currency);
  2738. }
  2739. print '</td>';
  2740. print '</tr>'."\n";
  2741. } else {
  2742. print '<tr><td class="fieldrequired">'.$langs->trans('Customer').'</td>';
  2743. print '<td colspan="2">';
  2744. print img_picto('', 'company').$form->select_company($soc->id, 'socid', '((s.client = 1 OR s.client = 3) AND s.status=1)', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300 widthcentpercentminusxx maxwidth500');
  2745. // Option to reload page to retrieve customer informations.
  2746. if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) {
  2747. print '<script type="text/javascript">
  2748. $(document).ready(function() {
  2749. $("#socid").change(function() {
  2750. /*
  2751. console.log("Submit page");
  2752. $(\'input[name="action"]\').val(\'create\');
  2753. $(\'input[name="force_cond_reglement_id"]\').val(\'1\');
  2754. $(\'input[name="force_mode_reglement_id"]\').val(\'1\');
  2755. $(\'input[name="force_fk_account"]\').val(\'1\');
  2756. $("#formtocreate").submit(); */
  2757. // For company change, we must reuse data of comany, not input already done, so we call a GET with action=create, not a POST submit.
  2758. console.log("We have changed the company - Reload page");
  2759. var socid = $(this).val();
  2760. var fac_rec = $(\'#fac_rec\').val();
  2761. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  2762. });
  2763. });
  2764. </script>';
  2765. }
  2766. if (!GETPOST('fac_rec', 'int')) {
  2767. print ' <a href="'.DOL_URL_ROOT.'/societe/card.php?action=create&client=3&fournisseur=0&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=create').'"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddThirdParty").'"></span></a>';
  2768. }
  2769. print '</td>';
  2770. print '</tr>'."\n";
  2771. }
  2772. // Overwrite some values if creation of invoice is from a predefined invoice
  2773. if (empty($origin) && empty($originid) && GETPOST('fac_rec', 'int') > 0) {
  2774. $invoice_predefined->fetch(GETPOST('fac_rec', 'int'));
  2775. $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later
  2776. if (empty($projectid)) {
  2777. $projectid = $invoice_predefined->fk_project;
  2778. }
  2779. $cond_reglement_id = $invoice_predefined->cond_reglement_id;
  2780. $mode_reglement_id = $invoice_predefined->mode_reglement_id;
  2781. $fk_account = $invoice_predefined->fk_account;
  2782. $note_public = $invoice_predefined->note_public;
  2783. $note_private = $invoice_predefined->note_private;
  2784. if (!empty($invoice_predefined->multicurrency_code)) {
  2785. $currency_code = $invoice_predefined->multicurrency_code;
  2786. }
  2787. if (!empty($invoice_predefined->multicurrency_tx)) {
  2788. $currency_tx = $invoice_predefined->multicurrency_tx;
  2789. }
  2790. $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc';
  2791. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r';
  2792. $sql .= ' WHERE r.fk_soc = '.((int) $invoice_predefined->socid);
  2793. $resql = $db->query($sql);
  2794. if ($resql) {
  2795. $num = $db->num_rows($resql);
  2796. $i = 0;
  2797. if ($num > 0) {
  2798. print '<tr><td>'.$langs->trans('CreateFromRepeatableInvoice').'</td><td>';
  2799. //print '<input type="hidden" name="fac_rec" id="fac_rec" value="'.GETPOST('fac_rec', 'int').'">';
  2800. print '<select class="flat" id="fac_rec" name="fac_rec">'; // We may want to change the template to use
  2801. print '<option value="0" selected></option>';
  2802. while ($i < $num) {
  2803. $objp = $db->fetch_object($resql);
  2804. print '<option value="'.$objp->rowid.'"';
  2805. if (GETPOST('fac_rec', 'int') == $objp->rowid) {
  2806. print ' selected';
  2807. $exampletemplateinvoice->fetch(GETPOST('fac_rec', 'int'));
  2808. }
  2809. print '>'.$objp->title.' ('.price($objp->total_ttc).' '.$langs->trans("TTC").')</option>';
  2810. $i++;
  2811. }
  2812. print '</select>';
  2813. // Option to reload page to retrieve customer informations. Note, this clear other input
  2814. if (empty($conf->global->RELOAD_PAGE_ON_TEMPLATE_CHANGE_DISABLED)) {
  2815. print '<script type="text/javascript">
  2816. $(document).ready(function() {
  2817. $("#fac_rec").change(function() {
  2818. console.log("We have changed the template invoice - Reload page");
  2819. var fac_rec = $(this).val();
  2820. var socid = $(\'#socid\').val();
  2821. // 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.
  2822. window.location.href = "'.$_SERVER["PHP_SELF"].'?action=create&socid="+socid+"&fac_rec="+fac_rec;
  2823. });
  2824. });
  2825. </script>';
  2826. }
  2827. print '</td></tr>';
  2828. }
  2829. $db->free($resql);
  2830. } else {
  2831. dol_print_error($db);
  2832. }
  2833. }
  2834. print '<tr><td class="tdtop fieldrequired">'.$langs->trans('Type').'</td><td colspan="2">';
  2835. print '<div class="tagtable">'."\n";
  2836. // Standard invoice
  2837. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2838. $tmp = '<input type="radio" id="radio_standard" name="type" value="0"'.(GETPOST('type') == 0 ? ' checked' : '').'> ';
  2839. $tmp = $tmp.'<label for="radio_standard" >'.$langs->trans("InvoiceStandardAsk").'</label>';
  2840. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceStandardDesc"), 1, 'help', '', 0, 3);
  2841. print '<table class="nobordernopadding"><tr>';
  2842. print '<td>';
  2843. print $desc;
  2844. print '</td>';
  2845. if ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid))) {
  2846. /*print '<td class="nowrap" style="padding-left: 5px">';
  2847. $arraylist = array(
  2848. //'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  2849. //'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  2850. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  2851. );
  2852. print $form->selectarray('typestandard', $arraylist, GETPOST('typestandard', 'aZ09'), 0, 0, 0, '', 1);
  2853. print '</td>';*/
  2854. print '<td class="nowrap" style="padding-left: 15px">';
  2855. print '<span class="opacitymedium">'.$langs->trans('PercentOfOriginalObject').'</span>:<input class="right" placeholder="100%" type="text" id="valuestandardinvoice" name="valuestandardinvoice" size="3" value="'.(GETPOSTISSET('valuestandardinvoice') ? GETPOST('valuestandardinvoice', 'alpha') : '100%').'"/>';
  2856. print '</td>';
  2857. }
  2858. print '</tr></table>';
  2859. print '</div></div>';
  2860. if ((empty($origin)) || ((($origin == 'propal') || ($origin == 'commande')) && (!empty($originid)))) {
  2861. // Deposit - Down payment
  2862. if (empty($conf->global->INVOICE_DISABLE_DEPOSIT)) {
  2863. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2864. $tmp = '<input type="radio" id="radio_deposit" name="type" value="3"'.(GETPOST('type') == 3 ? ' checked' : '').'> ';
  2865. print '<script type="text/javascript" language="javascript">
  2866. jQuery(document).ready(function() {
  2867. jQuery("#typestandardinvoice, #valuestandardinvoice").click(function() {
  2868. jQuery("#radio_standard").prop("checked", true);
  2869. });
  2870. jQuery("#typedeposit, #valuedeposit").click(function() {
  2871. jQuery("#radio_deposit").prop("checked", true);
  2872. });
  2873. jQuery("#typedeposit").change(function() {
  2874. console.log("We change type of down payment");
  2875. jQuery("#radio_deposit").prop("checked", true);
  2876. setRadioForTypeOfIncoice();
  2877. });
  2878. jQuery("#radio_standard, #radio_deposit, #radio_replacement, #radio_template").change(function() {
  2879. setRadioForTypeOfIncoice();
  2880. });
  2881. function setRadioForTypeOfIncoice() {
  2882. console.log("Change radio");
  2883. if (jQuery("#radio_deposit").prop("checked") && (jQuery("#typedeposit").val() == \'amount\' || jQuery("#typedeposit").val() == \'variable\')) {
  2884. jQuery(".checkforselect").prop("disabled", true);
  2885. jQuery(".checkforselect").prop("checked", false);
  2886. } else {
  2887. jQuery(".checkforselect").prop("disabled", false);
  2888. jQuery(".checkforselect").prop("checked", true);
  2889. }
  2890. };
  2891. });
  2892. </script>';
  2893. $tmp = $tmp.'<label for="radio_deposit" >'.$langs->trans("InvoiceDeposit").'</label>';
  2894. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceDepositDesc"), 1, 'help', '', 0, 3);
  2895. print '<table class="nobordernopadding"><tr>';
  2896. print '<td>';
  2897. print $desc;
  2898. print '</td>';
  2899. if (($origin == 'propal') || ($origin == 'commande')) {
  2900. print '<td class="nowrap" style="padding-left: 15px">';
  2901. $arraylist = array(
  2902. 'amount' => $langs->transnoentitiesnoconv('FixAmount', $langs->transnoentitiesnoconv('Deposit')),
  2903. 'variable' => $langs->transnoentitiesnoconv('VarAmountOneLine', $langs->transnoentitiesnoconv('Deposit')),
  2904. 'variablealllines' => $langs->transnoentitiesnoconv('VarAmountAllLines')
  2905. );
  2906. print $form->selectarray('typedeposit', $arraylist, GETPOST('typedeposit', 'aZ09'), 0, 0, 0, '', 1);
  2907. print '</td>';
  2908. print '<td class="nowrap" style="padding-left: 5px">';
  2909. print '<span class="opacitymedium paddingleft">'.$langs->trans("AmountOrPercent").'</span><input type="text" id="valuedeposit" name="valuedeposit" class="width75 right" value="'.GETPOST('valuedeposit', 'int').'"/>';
  2910. print '</td>';
  2911. }
  2912. print '</tr></table>';
  2913. print '</div></div>';
  2914. }
  2915. }
  2916. if ($socid > 0) {
  2917. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  2918. // First situation invoice
  2919. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2920. $tmp = '<input id="radio_situation" type="radio" name="type" value="5"'.(GETPOST('type') == 5 ? ' checked' : '').'> ';
  2921. $tmp = $tmp.'<label for="radio_situation" >'.$langs->trans("InvoiceFirstSituationAsk").'</label>';
  2922. $desc = $form->textwithpicto($tmp, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3);
  2923. print $desc;
  2924. print '</div></div>';
  2925. // Next situation invoice
  2926. $opt = $form->selectSituationInvoices(GETPOST('originid', 'int'), $socid);
  2927. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2928. $tmp = '<input type="radio" name="type" value="5"'.(GETPOST('type') == 5 && GETPOST('originid', 'int') ? ' checked' : '');
  2929. if ($opt == ('<option value ="0" selected>'.$langs->trans('NoSituations').'</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
  2930. $tmp .= ' disabled';
  2931. }
  2932. $tmp .= '> ';
  2933. $text = '<label>'.$tmp.$langs->trans("InvoiceSituationAsk").'</label> ';
  2934. $text .= '<select class="flat" id="situations" name="situations"';
  2935. if ($opt == ('<option value ="0" selected>'.$langs->trans('NoSituations').'</option>') || (GETPOST('origin') && GETPOST('origin') != 'facture' && GETPOST('origin') != 'commande')) {
  2936. $text .= ' disabled';
  2937. }
  2938. $text .= '>';
  2939. $text .= $opt;
  2940. $text .= '</select>';
  2941. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceSituationDesc"), 1, 'help', '', 0, 3);
  2942. print $desc;
  2943. print '</div></div>';
  2944. }
  2945. // Replacement
  2946. if (empty($conf->global->INVOICE_DISABLE_REPLACEMENT)) {
  2947. // Type de facture
  2948. $facids = $facturestatic->list_replacable_invoices($soc->id);
  2949. if ($facids < 0) {
  2950. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  2951. exit();
  2952. }
  2953. $options = "";
  2954. if (is_array($facids)) {
  2955. foreach ($facids as $facparam) {
  2956. $options .= '<option value="'.$facparam ['id'].'"';
  2957. if ($facparam['id'] == GETPOST('fac_replacement', 'int')) {
  2958. $options .= ' selected';
  2959. }
  2960. $options .= '>'.$facparam['ref'];
  2961. $options .= ' ('.$facturestatic->LibStatut($facparam['paid'], $facparam['status'], 0, $facparam['alreadypaid']).')';
  2962. $options .= '</option>';
  2963. }
  2964. }
  2965. print '<!-- replacement line -->';
  2966. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2967. $tmp = '<input type="radio" name="type" id="radio_replacement" value="1"'.(GETPOST('type') == 1 ? ' checked' : '');
  2968. if (!$options || $invoice_predefined->id > 0) {
  2969. $tmp .= ' disabled';
  2970. }
  2971. $tmp .= '> ';
  2972. print '<script type="text/javascript" language="javascript">
  2973. jQuery(document).ready(function() {
  2974. jQuery("#fac_replacement").change(function() {
  2975. jQuery("#radio_replacement").prop("checked", true);
  2976. });
  2977. });
  2978. </script>';
  2979. $text = '<label>'.$tmp.$langs->trans("InvoiceReplacementAsk").'</label>';
  2980. $text .= '<select class="flat" name="fac_replacement" id="fac_replacement"';
  2981. if (!$options || $invoice_predefined->id > 0) {
  2982. $text .= ' disabled';
  2983. }
  2984. $text .= '>';
  2985. if ($options) {
  2986. $text .= '<option value="-1">&nbsp;</option>';
  2987. $text .= $options;
  2988. } else {
  2989. $text .= '<option value="-1">'.$langs->trans("NoReplacableInvoice").'</option>';
  2990. }
  2991. $text .= '</select>';
  2992. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  2993. print $desc;
  2994. print '</div></div>';
  2995. }
  2996. } else {
  2997. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  2998. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  2999. $tmp = '<input type="radio" name="type" id="radio_situation" value="0" disabled> ';
  3000. $text = '<label>'.$tmp.$langs->trans("InvoiceFirstSituationAsk").'</label> ';
  3001. $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
  3002. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3);
  3003. print $desc;
  3004. print '</div></div>';
  3005. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3006. $tmp = '<input type="radio" name="type" id="radio_situation" value="0" disabled> ';
  3007. $text = '<label>'.$tmp.$langs->trans("InvoiceSituationAsk").'</label> ';
  3008. $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
  3009. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceFirstSituationDesc"), 1, 'help', '', 0, 3);
  3010. print $desc;
  3011. print '</div></div>';
  3012. }
  3013. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3014. $tmp = '<input type="radio" name="type" id="radio_replacement" value="0" disabled> ';
  3015. $text = '<label>'.$tmp.$langs->trans("InvoiceReplacement").'</label> ';
  3016. $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
  3017. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceReplacementDesc"), 1, 'help', '', 0, 3);
  3018. print $desc;
  3019. print '</div></div>';
  3020. }
  3021. if (empty($origin)) {
  3022. if ($socid > 0) {
  3023. // Credit note
  3024. if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) {
  3025. // Show link for credit note
  3026. $facids = $facturestatic->list_qualified_avoir_invoices($soc->id);
  3027. if ($facids < 0) {
  3028. dol_print_error($db, $facturestatic->error, $facturestatic->errors);
  3029. exit;
  3030. }
  3031. $optionsav = "";
  3032. $newinvoice_static = new Facture($db);
  3033. foreach ($facids as $key => $valarray) {
  3034. $newinvoice_static->id = $key;
  3035. $newinvoice_static->ref = $valarray ['ref'];
  3036. $newinvoice_static->statut = $valarray ['status'];
  3037. $newinvoice_static->type = $valarray ['type'];
  3038. $newinvoice_static->paye = $valarray ['paye'];
  3039. $optionsav .= '<option value="'.$key.'"';
  3040. if ($key == GETPOST('fac_avoir')) {
  3041. $optionsav .= ' selected';
  3042. }
  3043. $optionsav .= '>';
  3044. $optionsav .= $newinvoice_static->ref;
  3045. $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')';
  3046. $optionsav .= '</option>';
  3047. }
  3048. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3049. $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST('type') == 2 ? ' checked' : '');
  3050. if ((!$optionsav && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) || $invoice_predefined->id > 0) {
  3051. $tmp .= ' disabled';
  3052. }
  3053. $tmp .= '> ';
  3054. // Show credit note options only if we checked credit note
  3055. print '<script type="text/javascript" language="javascript">
  3056. jQuery(document).ready(function() {
  3057. if (! jQuery("#radio_creditnote").is(":checked"))
  3058. {
  3059. jQuery("#credit_note_options").hide();
  3060. }
  3061. jQuery("#radio_creditnote").click(function() {
  3062. jQuery("#credit_note_options").show();
  3063. });
  3064. jQuery("#radio_standard, #radio_replacement, #radio_deposit").click(function() {
  3065. jQuery("#credit_note_options").hide();
  3066. });
  3067. });
  3068. </script>';
  3069. $text = '<label>'.$tmp.$langs->transnoentities("InvoiceAvoirAsk").'</label> ';
  3070. // $text.='<input type="text" value="">';
  3071. $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"';
  3072. if (!$optionsav || $invoice_predefined->id > 0) {
  3073. $text .= ' disabled';
  3074. }
  3075. $text .= '>';
  3076. if ($optionsav) {
  3077. $text .= '<option value="-1"></option>';
  3078. $text .= $optionsav;
  3079. } else {
  3080. $text .= '<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
  3081. }
  3082. $text .= '</select>';
  3083. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  3084. print $desc;
  3085. print '<div id="credit_note_options" class="clearboth">';
  3086. print '&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithLines" id="invoiceAvoirWithLines" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithLines', 'int') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithLines">'.$langs->trans('invoiceAvoirWithLines')."</label>";
  3087. print '<br>&nbsp;&nbsp;&nbsp; <input type="checkbox" name="invoiceAvoirWithPaymentRestAmount" id="invoiceAvoirWithPaymentRestAmount" value="1" onclick="$(\'#credit_note_options input[type=checkbox]\').not(this).prop(\'checked\', false);" '.(GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') > 0 ? 'checked' : '').' /> <label for="invoiceAvoirWithPaymentRestAmount">'.$langs->trans('invoiceAvoirWithPaymentRestAmount')."</label>";
  3088. print '</div>';
  3089. print '</div></div>';
  3090. }
  3091. } else {
  3092. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3093. if (empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) {
  3094. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="0" disabled> ';
  3095. } else {
  3096. $tmp = '<input type="radio" name="type" id="radio_creditnote" value="2" > ';
  3097. }
  3098. $text = '<label>'.$tmp.$langs->trans("InvoiceAvoir").'</label> ';
  3099. $text .= '<span class="opacitymedium">('.$langs->trans("YouMustCreateInvoiceFromThird").')</span> ';
  3100. $desc = $form->textwithpicto($text, $langs->transnoentities("InvoiceAvoirDesc"), 1, 'help', '', 0, 3);
  3101. print $desc;
  3102. print '</div></div>'."\n";
  3103. }
  3104. }
  3105. // Template invoice
  3106. print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">';
  3107. $tmp = '<input type="radio" name="type" id="radio_template" value="0" disabled> ';
  3108. $text = '<label>'.$tmp.$langs->trans("RepeatableInvoice").'</label> ';
  3109. //$text.= '('.$langs->trans("YouMustCreateStandardInvoiceFirst").') ';
  3110. $desc = $form->textwithpicto($text, $langs->transnoentities("YouMustCreateStandardInvoiceFirstDesc"), 1, 'help', '', 0, 3);
  3111. print $desc;
  3112. print '</div></div>';
  3113. print '</div>';
  3114. if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) { // Hidden conf
  3115. // Add auto select default document model
  3116. $listtType = array(Facture::TYPE_STANDARD, Facture::TYPE_REPLACEMENT, Facture::TYPE_CREDIT_NOTE, Facture::TYPE_DEPOSIT, Facture::TYPE_SITUATION);
  3117. $jsListType = '';
  3118. foreach ($listtType as $type) {
  3119. $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$type;
  3120. $curent = !empty($conf->global->{$thisTypeConfName}) ? $conf->global->{$thisTypeConfName}:$conf->global->FACTURE_ADDON_PDF;
  3121. $jsListType .= (!empty($jsListType) ? ',' : '').'"'.$type.'":"'.$curent.'"';
  3122. }
  3123. print '<script type="text/javascript" language="javascript">
  3124. $(document).ready(function() {
  3125. var listType = {'.$jsListType.'};
  3126. $("[name=\'type\'").change(function() {
  3127. if($( this ).prop("checked"))
  3128. {
  3129. if(($( this ).val() in listType))
  3130. {
  3131. $("#model").val(listType[$( this ).val()]);
  3132. }
  3133. else
  3134. {
  3135. $("#model").val("'.$conf->global->FACTURE_ADDON_PDF.'");
  3136. }
  3137. }
  3138. });
  3139. });
  3140. </script>';
  3141. }
  3142. print '</td></tr>';
  3143. if ($socid > 0) {
  3144. // Discounts for third party
  3145. print '<tr><td>'.$langs->trans('Discounts').'</td><td colspan="2">';
  3146. $thirdparty = $soc;
  3147. $discount_type = 0;
  3148. $backtopage = urlencode($_SERVER["PHP_SELF"].'?socid='.$thirdparty->id.'&action='.$action.'&origin='.GETPOST('origin', 'alpha').'&originid='.GETPOST('originid', 'int'));
  3149. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  3150. print '</td></tr>';
  3151. }
  3152. $newdateinvoice = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'), 'tzserver');
  3153. $date_pointoftax = dol_mktime(0, 0, 0, GETPOST('date_pointoftaxmonth', 'int'), GETPOST('date_pointoftaxday', 'int'), GETPOST('date_pointoftaxyear', 'int'), 'tzserver');
  3154. // Date invoice
  3155. print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td colspan="2">';
  3156. print $form->selectDate($newdateinvoice ? $newdateinvoice : $dateinvoice, '', '', '', '', "add", 1, 1);
  3157. print '</td></tr>';
  3158. // Date point of tax
  3159. if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
  3160. print '<tr><td class="fieldrequired">'.$langs->trans('DatePointOfTax').'</td><td colspan="2">';
  3161. print $form->selectDate($date_pointoftax ? $date_pointoftax : -1, 'date_pointoftax', '', '', '', "add", 1, 1);
  3162. print '</td></tr>';
  3163. }
  3164. // Payment term
  3165. print '<tr><td class="nowrap fieldrequired">'.$langs->trans('PaymentConditionsShort').'</td><td colspan="2">';
  3166. $form->select_conditions_paiements(GETPOSTISSET('cond_reglement_id') ? GETPOST('cond_reglement_id', 'int') : $cond_reglement_id, 'cond_reglement_id');
  3167. print '</td></tr>';
  3168. if ($conf->global->INVOICE_USE_RETAINED_WARRANTY) {
  3169. $rwStyle = 'display:none;';
  3170. if (in_array(GETPOST('type', 'int'), $retainedWarrantyInvoiceAvailableType)) {
  3171. $rwStyle = '';
  3172. }
  3173. $retained_warranty = GETPOST('retained_warranty', 'int');
  3174. if (empty($retained_warranty)) {
  3175. if (!empty($objectsrc->retained_warranty)) { // use previous situation value
  3176. $retained_warranty = $objectsrc->retained_warranty;
  3177. }
  3178. }
  3179. $retained_warranty_js_default = !empty($retained_warranty) ? $retained_warranty : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_PERCENT;
  3180. print '<tr class="retained-warranty-line" style="'.$rwStyle.'" ><td class="nowrap">'.$langs->trans('RetainedWarranty').'</td><td colspan="2">';
  3181. print '<input id="new-situation-invoice-retained-warranty" name="retained_warranty" type="number" value="'.$retained_warranty.'" step="0.01" min="0" max="100" />%';
  3182. // Retained warranty payment term
  3183. print '<tr class="retained-warranty-line" style="'.$rwStyle.'" ><td class="nowrap">'.$langs->trans('PaymentConditionsShortRetainedWarranty').'</td><td colspan="2">';
  3184. $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  3185. if (empty($retained_warranty_fk_cond_reglement)) {
  3186. $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  3187. if (!empty($objectsrc->retained_warranty_fk_cond_reglement)) { // use previous situation value
  3188. $retained_warranty_fk_cond_reglement = $objectsrc->retained_warranty_fk_cond_reglement;
  3189. } else {
  3190. $retained_warranty_fk_cond_reglement = $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  3191. }
  3192. }
  3193. $form->select_conditions_paiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
  3194. print '</td></tr>';
  3195. print '<script type="text/javascript" language="javascript">
  3196. $(document).ready(function() {
  3197. $("[name=\'type\']").change(function() {
  3198. if($( this ).prop("checked") && $.inArray($( this ).val(), '.json_encode($retainedWarrantyInvoiceAvailableType).' ) !== -1)
  3199. {
  3200. $(".retained-warranty-line").show();
  3201. $("#new-situation-invoice-retained-warranty").val("'.floatval($retained_warranty_js_default).'");
  3202. }
  3203. else{
  3204. $(".retained-warranty-line").hide();
  3205. $("#new-situation-invoice-retained-warranty").val("");
  3206. }
  3207. });
  3208. $("[name=\'type\']:checked").trigger("change");
  3209. });
  3210. </script>';
  3211. }
  3212. // Payment mode
  3213. print '<tr><td>'.$langs->trans('PaymentMode').'</td><td colspan="2">';
  3214. print img_picto('', 'bank', 'class="pictofixedwidth"');
  3215. $form->select_types_paiements(GETPOSTISSET('mode_reglement_id') ? GETPOST('mode_reglement_id') : $mode_reglement_id, 'mode_reglement_id', 'CRDT', 0, 1, 0, 0, 1, 'maxwidth200 widthcentpercentminusx');
  3216. print '</td></tr>';
  3217. // Bank Account
  3218. if (!empty($conf->banque->enabled)) {
  3219. print '<tr><td>'.$langs->trans('BankAccount').'</td><td colspan="2">';
  3220. $fk_account = GETPOST('fk_account', 'int');
  3221. print img_picto('', 'bank_account', 'class="pictofixedwidth"').$form->select_comptes(($fk_account < 0 ? '' : $fk_account), 'fk_account', 0, '', 1, '', 0, 'maxwidth200 widthcentpercentminusx', 1);
  3222. print '</td></tr>';
  3223. }
  3224. // Project
  3225. if (!empty($conf->projet->enabled)) {
  3226. $langs->load('projects');
  3227. print '<tr><td>'.$langs->trans('Project').'</td><td colspan="2">';
  3228. print img_picto('', 'project').$formproject->select_projects(($socid > 0 ? $socid : -1), $projectid, 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500 widthcentpercentminusxx');
  3229. 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>';
  3230. print '</td></tr>';
  3231. }
  3232. // Incoterms
  3233. if (!empty($conf->incoterm->enabled)) {
  3234. print '<tr>';
  3235. print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $objectsrc->label_incoterms, 1).'</label></td>';
  3236. print '<td colspan="2" class="maxwidthonsmartphone">';
  3237. $incoterm_id = GETPOST('incoterm_id');
  3238. $incoterm_location = GETPOST('location_incoterms');
  3239. if (empty($incoterm_id)) {
  3240. $incoterm_id = (!empty($objectsrc->fk_incoterms) ? $objectsrc->fk_incoterms : $soc->fk_incoterms);
  3241. $incoterm_location = (!empty($objectsrc->location_incoterms) ? $objectsrc->location_incoterms : $soc->location_incoterms);
  3242. }
  3243. print $form->select_incoterms($incoterm_id, $incoterm_location);
  3244. print '</td></tr>';
  3245. }
  3246. // Other attributes
  3247. $parameters = array('objectsrc' => $objectsrc, 'colspan' => ' colspan="2"', 'cols' => '2', 'socid'=>$socid);
  3248. $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  3249. print $hookmanager->resPrint;
  3250. if (empty($reshook)) {
  3251. if (!empty($conf->global->THIRDPARTY_PROPAGATE_EXTRAFIELDS_TO_INVOICE) && !empty($soc->id)) {
  3252. // copy from thirdparty
  3253. $tpExtrafields = new Extrafields($db);
  3254. $tpExtrafieldLabels = $tpExtrafields->fetch_name_optionals_label($soc->table_element);
  3255. if ($soc->fetch_optionals() > 0) {
  3256. $object->array_options = array_merge($object->array_options, $soc->array_options);
  3257. }
  3258. };
  3259. print $object->showOptionals($extrafields, 'create', $parameters);
  3260. }
  3261. // Template to use by default
  3262. print '<tr><td>'.$langs->trans('Model').'</td>';
  3263. print '<td colspan="2">';
  3264. print img_picto('', 'pdf', 'class="pictofixedwidth"');
  3265. include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
  3266. $liste = ModelePDFFactures::liste_modeles($db);
  3267. if (!empty($conf->global->INVOICE_USE_DEFAULT_DOCUMENT)) {
  3268. // Hidden conf
  3269. $paramkey = 'FACTURE_ADDON_PDF_'.$object->type;
  3270. $preselected = !empty($conf->global->$paramkey) ? $conf->global->$paramkey : $conf->global->FACTURE_ADDON_PDF;
  3271. } else {
  3272. $preselected = $conf->global->FACTURE_ADDON_PDF;
  3273. }
  3274. print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1);
  3275. print "</td></tr>";
  3276. // Multicurrency
  3277. if (!empty($conf->multicurrency->enabled)) {
  3278. print '<tr>';
  3279. print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>';
  3280. print '<td colspan="2" class="maxwidthonsmartphone">';
  3281. print $form->selectMultiCurrency($currency_code, 'multicurrency_code');
  3282. print '</td></tr>';
  3283. }
  3284. // Help of substitution key
  3285. $htmltext = '';
  3286. if (GETPOST('fac_rec', 'int') > 0) {
  3287. $dateexample = ($newdateinvoice ? $newdateinvoice : $dateinvoice);
  3288. if (empty($dateexample)) {
  3289. $dateexample = dol_now();
  3290. }
  3291. $substitutionarray = array(
  3292. '__TOTAL_HT__' => $langs->trans("AmountHT").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ht).')',
  3293. '__TOTAL_TTC__' => $langs->trans("AmountTTC").' ('.$langs->trans("Example").': '.price($exampletemplateinvoice->total_ttc).')',
  3294. '__INVOICE_PREVIOUS_MONTH__' => $langs->trans("PreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%m').')',
  3295. '__INVOICE_MONTH__' => $langs->trans("MonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%m').')',
  3296. '__INVOICE_NEXT_MONTH__' => $langs->trans("NextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%m').')',
  3297. '__INVOICE_PREVIOUS_MONTH_TEXT__' => $langs->trans("TextPreviousMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'm'), '%B').')',
  3298. '__INVOICE_MONTH_TEXT__' => $langs->trans("TextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%B').')',
  3299. '__INVOICE_NEXT_MONTH_TEXT__' => $langs->trans("TextNextMonthOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'm'), '%B').')',
  3300. '__INVOICE_PREVIOUS_YEAR__' => $langs->trans("PreviousYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, -1, 'y'), '%Y').')',
  3301. '__INVOICE_YEAR__' => $langs->trans("YearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date($dateexample, '%Y').')',
  3302. '__INVOICE_NEXT_YEAR__' => $langs->trans("NextYearOfInvoice").' ('.$langs->trans("Example").': '.dol_print_date(dol_time_plus_duree($dateexample, 1, 'y'), '%Y').')'
  3303. );
  3304. $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
  3305. foreach ($substitutionarray as $key => $val) {
  3306. $htmltext .= $key.' = '.$langs->trans($val).'<br>';
  3307. }
  3308. $htmltext .= '</i>';
  3309. }
  3310. // Public note
  3311. print '<tr>';
  3312. print '<td class="tdtop">';
  3313. print $form->textwithpicto($langs->trans('NotePublic'), $htmltext);
  3314. print '</td>';
  3315. print '<td valign="top" colspan="2">';
  3316. $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PUBLIC) ? 0 : 1, ROWS_3, '90%');
  3317. print $doleditor->Create(1);
  3318. // Private note
  3319. if (empty($user->socid)) {
  3320. print '<tr>';
  3321. print '<td class="tdtop">';
  3322. print $form->textwithpicto($langs->trans('NotePrivate'), $htmltext);
  3323. print '</td>';
  3324. print '<td valign="top" colspan="2">';
  3325. $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%');
  3326. print $doleditor->Create(1);
  3327. // print '<textarea name="note_private" wrap="soft" cols="70" rows="'.ROWS_3.'">'.$note_private.'.</textarea>
  3328. print '</td></tr>';
  3329. }
  3330. // Lines from source (TODO Show them also when creating invoice from template invoice)
  3331. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  3332. $langs->loadLangs(array('orders', 'propal'));
  3333. // TODO for compatibility
  3334. if ($origin == 'contrat') {
  3335. // Calcul contrat->price (HT), contrat->total (TTC), contrat->tva
  3336. $objectsrc->remise_absolue = $remise_absolue;
  3337. $objectsrc->remise_percent = $remise_percent;
  3338. $objectsrc->update_price(1, - 1, 1);
  3339. }
  3340. print "\n<!-- Show ref of origin ".$classname." -->\n";
  3341. print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n";
  3342. print '<input type="hidden" name="total" value="'.$objectsrc->total_ttc.'">'."\n";
  3343. print '<input type="hidden" name="tva" value="'.$objectsrc->total_tva.'">'."\n";
  3344. print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">';
  3345. print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">';
  3346. switch (get_class($objectsrc)) {
  3347. case 'Propal':
  3348. $newclassname = 'CommercialProposal';
  3349. break;
  3350. case 'Commande':
  3351. $newclassname = 'Order';
  3352. break;
  3353. case 'Expedition':
  3354. $newclassname = 'Sending';
  3355. break;
  3356. case 'Contrat':
  3357. $newclassname = 'Contract';
  3358. break;
  3359. case 'Fichinter':
  3360. $newclassname = 'Intervention';
  3361. break;
  3362. default:
  3363. $newclassname = get_class($objectsrc);
  3364. }
  3365. // Ref of origin
  3366. print '<tr><td>'.$langs->trans($newclassname).'</td>';
  3367. print '<td colspan="2">';
  3368. print $objectsrc->getNomUrl(1);
  3369. // We check if Origin document (id and type is known) has already at least one invoice attached to it
  3370. $objectsrc->fetchObjectLinked($originid, $origin, '', 'facture');
  3371. if (is_array($objectsrc->linkedObjects['facture']) && count($objectsrc->linkedObjects['facture']) >= 1) {
  3372. setEventMessages('WarningBillExist', null, 'warnings');
  3373. echo ' - '.$langs->trans('LatestRelatedBill').' '.end($objectsrc->linkedObjects['facture'])->getNomUrl(1);
  3374. }
  3375. echo '</td></tr>';
  3376. print '<tr><td>'.$langs->trans('AmountHT').'</td><td colspan="2">'.price($objectsrc->total_ht).'</td></tr>';
  3377. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td colspan="2">'.price($objectsrc->total_tva)."</td></tr>";
  3378. if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1
  3379. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1)."</td></tr>";
  3380. }
  3381. if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2
  3382. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2)."</td></tr>";
  3383. }
  3384. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc)."</td></tr>";
  3385. if (!empty($conf->multicurrency->enabled)) {
  3386. print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ht).'</td></tr>';
  3387. print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_tva)."</td></tr>";
  3388. print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td colspan="2">'.price($objectsrc->multicurrency_total_ttc)."</td></tr>";
  3389. }
  3390. }
  3391. print "</table>\n";
  3392. print dol_get_fiche_end();
  3393. // Button "Create Draft"
  3394. print '<div class="center">';
  3395. print '<input type="submit" class="button" name="bouton" value="'.$langs->trans('CreateDraft').'">';
  3396. print '<input type="button" class="button button-cancel" value="'.$langs->trans("Cancel").'" onClick="javascript:history.go(-1)">';
  3397. print '</div>';
  3398. // Show origin lines
  3399. if (!empty($origin) && !empty($originid) && is_object($objectsrc)) {
  3400. print '<br>';
  3401. $title = $langs->trans('ProductsAndServices');
  3402. print load_fiche_titre($title);
  3403. print '<table class="noborder centpercent">';
  3404. $objectsrc->printOriginLinesList('', $selectedLines);
  3405. print '</table>';
  3406. }
  3407. print '</form>';
  3408. } elseif ($id > 0 || !empty($ref)) {
  3409. /*
  3410. * Show object in view mode
  3411. */
  3412. $result = $object->fetch($id, $ref);
  3413. if ($result <= 0) {
  3414. dol_print_error($db, $object->error, $object->errors);
  3415. exit();
  3416. }
  3417. // fetch optionals attributes and labels
  3418. $extrafields->fetch_name_optionals_label($object->table_element);
  3419. if ($user->socid > 0 && $user->socid != $object->socid) {
  3420. accessforbidden('', 0, 1);
  3421. }
  3422. $result = $object->fetch_thirdparty();
  3423. $result = $soc->fetch($object->socid);
  3424. if ($result < 0) {
  3425. dol_print_error($db);
  3426. }
  3427. $selleruserevenustamp = $mysoc->useRevenueStamp();
  3428. $totalpaye = $object->getSommePaiement();
  3429. $totalcreditnotes = $object->getSumCreditNotesUsed();
  3430. $totaldeposits = $object->getSumDepositsUsed();
  3431. // print "totalpaye=".$totalpaye." totalcreditnotes=".$totalcreditnotes." totaldeposts=".$totaldeposits."
  3432. // selleruserrevenuestamp=".$selleruserevenustamp;
  3433. // We can also use bcadd to avoid pb with floating points
  3434. // For example print 239.2 - 229.3 - 9.9; does not return 0.
  3435. // $resteapayer=bcadd($object->total_ttc,$totalpaye,$conf->global->MAIN_MAX_DECIMALS_TOT);
  3436. // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT);
  3437. $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');
  3438. // Multicurrency
  3439. if (!empty($conf->multicurrency->enabled)) {
  3440. $multicurrency_totalpaye = $object->getSommePaiement(1);
  3441. $multicurrency_totalcreditnotes = $object->getSumCreditNotesUsed(1);
  3442. $multicurrency_totaldeposits = $object->getSumDepositsUsed(1);
  3443. $multicurrency_resteapayer = price2num($object->multicurrency_total_ttc - $multicurrency_totalpaye - $multicurrency_totalcreditnotes - $multicurrency_totaldeposits, 'MT');
  3444. $resteapayer = price2num($multicurrency_resteapayer / $object->multicurrency_tx, 'MT');
  3445. }
  3446. if ($object->paye) {
  3447. $resteapayer = 0;
  3448. }
  3449. $resteapayeraffiche = $resteapayer;
  3450. if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { // Never use this
  3451. $filterabsolutediscount = "fk_facture_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  3452. $filtercreditnote = "fk_facture_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
  3453. } else {
  3454. $filterabsolutediscount = "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')";
  3455. $filtercreditnote = "fk_facture_source IS NOT NULL AND (description NOT LIKE '(DEPOSIT)%' OR description LIKE '(EXCESS RECEIVED)%')";
  3456. }
  3457. $absolute_discount = $soc->getAvailableDiscounts('', $filterabsolutediscount);
  3458. $absolute_creditnote = $soc->getAvailableDiscounts('', $filtercreditnote);
  3459. $absolute_discount = price2num($absolute_discount, 'MT');
  3460. $absolute_creditnote = price2num($absolute_creditnote, 'MT');
  3461. $author = new User($db);
  3462. if ($object->user_author) {
  3463. $author->fetch($object->user_author);
  3464. }
  3465. $objectidnext = $object->getIdReplacingInvoice();
  3466. $head = facture_prepare_head($object);
  3467. print dol_get_fiche_head($head, 'compta', $langs->trans('InvoiceCustomer'), -1, 'bill');
  3468. $formconfirm = '';
  3469. // Confirmation de la conversion de l'avoir en reduc
  3470. if ($action == 'converttoreduc') {
  3471. if ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) {
  3472. $type_fac = 'ExcessReceived';
  3473. } elseif ($object->type == Facture::TYPE_CREDIT_NOTE) {
  3474. $type_fac = 'CreditNote';
  3475. } elseif ($object->type == Facture::TYPE_DEPOSIT) {
  3476. $type_fac = 'Deposit';
  3477. }
  3478. $text = $langs->trans('ConfirmConvertToReduc', strtolower($langs->transnoentities($type_fac)));
  3479. $text .= '<br>'.$langs->trans('ConfirmConvertToReduc2');
  3480. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2);
  3481. }
  3482. // Confirmation to delete invoice
  3483. if ($action == 'delete') {
  3484. $text = $langs->trans('ConfirmDeleteBill', $object->ref);
  3485. $formquestion = array();
  3486. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $object->statut >= 1) {
  3487. $qualified_for_stock_change = 0;
  3488. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  3489. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  3490. } else {
  3491. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  3492. }
  3493. if ($qualified_for_stock_change) {
  3494. $langs->load("stocks");
  3495. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  3496. $formproduct = new FormProduct($db);
  3497. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  3498. $forcecombo = 0;
  3499. if ($conf->browser->name == 'ie') {
  3500. $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy
  3501. }
  3502. $formquestion = array(
  3503. // 'text' => $langs->trans("ConfirmClone"),
  3504. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
  3505. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
  3506. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1, 0, 0, $langs->trans("NoStockAction"), 0, $forcecombo))
  3507. );
  3508. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', $formquestion, "yes", 1);
  3509. } else {
  3510. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
  3511. }
  3512. } else {
  3513. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('DeleteBill'), $text, 'confirm_delete', '', 'no', 1);
  3514. }
  3515. }
  3516. // Confirmation to remove invoice from cycle
  3517. if ($action == 'situationout') {
  3518. $text = $langs->trans('ConfirmRemoveSituationFromCycle', $object->ref);
  3519. $label = $langs->trans("ConfirmOuting");
  3520. $formquestion = array();
  3521. // remove situation from cycle
  3522. if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  3523. && $usercancreate
  3524. && !$objectidnext
  3525. && $object->is_last_in_cycle()
  3526. && $usercanunvalidate
  3527. ) {
  3528. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $label, $text, 'confirm_situationout', $formquestion, "yes", 1);
  3529. }
  3530. }
  3531. // Confirmation of validation
  3532. if ($action == 'valid') {
  3533. // we check object has a draft number
  3534. $objectref = substr($object->ref, 1, 4);
  3535. if ($objectref == 'PROV') {
  3536. $savdate = $object->date;
  3537. if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
  3538. $object->date = dol_now();
  3539. $object->date_lim_reglement = $object->calculate_date_lim_reglement();
  3540. }
  3541. $numref = $object->getNextNumRef($soc);
  3542. // $object->date=$savdate;
  3543. } else {
  3544. $numref = $object->ref;
  3545. }
  3546. $text = $langs->trans('ConfirmValidateBill', $numref);
  3547. if (!empty($conf->notification->enabled)) {
  3548. require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
  3549. $notify = new Notify($db);
  3550. $text .= '<br>';
  3551. $text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
  3552. }
  3553. $formquestion = array();
  3554. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  3555. $qualified_for_stock_change = 0;
  3556. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  3557. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  3558. } else {
  3559. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  3560. }
  3561. if ($qualified_for_stock_change) {
  3562. $langs->load("stocks");
  3563. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  3564. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  3565. $formproduct = new FormProduct($db);
  3566. $warehouse = new Entrepot($db);
  3567. $warehouse_array = $warehouse->list_array();
  3568. if (count($warehouse_array) == 1) {
  3569. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array));
  3570. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
  3571. } else {
  3572. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease");
  3573. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  3574. }
  3575. $formquestion = array(
  3576. // 'text' => $langs->trans("ConfirmClone"),
  3577. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  3578. // 1),
  3579. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  3580. // => 1),
  3581. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value));
  3582. }
  3583. }
  3584. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) { // Can happen only if $conf->global->FACTURE_ENABLE_NEGATIVE is on
  3585. $text .= '<br>'.img_warning().' '.$langs->trans("ErrorInvoiceOfThisTypeMustBePositive");
  3586. }
  3587. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, (($object->type != Facture::TYPE_CREDIT_NOTE && $object->total_ttc < 0) ? "no" : "yes"), 2);
  3588. }
  3589. // Confirm back to draft status
  3590. if ($action == 'modif') {
  3591. $text = $langs->trans('ConfirmUnvalidateBill', $object->ref);
  3592. $formquestion = array();
  3593. if ($object->type != Facture::TYPE_DEPOSIT && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  3594. $qualified_for_stock_change = 0;
  3595. if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  3596. $qualified_for_stock_change = $object->hasProductsOrServices(2);
  3597. } else {
  3598. $qualified_for_stock_change = $object->hasProductsOrServices(1);
  3599. }
  3600. if ($qualified_for_stock_change) {
  3601. $langs->load("stocks");
  3602. require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
  3603. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  3604. $formproduct = new FormProduct($db);
  3605. $warehouse = new Entrepot($db);
  3606. $warehouse_array = $warehouse->list_array();
  3607. if (count($warehouse_array) == 1) {
  3608. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array));
  3609. $value = '<input type="hidden" id="idwarehouse" name="idwarehouse" value="'.key($warehouse_array).'">';
  3610. } else {
  3611. $label = $object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease");
  3612. $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1);
  3613. }
  3614. $formquestion = array(
  3615. // 'text' => $langs->trans("ConfirmClone"),
  3616. // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' =>
  3617. // 1),
  3618. // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value'
  3619. // => 1),
  3620. array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value));
  3621. }
  3622. }
  3623. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('UnvalidateBill'), $text, 'confirm_modif', $formquestion, "yes", 1);
  3624. }
  3625. // Confirmation du classement paye
  3626. if ($action == 'paid' && $resteapayer <= 0) {
  3627. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', "yes", 1);
  3628. }
  3629. if ($action == 'paid' && $resteapayer > 0) {
  3630. $close = array();
  3631. // Code
  3632. $i = 0;
  3633. $close[$i]['code'] = 'discount_vat'; // escompte
  3634. $i++;
  3635. $close[$i]['code'] = 'badcustomer';
  3636. $i++;
  3637. $close[$i]['code'] = 'other';
  3638. $i++;
  3639. // Help
  3640. $i = 0;
  3641. $close[$i]['label'] = $langs->trans("HelpEscompte").'<br><br>'.$langs->trans("ConfirmClassifyPaidPartiallyReasonDiscountVatDesc");
  3642. $i++;
  3643. $close[$i]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  3644. $i++;
  3645. $close[$i]['label'] = $langs->trans("Other");
  3646. $i++;
  3647. // Texte
  3648. $i = 0;
  3649. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonDiscount", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
  3650. $i++;
  3651. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $resteapayer, $langs->trans("Currency".$conf->currency)), $close[$i]['label'], 1);
  3652. $i++;
  3653. $close[$i]['reason'] = $form->textwithpicto($langs->transnoentities("Other"), $close[$i]['label'], 1);
  3654. $i++;
  3655. // arrayreasons[code]=reason
  3656. foreach ($close as $key => $val) {
  3657. $arrayreasons[$close[$key]['code']] = $close[$key]['reason'];
  3658. }
  3659. // Cree un tableau formulaire
  3660. $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'));
  3661. // Paiement incomplet. On demande si motif = escompte ou autre
  3662. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidPartially', $object->ref), 'confirm_paid_partially', $formquestion, "yes", 1, 310);
  3663. }
  3664. // Confirmation du classement abandonne
  3665. if ($action == 'canceled') {
  3666. // S'il y a une facture de remplacement pas encore validee (etat brouillon),
  3667. // on ne permet pas de classer abandonner la facture.
  3668. if ($objectidnext) {
  3669. $facturereplacement = new Facture($db);
  3670. $facturereplacement->fetch($objectidnext);
  3671. $statusreplacement = $facturereplacement->statut;
  3672. }
  3673. if ($objectidnext && $statusreplacement == 0) {
  3674. print '<div class="error">'.$langs->trans("ErrorCantCancelIfReplacementInvoiceNotValidated").'</div>';
  3675. } else {
  3676. // Code
  3677. $close[1]['code'] = 'badcustomer';
  3678. $close[2]['code'] = 'abandon';
  3679. // Help
  3680. $close[1]['label'] = $langs->trans("ConfirmClassifyPaidPartiallyReasonBadCustomerDesc");
  3681. $close[2]['label'] = $langs->trans("ConfirmClassifyAbandonReasonOtherDesc");
  3682. // Texte
  3683. $close[1]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyPaidPartiallyReasonBadCustomer", $object->ref), $close[1]['label'], 1);
  3684. $close[2]['reason'] = $form->textwithpicto($langs->transnoentities("ConfirmClassifyAbandonReasonOther"), $close[2]['label'], 1);
  3685. // arrayreasons
  3686. $arrayreasons[$close[1]['code']] = $close[1]['reason'];
  3687. $arrayreasons[$close[2]['code']] = $close[2]['reason'];
  3688. // Cree un tableau formulaire
  3689. $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'));
  3690. $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('CancelBill'), $langs->trans('ConfirmCancelBill', $object->ref), 'confirm_canceled', $formquestion, "yes", 1, 250);
  3691. }
  3692. }
  3693. if ($action == 'deletepayment') {
  3694. $payment_id = GETPOST('paiement_id');
  3695. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 'no', 1);
  3696. }
  3697. // Confirmation de la suppression d'une ligne produit
  3698. if ($action == 'ask_deleteline') {
  3699. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 'no', 1);
  3700. }
  3701. // Clone confirmation
  3702. if ($action == 'clone') {
  3703. // Create an array for form
  3704. $formquestion = array(
  3705. array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company($object->socid, 'socid', '(s.client=1 OR s.client=2 OR s.client=3)', 1)),
  3706. array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now())
  3707. );
  3708. // Ask confirmatio to clone
  3709. $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?facid='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250);
  3710. }
  3711. if ($action == "remove_file_comfirm") {
  3712. $file = GETPOST('file', 'alpha');
  3713. $formconfirm = $form->formconfirm(
  3714. $_SERVER["PHP_SELF"].'?facid='.$object->id.'&file='.$file,
  3715. $langs->trans('DeleteFileHeader'),
  3716. $langs->trans('DeleteFileText')."<br><br>".$file,
  3717. 'remove_file',
  3718. '',
  3719. 'no',
  3720. 2
  3721. );
  3722. }
  3723. // Call Hook formConfirm
  3724. $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid, 'remainingtopay' => &$resteapayer);
  3725. $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  3726. if (empty($reshook)) {
  3727. $formconfirm .= $hookmanager->resPrint;
  3728. } elseif ($reshook > 0) {
  3729. $formconfirm = $hookmanager->resPrint;
  3730. }
  3731. // Print form confirm
  3732. print $formconfirm;
  3733. // Invoice content
  3734. $linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
  3735. $morehtmlref = '<div class="refidno">';
  3736. // Ref invoice
  3737. if ($object->status == $object::STATUS_DRAFT && !$mysoc->isInEEC() && !empty($conf->global->INVOICE_ALLOW_FREE_REF)) {
  3738. $morehtmlref .= $form->editfieldkey("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', 0, 1);
  3739. $morehtmlref .= $form->editfieldval("Ref", 'ref', $object->ref, $object, $usercancreate, 'string', '', null, null, '', 1);
  3740. $morehtmlref .= '<br>';
  3741. }
  3742. // Ref customer
  3743. $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1);
  3744. $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', null, null, '', 1);
  3745. // Thirdparty
  3746. $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer');
  3747. if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) {
  3748. $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->thirdparty->id.'&search_societe='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
  3749. }
  3750. // Project
  3751. if (!empty($conf->projet->enabled)) {
  3752. $langs->load("projects");
  3753. $morehtmlref .= '<br>'.$langs->trans('Project').' ';
  3754. if ($usercancreate) {
  3755. if ($action != 'classify') {
  3756. $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : ';
  3757. }
  3758. if ($action == 'classify') {
  3759. //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1);
  3760. $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">';
  3761. $morehtmlref .= '<input type="hidden" name="action" value="classin">';
  3762. $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">';
  3763. $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1);
  3764. $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  3765. $morehtmlref .= '</form>';
  3766. } else {
  3767. $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1);
  3768. }
  3769. } else {
  3770. if (!empty($object->fk_project)) {
  3771. $proj = new Project($db);
  3772. $proj->fetch($object->fk_project);
  3773. $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
  3774. $morehtmlref .= $proj->ref;
  3775. $morehtmlref .= '</a>';
  3776. } else {
  3777. $morehtmlref .= '';
  3778. }
  3779. }
  3780. }
  3781. $morehtmlref .= '</div>';
  3782. $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status
  3783. dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '');
  3784. print '<div class="fichecenter">';
  3785. print '<div class="fichehalfleft">';
  3786. print '<div class="underbanner clearboth"></div>';
  3787. print '<table class="border tableforfield" width="100%">';
  3788. // Type
  3789. print '<tr><td class="titlefield fieldname_type">'.$langs->trans('Type').'</td><td class="valuefield fieldname_type">';
  3790. print '<span class="badgeneutral">';
  3791. print $object->getLibType();
  3792. print '</span>';
  3793. if ($object->module_source) {
  3794. print ' <span class="opacitymediumbycolor paddingleft">('.$langs->trans("POS").' '.ucfirst($object->module_source).' - '.$langs->trans("Terminal").' '.$object->pos_source.')</span>';
  3795. }
  3796. if ($object->type == Facture::TYPE_REPLACEMENT) {
  3797. $facreplaced = new Facture($db);
  3798. $facreplaced->fetch($object->fk_facture_source);
  3799. print ' <span class="opacitymediumbycolor paddingleft">('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')</span>';
  3800. }
  3801. if ($object->type == Facture::TYPE_CREDIT_NOTE && !empty($object->fk_facture_source)) {
  3802. $facusing = new Facture($db);
  3803. $facusing->fetch($object->fk_facture_source);
  3804. print ' <span class="opacitymediumbycolor paddingleft">('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')</span>';
  3805. }
  3806. $facidavoir = $object->getListIdAvoirFromInvoice();
  3807. if (count($facidavoir) > 0) {
  3808. print ' <span class="opacitymediumbycolor paddingleft">('.$langs->transnoentities("InvoiceHasAvoir");
  3809. $i = 0;
  3810. foreach ($facidavoir as $id) {
  3811. if ($i == 0) {
  3812. print ' ';
  3813. } else {
  3814. print ',';
  3815. }
  3816. $facavoir = new Facture($db);
  3817. $facavoir->fetch($id);
  3818. print $facavoir->getNomUrl(1);
  3819. }
  3820. print ')</span>';
  3821. }
  3822. if ($objectidnext > 0) {
  3823. $facthatreplace = new Facture($db);
  3824. $facthatreplace->fetch($objectidnext);
  3825. print ' <span class="opacitymediumbycolor paddingleft">('.str_replace('{s1}', $facthatreplace->getNomUrl(1), $langs->transnoentities("ReplacedByInvoice", '{s1}')).')</span>';
  3826. }
  3827. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT) {
  3828. $discount = new DiscountAbsolute($db);
  3829. $result = $discount->fetch(0, $object->id);
  3830. if ($result > 0) {
  3831. print ' <span class="opacitymediumbycolor paddingleft">';
  3832. $s = $langs->trans("CreditNoteConvertedIntoDiscount", '{s1}', '{s2}');
  3833. $s = str_replace('{s1}', $object->getLibType(1), $s);
  3834. $s = str_replace('{s2}', $discount->getNomUrl(1, 'discount'), $s);
  3835. print $s;
  3836. print '</span><br>';
  3837. }
  3838. }
  3839. if ($object->fk_fac_rec_source > 0) {
  3840. $tmptemplate = new FactureRec($db);
  3841. $result = $tmptemplate->fetch($object->fk_fac_rec_source);
  3842. if ($result > 0) {
  3843. print ' <span class="opacitymediumbycolor paddingleft">';
  3844. $s = $langs->transnoentities("GeneratedFromTemplate", '{s1}');
  3845. $s = str_replace('{s1}', '<a href="'.DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$tmptemplate->id.'">'.dol_escape_htmltag($tmptemplate->ref).'</a>', $s);
  3846. print $s;
  3847. print '</span>';
  3848. }
  3849. }
  3850. print '</td></tr>';
  3851. // Relative and absolute discounts
  3852. print '<!-- Discounts -->'."\n";
  3853. print '<tr><td>'.$langs->trans('Discounts');
  3854. print '</td><td>';
  3855. $thirdparty = $soc;
  3856. $discount_type = 0;
  3857. $backtopage = urlencode($_SERVER["PHP_SELF"].'?facid='.$object->id);
  3858. include DOL_DOCUMENT_ROOT.'/core/tpl/object_discounts.tpl.php';
  3859. print '</td></tr>';
  3860. // Date invoice
  3861. print '<tr><td>';
  3862. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3863. print $langs->trans('DateInvoice');
  3864. print '</td>';
  3865. if ($action != 'editinvoicedate' && !empty($object->brouillon) && $usercancreate && empty($conf->global->FAC_FORCE_DATE_VALIDATION)) {
  3866. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editinvoicedate&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
  3867. }
  3868. print '</tr></table>';
  3869. print '</td><td>';
  3870. if ($action == 'editinvoicedate') {
  3871. $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date, 'invoicedate');
  3872. } else {
  3873. print '<span class="valuedate">'.dol_print_date($object->date, 'day').'</span>';
  3874. }
  3875. print '</td>';
  3876. print '</tr>';
  3877. if (!empty($conf->global->INVOICE_POINTOFTAX_DATE)) {
  3878. // Date invoice
  3879. print '<tr><td>';
  3880. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3881. print $langs->trans('DatePointOfTax');
  3882. print '</td>';
  3883. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_pointoftax&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
  3884. print '</tr></table>';
  3885. print '</td><td>';
  3886. if ($action == 'editdate_pointoftax') {
  3887. $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date_pointoftax, 'date_pointoftax');
  3888. } else {
  3889. print '<span class="valuedate">'.dol_print_date($object->date_pointoftax, 'day').'</span>';
  3890. }
  3891. print '</td></tr>';
  3892. }
  3893. // Payment term
  3894. print '<tr><td>';
  3895. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3896. print $langs->trans('PaymentConditionsShort');
  3897. print '</td>';
  3898. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editconditions' && $usercancreate) {
  3899. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>';
  3900. }
  3901. print '</tr></table>';
  3902. print '</td><td>';
  3903. if ($object->type != Facture::TYPE_CREDIT_NOTE) {
  3904. if ($action == 'editconditions') {
  3905. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'cond_reglement_id');
  3906. } else {
  3907. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->cond_reglement_id, 'none');
  3908. }
  3909. } else {
  3910. print '&nbsp;';
  3911. }
  3912. print '</td></tr>';
  3913. // Date payment term
  3914. print '<tr><td>';
  3915. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3916. print $langs->trans('DateMaxPayment');
  3917. print '</td>';
  3918. if ($object->type != Facture::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && $usercancreate) {
  3919. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editpaymentterm&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetDate'), 1).'</a></td>';
  3920. }
  3921. print '</tr></table>';
  3922. print '</td><td>';
  3923. if ($object->type != Facture::TYPE_CREDIT_NOTE) {
  3924. if ($action == 'editpaymentterm') {
  3925. $form->form_date($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->date_lim_reglement, 'paymentterm');
  3926. } else {
  3927. print '<span class="valuedate">'.dol_print_date($object->date_lim_reglement, 'day').'</span>';
  3928. if ($object->hasDelay()) {
  3929. print img_warning($langs->trans('Late'));
  3930. }
  3931. }
  3932. } else {
  3933. print '&nbsp;';
  3934. }
  3935. print '</td></tr>';
  3936. // Payment mode
  3937. print '<tr><td>';
  3938. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3939. print $langs->trans('PaymentMode');
  3940. print '</td>';
  3941. if ($action != 'editmode' && $usercancreate) {
  3942. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>';
  3943. }
  3944. print '</tr></table>';
  3945. print '</td><td>';
  3946. if ($action == 'editmode') {
  3947. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'CRDT', 1, 1);
  3948. } else {
  3949. $form->form_modes_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->mode_reglement_id, 'none', 'CRDT');
  3950. }
  3951. print '</td></tr>';
  3952. // Multicurrency
  3953. if (!empty($conf->multicurrency->enabled)) {
  3954. // Multicurrency code
  3955. print '<tr>';
  3956. print '<td>';
  3957. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3958. print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0);
  3959. print '</td>';
  3960. if ($usercancreate && $action != 'editmulticurrencycode' && !empty($object->brouillon)) {
  3961. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
  3962. }
  3963. print '</tr></table>';
  3964. print '</td><td>';
  3965. $htmlname = (($usercancreate && $action == 'editmulticurrencycode') ? 'multicurrency_code' : 'none');
  3966. $form->form_multicurrency_code($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_code, $htmlname);
  3967. print '</td></tr>';
  3968. // Multicurrency rate
  3969. if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) {
  3970. print '<tr>';
  3971. print '<td>';
  3972. print '<table class="nobordernopadding" width="100%"><tr><td>';
  3973. print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0);
  3974. print '</td>';
  3975. if ($usercancreate && $action != 'editmulticurrencyrate' && !empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  3976. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>';
  3977. }
  3978. print '</tr></table>';
  3979. print '</td><td>';
  3980. if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') {
  3981. if ($action == 'actualizemulticurrencyrate') {
  3982. list($object->fk_multicurrency, $object->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($object->db, $object->multicurrency_code);
  3983. }
  3984. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, ($usercancreate ? 'multicurrency_tx' : 'none'), $object->multicurrency_code);
  3985. } else {
  3986. $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$object->id, $object->multicurrency_tx, 'none', $object->multicurrency_code);
  3987. if ($object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) {
  3988. print '<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; ';
  3989. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=actualizemulticurrencyrate">'.$langs->trans("ActualizeCurrency").'</a>';
  3990. print '</div>';
  3991. }
  3992. }
  3993. print '</td></tr>';
  3994. }
  3995. }
  3996. // Bank Account
  3997. if (!empty($conf->banque->enabled)) {
  3998. print '<tr><td class="nowrap">';
  3999. print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">';
  4000. print $langs->trans('BankAccount');
  4001. print '<td>';
  4002. if (($action != 'editbankaccount') && $usercancreate) {
  4003. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>';
  4004. }
  4005. print '</tr></table>';
  4006. print '</td><td>';
  4007. if ($action == 'editbankaccount') {
  4008. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1);
  4009. } else {
  4010. $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none');
  4011. }
  4012. print "</td>";
  4013. print '</tr>';
  4014. }
  4015. // Incoterms
  4016. if (!empty($conf->incoterm->enabled)) {
  4017. print '<tr><td>';
  4018. print '<table width="100%" class="nobordernopadding"><tr><td>';
  4019. print $langs->trans('IncotermLabel');
  4020. print '<td><td class="right">';
  4021. if ($usercancreate) {
  4022. print '<a class="editfielda" href="'.DOL_URL_ROOT.'/compta/facture/card.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>';
  4023. } else {
  4024. print '&nbsp;';
  4025. }
  4026. print '</td></tr></table>';
  4027. print '</td>';
  4028. print '<td>';
  4029. if ($action != 'editincoterm') {
  4030. print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1);
  4031. } else {
  4032. print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id);
  4033. }
  4034. print '</td></tr>';
  4035. }
  4036. if (!empty($object->retained_warranty) || !empty($conf->global->INVOICE_USE_RETAINED_WARRANTY)) {
  4037. $displayWarranty = true;
  4038. if (!in_array($object->type, $retainedWarrantyInvoiceAvailableType) && empty($object->retained_warranty)) {
  4039. $displayWarranty = false;
  4040. }
  4041. if ($displayWarranty) {
  4042. // Retained Warranty
  4043. print '<tr class="retained-warranty-lines" ><td>';
  4044. print '<table id="retained-warranty-table" class="nobordernopadding" width="100%"><tr><td>';
  4045. print $langs->trans('RetainedWarranty');
  4046. print '</td>';
  4047. if ($action != 'editretainedwarranty' && $user->rights->facture->creer) {
  4048. print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarranty&amp;facid='.$object->id.'">'.img_edit($langs->trans('setretainedwarranty'), 1).'</a></td>';
  4049. }
  4050. print '</tr></table>';
  4051. print '</td><td>';
  4052. if ($action == 'editretainedwarranty') {
  4053. print '<form id="retained-warranty-form" method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
  4054. print '<input type="hidden" name="action" value="setretainedwarranty">';
  4055. print '<input type="hidden" name="token" value="'.newToken().'">';
  4056. print '<input name="retained_warranty" type="number" step="0.01" min="0" max="100" value="'.$object->retained_warranty.'" >';
  4057. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4058. print '</form>';
  4059. } else {
  4060. print price($object->retained_warranty).'%';
  4061. }
  4062. print '</td></tr>';
  4063. // Retained warranty payment term
  4064. print '<tr class="retained-warranty-lines" ><td>';
  4065. print '<table id="retained-warranty-cond-reglement-table" class="nobordernopadding" width="100%"><tr><td>';
  4066. print $langs->trans('PaymentConditionsShortRetainedWarranty');
  4067. print '</td>';
  4068. if ($action != 'editretainedwarrantypaymentterms' && $user->rights->facture->creer) {
  4069. print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarrantypaymentterms&amp;facid='.$object->id.'">'.img_edit($langs->trans('setPaymentConditionsShortRetainedWarranty'), 1).'</a></td>';
  4070. }
  4071. print '</tr></table>';
  4072. print '</td><td>';
  4073. $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
  4074. if ($object->date > $defaultDate) {
  4075. $defaultDate = $object->date;
  4076. }
  4077. if ($action == 'editretainedwarrantypaymentterms') {
  4078. //date('Y-m-d',$object->date_lim_reglement)
  4079. print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
  4080. print '<input type="hidden" name="action" value="setretainedwarrantyconditions">';
  4081. print '<input type="hidden" name="token" value="'.newToken().'">';
  4082. $retained_warranty_fk_cond_reglement = GETPOST('retained_warranty_fk_cond_reglement', 'int');
  4083. $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $object->retained_warranty_fk_cond_reglement;
  4084. $retained_warranty_fk_cond_reglement = !empty($retained_warranty_fk_cond_reglement) ? $retained_warranty_fk_cond_reglement : $conf->global->INVOICE_SITUATION_DEFAULT_RETAINED_WARRANTY_COND_ID;
  4085. $form->select_conditions_paiements($retained_warranty_fk_cond_reglement, 'retained_warranty_fk_cond_reglement', -1, 1);
  4086. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4087. print '</form>';
  4088. } else {
  4089. $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?facid='.$object->id, $object->retained_warranty_fk_cond_reglement, 'none');
  4090. if (!$displayWarranty) {
  4091. print img_picto($langs->trans('RetainedWarrantyNeed100Percent'), 'warning.png', 'class="pictowarning valignmiddle" ');
  4092. }
  4093. }
  4094. print '</td></tr>';
  4095. // Retained Warranty payment date limit
  4096. print '<tr class="retained-warranty-lines" ><td>';
  4097. print '<table id="retained-warranty-date-limit-table" class="nobordernopadding" width="100%"><tr><td>';
  4098. print $langs->trans('RetainedWarrantyDateLimit');
  4099. print '</td>';
  4100. if ($action != 'editretainedwarrantydatelimit' && $user->rights->facture->creer) {
  4101. print '<td align="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editretainedwarrantydatelimit&amp;facid='.$object->id.'">'.img_edit($langs->trans('setretainedwarrantyDateLimit'), 1).'</a></td>';
  4102. }
  4103. print '</tr></table>';
  4104. print '</td><td>';
  4105. $defaultDate = !empty($object->retained_warranty_date_limit) ? $object->retained_warranty_date_limit : strtotime('-1 years', $object->date_lim_reglement);
  4106. if ($object->date > $defaultDate) {
  4107. $defaultDate = $object->date;
  4108. }
  4109. if ($action == 'editretainedwarrantydatelimit') {
  4110. //date('Y-m-d',$object->date_lim_reglement)
  4111. print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'">';
  4112. print '<input type="hidden" name="action" value="setretainedwarrantydatelimit">';
  4113. print '<input type="hidden" name="token" value="'.newToken().'">';
  4114. print '<input name="retained_warranty_date_limit" type="date" step="1" min="'.dol_print_date($object->date, '%Y-%m-%d').'" value="'.dol_print_date($defaultDate, '%Y-%m-%d').'" >';
  4115. print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
  4116. print '</form>';
  4117. } else {
  4118. print dol_print_date($object->retained_warranty_date_limit, 'day');
  4119. }
  4120. print '</td></tr>';
  4121. }
  4122. }
  4123. // Other attributes
  4124. $cols = 2;
  4125. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
  4126. print '</table>';
  4127. print '</div>';
  4128. print '<div class="fichehalfright">';
  4129. print '<div class="ficheaddleft">';
  4130. print '<!-- amounts -->'."\n";
  4131. print '<table class="border bordertop tableforfield centpercent">';
  4132. $sign = 1;
  4133. if (!empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE_SCREEN) && $object->type == $object::TYPE_CREDIT_NOTE) {
  4134. $sign = -1; // We invert sign for output
  4135. }
  4136. if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) {
  4137. // Multicurrency Amount HT
  4138. print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>';
  4139. print '<td class="nowrap amountcard">'.price($sign * $object->multicurrency_total_ht, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  4140. print '</tr>';
  4141. // Multicurrency Amount VAT
  4142. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountVAT', 'multicurrency_total_tva', '', $object, 0).'</td>';
  4143. print '<td class="nowrap amountcard">'.price($sign * $object->multicurrency_total_tva, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  4144. print '</tr>';
  4145. // Multicurrency Amount TTC
  4146. print '<tr><td>'.$form->editfieldkey('MulticurrencyAmountTTC', 'multicurrency_total_ttc', '', $object, 0).'</td>';
  4147. print '<td class="nowrap amountcard">'.price($sign * $object->multicurrency_total_ttc, '', $langs, 0, -1, -1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>';
  4148. print '</tr>';
  4149. }
  4150. // Amount
  4151. print '<tr><td class="titlefieldmiddle">'.$langs->trans('AmountHT').'</td>';
  4152. print '<td class="nowrap amountcard">'.price($sign * $object->total_ht, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  4153. // Vat
  4154. print '<tr><td>'.$langs->trans('AmountVAT').'</td><td colspan="3" class="nowrap amountcard">'.price($sign * $object->total_tva, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  4155. print '</tr>';
  4156. // Amount Local Taxes
  4157. if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1
  4158. print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>';
  4159. print '<td class="nowrap amountcard">'.price($sign * $object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  4160. }
  4161. if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2
  4162. print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>';
  4163. print '<td class=nowrap amountcard">'.price($sign * $object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  4164. }
  4165. // Revenue stamp
  4166. if ($selleruserevenustamp) { // Test company use revenue stamp
  4167. print '<tr><td>';
  4168. print '<table class="nobordernopadding" width="100%"><tr><td>';
  4169. print $langs->trans('RevenueStamp');
  4170. print '</td>';
  4171. if ($action != 'editrevenuestamp' && !empty($object->brouillon) && $usercancreate) {
  4172. print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editrevenuestamp&amp;facid='.$object->id.'">'.img_edit($langs->trans('SetRevenuStamp'), 1).'</a></td>';
  4173. }
  4174. print '</tr></table>';
  4175. print '</td><td>';
  4176. if ($action == 'editrevenuestamp') {
  4177. print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
  4178. print '<input type="hidden" name="token" value="'.newToken().'">';
  4179. print '<input type="hidden" name="action" value="setrevenuestamp">';
  4180. print '<input type="hidden" name="revenuestamp" id="revenuestamp_val" value="'.price2num($object->revenuestamp).'">';
  4181. print $formother->select_revenue_stamp('', 'revenuestamp_type', $mysoc->country_code);
  4182. print ' &rarr; <span id="revenuestamp_span"></span>';
  4183. print ' <input type="submit" class="button buttongen" value="'.$langs->trans('Modify').'">';
  4184. print '</form>';
  4185. print " <script>
  4186. $(document).ready(function(){
  4187. js_recalculate_revenuestamp();
  4188. $('select[name=revenuestamp_type]').on('change',function(){
  4189. js_recalculate_revenuestamp();
  4190. });
  4191. });
  4192. function js_recalculate_revenuestamp(){
  4193. var valselected = $('select[name=revenuestamp_type]').val();
  4194. console.log('Calculate revenue stamp from '+valselected);
  4195. var revenue = 0;
  4196. if (valselected.indexOf('%') == -1)
  4197. {
  4198. revenue = valselected;
  4199. }
  4200. else
  4201. {
  4202. var revenue_type = parseFloat(valselected);
  4203. var amount_net = ".round($object->total_ht, 2).";
  4204. revenue = revenue_type * amount_net / 100;
  4205. revenue = revenue.toFixed(2);
  4206. }
  4207. $('#revenuestamp_val').val(revenue);
  4208. $('#revenuestamp_span').html(revenue);
  4209. }
  4210. </script>";
  4211. } else {
  4212. print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency);
  4213. }
  4214. print '</td></tr>';
  4215. }
  4216. // Total with tax
  4217. print '<tr><td>'.$langs->trans('AmountTTC').'</td><td class="nowrap amountcard">'.price($sign * $object->total_ttc, 1, '', 1, - 1, - 1, $conf->currency).'</td></tr>';
  4218. print '</table>';
  4219. $nbrows = 8;
  4220. $nbcols = 3;
  4221. if (!empty($conf->projet->enabled)) {
  4222. $nbrows++;
  4223. }
  4224. if (!empty($conf->banque->enabled)) {
  4225. $nbrows++;
  4226. $nbcols++;
  4227. }
  4228. if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) {
  4229. $nbrows++;
  4230. }
  4231. if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) {
  4232. $nbrows++;
  4233. }
  4234. if ($selleruserevenustamp) {
  4235. $nbrows++;
  4236. }
  4237. if (!empty($conf->multicurrency->enabled)) {
  4238. $nbrows += 5;
  4239. }
  4240. if (!empty($conf->incoterm->enabled)) {
  4241. $nbrows += 1;
  4242. }
  4243. // List of previous situation invoices
  4244. if (($object->situation_cycle_ref > 0) && !empty($conf->global->INVOICE_USE_SITUATION)) {
  4245. print '<table class="noborder situationstable" width="100%">';
  4246. print '<tr class="liste_titre">';
  4247. print '<td>'.$langs->trans('ListOfSituationInvoices').'</td>';
  4248. print '<td></td>';
  4249. print '<td class="center">'.$langs->trans('Situation').'</td>';
  4250. if (!empty($conf->banque->enabled)) {
  4251. print '<td class="right"></td>';
  4252. }
  4253. print '<td class="right">'.$langs->trans('AmountHT').'</td>';
  4254. print '<td class="right">'.$langs->trans('AmountTTC').'</td>';
  4255. print '<td width="18">&nbsp;</td>';
  4256. print '</tr>';
  4257. $total_prev_ht = $total_prev_ttc = 0;
  4258. $total_global_ht = $total_global_ttc = 0;
  4259. if (count($object->tab_previous_situation_invoice) > 0) {
  4260. // List of previous invoices
  4261. $current_situation_counter = array();
  4262. foreach ($object->tab_previous_situation_invoice as $prev_invoice) {
  4263. $tmptotalpaidforthisinvoice = $prev_invoice->getSommePaiement();
  4264. $total_prev_ht += $prev_invoice->total_ht;
  4265. $total_prev_ttc += $prev_invoice->total_ttc;
  4266. $current_situation_counter[] = (($prev_invoice->type == Facture::TYPE_CREDIT_NOTE) ?-1 : 1) * $prev_invoice->situation_counter;
  4267. print '<tr class="oddeven">';
  4268. print '<td>'.$prev_invoice->getNomUrl(1).'</td>';
  4269. print '<td></td>';
  4270. print '<td align="center" >'.(($prev_invoice->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$prev_invoice->situation_counter.'</td>';
  4271. if (!empty($conf->banque->enabled)) {
  4272. print '<td class="right"></td>';
  4273. }
  4274. print '<td class="right"><span class="amount">'.price($prev_invoice->total_ht).'</span></td>';
  4275. print '<td class="right"><span class="amount">'.price($prev_invoice->total_ttc).'</span></td>';
  4276. print '<td class="right">'.$prev_invoice->getLibStatut(3, $tmptotalpaidforthisinvoice).'</td>';
  4277. print '</tr>';
  4278. }
  4279. }
  4280. $total_global_ht += $total_prev_ht;
  4281. $total_global_ttc += $total_prev_ttc;
  4282. $total_global_ht += $object->total_ht;
  4283. $total_global_ttc += $object->total_ttc;
  4284. $current_situation_counter[] = (($object->type == Facture::TYPE_CREDIT_NOTE) ?-1 : 1) * $object->situation_counter;
  4285. print '<tr class="oddeven">';
  4286. print '<td>'.$object->getNomUrl(1).'</td>';
  4287. print '<td></td>';
  4288. print '<td class="center">'.(($object->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$object->situation_counter.'</td>';
  4289. if (!empty($conf->banque->enabled)) {
  4290. print '<td class="right"></td>';
  4291. }
  4292. print '<td class="right"><span class="amount">'.price($object->total_ht).'</span></td>';
  4293. print '<td class="right"><span class="amount">'.price($object->total_ttc).'</span></td>';
  4294. print '<td class="right">'.$object->getLibStatut(3, $object->getSommePaiement()).'</td>';
  4295. print '</tr>';
  4296. print '<tr class="oddeven">';
  4297. print '<td colspan="2" class="left"><b>'.$langs->trans('CurrentSituationTotal').'</b></td>';
  4298. print '<td>';
  4299. $i = 0;
  4300. foreach ($current_situation_counter as $sit) {
  4301. $curSign = $sit > 0 ? '+' : '-';
  4302. $curType = $sit > 0 ? $langs->trans('situationInvoiceShortcode_S') : $langs->trans('situationInvoiceShortcode_AS');
  4303. if ($i > 0) {
  4304. print ' '.$curSign.' ';
  4305. }
  4306. print $curType.abs($sit);
  4307. $i++;
  4308. }
  4309. print '</td>';
  4310. if (!empty($conf->banque->enabled)) {
  4311. print '<td></td>';
  4312. }
  4313. print '<td class="right"><b>'.price($total_global_ht).'</b></td>';
  4314. print '<td class="right"><b>'.price($total_global_ttc).'</b></td>';
  4315. print '<td width="18">&nbsp;</td>';
  4316. print '</tr>';
  4317. if (count($object->tab_next_situation_invoice) > 0) {
  4318. // List of next invoices
  4319. /*print '<tr class="liste_titre">';
  4320. print '<td>' . $langs->trans('ListOfNextSituationInvoices') . '</td>';
  4321. print '<td></td>';
  4322. print '<td></td>';
  4323. if (! empty($conf->banque->enabled)) print '<td class="right"></td>';
  4324. print '<td class="right">' . $langs->trans('AmountHT') . '</td>';
  4325. print '<td class="right">' . $langs->trans('AmountTTC') . '</td>';
  4326. print '<td width="18">&nbsp;</td>';
  4327. print '</tr>';*/
  4328. $total_next_ht = $total_next_ttc = 0;
  4329. foreach ($object->tab_next_situation_invoice as $next_invoice) {
  4330. $totalpaye = $next_invoice->getSommePaiement();
  4331. $total_next_ht += $next_invoice->total_ht;
  4332. $total_next_ttc += $next_invoice->total_ttc;
  4333. print '<tr class="oddeven">';
  4334. print '<td>'.$next_invoice->getNomUrl(1).'</td>';
  4335. print '<td></td>';
  4336. print '<td class="center">'.(($next_invoice->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$next_invoice->situation_counter.'</td>';
  4337. if (!empty($conf->banque->enabled)) {
  4338. print '<td class="right"></td>';
  4339. }
  4340. print '<td class="right"><span class="amount">'.price($next_invoice->total_ht).'</span></td>';
  4341. print '<td class="right"><span class="amount">'.price($next_invoice->total_ttc).'</span></td>';
  4342. print '<td class="right">'.$next_invoice->getLibStatut(3, $totalpaye).'</td>';
  4343. print '</tr>';
  4344. }
  4345. $total_global_ht += $total_next_ht;
  4346. $total_global_ttc += $total_next_ttc;
  4347. print '<tr class="oddeven">';
  4348. print '<td colspan="3" class="right"></td>';
  4349. if (!empty($conf->banque->enabled)) {
  4350. print '<td class="right"></td>';
  4351. }
  4352. print '<td class="right"><b>'.price($total_global_ht).'</b></td>';
  4353. print '<td class="right"><b>'.price($total_global_ttc).'</b></td>';
  4354. print '<td width="18">&nbsp;</td>';
  4355. print '</tr>';
  4356. }
  4357. print '</table>';
  4358. }
  4359. $sign = 1;
  4360. if ($object->type == $object::TYPE_CREDIT_NOTE) {
  4361. $sign = -1;
  4362. }
  4363. // List of payments already done
  4364. print '<div class="div-table-responsive-no-min">';
  4365. print '<table class="noborder paymenttable" width="100%">';
  4366. print '<tr class="liste_titre">';
  4367. print '<td class="liste_titre">'.($object->type == Facture::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>';
  4368. print '<td class="liste_titre">'.$langs->trans('Date').'</td>';
  4369. print '<td class="liste_titre">'.$langs->trans('Type').'</td>';
  4370. if (!empty($conf->banque->enabled)) {
  4371. print '<td class="liste_titre right">'.$langs->trans('BankAccount').'</td>';
  4372. }
  4373. print '<td class="liste_titre right">'.$langs->trans('Amount').'</td>';
  4374. print '<td class="liste_titre" width="18">&nbsp;</td>';
  4375. print '</tr>';
  4376. // Payments already done (from payment on this invoice)
  4377. $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,';
  4378. $sql .= ' c.code as payment_code, c.libelle as payment_label,';
  4379. $sql .= ' pf.amount,';
  4380. $sql .= ' ba.rowid as baid, ba.ref as baref, ba.label, ba.number as banumber, ba.account_number, ba.fk_accountancy_journal';
  4381. $sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf, '.MAIN_DB_PREFIX.'paiement as p';
  4382. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id';
  4383. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid';
  4384. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid';
  4385. $sql .= ' WHERE pf.fk_facture = '.$object->id.' AND pf.fk_paiement = p.rowid';
  4386. $sql .= ' AND p.entity IN ('.getEntity('invoice').')';
  4387. $sql .= ' ORDER BY p.datep, p.tms';
  4388. $result = $db->query($sql);
  4389. if ($result) {
  4390. $num = $db->num_rows($result);
  4391. $i = 0;
  4392. if ($num > 0) {
  4393. while ($i < $num) {
  4394. $objp = $db->fetch_object($result);
  4395. $paymentstatic->id = $objp->rowid;
  4396. $paymentstatic->datepaye = $db->jdate($objp->dp);
  4397. $paymentstatic->ref = $objp->ref;
  4398. $paymentstatic->num_payment = $objp->num_payment;
  4399. $paymentstatic->payment_code = $objp->payment_code;
  4400. print '<tr class="oddeven"><td class="nowraponall">';
  4401. print $paymentstatic->getNomUrl(1);
  4402. print '</td>';
  4403. print '<td>';
  4404. $dateofpayment = $db->jdate($objp->dp);
  4405. $tmparray = dol_getdate($dateofpayment);
  4406. if ($tmparray['seconds'] == 0 && $tmparray['minutes'] == 0 && ($tmparray['hours'] == 0 || $tmparray['hours'] == 12)) { // We set hours to 0:00 or 12:00 because we don't know it
  4407. print dol_print_date($dateofpayment, 'day');
  4408. } else { // Hours was set to real date of payment (special case for POS for example)
  4409. print dol_print_date($dateofpayment, 'dayhour', 'tzuser');
  4410. }
  4411. print '</td>';
  4412. $label = ($langs->trans("PaymentType".$objp->payment_code) != ("PaymentType".$objp->payment_code)) ? $langs->trans("PaymentType".$objp->payment_code) : $objp->payment_label;
  4413. print '<td>'.$label.' '.$objp->num_payment.'</td>';
  4414. if (!empty($conf->banque->enabled)) {
  4415. $bankaccountstatic->id = $objp->baid;
  4416. $bankaccountstatic->ref = $objp->baref;
  4417. $bankaccountstatic->label = $objp->baref;
  4418. $bankaccountstatic->number = $objp->banumber;
  4419. if (!empty($conf->accounting->enabled)) {
  4420. $bankaccountstatic->account_number = $objp->account_number;
  4421. $accountingjournal = new AccountingJournal($db);
  4422. $accountingjournal->fetch($objp->fk_accountancy_journal);
  4423. $bankaccountstatic->accountancy_journal = $accountingjournal->getNomUrl(0, 1, 1, '', 1);
  4424. }
  4425. print '<td class="nowraponall">';
  4426. if ($bankaccountstatic->id) {
  4427. print $bankaccountstatic->getNomUrl(1, 'transactions');
  4428. }
  4429. print '</td>';
  4430. }
  4431. print '<td class="right"><span class="amount">'.price($sign * $objp->amount).'</span></td>';
  4432. print '<td class="center">';
  4433. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) {
  4434. print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">';
  4435. print img_delete();
  4436. print '</a>';
  4437. }
  4438. print '</td>';
  4439. print '</tr>';
  4440. $i++;
  4441. }
  4442. }
  4443. $db->free($result);
  4444. } else {
  4445. dol_print_error($db);
  4446. }
  4447. if ($object->type != Facture::TYPE_CREDIT_NOTE) {
  4448. // Total already paid
  4449. print '<tr><td colspan="'.$nbcols.'" class="right">';
  4450. print '<span class="opacitymedium">';
  4451. if ($object->type != Facture::TYPE_DEPOSIT) {
  4452. print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits');
  4453. } else {
  4454. print $langs->trans('AlreadyPaid');
  4455. }
  4456. print '</span></td><td class="right'.(($totalpaye > 0) ? ' amountalreadypaid' : '').'">'.price($totalpaye).'</td><td>&nbsp;</td></tr>';
  4457. $resteapayeraffiche = $resteapayer;
  4458. $cssforamountpaymentcomplete = 'amountpaymentcomplete';
  4459. // Loop on each credit note or deposit amount applied
  4460. $creditnoteamount = 0;
  4461. $depositamount = 0;
  4462. $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
  4463. $sql .= " re.description, re.fk_facture_source";
  4464. $sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
  4465. $sql .= " WHERE fk_facture = ".$object->id;
  4466. $resql = $db->query($sql);
  4467. if ($resql) {
  4468. $num = $db->num_rows($resql);
  4469. $i = 0;
  4470. $invoice = new Facture($db);
  4471. while ($i < $num) {
  4472. $obj = $db->fetch_object($resql);
  4473. $invoice->fetch($obj->fk_facture_source);
  4474. print '<tr><td colspan="'.$nbcols.'" class="right">';
  4475. print '<span class="opacitymedium">';
  4476. if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
  4477. print $langs->trans("CreditNote").' ';
  4478. }
  4479. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  4480. print $langs->trans("Deposit").' ';
  4481. }
  4482. print $invoice->getNomUrl(0);
  4483. print '</span>';
  4484. print '</td>';
  4485. print '<td class="right"><span class="amount">'.price($obj->amount_ttc).'</span></td>';
  4486. print '<td class="right">';
  4487. print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>';
  4488. print '</td></tr>';
  4489. $i++;
  4490. if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
  4491. $creditnoteamount += $obj->amount_ttc;
  4492. }
  4493. if ($invoice->type == Facture::TYPE_DEPOSIT) {
  4494. $depositamount += $obj->amount_ttc;
  4495. }
  4496. }
  4497. } else {
  4498. dol_print_error($db);
  4499. }
  4500. // Paye partiellement 'escompte'
  4501. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'discount_vat') {
  4502. print '<tr><td colspan="'.$nbcols.'" class="nowrap right">';
  4503. print '<span class="opacitymedium">';
  4504. print $form->textwithpicto($langs->trans("Discount"), $langs->trans("HelpEscompte"), - 1);
  4505. print '</span>';
  4506. print '</td><td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')).'</span></td><td>&nbsp;</td></tr>';
  4507. $resteapayeraffiche = 0;
  4508. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  4509. }
  4510. // Paye partiellement ou Abandon 'badcustomer'
  4511. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'badcustomer') {
  4512. print '<tr><td colspan="'.$nbcols.'" class="nowrap right">';
  4513. print '<span class="opacitymedium">';
  4514. print $form->textwithpicto($langs->trans("Abandoned"), $langs->trans("HelpAbandonBadCustomer"), - 1);
  4515. print '</span>';
  4516. print '</td><td class="right">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')).'</td><td>&nbsp;</td></tr>';
  4517. // $resteapayeraffiche=0;
  4518. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  4519. }
  4520. // Paye partiellement ou Abandon 'product_returned'
  4521. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'product_returned') {
  4522. print '<tr><td colspan="'.$nbcols.'" class="nowrap right">';
  4523. print '<span class="opacitymedium">';
  4524. print $form->textwithpicto($langs->trans("ProductReturned"), $langs->trans("HelpAbandonProductReturned"), - 1);
  4525. print '</span>';
  4526. print '</td><td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')).'</span></td><td>&nbsp;</td></tr>';
  4527. $resteapayeraffiche = 0;
  4528. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  4529. }
  4530. // Paye partiellement ou Abandon 'abandon'
  4531. if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') {
  4532. print '<tr><td colspan="'.$nbcols.'" class="nowrap right">';
  4533. $text = $langs->trans("HelpAbandonOther");
  4534. if ($object->close_note) {
  4535. $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note;
  4536. }
  4537. print '<span class="opacitymedium">';
  4538. print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1);
  4539. print '</span>';
  4540. print '</td><td class="right"><span class="amount">'.price(price2num($object->total_ttc - $creditnoteamount - $depositamount - $totalpaye, 'MT')).'</span></td><td>&nbsp;</td></tr>';
  4541. $resteapayeraffiche = 0;
  4542. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  4543. }
  4544. // Billed
  4545. print '<tr><td colspan="'.$nbcols.'" class="right">';
  4546. print '<span class="opacitymedium">';
  4547. print $langs->trans("Billed");
  4548. print '</td><td class="right">'.price($object->total_ttc).'</td><td>&nbsp;</td></tr>';
  4549. // Remainder to pay
  4550. print '<tr><td colspan="'.$nbcols.'" class="right">';
  4551. print '<span class="opacitymedium">';
  4552. print $langs->trans('RemainderToPay');
  4553. if ($resteapayeraffiche < 0) {
  4554. print ' ('.$langs->trans('ExcessReceived').')';
  4555. }
  4556. print '</span>';
  4557. print '</td>';
  4558. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td>';
  4559. print '<td class="nowrap">&nbsp;</td></tr>';
  4560. // Retained warranty : usualy use on construction industry
  4561. if (!empty($object->situation_final) && !empty($object->retained_warranty) && $displayWarranty) {
  4562. // Billed - retained warranty
  4563. if ($object->type == Facture::TYPE_SITUATION) {
  4564. $retainedWarranty = $total_global_ttc * $object->retained_warranty / 100;
  4565. } else {
  4566. // Because one day retained warranty could be used on standard invoices
  4567. $retainedWarranty = $object->total_ttc * $object->retained_warranty / 100;
  4568. }
  4569. $billedWithRetainedWarranty = $object->total_ttc - $retainedWarranty;
  4570. print '<tr><td colspan="'.$nbcols.'" align="right">'.$langs->trans("ToPayOn", dol_print_date($object->date_lim_reglement, 'day')).' :</td><td align="right">'.price($billedWithRetainedWarranty).'</td><td>&nbsp;</td></tr>';
  4571. // retained warranty
  4572. print '<tr><td colspan="'.$nbcols.'" align="right">';
  4573. print $langs->trans("RetainedWarranty").' ('.$object->retained_warranty.'%)';
  4574. print !empty($object->retained_warranty_date_limit) ? ' '.$langs->trans("ToPayOn", dol_print_date($object->retained_warranty_date_limit, 'day')) : '';
  4575. print ' :</td><td align="right">'.price($retainedWarranty).'</td><td>&nbsp;</td></tr>';
  4576. }
  4577. } else { // Credit note
  4578. $cssforamountpaymentcomplete = 'amountpaymentneutral';
  4579. // Total already paid back
  4580. print '<tr><td colspan="'.$nbcols.'" class="right">';
  4581. print $langs->trans('AlreadyPaidBack');
  4582. print ' :</td><td class="right"><span class="amount">'.price($sign * $totalpaye).'</span></td><td>&nbsp;</td></tr>';
  4583. // Billed
  4584. print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($sign * $object->total_ttc).'</td><td>&nbsp;</td></tr>';
  4585. // Remainder to pay back
  4586. print '<tr><td colspan="'.$nbcols.'" class="right">';
  4587. print $langs->trans('RemainderToPayBack');
  4588. if ($resteapayeraffiche > 0) {
  4589. print ' ('.$langs->trans('ExcessPaid').')';
  4590. }
  4591. print ' :</td>';
  4592. print '<td class="right'.($resteapayeraffiche ? ' amountremaintopayback' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche).'</td>';
  4593. print '<td class="nowrap">&nbsp;</td></tr>';
  4594. // Sold credit note
  4595. // print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('TotalTTC').' :</td>';
  4596. // print '<td class="right" style="border: 1px solid;" bgcolor="#f0f0f0"><b>'.price($sign *
  4597. // $object->total_ttc).'</b></td><td>&nbsp;</td></tr>';
  4598. }
  4599. print '</table>';
  4600. print '</div>';
  4601. // Margin Infos
  4602. if (!empty($conf->margin->enabled)) {
  4603. $formmargin->displayMarginInfos($object);
  4604. }
  4605. print '</div>';
  4606. print '</div>';
  4607. print '</div>';
  4608. print '<div class="clearboth"></div><br>';
  4609. if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) {
  4610. $blocname = 'contacts';
  4611. $title = $langs->trans('ContactsAddresses');
  4612. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  4613. }
  4614. if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) {
  4615. $blocname = 'notes';
  4616. $title = $langs->trans('Notes');
  4617. include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
  4618. }
  4619. // Lines
  4620. $result = $object->getLinesArray();
  4621. // Show global modifiers
  4622. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  4623. if ($object->situation_cycle_ref && $object->statut == 0) {
  4624. print '<!-- Area to change globally the situation percent -->'."\n";
  4625. print '<div class="div-table-responsive">';
  4626. print '<form name="updatealllines" id="updatealllines" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'#updatealllines" method="POST">';
  4627. print '<input type="hidden" name="token" value="'.newToken().'" />';
  4628. print '<input type="hidden" name="action" value="updatealllines" />';
  4629. print '<input type="hidden" name="id" value="'.$object->id.'" />';
  4630. print '<table id="tablelines_all_progress" class="noborder noshadow" width="100%">';
  4631. print '<tr class="liste_titre nodrag nodrop">';
  4632. // Adds a line numbering column
  4633. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  4634. print '<td align="center" width="5">&nbsp;</td>';
  4635. }
  4636. print '<td class="minwidth500imp">'.$langs->trans('ModifyAllLines').'</td>';
  4637. print '<td class="right">'.$langs->trans('Progress').'</td>';
  4638. print '<td>&nbsp;</td>';
  4639. print "</tr>\n";
  4640. print '<tr class="nodrag nodrop">';
  4641. // Adds a line numbering column
  4642. if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
  4643. print '<td align="center" width="5">&nbsp;</td>';
  4644. }
  4645. print '<td>&nbsp;</td>';
  4646. print '<td class="nowrap right"><input type="text" size="1" value="" name="all_progress">%</td>';
  4647. print '<td class="right"><input class="button" type="submit" name="all_percent" value="Modifier" /></td>';
  4648. print '</tr>';
  4649. print '</table>';
  4650. print '</form>';
  4651. print '</div>';
  4652. }
  4653. }
  4654. print ' <form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '' : '#line_'.GETPOST('lineid', 'int')).'" method="POST">
  4655. <input type="hidden" name="token" value="' . newToken().'">
  4656. <input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline').'">
  4657. <input type="hidden" name="mode" value="">
  4658. <input type="hidden" name="page_y" value="">
  4659. <input type="hidden" name="id" value="' . $object->id.'">
  4660. ';
  4661. if (!empty($conf->use_javascript_ajax) && $object->statut == 0) {
  4662. include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
  4663. }
  4664. print '<div class="div-table-responsive-no-min">';
  4665. print '<table id="tablelines" class="noborder noshadow" width="100%">';
  4666. // Show object lines
  4667. if (!empty($object->lines)) {
  4668. $ret = $object->printObjectLines($action, $mysoc, $soc, $lineid, 1);
  4669. }
  4670. // Form to add new line
  4671. if ($object->statut == 0 && $usercancreate && $action != 'valid' && $action != 'editline') {
  4672. if ($action != 'editline' && $action != 'selectlines') {
  4673. // Add free products/services
  4674. $parameters = array();
  4675. $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  4676. if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
  4677. if (empty($reshook))
  4678. $object->formAddObjectLine(1, $mysoc, $soc);
  4679. }
  4680. }
  4681. print "</table>\n";
  4682. print "</div>";
  4683. print "</form>\n";
  4684. print dol_get_fiche_end();
  4685. // Actions buttons
  4686. if ($action != 'prerelance' && $action != 'presend' && $action != 'valid' && $action != 'editline') {
  4687. print '<div class="tabsAction">';
  4688. $parameters = array();
  4689. $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
  4690. if (empty($reshook)) {
  4691. // Editer une facture deja validee, sans paiement effectue et pas exporte en compta
  4692. if ($object->statut == Facture::STATUS_VALIDATED) {
  4693. // We check if lines of invoice are not already transfered into accountancy
  4694. $ventilExportCompta = $object->getVentilExportCompta();
  4695. if ($ventilExportCompta == 0) {
  4696. if (!empty($conf->global->INVOICE_CAN_ALWAYS_BE_EDITED) || ($resteapayer == price2num($object->total_ttc, 'MT', 1) && empty($object->paye))) {
  4697. if (!$objectidnext && $object->is_last_in_cycle()) {
  4698. if ($usercanunvalidate) {
  4699. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=modif">'.$langs->trans('Modify').'</a>';
  4700. } else {
  4701. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans('Modify').'</span>';
  4702. }
  4703. } elseif (!$object->is_last_in_cycle()) {
  4704. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("NotLastInCycle").'">'.$langs->trans('Modify').'</span>';
  4705. } else {
  4706. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Modify').'</span>';
  4707. }
  4708. }
  4709. } else {
  4710. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Modify').'</span>';
  4711. }
  4712. }
  4713. $discount = new DiscountAbsolute($db);
  4714. $result = $discount->fetch(0, $object->id);
  4715. // Reopen a standard paid invoice
  4716. if ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT)
  4717. || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id))
  4718. || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id))
  4719. || ($object->type == Facture::TYPE_SITUATION && empty($discount->id)))
  4720. && ($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data
  4721. && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || $usercanreopen)) { // A paid invoice (partially or completely)
  4722. if ($object->close_code != 'replaced' || (!$objectidnext)) { // Not replaced by another invoice or replaced but the replacement invoice has been deleted
  4723. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=reopen">'.$langs->trans('ReOpen').'</a>';
  4724. } else {
  4725. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ReOpen').'</span>';
  4726. }
  4727. }
  4728. // Validate
  4729. if ($object->statut == Facture::STATUS_DRAFT && count($object->lines) > 0 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (!empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0)) || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) {
  4730. if ($usercanvalidate) {
  4731. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=valid">'.$langs->trans('Validate').'</a>';
  4732. }
  4733. }
  4734. // Send by mail
  4735. if (empty($user->socid)) {
  4736. if (($object->statut == Facture::STATUS_VALIDATED || $object->statut == Facture::STATUS_CLOSED) || !empty($conf->global->FACTURE_SENDBYEMAIL_FOR_ALL_STATUS)) {
  4737. if ($objectidnext) {
  4738. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('SendMail').'</span>';
  4739. } else {
  4740. if ($usercansend) {
  4741. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>';
  4742. } else {
  4743. print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a>';
  4744. }
  4745. }
  4746. }
  4747. }
  4748. // Request a direct debit order
  4749. if ($object->statut > Facture::STATUS_DRAFT && $object->paye == 0 && $num == 0) {
  4750. if ($resteapayer > 0) {
  4751. if ($usercancreatewithdrarequest) {
  4752. if (!$objectidnext && $object->close_code != 'replaced') { // Not replaced by another invoice
  4753. print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id.'" title="'.dol_escape_htmltag($langs->trans("MakeWithdrawRequest")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  4754. } else {
  4755. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('MakeWithdrawRequest').'</span>';
  4756. }
  4757. } else {
  4758. //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotEnoughPermissions")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  4759. }
  4760. } else {
  4761. //print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("AmountMustBePositive")).'">'.$langs->trans("MakeWithdrawRequest").'</a>';
  4762. }
  4763. }
  4764. // POS Ticket
  4765. if (!empty($conf->takepos->enabled) && $object->module_source == 'takepos') {
  4766. $langs->load("cashdesk");
  4767. $receipt_url = DOL_URL_ROOT."/takepos/receipt.php";
  4768. print '<a target="_blank" class="butAction" href="'.$receipt_url.'?facid='.$object->id.'">'.$langs->trans('POSTicket').'</a>';
  4769. }
  4770. // Create payment
  4771. if ($object->type != Facture::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0 && $usercanissuepayment) {
  4772. if ($objectidnext) {
  4773. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('DoPayment').'</span>';
  4774. } else {
  4775. //if ($resteapayer == 0) { // Sometimes we can receive more, so we accept to enter more and will offer a button to convert into discount (but it is not a credit note, just a prepayment done)
  4776. // print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip" title="' . $langs->trans("DisabledBecauseRemainderToPayIsZero") . '">' . $langs->trans('DoPayment') . '</span></div>';
  4777. //} else {
  4778. print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPayment').'</a>';
  4779. //}
  4780. }
  4781. }
  4782. // Reverse back money or convert to reduction
  4783. if ($object->type == Facture::TYPE_CREDIT_NOTE || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) {
  4784. // For credit note only
  4785. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment) {
  4786. if ($resteapayer == 0) {
  4787. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span>';
  4788. } else {
  4789. print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a>';
  4790. }
  4791. }
  4792. // For standard invoice with excess received
  4793. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->statut == Facture::STATUS_VALIDATED && empty($object->paye) && $resteapayer < 0 && $usercancreate && empty($discount->id)) {
  4794. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertExcessReceivedToReduc').'</a>';
  4795. }
  4796. // For credit note
  4797. if ($object->type == Facture::TYPE_CREDIT_NOTE && $object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercancreate
  4798. && (!empty($conf->global->INVOICE_ALLOW_REUSE_OF_CREDIT_WHEN_PARTIALLY_REFUNDED) || $object->getSommePaiement() == 0)
  4799. ) {
  4800. 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("ConfirmConvertToReduc2")).'">'.$langs->trans('ConvertToReduc').'</a>';
  4801. }
  4802. // For deposit invoice
  4803. if ($object->type == Facture::TYPE_DEPOSIT && $usercancreate && $object->statut > 0 && empty($discount->id)) {
  4804. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a>';
  4805. }
  4806. }
  4807. // Classify paid
  4808. if (($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment && (($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && $resteapayer <= 0) || ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0)))
  4809. || ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 0 && $object->total_ttc > 0 && $resteapayer == 0 && $usercanissuepayment && empty($discount->id))
  4810. ) {
  4811. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaid').'</a>';
  4812. }
  4813. // Classify 'closed not completely paid' (possible if validated and not yet filed paid)
  4814. if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && $usercanissuepayment) {
  4815. if ($totalpaye > 0 || $totalcreditnotes > 0) {
  4816. // If one payment or one credit note was linked to this invoice
  4817. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=paid">'.$langs->trans('ClassifyPaidPartially').'</a>';
  4818. } else {
  4819. if (empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED)) {
  4820. if ($objectidnext) {
  4821. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('ClassifyCanceled').'</span>';
  4822. } else {
  4823. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=canceled">'.$langs->trans('ClassifyCanceled').'</a>';
  4824. }
  4825. }
  4826. }
  4827. }
  4828. // Create a credit note
  4829. if (($object->type == Facture::TYPE_STANDARD || ($object->type == Facture::TYPE_DEPOSIT && empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) {
  4830. if (!$objectidnext) {
  4831. 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 : '').($object->entity > 0 ? '&amp;originentity='.$object->entity : '').'">'.$langs->trans("CreateCreditNote").'</a>';
  4832. }
  4833. }
  4834. // For situation invoice with excess received
  4835. if ($object->statut > Facture::STATUS_DRAFT
  4836. && $object->type == Facture::TYPE_SITUATION
  4837. && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) > 0
  4838. && $usercancreate
  4839. && !$objectidnext
  4840. && $object->is_last_in_cycle()
  4841. && $conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE
  4842. ) {
  4843. if ($usercanunvalidate) {
  4844. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&amp;invoiceAvoirWithLines=1&amp;action=create&amp;type=2'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').'">'.$langs->trans("CreateCreditNote").'</a>';
  4845. } else {
  4846. print '<span class="butActionRefused classfortooltip" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("CreateCreditNote").'</span>';
  4847. }
  4848. }
  4849. // Clone
  4850. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $usercancreate) {
  4851. print '<a class="butAction'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=clone&amp;object=invoice">'.$langs->trans("ToClone").'</a>';
  4852. }
  4853. // Clone as predefined / Create template
  4854. if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut == 0 && $usercancreate) {
  4855. if (!$objectidnext && count($object->lines) > 0) {
  4856. print '<a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$object->id.'&amp;action=create">'.$langs->trans("ChangeIntoRepeatableInvoice").'</a>';
  4857. }
  4858. }
  4859. // Remove situation from cycle
  4860. if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED))
  4861. && $object->type == Facture::TYPE_SITUATION
  4862. && $usercancreate
  4863. && !$objectidnext
  4864. && $object->situation_counter > 1
  4865. && $object->is_last_in_cycle()
  4866. && $usercanunvalidate
  4867. ) {
  4868. if (($object->total_ttc - $totalcreditnotes) == 0) {
  4869. print '<a id="butSituationOut" class="butAction" href="'.$_SERVER['PHP_SELF'].'?facid='.$object->id.'&amp;action=situationout">'.$langs->trans("RemoveSituationFromCycle").'</a>';
  4870. } else {
  4871. print '<a id="butSituationOutRefused" class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotEnouthCreditNote").'" >'.$langs->trans("RemoveSituationFromCycle").'</a>';
  4872. }
  4873. }
  4874. // Create next situation invoice
  4875. if ($usercancreate && ($object->type == 5) && ($object->statut == 1 || $object->statut == 2)) {
  4876. if ($object->is_last_in_cycle() && $object->situation_final != 1) {
  4877. print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=create&amp;type=5&amp;origin=facture&amp;originid='.$object->id.'&amp;socid='.$object->socid.'" >'.$langs->trans('CreateNextSituationInvoice').'</a>';
  4878. } elseif (!$object->is_last_in_cycle()) {
  4879. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInCycle").'">'.$langs->trans('CreateNextSituationInvoice').'</a>';
  4880. } else {
  4881. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseFinal").'">'.$langs->trans('CreateNextSituationInvoice').'</a>';
  4882. }
  4883. }
  4884. // Delete
  4885. $isErasable = $object->is_erasable();
  4886. if ($usercandelete || ($usercancreate && $isErasable == 1)) { // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions)
  4887. //var_dump($isErasable);
  4888. if ($isErasable == -4) {
  4889. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a>';
  4890. } elseif ($isErasable == -3) {
  4891. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastSituationInvoice").'">'.$langs->trans('Delete').'</a>';
  4892. } elseif ($isErasable == -2) {
  4893. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInvoice").'">'.$langs->trans('Delete').'</a>';
  4894. } elseif ($isErasable == -1) {
  4895. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Delete').'</a>';
  4896. } elseif ($isErasable <= 0) { // Any other cases
  4897. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a>';
  4898. } elseif ($objectidnext) {
  4899. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseReplacedInvoice").'">'.$langs->trans('Delete').'</a>';
  4900. } else {
  4901. print '<a class="butActionDelete'.($conf->use_javascript_ajax ? ' reposition' : '').'" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>';
  4902. }
  4903. } else {
  4904. print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans('Delete').'</a>';
  4905. }
  4906. }
  4907. print '</div>';
  4908. }
  4909. // Select mail models is same action as presend
  4910. if (GETPOST('modelselected', 'alpha')) {
  4911. $action = 'presend';
  4912. }
  4913. if ($action != 'prerelance' && $action != 'presend') {
  4914. print '<div class="fichecenter"><div class="fichehalfleft">';
  4915. print '<a name="builddoc"></a>'; // ancre
  4916. // Generated documents
  4917. $filename = dol_sanitizeFileName($object->ref);
  4918. $filedir = $conf->facture->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref);
  4919. $urlsource = $_SERVER['PHP_SELF'].'?facid='.$object->id;
  4920. $genallowed = $usercanread;
  4921. $delallowed = $usercancreate;
  4922. print $formfile->showdocuments(
  4923. 'facture',
  4924. $filename,
  4925. $filedir,
  4926. $urlsource,
  4927. $genallowed,
  4928. $delallowed,
  4929. $object->model_pdf,
  4930. 1,
  4931. 0,
  4932. 0,
  4933. 28,
  4934. 0,
  4935. '',
  4936. '',
  4937. '',
  4938. $soc->default_lang,
  4939. '',
  4940. $object,
  4941. 0,
  4942. 'remove_file_comfirm'
  4943. );
  4944. $somethingshown = $formfile->numoffiles;
  4945. // Show links to link elements
  4946. $linktoelem = $form->showLinkToObjectBlock($object, null, array('invoice'));
  4947. $compatibleImportElementsList = false;
  4948. if ($usercancreate
  4949. && $object->statut == Facture::STATUS_DRAFT
  4950. && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION)) {
  4951. $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements
  4952. }
  4953. $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList);
  4954. // Show online payment link
  4955. $useonlinepayment = (!empty($conf->paypal->enabled) || !empty($conf->stripe->enabled) || !empty($conf->paybox->enabled));
  4956. if ($object->statut != Facture::STATUS_DRAFT && $useonlinepayment) {
  4957. print '<br><!-- Link to pay -->'."\n";
  4958. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  4959. print showOnlinePaymentUrl('invoice', $object->ref).'<br>';
  4960. }
  4961. print '</div><div class="fichehalfright"><div class="ficheaddleft">';
  4962. // List of actions on element
  4963. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
  4964. $formactions = new FormActions($db);
  4965. $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1);
  4966. print '</div></div></div>';
  4967. }
  4968. // Presend form
  4969. $modelmail = 'facture_send';
  4970. $defaulttopic = 'SendBillRef';
  4971. $diroutput = $conf->facture->multidir_output[$object->entity];
  4972. $trackid = 'inv'.$object->id;
  4973. include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php';
  4974. }
  4975. // End of page
  4976. llxFooter();
  4977. $db->close();