card.php 257 KB

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