card.php 254 KB

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