facture.class.php 209 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796
  1. <?php
  2. /* Copyright (C) 2002-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Sebastien Di Cintio <sdicintio@ressource-toi.org>
  5. * Copyright (C) 2004 Benoit Mortier <benoit.mortier@opensides.be>
  6. * Copyright (C) 2005 Marc Barilley / Ocebo <marc@ocebo.com>
  7. * Copyright (C) 2005-2014 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  9. * Copyright (C) 2007 Franky Van Liedekerke <franky.van.liedekerke@telenet.be>
  10. * Copyright (C) 2010-2020 Juanjo Menent <jmenent@2byte.es>
  11. * Copyright (C) 2012-2014 Christophe Battarel <christophe.battarel@altairis.fr>
  12. * Copyright (C) 2012-2015 Marcos García <marcosgdf@gmail.com>
  13. * Copyright (C) 2012 Cédric Salvador <csalvador@gpcsolutions.fr>
  14. * Copyright (C) 2012-2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  15. * Copyright (C) 2013 Cedric Gross <c.gross@kreiz-it.fr>
  16. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  17. * Copyright (C) 2016 Ferran Marcet <fmarcet@2byte.es>
  18. * Copyright (C) 2018 Alexandre Spangaro <aspangaro@open-dsi.fr>
  19. * Copyright (C) 2018 Nicolas ZABOURI <info@inovea-conseil.com>
  20. *
  21. * This program is free software; you can redistribute it and/or modify
  22. * it under the terms of the GNU General Public License as published by
  23. * the Free Software Foundation; either version 3 of the License, or
  24. * (at your option) any later version.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU General Public License
  32. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  33. */
  34. /**
  35. * \file htdocs/compta/facture/class/facture.class.php
  36. * \ingroup facture
  37. * \brief File of class to manage invoices
  38. */
  39. include_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php';
  44. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  45. if (!empty($conf->accounting->enabled)) {
  46. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
  47. }
  48. if (!empty($conf->accounting->enabled)) {
  49. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
  50. }
  51. /**
  52. * Class to manage invoices
  53. */
  54. class Facture extends CommonInvoice
  55. {
  56. /**
  57. * @var string ID to identify managed object
  58. */
  59. public $element = 'facture';
  60. /**
  61. * @var string Name of table without prefix where object is stored
  62. */
  63. public $table_element = 'facture';
  64. /**
  65. * @var string Name of subtable line
  66. */
  67. public $table_element_line = 'facturedet';
  68. /**
  69. * @var string Fieldname with ID of parent key if this field has a parent
  70. */
  71. public $fk_element = 'fk_facture';
  72. /**
  73. * @var string String with name of icon for myobject.
  74. */
  75. public $picto = 'bill';
  76. /**
  77. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  78. * @var int
  79. */
  80. public $ismultientitymanaged = 1;
  81. /**
  82. * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  83. * @var integer
  84. */
  85. public $restrictiononfksoc = 1;
  86. /**
  87. * {@inheritdoc}
  88. */
  89. protected $table_ref_field = 'ref';
  90. /**
  91. * @var int 1 if status is draft
  92. * @deprecated
  93. */
  94. public $brouillon;
  95. /**
  96. * @var int thirdparty ID
  97. */
  98. public $socid;
  99. public $author;
  100. /**
  101. * @var int ID
  102. */
  103. public $fk_user_author;
  104. /**
  105. * @var int ID
  106. */
  107. public $fk_user_valid;
  108. public $date; // Date invoice
  109. public $datem;
  110. /**
  111. * @var int Date expected for delivery
  112. * @deprecated
  113. */
  114. public $date_livraison; // deprecated; Use delivery_date instead.
  115. public $delivery_date; // Date expected of shipment (date starting shipment, not the reception that occurs some days after)
  116. /**
  117. * @var string customer ref
  118. */
  119. public $ref_client;
  120. /**
  121. * @var int Ref Int
  122. * @deprecated
  123. */
  124. public $ref_int; // deprecated
  125. //Check constants for types
  126. public $type = self::TYPE_STANDARD;
  127. //var $amount;
  128. public $remise_absolue;
  129. public $remise_percent;
  130. public $total_ht = 0;
  131. public $total_tva = 0;
  132. public $total_localtax1 = 0;
  133. public $total_localtax2 = 0;
  134. public $total_ttc = 0;
  135. public $revenuestamp;
  136. /**
  137. * ! Closing after partial payment: discount_vat, badsupplier, abandon
  138. * ! Closing when no payment: replaced, abandoned
  139. * @var string Close code
  140. */
  141. public $close_code;
  142. /**
  143. * ! Comment if paid without full payment
  144. * @var string Close note
  145. */
  146. public $close_note;
  147. /**
  148. * 1 if invoice paid COMPLETELY, 0 otherwise (do not use it anymore, use statut and close_code)
  149. */
  150. public $paye;
  151. //! key of module source when invoice generated from a dedicated module ('cashdesk', 'takepos', ...)
  152. public $module_source;
  153. //! key of pos source ('0', '1', ...)
  154. public $pos_source;
  155. //! id of template invoice when generated from a template invoice
  156. public $fk_fac_rec_source;
  157. //! id of source invoice if replacement invoice or credit note
  158. public $fk_facture_source;
  159. public $linked_objects = array();
  160. public $date_lim_reglement;
  161. public $cond_reglement_code; // Code in llx_c_paiement
  162. public $mode_reglement_code; // Code in llx_c_paiement
  163. /**
  164. * @var int ID Field to store bank id to use when payment mode is withdraw
  165. */
  166. public $fk_bank;
  167. /**
  168. * @var FactureLigne[]
  169. */
  170. public $lines = array();
  171. public $line;
  172. public $extraparams = array();
  173. public $fac_rec;
  174. public $date_pointoftax;
  175. // Multicurrency
  176. /**
  177. * @var int ID
  178. */
  179. public $fk_multicurrency;
  180. public $multicurrency_code;
  181. public $multicurrency_tx;
  182. public $multicurrency_total_ht;
  183. public $multicurrency_total_tva;
  184. public $multicurrency_total_ttc;
  185. /**
  186. * @var int Situation cycle reference number
  187. */
  188. public $situation_cycle_ref;
  189. /**
  190. * @var int Situation counter inside the cycle
  191. */
  192. public $situation_counter;
  193. /**
  194. * @var int Final situation flag
  195. */
  196. public $situation_final;
  197. /**
  198. * @var array Table of previous situations
  199. */
  200. public $tab_previous_situation_invoice = array();
  201. /**
  202. * @var array Table of next situations
  203. */
  204. public $tab_next_situation_invoice = array();
  205. public $oldcopy;
  206. /**
  207. * @var double percentage of retainage
  208. */
  209. public $retained_warranty;
  210. /**
  211. * @var int timestamp of date limit of retainage
  212. */
  213. public $retained_warranty_date_limit;
  214. /**
  215. * @var int Code in llx_c_paiement
  216. */
  217. public $retained_warranty_fk_cond_reglement;
  218. /**
  219. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  220. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  221. * 'label' the translation key.
  222. * 'enabled' is a condition when the field must be managed.
  223. * 'position' is the sort order of field.
  224. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  225. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  226. * 'noteditable' says if field is not editable (1 or 0)
  227. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  228. * 'index' if we want an index in database.
  229. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  230. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  231. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  232. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  233. * 'help' is a string visible as a tooltip on field
  234. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  235. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  236. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  237. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  238. *
  239. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  240. */
  241. // BEGIN MODULEBUILDER PROPERTIES
  242. /**
  243. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  244. */
  245. public $fields = array(
  246. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>1),
  247. 'ref' =>array('type'=>'varchar(30)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>5),
  248. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>20, 'index'=>1),
  249. 'ref_client' =>array('type'=>'varchar(255)', 'label'=>'RefCustomer', 'enabled'=>1, 'visible'=>-1, 'position'=>10),
  250. 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>0, 'position'=>12),
  251. //'ref_int' =>array('type'=>'varchar(255)', 'label'=>'Ref int', 'enabled'=>1, 'visible'=>0, 'position'=>30), // deprecated
  252. 'type' =>array('type'=>'smallint(6)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
  253. //'increment' =>array('type'=>'varchar(10)', 'label'=>'Increment', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  254. 'fk_soc' =>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>50),
  255. 'datef' =>array('type'=>'date', 'label'=>'DateInvoice', 'enabled'=>1, 'visible'=>1, 'position'=>20),
  256. 'date_valid' =>array('type'=>'date', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>22),
  257. 'date_lim_reglement' =>array('type'=>'date', 'label'=>'DateDue', 'enabled'=>1, 'visible'=>1, 'position'=>25),
  258. 'date_closing' =>array('type'=>'datetime', 'label'=>'Date closing', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
  259. 'paye' =>array('type'=>'smallint(6)', 'label'=>'InvoicePaidCompletely', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>80),
  260. //'amount' =>array('type'=>'double(24,8)', 'label'=>'Amount', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>85),
  261. 'remise_percent' =>array('type'=>'double', 'label'=>'RelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  262. 'remise_absolue' =>array('type'=>'double', 'label'=>'CustomerRelativeDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>91),
  263. //'remise' =>array('type'=>'double', 'label'=>'Remise', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
  264. 'close_code' =>array('type'=>'varchar(16)', 'label'=>'EarlyClosingReason', 'enabled'=>1, 'visible'=>-1, 'position'=>92),
  265. 'close_note' =>array('type'=>'varchar(128)', 'label'=>'EarlyClosingComment', 'enabled'=>1, 'visible'=>-1, 'position'=>93),
  266. 'total_ht' =>array('type'=>'double(24,8)', 'label'=>'AmountHT', 'enabled'=>1, 'visible'=>1, 'position'=>95, 'isameasure'=>1),
  267. 'total_tva' =>array('type'=>'double(24,8)', 'label'=>'AmountVAT', 'enabled'=>1, 'visible'=>-1, 'position'=>100, 'isameasure'=>1),
  268. 'localtax1' =>array('type'=>'double(24,8)', 'label'=>'LT1', 'enabled'=>1, 'visible'=>-1, 'position'=>110, 'isameasure'=>1),
  269. 'localtax2' =>array('type'=>'double(24,8)', 'label'=>'LT2', 'enabled'=>1, 'visible'=>-1, 'position'=>120, 'isameasure'=>1),
  270. 'revenuestamp' =>array('type'=>'double(24,8)', 'label'=>'RevenueStamp', 'enabled'=>1, 'visible'=>-1, 'position'=>115, 'isameasure'=>1),
  271. 'total_ttc' =>array('type'=>'double(24,8)', 'label'=>'AmountTTC', 'enabled'=>1, 'visible'=>1, 'position'=>130, 'isameasure'=>1),
  272. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-1, 'position'=>165),
  273. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>166),
  274. 'fk_user_valid' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>167),
  275. 'fk_user_closing' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserClosing', 'enabled'=>1, 'visible'=>-1, 'position'=>168),
  276. 'fk_facture_source' =>array('type'=>'integer', 'label'=>'SourceInvoice', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
  277. 'fk_projet' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
  278. 'fk_account' =>array('type'=>'integer', 'label'=>'Fk account', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
  279. 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'CurrencyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  280. 'fk_cond_reglement' =>array('type'=>'integer', 'label'=>'PaymentTerm', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>190),
  281. 'fk_mode_reglement' =>array('type'=>'integer', 'label'=>'PaymentMode', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
  282. 'note_private' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>205),
  283. 'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>210),
  284. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>215),
  285. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>225),
  286. 'situation_cycle_ref' =>array('type'=>'smallint(6)', 'label'=>'Situation cycle ref', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION', 'visible'=>-1, 'position'=>230),
  287. 'situation_counter' =>array('type'=>'smallint(6)', 'label'=>'Situation counter', 'enabled'=>'$conf->global->INVOICE_USE_SITUATION', 'visible'=>-1, 'position'=>235),
  288. 'situation_final' =>array('type'=>'smallint(6)', 'label'=>'Situation final', 'enabled'=>'empty($conf->global->INVOICE_USE_SITUATION) ? 0 : 1', 'visible'=>-1, 'position'=>240),
  289. 'retained_warranty' =>array('type'=>'double', 'label'=>'Retained warranty', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>245),
  290. 'retained_warranty_date_limit' =>array('type'=>'date', 'label'=>'Retained warranty date limit', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>250),
  291. 'retained_warranty_fk_cond_reglement' =>array('type'=>'integer', 'label'=>'Retained warranty fk cond reglement', 'enabled'=>'$conf->global->INVOICE_USE_RETAINED_WARRANTY', 'visible'=>-1, 'position'=>255),
  292. 'fk_incoterms' =>array('type'=>'integer', 'label'=>'IncotermCode', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>260),
  293. 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'IncotermLabel', 'enabled'=>'$conf->incoterm->enabled', 'visible'=>-1, 'position'=>265),
  294. 'date_pointoftax' =>array('type'=>'date', 'label'=>'DatePointOfTax', 'enabled'=>'$conf->global->INVOICE_POINTOFTAX_DATE', 'visible'=>-1, 'position'=>270),
  295. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'MulticurrencyID', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>275),
  296. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Currency', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>280),
  297. 'multicurrency_tx' =>array('type'=>'double(24,8)', 'label'=>'CurrencyRate', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
  298. 'multicurrency_total_ht' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountHT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
  299. 'multicurrency_total_tva' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountVAT', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>291, 'isameasure'=>1),
  300. 'multicurrency_total_ttc' =>array('type'=>'double(24,8)', 'label'=>'MulticurrencyAmountTTC', 'enabled'=>'$conf->multicurrency->enabled', 'visible'=>-1, 'position'=>292, 'isameasure'=>1),
  301. 'fk_fac_rec_source' =>array('type'=>'integer', 'label'=>'RecurringInvoiceSource', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
  302. 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>310),
  303. 'module_source' =>array('type'=>'varchar(32)', 'label'=>'POSModule', 'enabled'=>1, 'visible'=>-1, 'position'=>315),
  304. 'pos_source' =>array('type'=>'varchar(32)', 'label'=>'POSTerminal', 'enabled'=>1, 'visible'=>-1, 'position'=>320),
  305. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
  306. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModificationShort', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>500),
  307. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>900),
  308. 'fk_statut' =>array('type'=>'smallint(6)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Paid', 3=>'Abandonned')),
  309. );
  310. // END MODULEBUILDER PROPERTIES
  311. /**
  312. * Standard invoice
  313. */
  314. const TYPE_STANDARD = 0;
  315. /**
  316. * Replacement invoice
  317. */
  318. const TYPE_REPLACEMENT = 1;
  319. /**
  320. * Credit note invoice
  321. */
  322. const TYPE_CREDIT_NOTE = 2;
  323. /**
  324. * Deposit invoice
  325. */
  326. const TYPE_DEPOSIT = 3;
  327. /**
  328. * Proforma invoice (should not be used. a proforma is an order)
  329. */
  330. const TYPE_PROFORMA = 4;
  331. /**
  332. * Situation invoice
  333. */
  334. const TYPE_SITUATION = 5;
  335. /**
  336. * Draft status
  337. */
  338. const STATUS_DRAFT = 0;
  339. /**
  340. * Validated (need to be paid)
  341. */
  342. const STATUS_VALIDATED = 1;
  343. /**
  344. * Classified paid.
  345. * If paid partially, $this->close_code can be:
  346. * - CLOSECODE_DISCOUNTVAT
  347. * - CLOSECODE_BADDEBT
  348. * If paid completely, this->close_code will be null
  349. */
  350. const STATUS_CLOSED = 2;
  351. /**
  352. * Classified abandoned and no payment done.
  353. * $this->close_code can be:
  354. * - CLOSECODE_BADDEBT
  355. * - CLOSECODE_ABANDONED
  356. * - CLOSECODE_REPLACED
  357. */
  358. const STATUS_ABANDONED = 3;
  359. const CLOSECODE_DISCOUNTVAT = 'discount_vat'; // Abandonned remain - escompte
  360. const CLOSECODE_BADDEBT = 'badcustomer'; // Abandonned - bad
  361. const CLOSECODE_ABANDONED = 'abandon'; // Abandonned - other
  362. const CLOSECODE_REPLACED = 'replaced'; // Closed after doing a replacement invoice
  363. /**
  364. * Constructor
  365. *
  366. * @param DoliDB $db Database handler
  367. */
  368. public function __construct($db)
  369. {
  370. $this->db = $db;
  371. }
  372. /**
  373. * Create invoice in database.
  374. * Note: this->ref can be set or empty. If empty, we will use "(PROV999)"
  375. * Note: this->fac_rec must be set to create invoice from a recurring invoice
  376. *
  377. * @param User $user Object user that create
  378. * @param int $notrigger 1=Does not execute triggers, 0 otherwise
  379. * @param int $forceduedate If set, do not recalculate due date from payment condition but force it with value
  380. * @return int <0 if KO, >0 if OK
  381. */
  382. public function create(User $user, $notrigger = 0, $forceduedate = 0)
  383. {
  384. global $langs, $conf, $mysoc, $hookmanager;
  385. $error = 0;
  386. // Clean parameters
  387. if (empty($this->type)) {
  388. $this->type = self::TYPE_STANDARD;
  389. }
  390. $this->ref_client = trim($this->ref_client);
  391. $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
  392. $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private));
  393. $this->note_public = trim($this->note_public);
  394. if (!$this->cond_reglement_id) {
  395. $this->cond_reglement_id = 0;
  396. }
  397. if (!$this->mode_reglement_id) {
  398. $this->mode_reglement_id = 0;
  399. }
  400. $this->brouillon = 1;
  401. $this->status = self::STATUS_DRAFT;
  402. $this->statut = self::STATUS_DRAFT;
  403. // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate)
  404. if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) {
  405. list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date);
  406. } else {
  407. $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  408. }
  409. if (empty($this->fk_multicurrency)) {
  410. $this->multicurrency_code = $conf->currency;
  411. $this->fk_multicurrency = 0;
  412. $this->multicurrency_tx = 1;
  413. }
  414. dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date);
  415. // Check parameters
  416. if (empty($this->date)) {
  417. $this->error = "Try to create an invoice with an empty parameter (date)";
  418. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  419. return -3;
  420. }
  421. $soc = new Societe($this->db);
  422. $result = $soc->fetch($this->socid);
  423. if ($result < 0) {
  424. $this->error = "Failed to fetch company: ".$soc->error;
  425. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  426. return -2;
  427. }
  428. $now = dol_now();
  429. $this->db->begin();
  430. $originaldatewhen = null;
  431. $nextdatewhen = null;
  432. $previousdaynextdatewhen = null;
  433. // Create invoice from a template recurring invoice
  434. if ($this->fac_rec > 0) {
  435. $this->fk_fac_rec_source = $this->fac_rec;
  436. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php';
  437. $_facrec = new FactureRec($this->db);
  438. $result = $_facrec->fetch($this->fac_rec);
  439. $result = $_facrec->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); // This load $_facrec->linkedObjectsIds
  440. // Define some dates
  441. $originaldatewhen = $_facrec->date_when;
  442. $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency);
  443. $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd');
  444. if (!empty($_facrec->frequency)) { // Invoice are created on same thirdparty than template when there is a recurrence, but not necessarly when there is no recurrence.
  445. $this->socid = $_facrec->socid;
  446. }
  447. $this->entity = $_facrec->entity; // Invoice created in same entity than template
  448. // Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI
  449. $this->fk_project = GETPOST('projectid', 'int') > 0 ? ((int) GETPOST('projectid', 'int')) : $_facrec->fk_project;
  450. $this->note_public = GETPOST('note_public', 'none') ? GETPOST('note_public', 'restricthtml') : $_facrec->note_public;
  451. $this->note_private = GETPOST('note_private', 'none') ? GETPOST('note_private', 'restricthtml') : $_facrec->note_private;
  452. $this->model_pdf = GETPOST('model', 'alpha') ? GETPOST('model', 'alpha') : $_facrec->model_pdf;
  453. $this->cond_reglement_id = GETPOST('cond_reglement_id', 'int') > 0 ? ((int) GETPOST('cond_reglement_id', 'int')) : $_facrec->cond_reglement_id;
  454. $this->mode_reglement_id = GETPOST('mode_reglement_id', 'int') > 0 ? ((int) GETPOST('mode_reglement_id', 'int')) : $_facrec->mode_reglement_id;
  455. $this->fk_account = GETPOST('fk_account') > 0 ? ((int) GETPOST('fk_account')) : $_facrec->fk_account;
  456. // Set here to have this defined for substitution into notes, should be recalculated after adding lines to get same result
  457. $this->total_ht = $_facrec->total_ht;
  458. $this->total_ttc = $_facrec->total_ttc;
  459. // Fields always coming from template
  460. $this->remise_absolue = $_facrec->remise_absolue;
  461. $this->remise_percent = $_facrec->remise_percent;
  462. $this->fk_incoterms = $_facrec->fk_incoterms;
  463. $this->location_incoterms = $_facrec->location_incoterms;
  464. // Clean parameters
  465. if (!$this->type) {
  466. $this->type = self::TYPE_STANDARD;
  467. }
  468. $this->ref_client = trim($this->ref_client);
  469. $this->note_public = trim($this->note_public);
  470. $this->note_private = trim($this->note_private);
  471. $this->note_private = dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
  472. $this->array_options = $_facrec->array_options;
  473. //if (! $this->remise) $this->remise = 0;
  474. if (!$this->mode_reglement_id) {
  475. $this->mode_reglement_id = 0;
  476. }
  477. $this->brouillon = 1;
  478. $this->status = self::STATUS_DRAFT;
  479. $this->statut = self::STATUS_DRAFT;
  480. $this->linked_objects = $_facrec->linkedObjectsIds;
  481. // We do not add link to template invoice or next invoice will be linked to all generated invoices
  482. //$this->linked_objects['facturerec'][0] = $this->fac_rec;
  483. $forceduedate = $this->calculate_date_lim_reglement();
  484. // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
  485. if ($_facrec->frequency > 0) {
  486. dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when");
  487. if (empty($_facrec->date_when)) {
  488. $_facrec->date_when = $now;
  489. }
  490. $next_date = $_facrec->getNextDate(); // Calculate next date
  491. $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, '');
  492. //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1.
  493. $result = $_facrec->setNextDate($next_date, 1);
  494. }
  495. // Define lang of customer
  496. $outputlangs = $langs;
  497. $newlang = '';
  498. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) {
  499. $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ...
  500. }
  501. if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) {
  502. $newlang = $this->default_lang; // for thirdparty
  503. }
  504. if (!empty($newlang)) {
  505. $outputlangs = new Translate("", $conf);
  506. $outputlangs->setDefaultLang($newlang);
  507. }
  508. // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
  509. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $this);
  510. $substitutionarray['__INVOICE_PREVIOUS_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%m');
  511. $substitutionarray['__INVOICE_MONTH__'] = dol_print_date($this->date, '%m');
  512. $substitutionarray['__INVOICE_NEXT_MONTH__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%m');
  513. $substitutionarray['__INVOICE_PREVIOUS_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'm'), '%B');
  514. $substitutionarray['__INVOICE_MONTH_TEXT__'] = dol_print_date($this->date, '%B');
  515. $substitutionarray['__INVOICE_NEXT_MONTH_TEXT__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'm'), '%B');
  516. $substitutionarray['__INVOICE_PREVIOUS_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, -1, 'y'), '%Y');
  517. $substitutionarray['__INVOICE_YEAR__'] = dol_print_date($this->date, '%Y');
  518. $substitutionarray['__INVOICE_NEXT_YEAR__'] = dol_print_date(dol_time_plus_duree($this->date, 1, 'y'), '%Y');
  519. // Only for template invoice
  520. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_BEFORE_GEN__'] = dol_print_date($originaldatewhen, 'dayhour');
  521. $substitutionarray['__INVOICE_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($nextdatewhen, 'dayhour');
  522. $substitutionarray['__INVOICE_PREVIOUS_DATE_NEXT_INVOICE_AFTER_GEN__'] = dol_print_date($previousdaynextdatewhen, 'dayhour');
  523. $substitutionarray['__INVOICE_COUNTER_CURRENT__'] = $_facrec->nb_gen_done;
  524. $substitutionarray['__INVOICE_COUNTER_MAX__'] = $_facrec->nb_gen_max;
  525. //var_dump($substitutionarray);exit;
  526. complete_substitutions_array($substitutionarray, $outputlangs);
  527. $this->note_public = make_substitutions($this->note_public, $substitutionarray);
  528. $this->note_private = make_substitutions($this->note_private, $substitutionarray);
  529. }
  530. // Define due date if not already defined
  531. if (empty($forceduedate)) {
  532. $duedate = $this->calculate_date_lim_reglement();
  533. /*if ($duedate < 0) { Regression, a date can be negative if before 1970.
  534. dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR);
  535. return -1;
  536. }*/
  537. $this->date_lim_reglement = $duedate;
  538. } else {
  539. $this->date_lim_reglement = $forceduedate;
  540. }
  541. // Insert into database
  542. $socid = $this->socid;
  543. $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture (";
  544. $sql .= " ref";
  545. $sql .= ", entity";
  546. $sql .= ", ref_ext";
  547. $sql .= ", type";
  548. $sql .= ", fk_soc";
  549. $sql .= ", datec";
  550. $sql .= ", remise_absolue";
  551. $sql .= ", remise_percent";
  552. $sql .= ", datef";
  553. $sql .= ", date_pointoftax";
  554. $sql .= ", note_private";
  555. $sql .= ", note_public";
  556. $sql .= ", ref_client, ref_int";
  557. $sql .= ", fk_account";
  558. $sql .= ", module_source, pos_source, fk_fac_rec_source, fk_facture_source, fk_user_author, fk_projet";
  559. $sql .= ", fk_cond_reglement, fk_mode_reglement, date_lim_reglement, model_pdf";
  560. $sql .= ", situation_cycle_ref, situation_counter, situation_final";
  561. $sql .= ", fk_incoterms, location_incoterms";
  562. $sql .= ", fk_multicurrency";
  563. $sql .= ", multicurrency_code";
  564. $sql .= ", multicurrency_tx";
  565. $sql .= ", retained_warranty";
  566. $sql .= ", retained_warranty_date_limit";
  567. $sql .= ", retained_warranty_fk_cond_reglement";
  568. $sql .= ")";
  569. $sql .= " VALUES (";
  570. $sql .= "'(PROV)'";
  571. $sql .= ", ".setEntity($this);
  572. $sql .= ", ".($this->ref_ext ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  573. $sql .= ", '".$this->db->escape($this->type)."'";
  574. $sql .= ", ".((int) $socid);
  575. $sql .= ", '".$this->db->idate($now)."'";
  576. $sql .= ", ".($this->remise_absolue > 0 ? $this->remise_absolue : 'NULL');
  577. $sql .= ", ".($this->remise_percent > 0 ? $this->remise_percent : 'NULL');
  578. $sql .= ", '".$this->db->idate($this->date)."'";
  579. $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'");
  580. $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null");
  581. $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null");
  582. $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null");
  583. $sql .= ", ".($this->ref_int ? "'".$this->db->escape($this->ref_int)."'" : "null");
  584. $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL');
  585. $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null");
  586. $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null");
  587. $sql .= ", ".($this->fk_fac_rec_source ? "'".$this->db->escape($this->fk_fac_rec_source)."'" : "null");
  588. $sql .= ", ".($this->fk_facture_source ? "'".$this->db->escape($this->fk_facture_source)."'" : "null");
  589. $sql .= ", ".($user->id > 0 ? (int) $user->id : "null");
  590. $sql .= ", ".($this->fk_project ? $this->fk_project : "null");
  591. $sql .= ", ".$this->cond_reglement_id;
  592. $sql .= ", ".$this->mode_reglement_id;
  593. $sql .= ", '".$this->db->idate($this->date_lim_reglement)."'";
  594. $sql .= ", ".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null");
  595. $sql .= ", ".($this->situation_cycle_ref ? "'".$this->db->escape($this->situation_cycle_ref)."'" : "null");
  596. $sql .= ", ".($this->situation_counter ? "'".$this->db->escape($this->situation_counter)."'" : "null");
  597. $sql .= ", ".($this->situation_final ? $this->situation_final : 0);
  598. $sql .= ", ".(int) $this->fk_incoterms;
  599. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  600. $sql .= ", ".(int) $this->fk_multicurrency;
  601. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  602. $sql .= ", ".(double) $this->multicurrency_tx;
  603. $sql .= ", ".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty));
  604. $sql .= ", ".(!empty($this->retained_warranty_date_limit) ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'NULL');
  605. $sql .= ", ".(int) $this->retained_warranty_fk_cond_reglement;
  606. $sql .= ")";
  607. $resql = $this->db->query($sql);
  608. if ($resql) {
  609. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture');
  610. // Update ref with new one
  611. $this->ref = '(PROV'.$this->id.')';
  612. $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".((int) $this->id);
  613. $resql = $this->db->query($sql);
  614. if (!$resql) {
  615. $error++;
  616. }
  617. if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects
  618. $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds
  619. }
  620. // Add object linked
  621. if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) {
  622. foreach ($this->linked_objects as $origin => $tmp_origin_id) {
  623. if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...))
  624. foreach ($tmp_origin_id as $origin_id) {
  625. $ret = $this->add_object_linked($origin, $origin_id);
  626. if (!$ret) {
  627. $this->error = $this->db->lasterror();
  628. $error++;
  629. }
  630. }
  631. } else // Old behaviour, if linked_object has only one link per type, so is something like array('contract'=>id1))
  632. {
  633. $origin_id = $tmp_origin_id;
  634. $ret = $this->add_object_linked($origin, $origin_id);
  635. if (!$ret) {
  636. $this->error = $this->db->lasterror();
  637. $error++;
  638. }
  639. }
  640. }
  641. }
  642. // Propagate contacts
  643. if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object
  644. $originforcontact = $this->origin;
  645. $originidforcontact = $this->origin_id;
  646. if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order
  647. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  648. $exp = new Expedition($this->db);
  649. $exp->fetch($this->origin_id);
  650. $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0);
  651. if (count($exp->linkedObjectsIds['commande']) > 0) {
  652. foreach ($exp->linkedObjectsIds['commande'] as $key => $value) {
  653. $originforcontact = 'commande';
  654. if (is_object($value)) {
  655. $originidforcontact = $value->id;
  656. } else {
  657. $originidforcontact = $value;
  658. }
  659. break; // We take first one
  660. }
  661. }
  662. }
  663. $sqlcontact = "SELECT ctc.code, ctc.source, ec.fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc";
  664. $sqlcontact .= " WHERE element_id = ".((int) $originidforcontact)." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'";
  665. $resqlcontact = $this->db->query($sqlcontact);
  666. if ($resqlcontact) {
  667. while ($objcontact = $this->db->fetch_object($resqlcontact)) {
  668. //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n";
  669. $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object
  670. }
  671. } else {
  672. dol_print_error($resqlcontact);
  673. }
  674. }
  675. /*
  676. * Insert lines of invoices, if not from template invoice, into database
  677. */
  678. if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode)
  679. $fk_parent_line = 0;
  680. dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects");
  681. foreach ($this->lines as $i => $val) {
  682. $newinvoiceline = $this->lines[$i];
  683. $newinvoiceline->fk_facture = $this->id;
  684. $newinvoiceline->origin = $this->lines[$i]->element;
  685. $newinvoiceline->origin_id = $this->lines[$i]->id;
  686. // Auto set date of service ?
  687. if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) { // $originaldatewhen is defined when generating from recurring invoice only
  688. $newinvoiceline->date_start = $originaldatewhen;
  689. }
  690. if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) { // $previousdaynextdatewhen is defined when generating from recurring invoice only
  691. $newinvoiceline->date_end = $previousdaynextdatewhen;
  692. }
  693. if ($result >= 0) {
  694. // Reset fk_parent_line for no child products and special product
  695. if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) {
  696. $fk_parent_line = 0;
  697. }
  698. $newinvoiceline->fk_parent_line = $fk_parent_line;
  699. if ($this->type === Facture::TYPE_REPLACEMENT && $newinvoiceline->fk_remise_except) {
  700. $discount = new DiscountAbsolute($this->db);
  701. $discount->fetch($newinvoiceline->fk_remise_except);
  702. $discountId = $soc->set_remise_except($discount->amount_ht, $user, $discount->description, $discount->tva_tx);
  703. $newinvoiceline->fk_remise_except = $discountId;
  704. }
  705. $result = $newinvoiceline->insert();
  706. // Defined the new fk_parent_line
  707. if ($result > 0 && $newinvoiceline->product_type == 9) {
  708. $fk_parent_line = $result;
  709. }
  710. }
  711. if ($result < 0) {
  712. $this->error = $newinvoiceline->error;
  713. $this->errors = $newinvoiceline->errors;
  714. $error++;
  715. break;
  716. }
  717. }
  718. } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays
  719. $fk_parent_line = 0;
  720. dol_syslog("There is ".count($this->lines)." lines that are array lines");
  721. foreach ($this->lines as $i => $val) {
  722. $line = $this->lines[$i];
  723. // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array
  724. //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object.
  725. if (!is_object($line)) {
  726. $line = (object) $line;
  727. }
  728. if ($result >= 0) {
  729. // Reset fk_parent_line for no child products and special product
  730. if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) {
  731. $fk_parent_line = 0;
  732. }
  733. // Complete vat rate with code
  734. $vatrate = $line->tva_tx;
  735. if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) {
  736. $vatrate .= ' ('.$line->vat_src_code.')';
  737. }
  738. if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) {
  739. $originid = $line->origin_id;
  740. $origintype = $line->origin;
  741. } else {
  742. $originid = $line->id;
  743. $origintype = $this->element;
  744. }
  745. // init ref_ext
  746. if (empty($line->ref_ext)) {
  747. $line->ref_ext = '';
  748. }
  749. $result = $this->addline(
  750. $line->desc,
  751. $line->subprice,
  752. $line->qty,
  753. $vatrate,
  754. $line->localtax1_tx,
  755. $line->localtax2_tx,
  756. $line->fk_product,
  757. $line->remise_percent,
  758. $line->date_start,
  759. $line->date_end,
  760. $line->fk_code_ventilation,
  761. $line->info_bits,
  762. $line->fk_remise_except,
  763. 'HT',
  764. 0,
  765. $line->product_type,
  766. $line->rang,
  767. $line->special_code,
  768. $origintype,
  769. $originid,
  770. $fk_parent_line,
  771. $line->fk_fournprice,
  772. $line->pa_ht,
  773. $line->label,
  774. $line->array_options,
  775. $line->situation_percent,
  776. $line->fk_prev_id,
  777. $line->fk_unit,
  778. $line->multicurrency_subprice,
  779. $line->ref_ext
  780. );
  781. if ($result < 0) {
  782. $this->error = $this->db->lasterror();
  783. dol_print_error($this->db);
  784. $this->db->rollback();
  785. return -1;
  786. }
  787. // Defined the new fk_parent_line
  788. if ($result > 0 && $line->product_type == 9) {
  789. $fk_parent_line = $result;
  790. }
  791. }
  792. }
  793. }
  794. /*
  795. * Insert lines of template invoices
  796. */
  797. if (!$error && $this->fac_rec > 0) {
  798. foreach ($_facrec->lines as $i => $val) {
  799. if ($_facrec->lines[$i]->fk_product) {
  800. $prod = new Product($this->db);
  801. $res = $prod->fetch($_facrec->lines[$i]->fk_product);
  802. }
  803. // For line from template invoice, we use data from template invoice
  804. /*
  805. $tva_tx = get_default_tva($mysoc,$soc,$prod->id);
  806. $tva_npr = get_default_npr($mysoc,$soc,$prod->id);
  807. if (empty($tva_tx)) $tva_npr=0;
  808. $localtax1_tx=get_localtax($tva_tx,1,$soc,$mysoc,$tva_npr);
  809. $localtax2_tx=get_localtax($tva_tx,2,$soc,$mysoc,$tva_npr);
  810. */
  811. $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : '');
  812. $tva_npr = $_facrec->lines[$i]->info_bits;
  813. if (empty($tva_tx)) {
  814. $tva_npr = 0;
  815. }
  816. $localtax1_tx = $_facrec->lines[$i]->localtax1_tx;
  817. $localtax2_tx = $_facrec->lines[$i]->localtax2_tx;
  818. $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ? null : $_facrec->lines[$i]->fk_product_fournisseur_price;
  819. $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice;
  820. // If buyprice not defined from template invoice, we try to guess the best value
  821. if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) {
  822. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  823. $producttmp = new ProductFournisseur($this->db);
  824. $producttmp->fetch($_facrec->lines[$i]->fk_product);
  825. // If margin module defined on costprice, we try the costprice
  826. // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price
  827. // else we get the best supplier price
  828. if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) {
  829. $buyprice = $producttmp->cost_price;
  830. } elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) {
  831. $buyprice = $producttmp->pmp;
  832. } else {
  833. if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) {
  834. if ($producttmp->product_fourn_price_id > 0) {
  835. $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU');
  836. }
  837. }
  838. }
  839. }
  840. $result_insert = $this->addline(
  841. $_facrec->lines[$i]->desc,
  842. $_facrec->lines[$i]->subprice,
  843. $_facrec->lines[$i]->qty,
  844. $tva_tx,
  845. $localtax1_tx,
  846. $localtax2_tx,
  847. $_facrec->lines[$i]->fk_product,
  848. $_facrec->lines[$i]->remise_percent,
  849. ($_facrec->lines[$i]->date_start_fill == 1 && $originaldatewhen) ? $originaldatewhen : '',
  850. ($_facrec->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) ? $previousdaynextdatewhen : '',
  851. 0,
  852. $tva_npr,
  853. '',
  854. 'HT',
  855. 0,
  856. $_facrec->lines[$i]->product_type,
  857. $_facrec->lines[$i]->rang,
  858. $_facrec->lines[$i]->special_code,
  859. '',
  860. 0,
  861. 0,
  862. $fk_product_fournisseur_price,
  863. $buyprice,
  864. $_facrec->lines[$i]->label,
  865. empty($_facrec->lines[$i]->array_options) ?null:$_facrec->lines[$i]->array_options,
  866. $_facrec->lines[$i]->situation_percent,
  867. '',
  868. $_facrec->lines[$i]->fk_unit,
  869. $_facrec->lines[$i]->multicurrency_subprice
  870. );
  871. if ($result_insert < 0) {
  872. $error++;
  873. $this->error = $this->db->error();
  874. break;
  875. }
  876. }
  877. }
  878. if (!$error) {
  879. $result = $this->update_price(1);
  880. if ($result > 0) {
  881. $action = 'create';
  882. // Actions on extra fields
  883. if (!$error) {
  884. $result = $this->insertExtraFields();
  885. if ($result < 0) {
  886. $error++;
  887. }
  888. }
  889. if (!$error && !$notrigger) {
  890. // Call trigger
  891. $result = $this->call_trigger('BILL_CREATE', $user);
  892. if ($result < 0) {
  893. $error++;
  894. }
  895. // End call triggers
  896. }
  897. if (!$error) {
  898. $this->db->commit();
  899. return $this->id;
  900. } else {
  901. $this->db->rollback();
  902. return -4;
  903. }
  904. } else {
  905. $this->error = $langs->trans('FailedToUpdatePrice');
  906. $this->db->rollback();
  907. return -3;
  908. }
  909. } else {
  910. dol_syslog(get_class($this)."::create error ".$this->error, LOG_ERR);
  911. $this->db->rollback();
  912. return -2;
  913. }
  914. } else {
  915. $this->error = $this->db->error();
  916. $this->db->rollback();
  917. return -1;
  918. }
  919. }
  920. /**
  921. * Create a new invoice in database from current invoice
  922. *
  923. * @param User $user Object user that ask creation
  924. * @param int $invertdetail Reverse sign of amounts for lines
  925. * @return int <0 if KO, >0 if OK
  926. */
  927. public function createFromCurrent(User $user, $invertdetail = 0)
  928. {
  929. global $conf;
  930. // Charge facture source
  931. $facture = new Facture($this->db);
  932. // Retrieve all extrafield
  933. // fetch optionals attributes and labels
  934. $this->fetch_optionals();
  935. if (!empty($this->array_options)) {
  936. $facture->array_options = $this->array_options;
  937. }
  938. foreach ($this->lines as &$line) {
  939. $line->fetch_optionals(); //fetch extrafields
  940. }
  941. $facture->fk_facture_source = $this->fk_facture_source;
  942. $facture->type = $this->type;
  943. $facture->socid = $this->socid;
  944. $facture->date = $this->date;
  945. $facture->date_pointoftax = $this->date_pointoftax;
  946. $facture->note_public = $this->note_public;
  947. $facture->note_private = $this->note_private;
  948. $facture->ref_client = $this->ref_client;
  949. $facture->modelpdf = $this->model_pdf; // deprecated
  950. $facture->model_pdf = $this->model_pdf;
  951. $facture->fk_project = $this->fk_project;
  952. $facture->cond_reglement_id = $this->cond_reglement_id;
  953. $facture->mode_reglement_id = $this->mode_reglement_id;
  954. $facture->remise_absolue = $this->remise_absolue;
  955. $facture->remise_percent = $this->remise_percent;
  956. $facture->origin = $this->origin;
  957. $facture->origin_id = $this->origin_id;
  958. $facture->lines = $this->lines; // Array of lines of invoice
  959. $facture->situation_counter = $this->situation_counter;
  960. $facture->situation_cycle_ref = $this->situation_cycle_ref;
  961. $facture->situation_final = $this->situation_final;
  962. $facture->retained_warranty = $this->retained_warranty;
  963. $facture->retained_warranty_fk_cond_reglement = $this->retained_warranty_fk_cond_reglement;
  964. $facture->retained_warranty_date_limit = $this->retained_warranty_date_limit;
  965. $facture->fk_user_author = $user->id;
  966. // Loop on each line of new invoice
  967. foreach ($facture->lines as $i => $tmpline) {
  968. $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid;
  969. if ($invertdetail) {
  970. $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice;
  971. $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht;
  972. $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva;
  973. $facture->lines[$i]->total_localtax1 = -$facture->lines[$i]->total_localtax1;
  974. $facture->lines[$i]->total_localtax2 = -$facture->lines[$i]->total_localtax2;
  975. $facture->lines[$i]->total_ttc = -$facture->lines[$i]->total_ttc;
  976. $facture->lines[$i]->ref_ext = '';
  977. }
  978. }
  979. dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines));
  980. $facid = $facture->create($user);
  981. if ($facid <= 0) {
  982. $this->error = $facture->error;
  983. $this->errors = $facture->errors;
  984. } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) {
  985. $this->fetchObjectLinked('', '', $this->id, 'facture');
  986. foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) {
  987. foreach ($Tfk_object as $fk_object) {
  988. $facture->add_object_linked($typeObject, $fk_object);
  989. }
  990. }
  991. $facture->add_object_linked('facture', $this->fk_facture_source);
  992. }
  993. return $facid;
  994. }
  995. /**
  996. * Load an object from its id and create a new one in database
  997. *
  998. * @param User $user User that clone
  999. * @param int $fromid Id of object to clone
  1000. * @return int New id of clone
  1001. */
  1002. public function createFromClone(User $user, $fromid = 0)
  1003. {
  1004. global $conf, $hookmanager;
  1005. $error = 0;
  1006. $object = new Facture($this->db);
  1007. $this->db->begin();
  1008. $object->fetch($fromid);
  1009. // Change socid if needed
  1010. if (!empty($this->socid) && $this->socid != $object->socid) {
  1011. $objsoc = new Societe($this->db);
  1012. if ($objsoc->fetch($this->socid) > 0) {
  1013. $object->socid = $objsoc->id;
  1014. $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0);
  1015. $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0);
  1016. $object->fk_project = '';
  1017. $object->fk_delivery_address = '';
  1018. }
  1019. // TODO Change product price if multi-prices
  1020. }
  1021. $object->id = 0;
  1022. $object->statut = self::STATUS_DRAFT;
  1023. $object->status = self::STATUS_DRAFT;
  1024. // Clear fields
  1025. $object->date = (empty($this->date) ? dol_now() : $this->date);
  1026. $object->user_author = $user->id; // deprecated
  1027. $object->user_valid = null; // deprecated
  1028. $object->fk_user_author = $user->id;
  1029. $object->fk_user_valid = null;
  1030. $object->fk_facture_source = 0;
  1031. $object->date_creation = '';
  1032. $object->date_modification = '';
  1033. $object->date_validation = '';
  1034. $object->ref_client = '';
  1035. $object->close_code = '';
  1036. $object->close_note = '';
  1037. if ($conf->global->MAIN_DONT_KEEP_NOTE_ON_CLONING == 1) {
  1038. $object->note_private = '';
  1039. $object->note_public = '';
  1040. }
  1041. // Loop on each line of new invoice
  1042. foreach ($object->lines as $i => $line) {
  1043. if (($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts
  1044. unset($object->lines[$i]);
  1045. continue;
  1046. }
  1047. // Bloc to update dates of service (month by month only if previously filled and similare to start and end of month)
  1048. // If it's a service with start and end dates
  1049. if (!empty($conf->global->INVOICE_AUTO_NEXT_MONTH_ON_LINES) && !empty($line->date_start) && !empty($line->date_end)) {
  1050. // Get the dates
  1051. $start = dol_getdate($line->date_start);
  1052. $end = dol_getdate($line->date_end);
  1053. // Get the first and last day of the month
  1054. $first = dol_get_first_day($start['year'], $start['mon']);
  1055. $last = dol_get_last_day($end['year'], $end['mon']);
  1056. //print dol_print_date(dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt'), 'dayhour').' '.dol_print_date($first, 'dayhour').'<br>';
  1057. //print dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt').' '.$last.'<br>';exit;
  1058. // If start date is first date of month and end date is last date of month
  1059. if (dol_mktime(0, 0, 0, $start['mon'], $start['mday'], $start['year'], 'gmt') == $first
  1060. && dol_mktime(23, 59, 59, $end['mon'], $end['mday'], $end['year'], 'gmt') == $last) {
  1061. $nextMonth = dol_get_next_month($end['mon'], $end['year']);
  1062. $newFirst = dol_get_first_day($nextMonth['year'], $nextMonth['month']);
  1063. $newLast = dol_get_last_day($nextMonth['year'], $nextMonth['month']);
  1064. $object->lines[$i]->date_start = $newFirst;
  1065. $object->lines[$i]->date_end = $newLast;
  1066. }
  1067. }
  1068. $object->lines[$i]->ref_ext = ''; // Do not clone ref_ext
  1069. }
  1070. // Create clone
  1071. $object->context['createfromclone'] = 'createfromclone';
  1072. $result = $object->create($user);
  1073. if ($result < 0) {
  1074. $error++;
  1075. $this->error = $object->error;
  1076. $this->errors = $object->errors;
  1077. } else {
  1078. // copy internal contacts
  1079. if ($object->copy_linked_contact($this, 'internal') < 0) {
  1080. $error++;
  1081. $this->error = $object->error;
  1082. $this->errors = $object->errors;
  1083. } elseif ($this->socid == $object->socid) {
  1084. // copy external contacts if same company
  1085. if ($object->copy_linked_contact($this, 'external') < 0) {
  1086. $error++;
  1087. $this->error = $object->error;
  1088. $this->errors = $object->errors;
  1089. }
  1090. }
  1091. }
  1092. if (!$error) {
  1093. // Hook of thirdparty module
  1094. if (is_object($hookmanager)) {
  1095. $parameters = array('objFrom'=>$this);
  1096. $action = '';
  1097. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
  1098. if ($reshook < 0) {
  1099. $error++;
  1100. }
  1101. }
  1102. }
  1103. unset($object->context['createfromclone']);
  1104. // End
  1105. if (!$error) {
  1106. $this->db->commit();
  1107. return $object->id;
  1108. } else {
  1109. $this->db->rollback();
  1110. return -1;
  1111. }
  1112. }
  1113. /**
  1114. * Load an object from an order and create a new invoice into database
  1115. *
  1116. * @param Object $object Object source
  1117. * @param User $user Object user
  1118. * @return int <0 if KO, 0 if nothing done, 1 if OK
  1119. */
  1120. public function createFromOrder($object, User $user)
  1121. {
  1122. global $conf, $hookmanager;
  1123. $error = 0;
  1124. // Closed order
  1125. $this->date = dol_now();
  1126. $this->source = 0;
  1127. $num = count($object->lines);
  1128. for ($i = 0; $i < $num; $i++) {
  1129. $line = new FactureLigne($this->db);
  1130. $line->libelle = $object->lines[$i]->libelle; // deprecated
  1131. $line->label = $object->lines[$i]->label;
  1132. $line->desc = $object->lines[$i]->desc;
  1133. $line->subprice = $object->lines[$i]->subprice;
  1134. $line->total_ht = $object->lines[$i]->total_ht;
  1135. $line->total_tva = $object->lines[$i]->total_tva;
  1136. $line->total_localtax1 = $object->lines[$i]->total_localtax1;
  1137. $line->total_localtax2 = $object->lines[$i]->total_localtax2;
  1138. $line->total_ttc = $object->lines[$i]->total_ttc;
  1139. $line->vat_src_code = $object->lines[$i]->vat_src_code;
  1140. $line->tva_tx = $object->lines[$i]->tva_tx;
  1141. $line->localtax1_tx = $object->lines[$i]->localtax1_tx;
  1142. $line->localtax2_tx = $object->lines[$i]->localtax2_tx;
  1143. $line->qty = $object->lines[$i]->qty;
  1144. $line->fk_remise_except = $object->lines[$i]->fk_remise_except;
  1145. $line->remise_percent = $object->lines[$i]->remise_percent;
  1146. $line->fk_product = $object->lines[$i]->fk_product;
  1147. $line->info_bits = $object->lines[$i]->info_bits;
  1148. $line->product_type = $object->lines[$i]->product_type;
  1149. $line->rang = $object->lines[$i]->rang;
  1150. $line->special_code = $object->lines[$i]->special_code;
  1151. $line->fk_parent_line = $object->lines[$i]->fk_parent_line;
  1152. $line->fk_unit = $object->lines[$i]->fk_unit;
  1153. $line->date_start = $object->lines[$i]->date_start;
  1154. $line->date_end = $object->lines[$i]->date_end;
  1155. // Multicurrency
  1156. $line->fk_multicurrency = $object->lines[$i]->fk_multicurrency;
  1157. $line->multicurrency_code = $object->lines[$i]->multicurrency_code;
  1158. $line->multicurrency_subprice = $object->lines[$i]->multicurrency_subprice;
  1159. $line->multicurrency_total_ht = $object->lines[$i]->multicurrency_total_ht;
  1160. $line->multicurrency_total_tva = $object->lines[$i]->multicurrency_total_tva;
  1161. $line->multicurrency_total_ttc = $object->lines[$i]->multicurrency_total_ttc;
  1162. $line->fk_fournprice = $object->lines[$i]->fk_fournprice;
  1163. $marginInfos = getMarginInfos($object->lines[$i]->subprice, $object->lines[$i]->remise_percent, $object->lines[$i]->tva_tx, $object->lines[$i]->localtax1_tx, $object->lines[$i]->localtax2_tx, $object->lines[$i]->fk_fournprice, $object->lines[$i]->pa_ht);
  1164. $line->pa_ht = $marginInfos[0];
  1165. // get extrafields from original line
  1166. $object->lines[$i]->fetch_optionals();
  1167. foreach ($object->lines[$i]->array_options as $options_key => $value) {
  1168. $line->array_options[$options_key] = $value;
  1169. }
  1170. $this->lines[$i] = $line;
  1171. }
  1172. $this->socid = $object->socid;
  1173. $this->fk_project = $object->fk_project;
  1174. $this->fk_account = $object->fk_account;
  1175. $this->cond_reglement_id = $object->cond_reglement_id;
  1176. $this->mode_reglement_id = $object->mode_reglement_id;
  1177. $this->availability_id = $object->availability_id;
  1178. $this->demand_reason_id = $object->demand_reason_id;
  1179. $this->delivery_date = (empty($object->delivery_date) ? $object->date_livraison : $object->delivery_date);
  1180. $this->date_livraison = $object->delivery_date; // deprecated
  1181. $this->fk_delivery_address = $object->fk_delivery_address; // deprecated
  1182. $this->contact_id = $object->contact_id;
  1183. $this->ref_client = $object->ref_client;
  1184. if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) {
  1185. $this->note_private = $object->note_private;
  1186. $this->note_public = $object->note_public;
  1187. }
  1188. $this->module_source = $object->module_source;
  1189. $this->pos_source = $object->pos_source;
  1190. $this->origin = $object->element;
  1191. $this->origin_id = $object->id;
  1192. $this->fk_user_author = $user->id;
  1193. // get extrafields from original line
  1194. $object->fetch_optionals();
  1195. foreach ($object->array_options as $options_key => $value) {
  1196. $this->array_options[$options_key] = $value;
  1197. }
  1198. // Possibility to add external linked objects with hooks
  1199. $this->linked_objects[$this->origin] = $this->origin_id;
  1200. if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) {
  1201. $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects);
  1202. }
  1203. $ret = $this->create($user);
  1204. if ($ret > 0) {
  1205. // Actions hooked (by external module)
  1206. $hookmanager->initHooks(array('invoicedao'));
  1207. $parameters = array('objFrom'=>$object);
  1208. $action = '';
  1209. $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1210. if ($reshook < 0) {
  1211. $error++;
  1212. }
  1213. if (!$error) {
  1214. return 1;
  1215. } else {
  1216. return -1;
  1217. }
  1218. } else {
  1219. return -1;
  1220. }
  1221. }
  1222. /**
  1223. * Return clicable link of object (with eventually picto)
  1224. *
  1225. * @param int $withpicto Add picto into link
  1226. * @param string $option Where point the link
  1227. * @param int $max Maxlength of ref
  1228. * @param int $short 1=Return just URL
  1229. * @param string $moretitle Add more text to title tooltip
  1230. * @param int $notooltip 1=Disable tooltip
  1231. * @param int $addlinktonotes 1=Add link to notes
  1232. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1233. * @param string $target Target of link ('', '_self', '_blank', '_parent', '_backoffice', ...)
  1234. * @return string String with URL
  1235. */
  1236. public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $addlinktonotes = 0, $save_lastsearch_value = -1, $target = '')
  1237. {
  1238. global $langs, $conf, $user, $mysoc;
  1239. if (!empty($conf->dol_no_mouse_hover)) {
  1240. $notooltip = 1; // Force disable tooltips
  1241. }
  1242. $result = '';
  1243. if ($option == 'withdraw') {
  1244. $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id;
  1245. } else {
  1246. $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id;
  1247. }
  1248. if (!$user->rights->facture->lire) {
  1249. $option = 'nolink';
  1250. }
  1251. if ($option !== 'nolink') {
  1252. // Add param to save lastsearch_values or not
  1253. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1254. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1255. $add_save_lastsearch_values = 1;
  1256. }
  1257. if ($add_save_lastsearch_values) {
  1258. $url .= '&save_lastsearch_values=1';
  1259. }
  1260. }
  1261. if ($short) {
  1262. return $url;
  1263. }
  1264. $picto = $this->picto;
  1265. if ($this->type == self::TYPE_REPLACEMENT) {
  1266. $picto .= 'r'; // Replacement invoice
  1267. }
  1268. if ($this->type == self::TYPE_CREDIT_NOTE) {
  1269. $picto .= 'a'; // Credit note
  1270. }
  1271. if ($this->type == self::TYPE_DEPOSIT) {
  1272. $picto .= 'd'; // Deposit invoice
  1273. }
  1274. $label = '';
  1275. if ($user->rights->facture->lire) {
  1276. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->trans("Invoice").'</u>';
  1277. if ($this->type == self::TYPE_REPLACEMENT) {
  1278. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("ReplacementInvoice").'</u>';
  1279. }
  1280. if ($this->type == self::TYPE_CREDIT_NOTE) {
  1281. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>';
  1282. }
  1283. if ($this->type == self::TYPE_DEPOSIT) {
  1284. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>';
  1285. }
  1286. if ($this->type == self::TYPE_SITUATION) {
  1287. $label = img_picto('', $picto).' <u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceSituation").'</u>';
  1288. }
  1289. if (isset($this->statut) && isset($this->alreadypaid)) {
  1290. $label .= ' '.$this->getLibStatut(5, $this->alreadypaid);
  1291. }
  1292. if (!empty($this->ref)) {
  1293. $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1294. }
  1295. if (!empty($this->ref_client)) {
  1296. $label .= '<br><b>'.$langs->trans('RefCustomer').':</b> '.$this->ref_client;
  1297. }
  1298. if (!empty($this->date)) {
  1299. $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day');
  1300. }
  1301. if (!empty($this->total_ht)) {
  1302. $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency);
  1303. }
  1304. if (!empty($this->total_tva)) {
  1305. $label .= '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency);
  1306. }
  1307. if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) { // We keep test != 0 because $this->total_localtax1 can be '0.00000000'
  1308. $label .= '<br><b>'.$langs->transcountry('AmountLT1', $mysoc->country_code).':</b> '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency);
  1309. }
  1310. if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) {
  1311. $label .= '<br><b>'.$langs->transcountry('AmountLT2', $mysoc->country_code).':</b> '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency);
  1312. }
  1313. if (!empty($this->total_ttc)) {
  1314. $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency);
  1315. }
  1316. if ($moretitle) {
  1317. $label .= ' - '.$moretitle;
  1318. }
  1319. }
  1320. $linkclose = ($target ? ' target="'.$target.'"' : '');
  1321. if (empty($notooltip) && $user->rights->facture->lire) {
  1322. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1323. $label = $langs->trans("Invoice");
  1324. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1325. }
  1326. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1327. $linkclose .= ' class="classfortooltip"';
  1328. }
  1329. $linkstart = '<a href="'.$url.'"';
  1330. $linkstart .= $linkclose.'>';
  1331. $linkend = '</a>';
  1332. if ($option == 'nolink') {
  1333. $linkstart = '';
  1334. $linkend = '';
  1335. }
  1336. $result .= $linkstart;
  1337. if ($withpicto) {
  1338. $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1339. }
  1340. if ($withpicto != 2) {
  1341. $result .= ($max ?dol_trunc($this->ref, $max) : $this->ref);
  1342. }
  1343. $result .= $linkend;
  1344. if ($addlinktonotes) {
  1345. $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
  1346. if ($txttoshow) {
  1347. //$notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
  1348. $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.$txttoshow;
  1349. $result .= ' <span class="note inline-block">';
  1350. $result .= '<a href="'.DOL_URL_ROOT.'/compta/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow, 1, 1).'">';
  1351. $result .= img_picto('', 'note');
  1352. $result .= '</a>';
  1353. //$result.=img_picto($langs->trans("ViewNote"),'object_generic');
  1354. //$result.='</a>';
  1355. $result .= '</span>';
  1356. }
  1357. }
  1358. global $action, $hookmanager;
  1359. $hookmanager->initHooks(array('invoicedao'));
  1360. $parameters = array('id'=>$this->id, 'getnomurl'=>$result, 'notooltip' => $notooltip, 'addlinktonotes' => $addlinktonotes, 'save_lastsearch_value'=> $save_lastsearch_value, 'target' => $target);
  1361. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1362. if ($reshook > 0) $result = $hookmanager->resPrint;
  1363. else $result .= $hookmanager->resPrint;
  1364. return $result;
  1365. }
  1366. /**
  1367. * Get object from database. Get also lines.
  1368. *
  1369. * @param int $rowid Id of object to load
  1370. * @param string $ref Reference of invoice
  1371. * @param string $ref_ext External reference of invoice
  1372. * @param int $notused Not used
  1373. * @param bool $fetch_situation Load also the previous and next situation invoice into $tab_previous_situation_invoice and $tab_next_situation_invoice
  1374. * @return int >0 if OK, <0 if KO, 0 if not found
  1375. */
  1376. public function fetch($rowid, $ref = '', $ref_ext = '', $notused = '', $fetch_situation = false)
  1377. {
  1378. global $conf;
  1379. if (empty($rowid) && empty($ref) && empty($ref_ext)) {
  1380. return -1;
  1381. }
  1382. $sql = 'SELECT f.rowid,f.entity,f.ref,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc';
  1383. $sql .= ', f.total_tva, f.localtax1, f.localtax2, f.total_ht, f.total_ttc, f.revenuestamp';
  1384. $sql .= ', f.remise_percent, f.remise_absolue, f.remise';
  1385. $sql .= ', f.datef as df, f.date_pointoftax';
  1386. $sql .= ', f.date_lim_reglement as dlr';
  1387. $sql .= ', f.datec as datec';
  1388. $sql .= ', f.date_valid as datev';
  1389. $sql .= ', f.tms as datem';
  1390. $sql .= ', f.note_private, f.note_public, f.fk_statut, f.paye, f.close_code, f.close_note, f.fk_user_author, f.fk_user_valid, f.model_pdf, f.last_main_doc';
  1391. $sql .= ', f.fk_facture_source, f.fk_fac_rec_source';
  1392. $sql .= ', f.fk_mode_reglement, f.fk_cond_reglement, f.fk_projet as fk_project, f.extraparams';
  1393. $sql .= ', f.situation_cycle_ref, f.situation_counter, f.situation_final';
  1394. $sql .= ', f.fk_account';
  1395. $sql .= ", f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc";
  1396. $sql .= ', p.code as mode_reglement_code, p.libelle as mode_reglement_libelle';
  1397. $sql .= ', c.code as cond_reglement_code, c.libelle as cond_reglement_libelle, c.libelle_facture as cond_reglement_libelle_doc';
  1398. $sql .= ', f.fk_incoterms, f.location_incoterms';
  1399. $sql .= ', f.module_source, f.pos_source';
  1400. $sql .= ", i.libelle as label_incoterms";
  1401. $sql .= ", f.retained_warranty as retained_warranty, f.retained_warranty_date_limit as retained_warranty_date_limit, f.retained_warranty_fk_cond_reglement as retained_warranty_fk_cond_reglement";
  1402. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as f';
  1403. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_payment_term as c ON f.fk_cond_reglement = c.rowid';
  1404. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id';
  1405. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid';
  1406. if ($rowid) {
  1407. $sql .= " WHERE f.rowid=".((int) $rowid);
  1408. } else {
  1409. $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Dont't use entity if you use rowid
  1410. if ($ref) {
  1411. $sql .= " AND f.ref='".$this->db->escape($ref)."'";
  1412. }
  1413. if ($ref_ext) {
  1414. $sql .= " AND f.ref_ext='".$this->db->escape($ref_ext)."'";
  1415. }
  1416. if ($notused) {
  1417. $sql .= " AND f.ref_int='".$this->db->escape($notused)."'"; // deprecated
  1418. }
  1419. }
  1420. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  1421. $result = $this->db->query($sql);
  1422. if ($result) {
  1423. if ($this->db->num_rows($result)) {
  1424. $obj = $this->db->fetch_object($result);
  1425. $this->id = $obj->rowid;
  1426. $this->entity = $obj->entity;
  1427. $this->ref = $obj->ref;
  1428. $this->ref_client = $obj->ref_client;
  1429. $this->ref_ext = $obj->ref_ext;
  1430. $this->type = $obj->type;
  1431. $this->date = $this->db->jdate($obj->df);
  1432. $this->date_pointoftax = $this->db->jdate($obj->date_pointoftax);
  1433. $this->date_creation = $this->db->jdate($obj->datec);
  1434. $this->date_validation = $this->db->jdate($obj->datev);
  1435. $this->date_modification = $this->db->jdate($obj->datem);
  1436. $this->datem = $this->db->jdate($obj->datem);
  1437. $this->remise_percent = $obj->remise_percent;
  1438. $this->remise_absolue = $obj->remise_absolue;
  1439. $this->total_ht = $obj->total_ht;
  1440. $this->total_tva = $obj->total_tva;
  1441. $this->total_localtax1 = $obj->localtax1;
  1442. $this->total_localtax2 = $obj->localtax2;
  1443. $this->total_ttc = $obj->total_ttc;
  1444. $this->revenuestamp = $obj->revenuestamp;
  1445. $this->paye = $obj->paye;
  1446. $this->close_code = $obj->close_code;
  1447. $this->close_note = $obj->close_note;
  1448. $this->socid = $obj->fk_soc;
  1449. $this->thirdparty = null; // Clear if another value was already set by fetch_thirdparty
  1450. $this->fk_project = $obj->fk_project;
  1451. $this->project = null; // Clear if another value was already set by fetch_projet
  1452. $this->statut = $obj->fk_statut;
  1453. $this->status = $obj->fk_statut;
  1454. $this->date_lim_reglement = $this->db->jdate($obj->dlr);
  1455. $this->mode_reglement_id = $obj->fk_mode_reglement;
  1456. $this->mode_reglement_code = $obj->mode_reglement_code;
  1457. $this->mode_reglement = $obj->mode_reglement_libelle;
  1458. $this->cond_reglement_id = $obj->fk_cond_reglement;
  1459. $this->cond_reglement_code = $obj->cond_reglement_code;
  1460. $this->cond_reglement = $obj->cond_reglement_libelle;
  1461. $this->cond_reglement_doc = $obj->cond_reglement_libelle_doc;
  1462. $this->fk_account = ($obj->fk_account > 0) ? $obj->fk_account : null;
  1463. $this->fk_facture_source = $obj->fk_facture_source;
  1464. $this->fk_fac_rec_source = $obj->fk_fac_rec_source;
  1465. $this->note = $obj->note_private; // deprecated
  1466. $this->note_private = $obj->note_private;
  1467. $this->note_public = $obj->note_public;
  1468. $this->user_author = $obj->fk_user_author; // deprecated
  1469. $this->user_valid = $obj->fk_user_valid; // deprecated
  1470. $this->fk_user_author = $obj->fk_user_author;
  1471. $this->fk_user_valid = $obj->fk_user_valid;
  1472. $this->model_pdf = $obj->model_pdf;
  1473. $this->modelpdf = $obj->model_pdf; // deprecated
  1474. $this->last_main_doc = $obj->last_main_doc;
  1475. $this->situation_cycle_ref = $obj->situation_cycle_ref;
  1476. $this->situation_counter = $obj->situation_counter;
  1477. $this->situation_final = $obj->situation_final;
  1478. $this->retained_warranty = $obj->retained_warranty;
  1479. $this->retained_warranty_date_limit = $this->db->jdate($obj->retained_warranty_date_limit);
  1480. $this->retained_warranty_fk_cond_reglement = $obj->retained_warranty_fk_cond_reglement;
  1481. $this->extraparams = (array) json_decode($obj->extraparams, true);
  1482. //Incoterms
  1483. $this->fk_incoterms = $obj->fk_incoterms;
  1484. $this->location_incoterms = $obj->location_incoterms;
  1485. $this->label_incoterms = $obj->label_incoterms;
  1486. $this->module_source = $obj->module_source;
  1487. $this->pos_source = $obj->pos_source;
  1488. // Multicurrency
  1489. $this->fk_multicurrency = $obj->fk_multicurrency;
  1490. $this->multicurrency_code = $obj->multicurrency_code;
  1491. $this->multicurrency_tx = $obj->multicurrency_tx;
  1492. $this->multicurrency_total_ht = $obj->multicurrency_total_ht;
  1493. $this->multicurrency_total_tva = $obj->multicurrency_total_tva;
  1494. $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc;
  1495. if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) {
  1496. $this->fetchPreviousNextSituationInvoice();
  1497. }
  1498. if ($this->status == self::STATUS_DRAFT) {
  1499. $this->brouillon = 1;
  1500. }
  1501. // Retrieve all extrafield
  1502. // fetch optionals attributes and labels
  1503. $this->fetch_optionals();
  1504. // Lines
  1505. $this->lines = array();
  1506. $result = $this->fetch_lines();
  1507. if ($result < 0) {
  1508. $this->error = $this->db->error();
  1509. return -3;
  1510. }
  1511. return 1;
  1512. } else {
  1513. $this->error = 'Invoice with id='.$rowid.' or ref='.$ref.' or ref_ext='.$ref_ext.' not found';
  1514. dol_syslog(get_class($this)."::fetch Error ".$this->error, LOG_ERR);
  1515. return 0;
  1516. }
  1517. } else {
  1518. $this->error = $this->db->error();
  1519. return -1;
  1520. }
  1521. }
  1522. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1523. /**
  1524. * Load all detailed lines into this->lines
  1525. *
  1526. * @param int $only_product Return only physical products
  1527. * @param int $loadalsotranslation Return translation for products
  1528. *
  1529. * @return int 1 if OK, < 0 if KO
  1530. */
  1531. public function fetch_lines($only_product = 0, $loadalsotranslation = 0)
  1532. {
  1533. global $langs, $conf;
  1534. // phpcs:enable
  1535. $this->lines = array();
  1536. $sql = 'SELECT l.rowid, l.fk_facture, l.fk_product, l.fk_parent_line, l.label as custom_label, l.description, l.product_type, l.price, l.qty, l.vat_src_code, l.tva_tx,';
  1537. $sql .= ' l.localtax1_tx, l.localtax2_tx, l.localtax1_type, l.localtax2_type, l.remise_percent, l.fk_remise_except, l.subprice, l.ref_ext,';
  1538. $sql .= ' l.situation_percent, l.fk_prev_id,';
  1539. $sql .= ' l.rang, l.special_code,';
  1540. $sql .= ' l.date_start as date_start, l.date_end as date_end,';
  1541. $sql .= ' l.info_bits, l.total_ht, l.total_tva, l.total_localtax1, l.total_localtax2, l.total_ttc, l.fk_code_ventilation, l.fk_product_fournisseur_price as fk_fournprice, l.buy_price_ht as pa_ht,';
  1542. $sql .= ' l.fk_unit,';
  1543. $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc,';
  1544. $sql .= ' p.ref as product_ref, p.fk_product_type as fk_product_type, p.label as product_label, p.description as product_desc';
  1545. $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as l';
  1546. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid';
  1547. $sql .= ' WHERE l.fk_facture = '.((int) $this->id);
  1548. $sql .= ' ORDER BY l.rang, l.rowid';
  1549. dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG);
  1550. $result = $this->db->query($sql);
  1551. if ($result) {
  1552. $num = $this->db->num_rows($result);
  1553. $i = 0;
  1554. while ($i < $num) {
  1555. $objp = $this->db->fetch_object($result);
  1556. $line = new FactureLigne($this->db);
  1557. $line->id = $objp->rowid;
  1558. $line->rowid = $objp->rowid; // deprecated
  1559. $line->fk_facture = $objp->fk_facture;
  1560. $line->label = $objp->custom_label; // deprecated
  1561. $line->desc = $objp->description; // Description line
  1562. $line->description = $objp->description; // Description line
  1563. $line->product_type = $objp->product_type; // Type of line
  1564. $line->ref = $objp->product_ref; // Ref product
  1565. $line->product_ref = $objp->product_ref; // Ref product
  1566. $line->libelle = $objp->product_label; // deprecated
  1567. $line->product_label = $objp->product_label; // Label product
  1568. $line->product_desc = $objp->product_desc; // Description product
  1569. $line->fk_product_type = $objp->fk_product_type; // Type of product
  1570. $line->qty = $objp->qty;
  1571. $line->subprice = $objp->subprice;
  1572. $line->ref_ext = $objp->ref_ext; // line external ref
  1573. $line->vat_src_code = $objp->vat_src_code;
  1574. $line->tva_tx = $objp->tva_tx;
  1575. $line->localtax1_tx = $objp->localtax1_tx;
  1576. $line->localtax2_tx = $objp->localtax2_tx;
  1577. $line->localtax1_type = $objp->localtax1_type;
  1578. $line->localtax2_type = $objp->localtax2_type;
  1579. $line->remise_percent = $objp->remise_percent;
  1580. $line->fk_remise_except = $objp->fk_remise_except;
  1581. $line->fk_product = $objp->fk_product;
  1582. $line->date_start = $this->db->jdate($objp->date_start);
  1583. $line->date_end = $this->db->jdate($objp->date_end);
  1584. $line->date_start = $this->db->jdate($objp->date_start);
  1585. $line->date_end = $this->db->jdate($objp->date_end);
  1586. $line->info_bits = $objp->info_bits;
  1587. $line->total_ht = $objp->total_ht;
  1588. $line->total_tva = $objp->total_tva;
  1589. $line->total_localtax1 = $objp->total_localtax1;
  1590. $line->total_localtax2 = $objp->total_localtax2;
  1591. $line->total_ttc = $objp->total_ttc;
  1592. $line->code_ventilation = $objp->fk_code_ventilation;
  1593. $line->fk_fournprice = $objp->fk_fournprice;
  1594. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $line->fk_fournprice, $objp->pa_ht);
  1595. $line->pa_ht = $marginInfos[0];
  1596. $line->marge_tx = $marginInfos[1];
  1597. $line->marque_tx = $marginInfos[2];
  1598. $line->rang = $objp->rang;
  1599. $line->special_code = $objp->special_code;
  1600. $line->fk_parent_line = $objp->fk_parent_line;
  1601. $line->situation_percent = $objp->situation_percent;
  1602. $line->fk_prev_id = $objp->fk_prev_id;
  1603. $line->fk_unit = $objp->fk_unit;
  1604. // Accountancy
  1605. $line->fk_accounting_account = $objp->fk_code_ventilation;
  1606. // Multicurrency
  1607. $line->fk_multicurrency = $objp->fk_multicurrency;
  1608. $line->multicurrency_code = $objp->multicurrency_code;
  1609. $line->multicurrency_subprice = $objp->multicurrency_subprice;
  1610. $line->multicurrency_total_ht = $objp->multicurrency_total_ht;
  1611. $line->multicurrency_total_tva = $objp->multicurrency_total_tva;
  1612. $line->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  1613. $line->fetch_optionals();
  1614. // multilangs
  1615. if (!empty($conf->global->MAIN_MULTILANGS) && !empty($objp->fk_product) && !empty($loadalsotranslation)) {
  1616. $line = new Product($this->db);
  1617. $line->fetch($objp->fk_product);
  1618. $line->getMultiLangs();
  1619. }
  1620. $this->lines[$i] = $line;
  1621. $i++;
  1622. }
  1623. $this->db->free($result);
  1624. return 1;
  1625. } else {
  1626. $this->error = $this->db->error();
  1627. return -3;
  1628. }
  1629. }
  1630. /**
  1631. * Fetch previous and next situations invoices.
  1632. * Return all previous and next invoices (both standard and credit notes).
  1633. *
  1634. * @return void
  1635. */
  1636. public function fetchPreviousNextSituationInvoice()
  1637. {
  1638. global $conf;
  1639. $this->tab_previous_situation_invoice = array();
  1640. $this->tab_next_situation_invoice = array();
  1641. $sql = 'SELECT rowid, type, situation_cycle_ref, situation_counter FROM '.MAIN_DB_PREFIX.'facture';
  1642. $sql .= " WHERE rowid <> ".((int) $this->id);
  1643. $sql .= ' AND entity = '.((int) $this->entity);
  1644. $sql .= ' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref;
  1645. $sql .= ' ORDER BY situation_counter ASC';
  1646. dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
  1647. $result = $this->db->query($sql);
  1648. if ($result && $this->db->num_rows($result) > 0) {
  1649. while ($objp = $this->db->fetch_object($result)) {
  1650. $invoice = new Facture($this->db);
  1651. if ($invoice->fetch($objp->rowid) > 0) {
  1652. if ($objp->situation_counter < $this->situation_counter
  1653. || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes
  1654. ) {
  1655. $this->tab_previous_situation_invoice[] = $invoice;
  1656. } else {
  1657. $this->tab_next_situation_invoice[] = $invoice;
  1658. }
  1659. }
  1660. }
  1661. }
  1662. }
  1663. /**
  1664. * Update database
  1665. *
  1666. * @param User $user User that modify
  1667. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  1668. * @return int <0 if KO, >0 if OK
  1669. */
  1670. public function update(User $user, $notrigger = 0)
  1671. {
  1672. global $conf;
  1673. $error = 0;
  1674. // Clean parameters
  1675. if (empty($this->type)) {
  1676. $this->type = self::TYPE_STANDARD;
  1677. }
  1678. if (isset($this->ref)) {
  1679. $this->ref = trim($this->ref);
  1680. }
  1681. if (isset($this->ref_ext)) {
  1682. $this->ref_ext = trim($this->ref_ext);
  1683. }
  1684. if (isset($this->ref_client)) {
  1685. $this->ref_client = trim($this->ref_client);
  1686. }
  1687. if (isset($this->increment)) {
  1688. $this->increment = trim($this->increment);
  1689. }
  1690. if (isset($this->close_code)) {
  1691. $this->close_code = trim($this->close_code);
  1692. }
  1693. if (isset($this->close_note)) {
  1694. $this->close_note = trim($this->close_note);
  1695. }
  1696. if (isset($this->note) || isset($this->note_private)) {
  1697. $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated
  1698. }
  1699. if (isset($this->note) || isset($this->note_private)) {
  1700. $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note));
  1701. }
  1702. if (isset($this->note_public)) {
  1703. $this->note_public = trim($this->note_public);
  1704. }
  1705. if (isset($this->model_pdf)) {
  1706. $this->model_pdf = trim($this->model_pdf);
  1707. }
  1708. if (isset($this->import_key)) {
  1709. $this->import_key = trim($this->import_key);
  1710. }
  1711. if (isset($this->retained_warranty)) {
  1712. $this->retained_warranty = floatval($this->retained_warranty);
  1713. }
  1714. // Check parameters
  1715. // Put here code to add control on parameters values
  1716. // Update request
  1717. $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET";
  1718. $sql .= " ref=".(isset($this->ref) ? "'".$this->db->escape($this->ref)."'" : "null").",";
  1719. $sql .= " ref_ext=".(isset($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null").",";
  1720. $sql .= " type=".(isset($this->type) ? $this->db->escape($this->type) : "null").",";
  1721. $sql .= " ref_client=".(isset($this->ref_client) ? "'".$this->db->escape($this->ref_client)."'" : "null").",";
  1722. $sql .= " increment=".(isset($this->increment) ? "'".$this->db->escape($this->increment)."'" : "null").",";
  1723. $sql .= " fk_soc=".(isset($this->socid) ? $this->db->escape($this->socid) : "null").",";
  1724. $sql .= " datec=".(strval($this->date_creation) != '' ? "'".$this->db->idate($this->date_creation)."'" : 'null').",";
  1725. $sql .= " datef=".(strval($this->date) != '' ? "'".$this->db->idate($this->date)."'" : 'null').",";
  1726. $sql .= " date_pointoftax=".(strval($this->date_pointoftax) != '' ? "'".$this->db->idate($this->date_pointoftax)."'" : 'null').",";
  1727. $sql .= " date_valid=".(strval($this->date_validation) != '' ? "'".$this->db->idate($this->date_validation)."'" : 'null').",";
  1728. $sql .= " paye=".(isset($this->paye) ? $this->db->escape($this->paye) : 0).",";
  1729. $sql .= " remise_percent=".(isset($this->remise_percent) ? $this->db->escape($this->remise_percent) : "null").",";
  1730. $sql .= " remise_absolue=".(isset($this->remise_absolue) ? $this->db->escape($this->remise_absolue) : "null").",";
  1731. $sql .= " close_code=".(isset($this->close_code) ? "'".$this->db->escape($this->close_code)."'" : "null").",";
  1732. $sql .= " close_note=".(isset($this->close_note) ? "'".$this->db->escape($this->close_note)."'" : "null").",";
  1733. $sql .= " total_tva=".(isset($this->total_tva) ? $this->total_tva : "null").",";
  1734. $sql .= " localtax1=".(isset($this->total_localtax1) ? $this->total_localtax1 : "null").",";
  1735. $sql .= " localtax2=".(isset($this->total_localtax2) ? $this->total_localtax2 : "null").",";
  1736. $sql .= " total_ht=".(isset($this->total_ht) ? $this->total_ht : "null").",";
  1737. $sql .= " total_ttc=".(isset($this->total_ttc) ? $this->total_ttc : "null").",";
  1738. $sql .= " revenuestamp=".((isset($this->revenuestamp) && $this->revenuestamp != '') ? $this->db->escape($this->revenuestamp) : "null").",";
  1739. $sql .= " fk_statut=".(isset($this->statut) ? $this->db->escape($this->statut) : "null").",";
  1740. $sql .= " fk_user_author=".(isset($this->user_author) ? $this->db->escape($this->user_author) : "null").",";
  1741. $sql .= " fk_user_valid=".(isset($this->fk_user_valid) ? $this->db->escape($this->fk_user_valid) : "null").",";
  1742. $sql .= " fk_facture_source=".(isset($this->fk_facture_source) ? $this->db->escape($this->fk_facture_source) : "null").",";
  1743. $sql .= " fk_projet=".(isset($this->fk_project) ? $this->db->escape($this->fk_project) : "null").",";
  1744. $sql .= " fk_cond_reglement=".(isset($this->cond_reglement_id) ? $this->db->escape($this->cond_reglement_id) : "null").",";
  1745. $sql .= " fk_mode_reglement=".(isset($this->mode_reglement_id) ? $this->db->escape($this->mode_reglement_id) : "null").",";
  1746. $sql .= " date_lim_reglement=".(strval($this->date_lim_reglement) != '' ? "'".$this->db->idate($this->date_lim_reglement)."'" : 'null').",";
  1747. $sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
  1748. $sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
  1749. $sql .= " model_pdf=".(isset($this->model_pdf) ? "'".$this->db->escape($this->model_pdf)."'" : "null").",";
  1750. $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").",";
  1751. $sql .= " situation_cycle_ref=".(empty($this->situation_cycle_ref) ? "null" : $this->db->escape($this->situation_cycle_ref)).",";
  1752. $sql .= " situation_counter=".(empty($this->situation_counter) ? "null" : $this->db->escape($this->situation_counter)).",";
  1753. $sql .= " situation_final=".(empty($this->situation_final) ? "0" : $this->db->escape($this->situation_final)).",";
  1754. $sql .= " retained_warranty=".(empty($this->retained_warranty) ? "0" : $this->db->escape($this->retained_warranty)).",";
  1755. $sql .= " retained_warranty_date_limit=".(strval($this->retained_warranty_date_limit) != '' ? "'".$this->db->idate($this->retained_warranty_date_limit)."'" : 'null').",";
  1756. $sql .= " retained_warranty_fk_cond_reglement=".(isset($this->retained_warranty_fk_cond_reglement) ?intval($this->retained_warranty_fk_cond_reglement) : "null");
  1757. $sql .= " WHERE rowid=".((int) $this->id);
  1758. $this->db->begin();
  1759. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1760. $resql = $this->db->query($sql);
  1761. if (!$resql) {
  1762. $error++;
  1763. $this->errors[] = "Error ".$this->db->lasterror();
  1764. }
  1765. if (!$error) {
  1766. $result = $this->insertExtraFields();
  1767. if ($result < 0) {
  1768. $error++;
  1769. }
  1770. }
  1771. if (!$error && !$notrigger) {
  1772. // Call trigger
  1773. $result = $this->call_trigger('BILL_MODIFY', $user);
  1774. if ($result < 0) {
  1775. $error++;
  1776. }
  1777. // End call triggers
  1778. }
  1779. // Commit or rollback
  1780. if ($error) {
  1781. foreach ($this->errors as $errmsg) {
  1782. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  1783. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1784. }
  1785. $this->db->rollback();
  1786. return -1 * $error;
  1787. } else {
  1788. $this->db->commit();
  1789. return 1;
  1790. }
  1791. }
  1792. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1793. /**
  1794. * Add a discount line into an invoice (as an invoice line) using an existing absolute discount (Consume the discount)
  1795. *
  1796. * @param int $idremise Id of absolute discount
  1797. * @return int >0 if OK, <0 if KO
  1798. */
  1799. public function insert_discount($idremise)
  1800. {
  1801. // phpcs:enable
  1802. global $langs;
  1803. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  1804. include_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  1805. $this->db->begin();
  1806. $remise = new DiscountAbsolute($this->db);
  1807. $result = $remise->fetch($idremise);
  1808. if ($result > 0) {
  1809. if ($remise->fk_facture) { // Protection against multiple submission
  1810. $this->error = $langs->trans("ErrorDiscountAlreadyUsed");
  1811. $this->db->rollback();
  1812. return -5;
  1813. }
  1814. $facligne = new FactureLigne($this->db);
  1815. $facligne->fk_facture = $this->id;
  1816. $facligne->fk_remise_except = $remise->id;
  1817. $facligne->desc = $remise->description; // Description ligne
  1818. $facligne->vat_src_code = $remise->vat_src_code;
  1819. $facligne->tva_tx = $remise->tva_tx;
  1820. $facligne->subprice = -$remise->amount_ht;
  1821. $facligne->fk_product = 0; // Id produit predefini
  1822. $facligne->qty = 1;
  1823. $facligne->remise_percent = 0;
  1824. $facligne->rang = -1;
  1825. $facligne->info_bits = 2;
  1826. // Get buy/cost price of invoice that is source of discount
  1827. if ($remise->fk_facture_source > 0) {
  1828. $srcinvoice = new Facture($this->db);
  1829. $srcinvoice->fetch($remise->fk_facture_source);
  1830. include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject
  1831. $formmargin = new FormMargin($this->db);
  1832. $arraytmp = $formmargin->getMarginInfosArray($srcinvoice, false);
  1833. $facligne->pa_ht = $arraytmp['pa_total'];
  1834. }
  1835. $facligne->total_ht = -$remise->amount_ht;
  1836. $facligne->total_tva = -$remise->amount_tva;
  1837. $facligne->total_ttc = -$remise->amount_ttc;
  1838. $facligne->multicurrency_subprice = -$remise->multicurrency_subprice;
  1839. $facligne->multicurrency_total_ht = -$remise->multicurrency_amount_ht;
  1840. $facligne->multicurrency_total_tva = -$remise->multicurrency_amount_tva;
  1841. $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc;
  1842. $lineid = $facligne->insert();
  1843. if ($lineid > 0) {
  1844. $result = $this->update_price(1);
  1845. if ($result > 0) {
  1846. // Create link between discount and invoice line
  1847. $result = $remise->link_to_invoice($lineid, 0);
  1848. if ($result < 0) {
  1849. $this->error = $remise->error;
  1850. $this->db->rollback();
  1851. return -4;
  1852. }
  1853. $this->db->commit();
  1854. return 1;
  1855. } else {
  1856. $this->error = $facligne->error;
  1857. $this->db->rollback();
  1858. return -1;
  1859. }
  1860. } else {
  1861. $this->error = $facligne->error;
  1862. $this->db->rollback();
  1863. return -2;
  1864. }
  1865. } else {
  1866. $this->db->rollback();
  1867. return -3;
  1868. }
  1869. }
  1870. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1871. /**
  1872. * Set customer ref
  1873. *
  1874. * @param string $ref_client Customer ref
  1875. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1876. * @return int <0 if KO, >0 if OK
  1877. */
  1878. public function set_ref_client($ref_client, $notrigger = 0)
  1879. {
  1880. // phpcs:enable
  1881. global $user;
  1882. $error = 0;
  1883. $this->db->begin();
  1884. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  1885. if (empty($ref_client)) {
  1886. $sql .= ' SET ref_client = NULL';
  1887. } else {
  1888. $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\'';
  1889. }
  1890. $sql .= " WHERE rowid = ".((int) $this->id);
  1891. dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG);
  1892. $resql = $this->db->query($sql);
  1893. if (!$resql) {
  1894. $this->errors[] = $this->db->error();
  1895. $error++;
  1896. }
  1897. if (!$error) {
  1898. $this->ref_client = $ref_client;
  1899. }
  1900. if (!$notrigger && empty($error)) {
  1901. // Call trigger
  1902. $result = $this->call_trigger('BILL_MODIFY', $user);
  1903. if ($result < 0) {
  1904. $error++;
  1905. }
  1906. // End call triggers
  1907. }
  1908. if (!$error) {
  1909. $this->ref_client = $ref_client;
  1910. $this->db->commit();
  1911. return 1;
  1912. } else {
  1913. foreach ($this->errors as $errmsg) {
  1914. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  1915. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1916. }
  1917. $this->db->rollback();
  1918. return -1 * $error;
  1919. }
  1920. }
  1921. /**
  1922. * Delete invoice
  1923. *
  1924. * @param User $user User making the deletion.
  1925. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1926. * @param int $idwarehouse Id warehouse to use for stock change.
  1927. * @return int <0 if KO, 0=Refused, >0 if OK
  1928. */
  1929. public function delete($user, $notrigger = 0, $idwarehouse = -1)
  1930. {
  1931. global $langs, $conf;
  1932. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1933. $rowid = $this->id;
  1934. dol_syslog(get_class($this)."::delete rowid=".$rowid.", ref=".$this->ref.", thirdparty=".(empty($this->thirdparty) ? '' : $this->thirdparty->name), LOG_DEBUG);
  1935. // Test to avoid invoice deletion (allowed if draft)
  1936. $result = $this->is_erasable();
  1937. if ($result <= 0) {
  1938. return 0;
  1939. }
  1940. $error = 0;
  1941. $this->db->begin();
  1942. if (!$error && !$notrigger) {
  1943. // Call trigger
  1944. $result = $this->call_trigger('BILL_DELETE', $user);
  1945. if ($result < 0) {
  1946. $error++;
  1947. }
  1948. // End call triggers
  1949. }
  1950. // Removed extrafields
  1951. if (!$error) {
  1952. $result = $this->deleteExtraFields();
  1953. if ($result < 0) {
  1954. $error++;
  1955. dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR);
  1956. }
  1957. }
  1958. if (!$error) {
  1959. // Delete linked object
  1960. $res = $this->deleteObjectLinked();
  1961. if ($res < 0) {
  1962. $error++;
  1963. }
  1964. }
  1965. if (!$error) {
  1966. // If invoice was converted into a discount not yet consumed, we remove discount
  1967. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except';
  1968. $sql .= ' WHERE fk_facture_source = '.((int) $rowid);
  1969. $sql .= ' AND fk_facture_line IS NULL';
  1970. $resql = $this->db->query($sql);
  1971. // If invoice has consumed discounts
  1972. $this->fetch_lines();
  1973. $list_rowid_det = array();
  1974. foreach ($this->lines as $key => $invoiceline) {
  1975. $list_rowid_det[] = $invoiceline->id;
  1976. }
  1977. // Consumed discounts are freed
  1978. if (count($list_rowid_det)) {
  1979. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  1980. $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL';
  1981. $sql .= ' WHERE fk_facture_line IN ('.$this->db->sanitize(join(',', $list_rowid_det)).')';
  1982. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1983. if (!$this->db->query($sql)) {
  1984. $this->error = $this->db->error()." sql=".$sql;
  1985. $this->errors[] = $this->error;
  1986. $this->db->rollback();
  1987. return -5;
  1988. }
  1989. }
  1990. // If we decrease stock on invoice validation, we increase back if a warehouse id was provided
  1991. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) {
  1992. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  1993. $langs->load("agenda");
  1994. $num = count($this->lines);
  1995. for ($i = 0; $i < $num; $i++) {
  1996. if ($this->lines[$i]->fk_product > 0) {
  1997. $mouvP = new MouvementStock($this->db);
  1998. $mouvP->origin = &$this;
  1999. // We decrease stock for product
  2000. if ($this->type == self::TYPE_CREDIT_NOTE) {
  2001. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref));
  2002. } else {
  2003. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
  2004. }
  2005. }
  2006. }
  2007. }
  2008. // Invoice line extrafileds
  2009. $main = MAIN_DB_PREFIX.'facturedet';
  2010. $ef = $main."_extrafields";
  2011. $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM ".$main." WHERE fk_facture = ".((int) $rowid).")";
  2012. // Delete invoice line
  2013. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facturedet WHERE fk_facture = '.((int) $rowid);
  2014. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  2015. if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact()) {
  2016. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.((int) $rowid);
  2017. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  2018. $resql = $this->db->query($sql);
  2019. if ($resql) {
  2020. // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive
  2021. $this->deleteEcmFiles();
  2022. // On efface le repertoire de pdf provisoire
  2023. $ref = dol_sanitizeFileName($this->ref);
  2024. if ($conf->facture->dir_output && !empty($this->ref)) {
  2025. $dir = $conf->facture->dir_output."/".$ref;
  2026. $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf";
  2027. if (file_exists($file)) { // We must delete all files before deleting directory
  2028. $ret = dol_delete_preview($this);
  2029. if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers
  2030. $langs->load("errors");
  2031. $this->error = $langs->trans("ErrorFailToDeleteFile", $file);
  2032. $this->errors[] = $this->error;
  2033. $this->db->rollback();
  2034. return 0;
  2035. }
  2036. }
  2037. if (file_exists($dir)) {
  2038. if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta
  2039. $langs->load("errors");
  2040. $this->error = $langs->trans("ErrorFailToDeleteDir", $dir);
  2041. $this->errors[] = $this->error;
  2042. $this->db->rollback();
  2043. return 0;
  2044. }
  2045. }
  2046. }
  2047. $this->db->commit();
  2048. return 1;
  2049. } else {
  2050. $this->error = $this->db->lasterror()." sql=".$sql;
  2051. $this->errors[] = $this->error;
  2052. $this->db->rollback();
  2053. return -6;
  2054. }
  2055. } else {
  2056. $this->error = $this->db->lasterror()." sql=".$sql;
  2057. $this->errors[] = $this->error;
  2058. $this->db->rollback();
  2059. return -4;
  2060. }
  2061. } else {
  2062. $this->db->rollback();
  2063. return -2;
  2064. }
  2065. }
  2066. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2067. /**
  2068. * Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1
  2069. * or partialy (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0
  2070. *
  2071. * @deprecated
  2072. * @see setPaid()
  2073. * @param User $user Object user that modify
  2074. * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple)
  2075. * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple)
  2076. * @return int <0 if KO, >0 if OK
  2077. */
  2078. public function set_paid($user, $close_code = '', $close_note = '')
  2079. {
  2080. // phpcs:enable
  2081. dol_syslog(get_class($this)."::set_paid is deprecated, use setPaid instead", LOG_NOTICE);
  2082. return $this->setPaid($user, $close_code, $close_note);
  2083. }
  2084. /**
  2085. * Tag the invoice as paid completely (if close_code is filled) => this->fk_statut=2, this->paye=1
  2086. * or partialy (if close_code filled) + appel trigger BILL_PAYED => this->fk_statut=2, this->paye stay 0
  2087. *
  2088. * @param User $user Object user that modify
  2089. * @param string $close_code Code renseigne si on classe a payee completement alors que paiement incomplet (cas escompte par exemple)
  2090. * @param string $close_note Commentaire renseigne si on classe a payee alors que paiement incomplet (cas escompte par exemple)
  2091. * @return int <0 if KO, >0 if OK
  2092. */
  2093. public function setPaid($user, $close_code = '', $close_note = '')
  2094. {
  2095. $error = 0;
  2096. if ($this->paye != 1) {
  2097. $this->db->begin();
  2098. $now = dol_now();
  2099. dol_syslog(get_class($this)."::set_paid rowid=".((int) $this->id), LOG_DEBUG);
  2100. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
  2101. $sql .= ' fk_statut='.self::STATUS_CLOSED;
  2102. if (!$close_code) {
  2103. $sql .= ', paye=1';
  2104. }
  2105. if ($close_code) {
  2106. $sql .= ", close_code='".$this->db->escape($close_code)."'";
  2107. }
  2108. if ($close_note) {
  2109. $sql .= ", close_note='".$this->db->escape($close_note)."'";
  2110. }
  2111. $sql .= ', fk_user_closing = '.((int) $user->id);
  2112. $sql .= ", date_closing = '".$this->db->idate($now)."'";
  2113. $sql .= " WHERE rowid = ".((int) $this->id);
  2114. $resql = $this->db->query($sql);
  2115. if ($resql) {
  2116. // Call trigger
  2117. $result = $this->call_trigger('BILL_PAYED', $user);
  2118. if ($result < 0) {
  2119. $error++;
  2120. }
  2121. // End call triggers
  2122. } else {
  2123. $error++;
  2124. $this->error = $this->db->lasterror();
  2125. }
  2126. if (!$error) {
  2127. $this->db->commit();
  2128. return 1;
  2129. } else {
  2130. $this->db->rollback();
  2131. return -1;
  2132. }
  2133. } else {
  2134. return 0;
  2135. }
  2136. }
  2137. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2138. /**
  2139. * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
  2140. * Fonction utilisee quand un paiement prelevement est refuse,
  2141. * ou quand une facture annulee et reouverte.
  2142. *
  2143. * @deprecated
  2144. * @see setUnpaid()
  2145. * @param User $user Object user that change status
  2146. * @return int <0 if KO, >0 if OK
  2147. */
  2148. public function set_unpaid($user)
  2149. {
  2150. // phpcs:enable
  2151. dol_syslog(get_class($this)."::set_unpaid is deprecated, use setUnpaid instead", LOG_NOTICE);
  2152. return $this->setUnpaid($user);
  2153. }
  2154. /**
  2155. * Tag la facture comme non payee completement + appel trigger BILL_UNPAYED
  2156. * Fonction utilisee quand un paiement prelevement est refuse,
  2157. * ou quand une facture annulee et reouverte.
  2158. *
  2159. * @param User $user Object user that change status
  2160. * @return int <0 if KO, >0 if OK
  2161. */
  2162. public function setUnpaid($user)
  2163. {
  2164. $error = 0;
  2165. $this->db->begin();
  2166. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2167. $sql .= ' SET paye=0, fk_statut='.self::STATUS_VALIDATED.', close_code=null, close_note=null,';
  2168. $sql .= ' date_closing=null,';
  2169. $sql .= ' fk_user_closing=null';
  2170. $sql .= " WHERE rowid = ".((int) $this->id);
  2171. dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG);
  2172. $resql = $this->db->query($sql);
  2173. if ($resql) {
  2174. // Call trigger
  2175. $result = $this->call_trigger('BILL_UNPAYED', $user);
  2176. if ($result < 0) {
  2177. $error++;
  2178. }
  2179. // End call triggers
  2180. } else {
  2181. $error++;
  2182. $this->error = $this->db->error();
  2183. dol_print_error($this->db);
  2184. }
  2185. if (!$error) {
  2186. $this->db->commit();
  2187. return 1;
  2188. } else {
  2189. $this->db->rollback();
  2190. return -1;
  2191. }
  2192. }
  2193. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2194. /**
  2195. * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL
  2196. * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because
  2197. * of no payment even if merchandises were sent).
  2198. *
  2199. * @deprecated
  2200. * @see setCanceled()
  2201. * @param User $user Object user making change
  2202. * @param string $close_code Code of closing invoice (CLOSECODE_REPLACED, CLOSECODE_...)
  2203. * @param string $close_note Comment
  2204. * @return int <0 if KO, >0 if OK
  2205. */
  2206. public function set_canceled($user, $close_code = '', $close_note = '')
  2207. {
  2208. // phpcs:enable
  2209. dol_syslog(get_class($this)."::set_canceled is deprecated, use setCanceled instead", LOG_NOTICE);
  2210. return $this->setCanceled($user, $close_code, $close_note);
  2211. }
  2212. /**
  2213. * Tag invoice as canceled, with no payment on it (example for replacement invoice or payment never received) + call trigger BILL_CANCEL
  2214. * Warning, if option to decrease stock on invoice was set, this function does not change stock (it might be a cancel because
  2215. * of no payment even if merchandises were sent).
  2216. *
  2217. * @param User $user Object user making change
  2218. * @param string $close_code Code of closing invoice (CLOSECODE_REPLACED, CLOSECODE_...)
  2219. * @param string $close_note Comment
  2220. * @return int <0 if KO, >0 if OK
  2221. */
  2222. public function setCanceled($user, $close_code = '', $close_note = '')
  2223. {
  2224. dol_syslog(get_class($this)."::setCanceled rowid=".((int) $this->id), LOG_DEBUG);
  2225. $this->db->begin();
  2226. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET';
  2227. $sql .= ' fk_statut='.self::STATUS_ABANDONED;
  2228. if ($close_code) {
  2229. $sql .= ", close_code='".$this->db->escape($close_code)."'";
  2230. }
  2231. if ($close_note) {
  2232. $sql .= ", close_note='".$this->db->escape($close_note)."'";
  2233. }
  2234. $sql .= " WHERE rowid = ".((int) $this->id);
  2235. $resql = $this->db->query($sql);
  2236. if ($resql) {
  2237. // Bound discounts are deducted from the invoice
  2238. // as they have not been used since the invoice is abandoned.
  2239. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  2240. $sql .= ' SET fk_facture = NULL';
  2241. $sql .= ' WHERE fk_facture = '.((int) $this->id);
  2242. $resql = $this->db->query($sql);
  2243. if ($resql) {
  2244. // Call trigger
  2245. $result = $this->call_trigger('BILL_CANCEL', $user);
  2246. if ($result < 0) {
  2247. $this->db->rollback();
  2248. return -1;
  2249. }
  2250. // End call triggers
  2251. $this->db->commit();
  2252. return 1;
  2253. } else {
  2254. $this->error = $this->db->error()." sql=".$sql;
  2255. $this->db->rollback();
  2256. return -1;
  2257. }
  2258. } else {
  2259. $this->error = $this->db->error()." sql=".$sql;
  2260. $this->db->rollback();
  2261. return -2;
  2262. }
  2263. }
  2264. /**
  2265. * Tag invoice as validated + call trigger BILL_VALIDATE
  2266. * Object must have lines loaded with fetch_lines
  2267. *
  2268. * @param User $user Object user that validate
  2269. * @param string $force_number Reference to force on invoice
  2270. * @param int $idwarehouse Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease)
  2271. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  2272. * @param int $batch_rule 0=do not decrement batch, else batch rule to use, 1=take in batches ordered by sellby and eatby dates
  2273. * @return int <0 if KO, 0=Nothing done because invoice is not a draft, >0 if OK
  2274. */
  2275. public function validate($user, $force_number = '', $idwarehouse = 0, $notrigger = 0, $batch_rule = 0)
  2276. {
  2277. global $conf, $langs;
  2278. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  2279. $productStatic = null;
  2280. $warehouseStatic = null;
  2281. if ($batch_rule > 0) {
  2282. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  2283. require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
  2284. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  2285. $productStatic = new Product($this->db);
  2286. $warehouseStatic = new Entrepot($this->db);
  2287. }
  2288. $now = dol_now();
  2289. $error = 0;
  2290. dol_syslog(get_class($this).'::validate user='.$user->id.', force_number='.$force_number.', idwarehouse='.$idwarehouse);
  2291. // Force to have object complete for checks
  2292. $this->fetch_thirdparty();
  2293. $this->fetch_lines();
  2294. // Check parameters
  2295. if ($this->statut != self::STATUS_DRAFT) {
  2296. dol_syslog(get_class($this)."::validate status is not draft. operation canceled.", LOG_WARNING);
  2297. return 0;
  2298. }
  2299. if (count($this->lines) <= 0) {
  2300. $langs->load("errors");
  2301. $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref);
  2302. return -1;
  2303. }
  2304. if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer))
  2305. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) {
  2306. $this->error = 'Permission denied';
  2307. dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR);
  2308. return -1;
  2309. }
  2310. $this->db->begin();
  2311. // Check parameters
  2312. if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice
  2313. // Check that source invoice is known
  2314. if ($this->fk_facture_source <= 0) {
  2315. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement"));
  2316. $this->db->rollback();
  2317. return -10;
  2318. }
  2319. // Load source invoice that has been replaced
  2320. $facreplaced = new Facture($this->db);
  2321. $result = $facreplaced->fetch($this->fk_facture_source);
  2322. if ($result <= 0) {
  2323. $this->error = $langs->trans("ErrorBadInvoice");
  2324. $this->db->rollback();
  2325. return -11;
  2326. }
  2327. // Check that source invoice not already replaced by another one.
  2328. $idreplacement = $facreplaced->getIdReplacingInvoice('validated');
  2329. if ($idreplacement && $idreplacement != $this->id) {
  2330. $facreplacement = new Facture($this->db);
  2331. $facreplacement->fetch($idreplacement);
  2332. $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref);
  2333. $this->db->rollback();
  2334. return -12;
  2335. }
  2336. $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, '');
  2337. if ($result < 0) {
  2338. $this->error = $facreplaced->error;
  2339. $this->db->rollback();
  2340. return -13;
  2341. }
  2342. }
  2343. // Define new ref
  2344. if ($force_number) {
  2345. $num = $force_number;
  2346. } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
  2347. if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date
  2348. $this->date = dol_now();
  2349. $this->date_lim_reglement = $this->calculate_date_lim_reglement();
  2350. }
  2351. $num = $this->getNextNumRef($this->thirdparty);
  2352. } else {
  2353. $num = $this->ref;
  2354. }
  2355. $this->newref = dol_sanitizeFileName($num);
  2356. if ($num) {
  2357. $this->update_price(1);
  2358. // Validate
  2359. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  2360. $sql .= " SET ref='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".($user->id > 0 ? $user->id : "null").", date_valid = '".$this->db->idate($now)."'";
  2361. if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date
  2362. $sql .= ", datef='".$this->db->idate($this->date)."'";
  2363. $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'";
  2364. }
  2365. $sql .= " WHERE rowid = ".((int) $this->id);
  2366. dol_syslog(get_class($this)."::validate", LOG_DEBUG);
  2367. $resql = $this->db->query($sql);
  2368. if (!$resql) {
  2369. dol_print_error($this->db);
  2370. $error++;
  2371. }
  2372. // On verifie si la facture etait une provisoire
  2373. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref))) {
  2374. // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne
  2375. }
  2376. if (!$error) {
  2377. // Define third party as a customer
  2378. $result = $this->thirdparty->set_as_client();
  2379. // Si active on decremente le produit principal et ses composants a la validation de facture
  2380. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) {
  2381. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  2382. $langs->load("agenda");
  2383. // Loop on each line
  2384. $cpt = count($this->lines);
  2385. for ($i = 0; $i < $cpt; $i++) {
  2386. if ($this->lines[$i]->fk_product > 0) {
  2387. $mouvP = new MouvementStock($this->db);
  2388. $mouvP->origin = &$this;
  2389. // We decrease stock for product
  2390. if ($this->type == self::TYPE_CREDIT_NOTE) {
  2391. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceValidatedInDolibarr", $num));
  2392. if ($result < 0) {
  2393. $error++;
  2394. $this->error = $mouvP->error;
  2395. }
  2396. } else {
  2397. $is_batch_line = false;
  2398. if ($batch_rule > 0) {
  2399. $productStatic->fetch($this->lines[$i]->fk_product);
  2400. if ($productStatic->hasbatch()) {
  2401. $is_batch_line = true;
  2402. $product_qty_remain = $this->lines[$i]->qty;
  2403. $sortfield = null;
  2404. $sortorder = null;
  2405. // find all batch order by sellby (DLC) and eatby dates (DLUO) first
  2406. if ($batch_rule == Productbatch::BATCH_RULE_SELLBY_EATBY_DATES_FIRST) {
  2407. $sortfield = 'pl.sellby,pl.eatby,pb.qty,pl.rowid';
  2408. $sortorder = 'ASC,ASC,ASC,ASC';
  2409. }
  2410. $resBatchList = Productbatch::findAllForProduct($this->db, $productStatic->id, $idwarehouse, (!empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) ? null : 0), $sortfield, $sortorder);
  2411. if (!is_array($resBatchList)) {
  2412. $error++;
  2413. $this->error = $this->db->lasterror();
  2414. }
  2415. if (!$error) {
  2416. $batchList = $resBatchList;
  2417. if (empty($batchList)) {
  2418. $error++;
  2419. $langs->load('errors');
  2420. $warehouseStatic->fetch($idwarehouse);
  2421. $this->error = $langs->trans('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
  2422. dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
  2423. }
  2424. foreach ($batchList as $batch) {
  2425. if ($batch->qty <= 0) {
  2426. continue; // try to decrement only batches have positive quantity first
  2427. }
  2428. // enough quantity in this batch
  2429. if ($batch->qty >= $product_qty_remain) {
  2430. $product_batch_qty = $product_qty_remain;
  2431. } else {
  2432. // not enough (take all in batch)
  2433. $product_batch_qty = $batch->qty;
  2434. }
  2435. $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
  2436. if ($result < 0) {
  2437. $error++;
  2438. $this->error = $mouvP->error;
  2439. break;
  2440. }
  2441. $product_qty_remain -= $product_batch_qty;
  2442. // all product quantity was decremented
  2443. if ($product_qty_remain <= 0) {
  2444. break;
  2445. }
  2446. }
  2447. if (!$error && $product_qty_remain > 0) {
  2448. if ($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER) {
  2449. // take in the first batch
  2450. $batch = $batchList[0];
  2451. $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_qty_remain, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch);
  2452. if ($result < 0) {
  2453. $error++;
  2454. $this->error = $mouvP->error;
  2455. }
  2456. } else {
  2457. $error++;
  2458. $langs->load('errors');
  2459. $warehouseStatic->fetch($idwarehouse);
  2460. $this->error = $langs->trans('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref);
  2461. dol_syslog(__METHOD__.' Error: '.$langs->transnoentitiesnoconv('ErrorBatchNoFoundEnoughQuantityForProductInWarehouse', $productStatic->label, $warehouseStatic->ref), LOG_ERR);
  2462. }
  2463. }
  2464. }
  2465. }
  2466. }
  2467. if (!$is_batch_line) {
  2468. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarr", $num));
  2469. if ($result < 0) {
  2470. $error++;
  2471. $this->error = $mouvP->error;
  2472. }
  2473. }
  2474. }
  2475. }
  2476. }
  2477. }
  2478. }
  2479. // Trigger calls
  2480. if (!$error && !$notrigger) {
  2481. // Call trigger
  2482. $result = $this->call_trigger('BILL_VALIDATE', $user);
  2483. if ($result < 0) {
  2484. $error++;
  2485. }
  2486. // End call triggers
  2487. }
  2488. if (!$error) {
  2489. $this->oldref = $this->ref;
  2490. // Rename directory if dir was a temporary ref
  2491. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  2492. // Now we rename also files into index
  2493. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'facture/".$this->db->escape($this->newref)."'";
  2494. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  2495. $resql = $this->db->query($sql);
  2496. if (!$resql) {
  2497. $error++;
  2498. $this->error = $this->db->lasterror();
  2499. }
  2500. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  2501. $oldref = dol_sanitizeFileName($this->ref);
  2502. $newref = dol_sanitizeFileName($num);
  2503. $dirsource = $conf->facture->dir_output.'/'.$oldref;
  2504. $dirdest = $conf->facture->dir_output.'/'.$newref;
  2505. if (!$error && file_exists($dirsource)) {
  2506. dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest);
  2507. if (@rename($dirsource, $dirdest)) {
  2508. dol_syslog("Rename ok");
  2509. // Rename docs starting with $oldref with $newref
  2510. $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  2511. foreach ($listoffiles as $fileentry) {
  2512. $dirsource = $fileentry['name'];
  2513. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  2514. $dirsource = $fileentry['path'].'/'.$dirsource;
  2515. $dirdest = $fileentry['path'].'/'.$dirdest;
  2516. @rename($dirsource, $dirdest);
  2517. }
  2518. }
  2519. }
  2520. }
  2521. }
  2522. if (!$error && !$this->is_last_in_cycle()) {
  2523. if (!$this->updatePriceNextInvoice($langs)) {
  2524. $error++;
  2525. }
  2526. }
  2527. // Set new ref and define current status
  2528. if (!$error) {
  2529. $this->ref = $num;
  2530. $this->ref = $num;
  2531. $this->statut = self::STATUS_VALIDATED;
  2532. $this->status = self::STATUS_VALIDATED;
  2533. $this->brouillon = 0;
  2534. $this->date_validation = $now;
  2535. $i = 0;
  2536. if (!empty($conf->global->INVOICE_USE_SITUATION)) {
  2537. $final = true;
  2538. $nboflines = count($this->lines);
  2539. while (($i < $nboflines) && $final) {
  2540. $final = ($this->lines[$i]->situation_percent == 100);
  2541. $i++;
  2542. }
  2543. if (empty($final)) {
  2544. $this->situation_final = 0;
  2545. } else {
  2546. $this->situation_final = 1;
  2547. }
  2548. $this->setFinal($user);
  2549. }
  2550. }
  2551. } else {
  2552. $error++;
  2553. }
  2554. if (!$error) {
  2555. $this->db->commit();
  2556. return 1;
  2557. } else {
  2558. $this->db->rollback();
  2559. return -1;
  2560. }
  2561. }
  2562. /**
  2563. * Update price of next invoice
  2564. *
  2565. * @param Translate $langs Translate object
  2566. * @return bool false if KO, true if OK
  2567. */
  2568. public function updatePriceNextInvoice(&$langs)
  2569. {
  2570. foreach ($this->tab_next_situation_invoice as $next_invoice) {
  2571. $is_last = $next_invoice->is_last_in_cycle();
  2572. if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) {
  2573. $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
  2574. return false;
  2575. }
  2576. $next_invoice->brouillon = 1;
  2577. foreach ($next_invoice->lines as $line) {
  2578. $result = $next_invoice->updateline(
  2579. $line->id,
  2580. $line->desc,
  2581. $line->subprice,
  2582. $line->qty,
  2583. $line->remise_percent,
  2584. $line->date_start,
  2585. $line->date_end,
  2586. $line->tva_tx,
  2587. $line->localtax1_tx,
  2588. $line->localtax2_tx,
  2589. 'HT',
  2590. $line->info_bits,
  2591. $line->product_type,
  2592. $line->fk_parent_line,
  2593. 0,
  2594. $line->fk_fournprice,
  2595. $line->pa_ht,
  2596. $line->label,
  2597. $line->special_code,
  2598. $line->array_options,
  2599. $line->situation_percent,
  2600. $line->fk_unit
  2601. );
  2602. if ($result < 0) {
  2603. $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
  2604. return false;
  2605. }
  2606. }
  2607. break; // Only the next invoice and not each next invoice
  2608. }
  2609. return true;
  2610. }
  2611. /**
  2612. * Set draft status
  2613. *
  2614. * @param User $user Object user that modify
  2615. * @param int $idwarehouse Id warehouse to use for stock change.
  2616. * @return int <0 if KO, >0 if OK
  2617. */
  2618. public function setDraft($user, $idwarehouse = -1)
  2619. {
  2620. // phpcs:enable
  2621. global $conf, $langs;
  2622. $error = 0;
  2623. if ($this->statut == self::STATUS_DRAFT) {
  2624. dol_syslog(__METHOD__." already draft status", LOG_WARNING);
  2625. return 0;
  2626. }
  2627. dol_syslog(__METHOD__, LOG_DEBUG);
  2628. $this->db->begin();
  2629. $sql = "UPDATE ".MAIN_DB_PREFIX."facture";
  2630. $sql .= " SET fk_statut = ".self::STATUS_DRAFT;
  2631. $sql .= " WHERE rowid = ".((int) $this->id);
  2632. $result = $this->db->query($sql);
  2633. if ($result) {
  2634. if (!$error) {
  2635. $this->oldcopy = clone $this;
  2636. }
  2637. // If we decrease stock on invoice validation, we increase back
  2638. if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  2639. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  2640. $langs->load("agenda");
  2641. $num = count($this->lines);
  2642. for ($i = 0; $i < $num; $i++) {
  2643. if ($this->lines[$i]->fk_product > 0) {
  2644. $mouvP = new MouvementStock($this->db);
  2645. $mouvP->origin = &$this;
  2646. // We decrease stock for product
  2647. if ($this->type == self::TYPE_CREDIT_NOTE) {
  2648. $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref));
  2649. } else {
  2650. $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value
  2651. }
  2652. }
  2653. }
  2654. }
  2655. if ($error == 0) {
  2656. $old_statut = $this->statut;
  2657. $this->brouillon = 1;
  2658. $this->statut = self::STATUS_DRAFT;
  2659. $this->status = self::STATUS_DRAFT;
  2660. // Call trigger
  2661. $result = $this->call_trigger('BILL_UNVALIDATE', $user);
  2662. if ($result < 0) {
  2663. $error++;
  2664. $this->statut = $old_statut;
  2665. $this->status = $old_statut;
  2666. $this->brouillon = 0;
  2667. }
  2668. // End call triggers
  2669. } else {
  2670. $this->db->rollback();
  2671. return -1;
  2672. }
  2673. if ($error == 0) {
  2674. $this->db->commit();
  2675. return 1;
  2676. } else {
  2677. $this->db->rollback();
  2678. return -1;
  2679. }
  2680. } else {
  2681. $this->error = $this->db->error();
  2682. $this->db->rollback();
  2683. return -1;
  2684. }
  2685. }
  2686. /**
  2687. * Add an invoice line into database (linked to product/service or not).
  2688. * Les parametres sont deja cense etre juste et avec valeurs finales a l'appel
  2689. * de cette methode. Aussi, pour le taux tva, il doit deja avoir ete defini
  2690. * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit)
  2691. * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue)
  2692. *
  2693. * @param string $desc Description of line
  2694. * @param double $pu_ht Unit price without tax (> 0 even for credit note)
  2695. * @param double $qty Quantity
  2696. * @param double $txtva Force Vat rate, -1 for auto (Can contain the vat_src_code too with syntax '9.9 (CODE)')
  2697. * @param double $txlocaltax1 Local tax 1 rate (deprecated, use instead txtva with code inside)
  2698. * @param double $txlocaltax2 Local tax 2 rate (deprecated, use instead txtva with code inside)
  2699. * @param int $fk_product Id of predefined product/service
  2700. * @param double $remise_percent Percent of discount on line
  2701. * @param int $date_start Date start of service
  2702. * @param int $date_end Date end of service
  2703. * @param int $ventil Code of dispatching into accountancy
  2704. * @param int $info_bits Bits of type of lines
  2705. * @param int $fk_remise_except Id discount used
  2706. * @param string $price_base_type 'HT' or 'TTC'
  2707. * @param double $pu_ttc Unit price with tax (> 0 even for credit note)
  2708. * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used.
  2709. * @param int $rang Position of line
  2710. * @param int $special_code Special code (also used by externals modules!)
  2711. * @param string $origin Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be 'orderdet', 'propaldet'..., else 'order','propal,'....
  2712. * @param int $origin_id Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be Id of origin object (aka line id), else object id
  2713. * @param int $fk_parent_line Id of parent line
  2714. * @param int $fk_fournprice Supplier price id (to calculate margin) or ''
  2715. * @param int $pa_ht Buying price of line (to calculate margin) or ''
  2716. * @param string $label Label of the line (deprecated, do not use)
  2717. * @param array $array_options extrafields array
  2718. * @param int $situation_percent Situation advance percentage
  2719. * @param int $fk_prev_id Previous situation line id reference
  2720. * @param string $fk_unit Code of the unit to use. Null to use the default one
  2721. * @param double $pu_ht_devise Unit price in foreign currency
  2722. * @param string $ref_ext External reference of the line
  2723. * @return int <0 if KO, Id of line if OK
  2724. */
  2725. public function addline(
  2726. $desc,
  2727. $pu_ht,
  2728. $qty,
  2729. $txtva,
  2730. $txlocaltax1 = 0,
  2731. $txlocaltax2 = 0,
  2732. $fk_product = 0,
  2733. $remise_percent = 0,
  2734. $date_start = '',
  2735. $date_end = '',
  2736. $ventil = 0,
  2737. $info_bits = 0,
  2738. $fk_remise_except = '',
  2739. $price_base_type = 'HT',
  2740. $pu_ttc = 0,
  2741. $type = self::TYPE_STANDARD,
  2742. $rang = -1,
  2743. $special_code = 0,
  2744. $origin = '',
  2745. $origin_id = 0,
  2746. $fk_parent_line = 0,
  2747. $fk_fournprice = null,
  2748. $pa_ht = 0,
  2749. $label = '',
  2750. $array_options = 0,
  2751. $situation_percent = 100,
  2752. $fk_prev_id = 0,
  2753. $fk_unit = null,
  2754. $pu_ht_devise = 0,
  2755. $ref_ext = ''
  2756. ) {
  2757. // Deprecation warning
  2758. if ($label) {
  2759. dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
  2760. //var_dump(debug_backtrace(false));exit;
  2761. }
  2762. global $mysoc, $conf, $langs;
  2763. dol_syslog(get_class($this)."::addline id=$this->id,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product,remise_percent=$remise_percent,date_start=$date_start,date_end=$date_end,ventil=$ventil,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type, fk_unit=$fk_unit", LOG_DEBUG);
  2764. if ($this->statut == self::STATUS_DRAFT) {
  2765. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2766. // Clean parameters
  2767. if (empty($remise_percent)) {
  2768. $remise_percent = 0;
  2769. }
  2770. if (empty($qty)) {
  2771. $qty = 0;
  2772. }
  2773. if (empty($info_bits)) {
  2774. $info_bits = 0;
  2775. }
  2776. if (empty($rang)) {
  2777. $rang = 0;
  2778. }
  2779. if (empty($ventil)) {
  2780. $ventil = 0;
  2781. }
  2782. if (empty($txtva)) {
  2783. $txtva = 0;
  2784. }
  2785. if (empty($txlocaltax1)) {
  2786. $txlocaltax1 = 0;
  2787. }
  2788. if (empty($txlocaltax2)) {
  2789. $txlocaltax2 = 0;
  2790. }
  2791. if (empty($fk_parent_line) || $fk_parent_line < 0) {
  2792. $fk_parent_line = 0;
  2793. }
  2794. if (empty($fk_prev_id)) {
  2795. $fk_prev_id = 'null';
  2796. }
  2797. if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
  2798. $situation_percent = 100;
  2799. }
  2800. if (empty($ref_ext)) {
  2801. $ref_ext = '';
  2802. }
  2803. $remise_percent = price2num($remise_percent);
  2804. $qty = price2num($qty);
  2805. $pu_ht = price2num($pu_ht);
  2806. $pu_ht_devise = price2num($pu_ht_devise);
  2807. $pu_ttc = price2num($pu_ttc);
  2808. $pa_ht = price2num($pa_ht);
  2809. if (!preg_match('/\((.*)\)/', $txtva)) {
  2810. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  2811. }
  2812. $txlocaltax1 = price2num($txlocaltax1);
  2813. $txlocaltax2 = price2num($txlocaltax2);
  2814. if ($price_base_type == 'HT') {
  2815. $pu = $pu_ht;
  2816. } else {
  2817. $pu = $pu_ttc;
  2818. }
  2819. // Check parameters
  2820. if ($type < 0) {
  2821. return -1;
  2822. }
  2823. if ($date_start && $date_end && $date_start > $date_end) {
  2824. $langs->load("errors");
  2825. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  2826. return -1;
  2827. }
  2828. $this->db->begin();
  2829. $product_type = $type;
  2830. if (!empty($fk_product) && $fk_product > 0) {
  2831. $product = new Product($this->db);
  2832. $result = $product->fetch($fk_product);
  2833. $product_type = $product->type;
  2834. if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
  2835. $langs->load("errors");
  2836. $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
  2837. $this->db->rollback();
  2838. return -3;
  2839. }
  2840. }
  2841. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  2842. // Clean vat code
  2843. $reg = array();
  2844. $vat_src_code = '';
  2845. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  2846. $vat_src_code = $reg[1];
  2847. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  2848. }
  2849. // Calcul du total TTC et de la TVA pour la ligne a partir de
  2850. // qty, pu, remise_percent et txtva
  2851. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  2852. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  2853. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $product_type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
  2854. $total_ht = $tabprice[0];
  2855. $total_tva = $tabprice[1];
  2856. $total_ttc = $tabprice[2];
  2857. $total_localtax1 = $tabprice[9];
  2858. $total_localtax2 = $tabprice[10];
  2859. $pu_ht = $tabprice[3];
  2860. // MultiCurrency
  2861. $multicurrency_total_ht = $tabprice[16];
  2862. $multicurrency_total_tva = $tabprice[17];
  2863. $multicurrency_total_ttc = $tabprice[18];
  2864. $pu_ht_devise = $tabprice[19];
  2865. // Rank to use
  2866. $ranktouse = $rang;
  2867. if ($ranktouse == -1) {
  2868. $rangmax = $this->line_max($fk_parent_line);
  2869. $ranktouse = $rangmax + 1;
  2870. }
  2871. // Insert line
  2872. $this->line = new FactureLigne($this->db);
  2873. $this->line->context = $this->context;
  2874. $this->line->fk_facture = $this->id;
  2875. $this->line->label = $label; // deprecated
  2876. $this->line->desc = $desc;
  2877. $this->line->ref_ext = $ref_ext;
  2878. $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
  2879. $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
  2880. $this->line->vat_src_code = $vat_src_code;
  2881. $this->line->tva_tx = $txtva;
  2882. $this->line->localtax1_tx = ($total_localtax1 ? $localtaxes_type[1] : 0);
  2883. $this->line->localtax2_tx = ($total_localtax2 ? $localtaxes_type[3] : 0);
  2884. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  2885. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  2886. $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative
  2887. $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc); // For credit note and if qty is negative, total is negative
  2888. $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva); // For credit note and if qty is negative, total is negative
  2889. $this->line->total_localtax1 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_localtax1) : $total_localtax1); // For credit note and if qty is negative, total is negative
  2890. $this->line->total_localtax2 = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_localtax2) : $total_localtax2); // For credit note and if qty is negative, total is negative
  2891. $this->line->fk_product = $fk_product;
  2892. $this->line->product_type = $product_type;
  2893. $this->line->remise_percent = $remise_percent;
  2894. $this->line->date_start = $date_start;
  2895. $this->line->date_end = $date_end;
  2896. $this->line->ventil = $ventil;
  2897. $this->line->rang = $ranktouse;
  2898. $this->line->info_bits = $info_bits;
  2899. $this->line->fk_remise_except = $fk_remise_except;
  2900. $this->line->special_code = $special_code;
  2901. $this->line->fk_parent_line = $fk_parent_line;
  2902. $this->line->origin = $origin;
  2903. $this->line->origin_id = $origin_id;
  2904. $this->line->situation_percent = $situation_percent;
  2905. $this->line->fk_prev_id = $fk_prev_id;
  2906. $this->line->fk_unit = $fk_unit;
  2907. // infos marge
  2908. $this->line->fk_fournprice = $fk_fournprice;
  2909. $this->line->pa_ht = $pa_ht;
  2910. // Multicurrency
  2911. $this->line->fk_multicurrency = $this->fk_multicurrency;
  2912. $this->line->multicurrency_code = $this->multicurrency_code;
  2913. $this->line->multicurrency_subprice = $pu_ht_devise;
  2914. $this->line->multicurrency_total_ht = $multicurrency_total_ht;
  2915. $this->line->multicurrency_total_tva = $multicurrency_total_tva;
  2916. $this->line->multicurrency_total_ttc = $multicurrency_total_ttc;
  2917. if (is_array($array_options) && count($array_options) > 0) {
  2918. $this->line->array_options = $array_options;
  2919. }
  2920. $result = $this->line->insert();
  2921. if ($result > 0) {
  2922. // Reorder if child line
  2923. if (!empty($fk_parent_line)) {
  2924. $this->line_order(true, 'DESC');
  2925. }
  2926. // Mise a jour informations denormalisees au niveau de la facture meme
  2927. $result = $this->update_price(1, 'auto', 0, $mysoc); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode.
  2928. if ($result > 0) {
  2929. $this->db->commit();
  2930. return $this->line->id;
  2931. } else {
  2932. $this->error = $this->db->lasterror();
  2933. $this->db->rollback();
  2934. return -1;
  2935. }
  2936. } else {
  2937. $this->error = $this->line->error;
  2938. $this->errors = $this->line->errors;
  2939. $this->db->rollback();
  2940. return -2;
  2941. }
  2942. } else {
  2943. dol_syslog(get_class($this)."::addline status of invoice must be Draft to allow use of ->addline()", LOG_ERR);
  2944. return -3;
  2945. }
  2946. }
  2947. /**
  2948. * Update a detail line
  2949. *
  2950. * @param int $rowid Id of line to update
  2951. * @param string $desc Description of line
  2952. * @param double $pu Prix unitaire (HT ou TTC selon price_base_type) (> 0 even for credit note lines)
  2953. * @param double $qty Quantity
  2954. * @param double $remise_percent Percentage discount of the line
  2955. * @param int $date_start Date de debut de validite du service
  2956. * @param int $date_end Date de fin de validite du service
  2957. * @param double $txtva VAT Rate (Can be '8.5', '8.5 (ABC)')
  2958. * @param double $txlocaltax1 Local tax 1 rate
  2959. * @param double $txlocaltax2 Local tax 2 rate
  2960. * @param string $price_base_type HT or TTC
  2961. * @param int $info_bits Miscellaneous informations
  2962. * @param int $type Type of line (0=product, 1=service)
  2963. * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines).
  2964. * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules)
  2965. * @param int $fk_fournprice Id of origin supplier price
  2966. * @param int $pa_ht Price (without tax) of product when it was bought
  2967. * @param string $label Label of the line (deprecated, do not use)
  2968. * @param int $special_code Special code (also used by externals modules!)
  2969. * @param array $array_options extrafields array
  2970. * @param int $situation_percent Situation advance percentage
  2971. * @param string $fk_unit Code of the unit to use. Null to use the default one
  2972. * @param double $pu_ht_devise Unit price in currency
  2973. * @param int $notrigger disable line update trigger
  2974. * @param string $ref_ext External reference of the line
  2975. * @return int < 0 if KO, > 0 if OK
  2976. */
  2977. public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '')
  2978. {
  2979. global $conf, $user;
  2980. // Deprecation warning
  2981. if ($label) {
  2982. dol_syslog(__METHOD__.": using line label is deprecated", LOG_WARNING);
  2983. }
  2984. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  2985. global $mysoc, $langs;
  2986. dol_syslog(get_class($this)."::updateline rowid=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, type=$type, fk_parent_line=$fk_parent_line pa_ht=$pa_ht, special_code=$special_code, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG);
  2987. if ($this->statut == self::STATUS_DRAFT) {
  2988. if (!$this->is_last_in_cycle() && empty($this->error)) {
  2989. if (!$this->checkProgressLine($rowid, $situation_percent)) {
  2990. if (!$this->error) {
  2991. $this->error = $langs->trans('invoiceLineProgressError');
  2992. }
  2993. return -3;
  2994. }
  2995. }
  2996. if ($date_start && $date_end && $date_start > $date_end) {
  2997. $langs->load("errors");
  2998. $this->error = $langs->trans('ErrorStartDateGreaterEnd');
  2999. return -1;
  3000. }
  3001. $this->db->begin();
  3002. // Clean parameters
  3003. if (empty($qty)) {
  3004. $qty = 0;
  3005. }
  3006. if (empty($fk_parent_line) || $fk_parent_line < 0) {
  3007. $fk_parent_line = 0;
  3008. }
  3009. if (empty($special_code) || $special_code == 3) {
  3010. $special_code = 0;
  3011. }
  3012. if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') {
  3013. $situation_percent = 100;
  3014. }
  3015. if (empty($ref_ext)) {
  3016. $ref_ext = '';
  3017. }
  3018. $remise_percent = price2num($remise_percent);
  3019. $qty = price2num($qty);
  3020. $pu = price2num($pu);
  3021. $pu_ht_devise = price2num($pu_ht_devise);
  3022. $pa_ht = price2num($pa_ht);
  3023. if (!preg_match('/\((.*)\)/', $txtva)) {
  3024. $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5'
  3025. }
  3026. $txlocaltax1 = price2num($txlocaltax1);
  3027. $txlocaltax2 = price2num($txlocaltax2);
  3028. // Check parameters
  3029. if ($type < 0) {
  3030. return -1;
  3031. }
  3032. // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva
  3033. // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker
  3034. // la part ht, tva et ttc, et ce au niveau de la ligne qui a son propre taux tva.
  3035. $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc);
  3036. // Clean vat code
  3037. $reg = array();
  3038. $vat_src_code = '';
  3039. if (preg_match('/\((.*)\)/', $txtva, $reg)) {
  3040. $vat_src_code = $reg[1];
  3041. $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate.
  3042. }
  3043. $tabprice = calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx, $pu_ht_devise);
  3044. $total_ht = $tabprice[0];
  3045. $total_tva = $tabprice[1];
  3046. $total_ttc = $tabprice[2];
  3047. $total_localtax1 = $tabprice[9];
  3048. $total_localtax2 = $tabprice[10];
  3049. $pu_ht = $tabprice[3];
  3050. $pu_tva = $tabprice[4];
  3051. $pu_ttc = $tabprice[5];
  3052. // MultiCurrency
  3053. $multicurrency_total_ht = $tabprice[16];
  3054. $multicurrency_total_tva = $tabprice[17];
  3055. $multicurrency_total_ttc = $tabprice[18];
  3056. $pu_ht_devise = $tabprice[19];
  3057. // Old properties: $price, $remise (deprecated)
  3058. $price = $pu;
  3059. $remise = 0;
  3060. if ($remise_percent > 0) {
  3061. $remise = round(($pu * $remise_percent / 100), 2);
  3062. $price = ($pu - $remise);
  3063. }
  3064. $price = price2num($price);
  3065. //Fetch current line from the database and then clone the object and set it in $oldline property
  3066. $line = new FactureLigne($this->db);
  3067. $line->fetch($rowid);
  3068. $line->fetch_optionals();
  3069. if (!empty($line->fk_product)) {
  3070. $product = new Product($this->db);
  3071. $result = $product->fetch($line->fk_product);
  3072. $product_type = $product->type;
  3073. if (!empty($conf->global->STOCK_MUST_BE_ENOUGH_FOR_INVOICE) && $product_type == 0 && $product->stock_reel < $qty) {
  3074. $langs->load("errors");
  3075. $this->error = $langs->trans('ErrorStockIsNotEnoughToAddProductOnInvoice', $product->ref);
  3076. $this->db->rollback();
  3077. return -3;
  3078. }
  3079. }
  3080. $staticline = clone $line;
  3081. $line->oldline = $staticline;
  3082. $this->line = $line;
  3083. $this->line->context = $this->context;
  3084. // Reorder if fk_parent_line change
  3085. if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) {
  3086. $rangmax = $this->line_max($fk_parent_line);
  3087. $this->line->rang = $rangmax + 1;
  3088. }
  3089. $this->line->id = $rowid;
  3090. $this->line->rowid = $rowid;
  3091. $this->line->label = $label;
  3092. $this->line->desc = $desc;
  3093. $this->line->ref_ext = $ref_ext;
  3094. $this->line->qty = ($this->type == self::TYPE_CREDIT_NOTE ?abs($qty) : $qty); // For credit note, quantity is always positive and unit price negative
  3095. $this->line->vat_src_code = $vat_src_code;
  3096. $this->line->tva_tx = $txtva;
  3097. $this->line->localtax1_tx = $txlocaltax1;
  3098. $this->line->localtax2_tx = $txlocaltax2;
  3099. $this->line->localtax1_type = empty($localtaxes_type[0]) ? '' : $localtaxes_type[0];
  3100. $this->line->localtax2_type = empty($localtaxes_type[2]) ? '' : $localtaxes_type[2];
  3101. $this->line->remise_percent = $remise_percent;
  3102. $this->line->subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht) : $pu_ht); // For credit note, unit price always negative, always positive otherwise
  3103. $this->line->date_start = $date_start;
  3104. $this->line->date_end = $date_end;
  3105. $this->line->total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ht) : $total_ht); // For credit note and if qty is negative, total is negative
  3106. $this->line->total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_tva) : $total_tva);
  3107. $this->line->total_localtax1 = $total_localtax1;
  3108. $this->line->total_localtax2 = $total_localtax2;
  3109. $this->line->total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($total_ttc) : $total_ttc);
  3110. $this->line->info_bits = $info_bits;
  3111. $this->line->special_code = $special_code;
  3112. $this->line->product_type = $type;
  3113. $this->line->fk_parent_line = $fk_parent_line;
  3114. $this->line->skip_update_total = $skip_update_total;
  3115. $this->line->situation_percent = $situation_percent;
  3116. $this->line->fk_unit = $fk_unit;
  3117. $this->line->fk_fournprice = $fk_fournprice;
  3118. $this->line->pa_ht = $pa_ht;
  3119. // Multicurrency
  3120. $this->line->multicurrency_subprice = ($this->type == self::TYPE_CREDIT_NOTE ?-abs($pu_ht_devise) : $pu_ht_devise); // For credit note, unit price always negative, always positive otherwise
  3121. $this->line->multicurrency_total_ht = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ht) : $multicurrency_total_ht); // For credit note and if qty is negative, total is negative
  3122. $this->line->multicurrency_total_tva = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_tva) : $multicurrency_total_tva);
  3123. $this->line->multicurrency_total_ttc = (($this->type == self::TYPE_CREDIT_NOTE || $qty < 0) ?-abs($multicurrency_total_ttc) : $multicurrency_total_ttc);
  3124. if (is_array($array_options) && count($array_options) > 0) {
  3125. // We replace values in this->line->array_options only for entries defined into $array_options
  3126. foreach ($array_options as $key => $value) {
  3127. $this->line->array_options[$key] = $array_options[$key];
  3128. }
  3129. }
  3130. $result = $this->line->update($user, $notrigger);
  3131. if ($result > 0) {
  3132. // Reorder if child line
  3133. if (!empty($fk_parent_line)) {
  3134. $this->line_order(true, 'DESC');
  3135. }
  3136. // Mise a jour info denormalisees au niveau facture
  3137. $this->update_price(1);
  3138. $this->db->commit();
  3139. return $result;
  3140. } else {
  3141. $this->error = $this->line->error;
  3142. $this->db->rollback();
  3143. return -1;
  3144. }
  3145. } else {
  3146. $this->error = "Invoice statut makes operation forbidden";
  3147. return -2;
  3148. }
  3149. }
  3150. /**
  3151. * Check if the percent edited is lower of next invoice line
  3152. *
  3153. * @param int $idline id of line to check
  3154. * @param float $situation_percent progress percentage need to be test
  3155. * @return false if KO, true if OK
  3156. */
  3157. public function checkProgressLine($idline, $situation_percent)
  3158. {
  3159. $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
  3160. INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
  3161. WHERE fd.fk_prev_id = '.((int) $idline).' AND f.fk_statut <> 0';
  3162. $result = $this->db->query($sql);
  3163. if (!$result) {
  3164. $this->error = $this->db->error();
  3165. return false;
  3166. }
  3167. $obj = $this->db->fetch_object($result);
  3168. if ($obj === null) {
  3169. return true;
  3170. } else {
  3171. return $situation_percent < $obj->situation_percent;
  3172. }
  3173. }
  3174. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3175. /**
  3176. * Update invoice line with percentage
  3177. *
  3178. * @param FactureLigne $line Invoice line
  3179. * @param int $percent Percentage
  3180. * @return void
  3181. */
  3182. public function update_percent($line, $percent)
  3183. {
  3184. // phpcs:enable
  3185. global $mysoc, $user;
  3186. // Progress should never be changed for discount lines
  3187. if (($line->info_bits & 2) == 2) {
  3188. return;
  3189. }
  3190. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  3191. // Cap percentages to 100
  3192. if ($percent > 100) {
  3193. $percent = 100;
  3194. }
  3195. $line->situation_percent = $percent;
  3196. $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, '', $percent);
  3197. $line->total_ht = $tabprice[0];
  3198. $line->total_tva = $tabprice[1];
  3199. $line->total_ttc = $tabprice[2];
  3200. $line->total_localtax1 = $tabprice[9];
  3201. $line->total_localtax2 = $tabprice[10];
  3202. $line->multicurrency_total_ht = $tabprice[16];
  3203. $line->multicurrency_total_tva = $tabprice[17];
  3204. $line->multicurrency_total_ttc = $tabprice[18];
  3205. $line->update($user);
  3206. $this->update_price(1);
  3207. }
  3208. /**
  3209. * Delete line in database
  3210. *
  3211. * @param int $rowid Id of line to delete
  3212. * @return int <0 if KO, >0 if OK
  3213. */
  3214. public function deleteline($rowid)
  3215. {
  3216. global $user;
  3217. dol_syslog(get_class($this)."::deleteline rowid=".((int) $rowid), LOG_DEBUG);
  3218. if ($this->statut != self::STATUS_DRAFT) {
  3219. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  3220. return -1;
  3221. }
  3222. $this->db->begin();
  3223. // Free discount linked to invoice line
  3224. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except';
  3225. $sql .= ' SET fk_facture_line = NULL';
  3226. $sql .= ' WHERE fk_facture_line = '.((int) $rowid);
  3227. dol_syslog(get_class($this)."::deleteline", LOG_DEBUG);
  3228. $result = $this->db->query($sql);
  3229. if (!$result) {
  3230. $this->error = $this->db->error();
  3231. $this->db->rollback();
  3232. return -1;
  3233. }
  3234. $line = new FactureLigne($this->db);
  3235. $line->context = $this->context;
  3236. // For triggers
  3237. $result = $line->fetch($rowid);
  3238. if (!($result > 0)) {
  3239. dol_print_error($this->db, $line->error, $line->errors);
  3240. }
  3241. if ($line->delete($user) > 0) {
  3242. $result = $this->update_price(1);
  3243. if ($result > 0) {
  3244. $this->db->commit();
  3245. return 1;
  3246. } else {
  3247. $this->db->rollback();
  3248. $this->error = $this->db->lasterror();
  3249. return -1;
  3250. }
  3251. } else {
  3252. $this->db->rollback();
  3253. $this->error = $line->error;
  3254. return -1;
  3255. }
  3256. }
  3257. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3258. /**
  3259. * Set percent discount
  3260. *
  3261. * @deprecated
  3262. * @see setDiscount()
  3263. * @param User $user User that set discount
  3264. * @param double $remise Discount
  3265. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3266. * @return int <0 if ko, >0 if ok
  3267. */
  3268. public function set_remise($user, $remise, $notrigger = 0)
  3269. {
  3270. // phpcs:enable
  3271. dol_syslog(get_class($this)."::set_remise is deprecated, use setDiscount instead", LOG_NOTICE);
  3272. return $this->setDiscount($user, $remise, $notrigger);
  3273. }
  3274. /**
  3275. * Set percent discount
  3276. *
  3277. * @param User $user User that set discount
  3278. * @param double $remise Discount
  3279. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3280. * @return int <0 if ko, >0 if ok
  3281. */
  3282. public function setDiscount($user, $remise, $notrigger = 0)
  3283. {
  3284. // Clean parameters
  3285. if (empty($remise)) {
  3286. $remise = 0;
  3287. }
  3288. if ($user->rights->facture->creer) {
  3289. $remise = price2num($remise, 2);
  3290. $error = 0;
  3291. $this->db->begin();
  3292. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  3293. $sql .= ' SET remise_percent = '.((float) $remise);
  3294. $sql .= " WHERE rowid = ".((int) $this->id);
  3295. $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
  3296. dol_syslog(__METHOD__, LOG_DEBUG);
  3297. $resql = $this->db->query($sql);
  3298. if (!$resql) {
  3299. $this->errors[] = $this->db->error();
  3300. $error++;
  3301. }
  3302. if (!$notrigger && empty($error)) {
  3303. // Call trigger
  3304. $result = $this->call_trigger('BILL_MODIFY', $user);
  3305. if ($result < 0) {
  3306. $error++;
  3307. }
  3308. // End call triggers
  3309. }
  3310. if (!$error) {
  3311. $this->remise_percent = $remise;
  3312. $this->update_price(1);
  3313. $this->db->commit();
  3314. return 1;
  3315. } else {
  3316. foreach ($this->errors as $errmsg) {
  3317. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  3318. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  3319. }
  3320. $this->db->rollback();
  3321. return -1 * $error;
  3322. }
  3323. }
  3324. }
  3325. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3326. /**
  3327. * Set absolute discount
  3328. *
  3329. * @param User $user User that set discount
  3330. * @param double $remise Discount
  3331. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  3332. * @return int <0 if KO, >0 if OK
  3333. */
  3334. public function set_remise_absolue($user, $remise, $notrigger = 0)
  3335. {
  3336. // phpcs:enable
  3337. if (empty($remise)) {
  3338. $remise = 0;
  3339. }
  3340. if ($user->rights->facture->creer) {
  3341. $error = 0;
  3342. $this->db->begin();
  3343. $remise = price2num($remise);
  3344. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture';
  3345. $sql .= ' SET remise_absolue = '.((float) $remise);
  3346. $sql .= " WHERE rowid = ".((int) $this->id);
  3347. $sql .= ' AND fk_statut = '.self::STATUS_DRAFT;
  3348. dol_syslog(__METHOD__, LOG_DEBUG);
  3349. $resql = $this->db->query($sql);
  3350. if (!$resql) {
  3351. $this->errors[] = $this->db->error();
  3352. $error++;
  3353. }
  3354. if (!$error) {
  3355. $this->oldcopy = clone $this;
  3356. $this->remise_absolue = $remise;
  3357. $this->update_price(1);
  3358. }
  3359. if (!$notrigger && empty($error)) {
  3360. // Call trigger
  3361. $result = $this->call_trigger('BILL_MODIFY', $user);
  3362. if ($result < 0) {
  3363. $error++;
  3364. }
  3365. // End call triggers
  3366. }
  3367. if (!$error) {
  3368. $this->db->commit();
  3369. return 1;
  3370. } else {
  3371. foreach ($this->errors as $errmsg) {
  3372. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  3373. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  3374. }
  3375. $this->db->rollback();
  3376. return -1 * $error;
  3377. }
  3378. }
  3379. }
  3380. /**
  3381. * Return next reference of customer invoice not already used (or last reference)
  3382. * according to numbering module defined into constant FACTURE_ADDON
  3383. *
  3384. * @param Societe $soc object company
  3385. * @param string $mode 'next' for next value or 'last' for last value
  3386. * @return string free ref or last ref
  3387. */
  3388. public function getNextNumRef($soc, $mode = 'next')
  3389. {
  3390. global $conf, $langs;
  3391. if ($this->module_source == 'takepos') {
  3392. $langs->load('cashdesk');
  3393. $moduleName = 'takepos';
  3394. $moduleSourceName = 'Takepos';
  3395. $addonConstName = 'TAKEPOS_REF_ADDON';
  3396. // Clean parameters (if not defined or using deprecated value)
  3397. if (empty($conf->global->TAKEPOS_REF_ADDON)) {
  3398. $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple';
  3399. }
  3400. $addon = $conf->global->TAKEPOS_REF_ADDON;
  3401. } else {
  3402. $langs->load('bills');
  3403. $moduleName = 'facture';
  3404. $moduleSourceName = 'Invoice';
  3405. $addonConstName = 'FACTURE_ADDON';
  3406. // Clean parameters (if not defined or using deprecated value)
  3407. if (empty($conf->global->FACTURE_ADDON)) {
  3408. $conf->global->FACTURE_ADDON = 'mod_facture_terre';
  3409. } elseif ($conf->global->FACTURE_ADDON == 'terre') {
  3410. $conf->global->FACTURE_ADDON = 'mod_facture_terre';
  3411. } elseif ($conf->global->FACTURE_ADDON == 'mercure') {
  3412. $conf->global->FACTURE_ADDON = 'mod_facture_mercure';
  3413. }
  3414. $addon = $conf->global->FACTURE_ADDON;
  3415. }
  3416. if (!empty($addon)) {
  3417. dol_syslog("Call getNextNumRef with ".$addonConstName." = ".$conf->global->FACTURE_ADDON.", thirdparty=".$soc->name.", type=".$soc->typent_code, LOG_DEBUG);
  3418. $mybool = false;
  3419. $file = $addon.'.php';
  3420. $classname = $addon;
  3421. // Include file with class
  3422. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  3423. foreach ($dirmodels as $reldir) {
  3424. $dir = dol_buildpath($reldir.'core/modules/'.$moduleName.'/');
  3425. // Load file with numbering class (if found)
  3426. if (is_file($dir.$file) && is_readable($dir.$file)) {
  3427. $mybool |= include_once $dir.$file;
  3428. }
  3429. }
  3430. // For compatibility
  3431. if (!$mybool) {
  3432. $file = $addon.'/'.$addon.'.modules.php';
  3433. $classname = 'mod_'.$moduleName.'_'.$addon;
  3434. $classname = preg_replace('/\-.*$/', '', $classname);
  3435. // Include file with class
  3436. foreach ($conf->file->dol_document_root as $dirroot) {
  3437. $dir = $dirroot.'/core/modules/'.$moduleName.'/';
  3438. // Load file with numbering class (if found)
  3439. if (is_file($dir.$file) && is_readable($dir.$file)) {
  3440. $mybool |= include_once $dir.$file;
  3441. }
  3442. }
  3443. }
  3444. if (!$mybool) {
  3445. dol_print_error('', 'Failed to include file '.$file);
  3446. return '';
  3447. }
  3448. $obj = new $classname();
  3449. $numref = $obj->getNextValue($soc, $this, $mode);
  3450. /**
  3451. * $numref can be empty in case we ask for the last value because if there is no invoice created with the
  3452. * set up mask.
  3453. */
  3454. if ($mode != 'last' && !$numref) {
  3455. $this->error = $obj->error;
  3456. return '';
  3457. }
  3458. return $numref;
  3459. } else {
  3460. $langs->load('errors');
  3461. print $langs->trans('Error').' '.$langs->trans('ErrorModuleSetupNotComplete', $langs->transnoentitiesnoconv($moduleSourceName));
  3462. return '';
  3463. }
  3464. }
  3465. /**
  3466. * Load miscellaneous information for tab "Info"
  3467. *
  3468. * @param int $id Id of object to load
  3469. * @return void
  3470. */
  3471. public function info($id)
  3472. {
  3473. $sql = 'SELECT c.rowid, datec, date_valid as datev, tms as datem,';
  3474. $sql .= ' date_closing as dateclosing,';
  3475. $sql .= ' fk_user_author, fk_user_valid, fk_user_closing';
  3476. $sql .= ' FROM '.MAIN_DB_PREFIX.'facture as c';
  3477. $sql .= ' WHERE c.rowid = '.((int) $id);
  3478. $result = $this->db->query($sql);
  3479. if ($result) {
  3480. if ($this->db->num_rows($result)) {
  3481. $obj = $this->db->fetch_object($result);
  3482. $this->id = $obj->rowid;
  3483. if ($obj->fk_user_author) {
  3484. $cuser = new User($this->db);
  3485. $cuser->fetch($obj->fk_user_author);
  3486. $this->user_creation = $cuser;
  3487. }
  3488. if ($obj->fk_user_valid) {
  3489. $vuser = new User($this->db);
  3490. $vuser->fetch($obj->fk_user_valid);
  3491. $this->user_validation = $vuser;
  3492. }
  3493. if ($obj->fk_user_closing) {
  3494. $cluser = new User($this->db);
  3495. $cluser->fetch($obj->fk_user_closing);
  3496. $this->user_closing = $cluser;
  3497. }
  3498. $this->date_creation = $this->db->jdate($obj->datec);
  3499. $this->date_modification = $this->db->jdate($obj->datem);
  3500. $this->date_validation = $this->db->jdate($obj->datev);
  3501. $this->date_closing = $this->db->jdate($obj->dateclosing);
  3502. }
  3503. $this->db->free($result);
  3504. } else {
  3505. dol_print_error($this->db);
  3506. }
  3507. }
  3508. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3509. /**
  3510. * Return list of invoices (eventually filtered on a user) into an array
  3511. *
  3512. * @param int $shortlist 0=Return array[id]=ref, 1=Return array[](id=>id,ref=>ref,name=>name)
  3513. * @param int $draft 0=not draft, 1=draft
  3514. * @param User $excluser Objet user to exclude
  3515. * @param int $socid Id third pary
  3516. * @param int $limit For pagination
  3517. * @param int $offset For pagination
  3518. * @param string $sortfield Sort criteria
  3519. * @param string $sortorder Sort order
  3520. * @return array|int -1 if KO, array with result if OK
  3521. */
  3522. public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC')
  3523. {
  3524. // phpcs:enable
  3525. global $conf, $user;
  3526. $ga = array();
  3527. $sql = "SELECT s.rowid, s.nom as name, s.client,";
  3528. $sql .= " f.rowid as fid, f.ref as ref, f.datef as df";
  3529. if (!$user->rights->societe->client->voir && !$socid) {
  3530. $sql .= ", sc.fk_soc, sc.fk_user";
  3531. }
  3532. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f";
  3533. if (!$user->rights->societe->client->voir && !$socid) {
  3534. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  3535. }
  3536. $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
  3537. $sql .= " AND f.fk_soc = s.rowid";
  3538. if (!$user->rights->societe->client->voir && !$socid) { //restriction
  3539. $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3540. }
  3541. if ($socid) {
  3542. $sql .= " AND s.rowid = ".((int) $socid);
  3543. }
  3544. if ($draft) {
  3545. $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT;
  3546. }
  3547. if (is_object($excluser)) {
  3548. $sql .= " AND f.fk_user_author <> ".((int) $excluser->id);
  3549. }
  3550. $sql .= $this->db->order($sortfield, $sortorder);
  3551. $sql .= $this->db->plimit($limit, $offset);
  3552. $result = $this->db->query($sql);
  3553. if ($result) {
  3554. $numc = $this->db->num_rows($result);
  3555. if ($numc) {
  3556. $i = 0;
  3557. while ($i < $numc) {
  3558. $obj = $this->db->fetch_object($result);
  3559. if ($shortlist == 1) {
  3560. $ga[$obj->fid] = $obj->ref;
  3561. } elseif ($shortlist == 2) {
  3562. $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')';
  3563. } else {
  3564. $ga[$i]['id'] = $obj->fid;
  3565. $ga[$i]['ref'] = $obj->ref;
  3566. $ga[$i]['name'] = $obj->name;
  3567. }
  3568. $i++;
  3569. }
  3570. }
  3571. return $ga;
  3572. } else {
  3573. dol_print_error($this->db);
  3574. return -1;
  3575. }
  3576. }
  3577. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3578. /**
  3579. * Return list of invoices qualified to be replaced by another invoice.
  3580. * Invoices matching the following rules are returned:
  3581. * (Status validated or abandonned for a reason 'other') + not payed + no payment at all + not already replaced
  3582. *
  3583. * @param int $socid Id thirdparty
  3584. * @return array|int Array of invoices ('id'=>id, 'ref'=>ref, 'status'=>status, 'paymentornot'=>0/1)
  3585. */
  3586. public function list_replacable_invoices($socid = 0)
  3587. {
  3588. // phpcs:enable
  3589. global $conf;
  3590. $return = array();
  3591. $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut as status, f.paye as paid,";
  3592. $sql .= " ff.rowid as rowidnext";
  3593. //$sql .= ", SUM(pf.amount) as alreadypaid";
  3594. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  3595. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  3596. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON f.rowid = ff.fk_facture_source";
  3597. $sql .= " WHERE (f.fk_statut = ".self::STATUS_VALIDATED." OR (f.fk_statut = ".self::STATUS_ABANDONED." AND f.close_code = '".self::CLOSECODE_ABANDONED."'))";
  3598. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3599. $sql .= " AND f.paye = 0"; // Not paid completely
  3600. $sql .= " AND pf.fk_paiement IS NULL"; // No payment already done
  3601. $sql .= " AND ff.fk_statut IS NULL"; // Return true if it is not a replacement invoice
  3602. if ($socid > 0) {
  3603. $sql .= " AND f.fk_soc = ".((int) $socid);
  3604. }
  3605. //$sql .= " GROUP BY f.rowid, f.ref, f.fk_statut, f.paye, ff.rowid";
  3606. $sql .= " ORDER BY f.ref";
  3607. dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG);
  3608. $resql = $this->db->query($sql);
  3609. if ($resql) {
  3610. while ($obj = $this->db->fetch_object($resql)) {
  3611. $return[$obj->rowid] = array(
  3612. 'id' => $obj->rowid,
  3613. 'ref' => $obj->ref,
  3614. 'status' => $obj->status,
  3615. 'paid' => $obj->paid,
  3616. 'alreadypaid' => 0
  3617. );
  3618. }
  3619. //print_r($return);
  3620. return $return;
  3621. } else {
  3622. $this->error = $this->db->error();
  3623. return -1;
  3624. }
  3625. }
  3626. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3627. /**
  3628. * Return list of invoices qualified to be corrected by a credit note.
  3629. * Invoices matching the following rules are returned:
  3630. * (validated + payment on process) or classified (payed completely or payed partiely) + not already replaced + not already a credit note
  3631. *
  3632. * @param int $socid Id thirdparty
  3633. * @return array Array of invoices ($id => array('ref'=>,'paymentornot'=>,'status'=>,'paye'=>)
  3634. */
  3635. public function list_qualified_avoir_invoices($socid = 0)
  3636. {
  3637. // phpcs:enable
  3638. global $conf;
  3639. $return = array();
  3640. $sql = "SELECT f.rowid as rowid, f.ref, f.fk_statut, f.type, f.paye, pf.fk_paiement";
  3641. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  3642. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture";
  3643. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as ff ON (f.rowid = ff.fk_facture_source AND ff.type=".self::TYPE_REPLACEMENT.")";
  3644. $sql .= " WHERE f.entity IN (".getEntity('invoice').")";
  3645. $sql .= " AND f.fk_statut in (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
  3646. // $sql.= " WHERE f.fk_statut >= 1";
  3647. // $sql.= " AND (f.paye = 1"; // Classee payee completement
  3648. // $sql.= " OR f.close_code IS NOT NULL)"; // Classee payee partiellement
  3649. $sql .= " AND ff.type IS NULL"; // Renvoi vrai si pas facture de remplacement
  3650. $sql .= " AND f.type <> ".self::TYPE_CREDIT_NOTE; // Exclude credit note invoices from selection
  3651. if (!empty($conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE)) {
  3652. // Keep invoices that are not situation invoices or that are the last in serie if it is a situation invoice
  3653. $sql .= " AND (f.type <> ".self::TYPE_SITUATION." OR f.rowid IN ";
  3654. $sql .= '(SELECT MAX(fs.rowid)'; // This select returns several ID becasue of the group by later
  3655. $sql .= " FROM ".MAIN_DB_PREFIX."facture as fs";
  3656. $sql .= " WHERE fs.entity IN (".getEntity('invoice').")";
  3657. $sql .= " AND fs.type = ".self::TYPE_SITUATION;
  3658. $sql .= " AND fs.fk_statut IN (".self::STATUS_VALIDATED.",".self::STATUS_CLOSED.")";
  3659. if ($socid > 0) {
  3660. $sql .= " AND fs.fk_soc = ".((int) $socid);
  3661. }
  3662. $sql .= " GROUP BY fs.situation_cycle_ref)"; // For each situation_cycle_ref, we take the higher rowid
  3663. $sql .= ")";
  3664. } else {
  3665. $sql .= " AND f.type <> ".self::TYPE_SITUATION; // Keep invoices that are not situation invoices
  3666. }
  3667. if ($socid > 0) {
  3668. $sql .= " AND f.fk_soc = ".((int) $socid);
  3669. }
  3670. $sql .= " ORDER BY f.ref";
  3671. dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG);
  3672. $resql = $this->db->query($sql);
  3673. if ($resql) {
  3674. while ($obj = $this->db->fetch_object($resql)) {
  3675. $qualified = 0;
  3676. if ($obj->fk_statut == self::STATUS_VALIDATED) {
  3677. $qualified = 1;
  3678. }
  3679. if ($obj->fk_statut == self::STATUS_CLOSED) {
  3680. $qualified = 1;
  3681. }
  3682. if ($qualified) {
  3683. //$ref=$obj->ref;
  3684. $paymentornot = ($obj->fk_paiement ? 1 : 0);
  3685. $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot);
  3686. }
  3687. }
  3688. return $return;
  3689. } else {
  3690. $this->error = $this->db->error();
  3691. return -1;
  3692. }
  3693. }
  3694. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3695. /**
  3696. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  3697. *
  3698. * @param User $user Object user
  3699. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  3700. */
  3701. public function load_board($user)
  3702. {
  3703. // phpcs:enable
  3704. global $conf, $langs;
  3705. $clause = " WHERE";
  3706. $sql = "SELECT f.rowid, f.date_lim_reglement as datefin,f.fk_statut, f.total_ht";
  3707. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  3708. if (!$user->rights->societe->client->voir && !$user->socid) {
  3709. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc";
  3710. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  3711. $clause = " AND";
  3712. }
  3713. $sql .= $clause." f.paye=0";
  3714. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3715. $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED;
  3716. if ($user->socid) {
  3717. $sql .= " AND f.fk_soc = ".((int) $user->socid);
  3718. }
  3719. $resql = $this->db->query($sql);
  3720. if ($resql) {
  3721. $langs->load("bills");
  3722. $now = dol_now();
  3723. $response = new WorkboardResponse();
  3724. $response->warning_delay = $conf->facture->client->warning_delay / 60 / 60 / 24;
  3725. $response->label = $langs->trans("CustomerBillsUnpaid");
  3726. $response->labelShort = $langs->trans("Unpaid");
  3727. $response->url = DOL_URL_ROOT.'/compta/facture/list.php?search_status=1&mainmenu=billing&leftmenu=customers_bills';
  3728. $response->img = img_object('', "bill");
  3729. $generic_facture = new Facture($this->db);
  3730. while ($obj = $this->db->fetch_object($resql)) {
  3731. $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin);
  3732. $generic_facture->statut = $obj->fk_statut;
  3733. $response->nbtodo++;
  3734. $response->total += $obj->total_ht;
  3735. if ($generic_facture->hasDelay()) {
  3736. $response->nbtodolate++;
  3737. $response->url_late = DOL_URL_ROOT.'/compta/facture/list.php?search_option=late&mainmenu=billing&leftmenu=customers_bills';
  3738. }
  3739. }
  3740. return $response;
  3741. } else {
  3742. dol_print_error($this->db);
  3743. $this->error = $this->db->error();
  3744. return -1;
  3745. }
  3746. }
  3747. /* gestion des contacts d'une facture */
  3748. /**
  3749. * Retourne id des contacts clients de facturation
  3750. *
  3751. * @return array Liste des id contacts facturation
  3752. */
  3753. public function getIdBillingContact()
  3754. {
  3755. return $this->getIdContact('external', 'BILLING');
  3756. }
  3757. /**
  3758. * Retourne id des contacts clients de livraison
  3759. *
  3760. * @return array Liste des id contacts livraison
  3761. */
  3762. public function getIdShippingContact()
  3763. {
  3764. return $this->getIdContact('external', 'SHIPPING');
  3765. }
  3766. /**
  3767. * Initialise an instance with random values.
  3768. * Used to build previews or test instances.
  3769. * id must be 0 if object instance is a specimen.
  3770. *
  3771. * @param string $option ''=Create a specimen invoice with lines, 'nolines'=No lines
  3772. * @return void
  3773. */
  3774. public function initAsSpecimen($option = '')
  3775. {
  3776. global $conf, $langs, $user;
  3777. $now = dol_now();
  3778. $arraynow = dol_getdate($now);
  3779. $nownotime = dol_mktime(0, 0, 0, $arraynow['mon'], $arraynow['mday'], $arraynow['year']);
  3780. // Load array of products prodids
  3781. $num_prods = 0;
  3782. $prodids = array();
  3783. $sql = "SELECT rowid";
  3784. $sql .= " FROM ".MAIN_DB_PREFIX."product";
  3785. $sql .= " WHERE entity IN (".getEntity('product').")";
  3786. $sql .= $this->db->plimit(100);
  3787. $resql = $this->db->query($sql);
  3788. if ($resql) {
  3789. $num_prods = $this->db->num_rows($resql);
  3790. $i = 0;
  3791. while ($i < $num_prods) {
  3792. $i++;
  3793. $row = $this->db->fetch_row($resql);
  3794. $prodids[$i] = $row[0];
  3795. }
  3796. }
  3797. //Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
  3798. if (empty($num_prods)) {
  3799. $num_prods = 1;
  3800. }
  3801. // Initialize parameters
  3802. $this->id = 0;
  3803. $this->entity = 1;
  3804. $this->ref = 'SPECIMEN';
  3805. $this->specimen = 1;
  3806. $this->socid = 1;
  3807. $this->date = $nownotime;
  3808. $this->date_lim_reglement = $nownotime + 3600 * 24 * 30;
  3809. $this->cond_reglement_id = 1;
  3810. $this->cond_reglement_code = 'RECEP';
  3811. $this->date_lim_reglement = $this->calculate_date_lim_reglement();
  3812. $this->mode_reglement_id = 0; // Not forced to show payment mode CHQ + VIR
  3813. $this->mode_reglement_code = ''; // Not forced to show payment mode CHQ + VIR
  3814. $this->note_public = 'This is a comment (public)';
  3815. $this->note_private = 'This is a comment (private)';
  3816. $this->note = 'This is a comment (private)';
  3817. $this->fk_user_author = $user->id;
  3818. $this->multicurrency_tx = 1;
  3819. $this->multicurrency_code = $conf->currency;
  3820. $this->fk_incoterms = 0;
  3821. $this->location_incoterms = '';
  3822. if (empty($option) || $option != 'nolines') {
  3823. // Lines
  3824. $nbp = 5;
  3825. $xnbp = 0;
  3826. while ($xnbp < $nbp) {
  3827. $line = new FactureLigne($this->db);
  3828. $line->desc = $langs->trans("Description")." ".$xnbp;
  3829. $line->qty = 1;
  3830. $line->subprice = 100;
  3831. $line->tva_tx = 19.6;
  3832. $line->localtax1_tx = 0;
  3833. $line->localtax2_tx = 0;
  3834. $line->remise_percent = 0;
  3835. if ($xnbp == 1) { // Qty is negative (product line)
  3836. $prodid = mt_rand(1, $num_prods);
  3837. $line->fk_product = $prodids[$prodid];
  3838. $line->qty = -1;
  3839. $line->total_ht = -100;
  3840. $line->total_ttc = -119.6;
  3841. $line->total_tva = -19.6;
  3842. $line->multicurrency_total_ht = -200;
  3843. $line->multicurrency_total_ttc = -239.2;
  3844. $line->multicurrency_total_tva = -39.2;
  3845. } elseif ($xnbp == 2) { // UP is negative (free line)
  3846. $line->subprice = -100;
  3847. $line->total_ht = -100;
  3848. $line->total_ttc = -119.6;
  3849. $line->total_tva = -19.6;
  3850. $line->remise_percent = 0;
  3851. $line->multicurrency_total_ht = -200;
  3852. $line->multicurrency_total_ttc = -239.2;
  3853. $line->multicurrency_total_tva = -39.2;
  3854. } elseif ($xnbp == 3) { // Discount is 50% (product line)
  3855. $prodid = mt_rand(1, $num_prods);
  3856. $line->fk_product = $prodids[$prodid];
  3857. $line->total_ht = 50;
  3858. $line->total_ttc = 59.8;
  3859. $line->total_tva = 9.8;
  3860. $line->multicurrency_total_ht = 100;
  3861. $line->multicurrency_total_ttc = 119.6;
  3862. $line->multicurrency_total_tva = 19.6;
  3863. $line->remise_percent = 50;
  3864. } else // (product line)
  3865. {
  3866. $prodid = mt_rand(1, $num_prods);
  3867. $line->fk_product = $prodids[$prodid];
  3868. $line->total_ht = 100;
  3869. $line->total_ttc = 119.6;
  3870. $line->total_tva = 19.6;
  3871. $line->multicurrency_total_ht = 200;
  3872. $line->multicurrency_total_ttc = 239.2;
  3873. $line->multicurrency_total_tva = 39.2;
  3874. $line->remise_percent = 0;
  3875. }
  3876. $this->lines[$xnbp] = $line;
  3877. $this->total_ht += $line->total_ht;
  3878. $this->total_tva += $line->total_tva;
  3879. $this->total_ttc += $line->total_ttc;
  3880. $this->multicurrency_total_ht += $line->multicurrency_total_ht;
  3881. $this->multicurrency_total_tva += $line->multicurrency_total_tva;
  3882. $this->multicurrency_total_ttc += $line->multicurrency_total_ttc;
  3883. $xnbp++;
  3884. }
  3885. $this->revenuestamp = 0;
  3886. // Add a line "offered"
  3887. $line = new FactureLigne($this->db);
  3888. $line->desc = $langs->trans("Description")." (offered line)";
  3889. $line->qty = 1;
  3890. $line->subprice = 100;
  3891. $line->tva_tx = 19.6;
  3892. $line->localtax1_tx = 0;
  3893. $line->localtax2_tx = 0;
  3894. $line->remise_percent = 100;
  3895. $line->total_ht = 0;
  3896. $line->total_ttc = 0; // 90 * 1.196
  3897. $line->total_tva = 0;
  3898. $line->multicurrency_total_ht = 0;
  3899. $line->multicurrency_total_ttc = 0;
  3900. $line->multicurrency_total_tva = 0;
  3901. $prodid = mt_rand(1, $num_prods);
  3902. $line->fk_product = $prodids[$prodid];
  3903. $this->lines[$xnbp] = $line;
  3904. $xnbp++;
  3905. }
  3906. }
  3907. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3908. /**
  3909. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  3910. *
  3911. * @return int <0 if KO, >0 if OK
  3912. */
  3913. public function load_state_board()
  3914. {
  3915. // phpcs:enable
  3916. global $conf, $user;
  3917. $this->nb = array();
  3918. $clause = "WHERE";
  3919. $sql = "SELECT count(f.rowid) as nb";
  3920. $sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
  3921. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid";
  3922. if (!$user->rights->societe->client->voir && !$user->socid) {
  3923. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc";
  3924. $sql .= " WHERE sc.fk_user = ".((int) $user->id);
  3925. $clause = "AND";
  3926. }
  3927. $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")";
  3928. $resql = $this->db->query($sql);
  3929. if ($resql) {
  3930. while ($obj = $this->db->fetch_object($resql)) {
  3931. $this->nb["invoices"] = $obj->nb;
  3932. }
  3933. $this->db->free($resql);
  3934. return 1;
  3935. } else {
  3936. dol_print_error($this->db);
  3937. $this->error = $this->db->error();
  3938. return -1;
  3939. }
  3940. }
  3941. /**
  3942. * Create an array of invoice lines
  3943. *
  3944. * @return int >0 if OK, <0 if KO
  3945. */
  3946. public function getLinesArray()
  3947. {
  3948. return $this->fetch_lines();
  3949. }
  3950. /**
  3951. * Create a document onto disk according to template module.
  3952. *
  3953. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model','alpha') for example.
  3954. * @param Translate $outputlangs Object lang to use for translation
  3955. * @param int $hidedetails Hide details of lines
  3956. * @param int $hidedesc Hide description
  3957. * @param int $hideref Hide ref
  3958. * @param null|array $moreparams Array to provide more information
  3959. * @return int <0 if KO, >0 if OK
  3960. */
  3961. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  3962. {
  3963. global $conf, $langs;
  3964. $outputlangs->loadLangs(array("bills", "products"));
  3965. if (!dol_strlen($modele)) {
  3966. $modele = 'crabe';
  3967. $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type;
  3968. if (!empty($this->model_pdf)) {
  3969. $modele = $this->model_pdf;
  3970. } elseif (!empty($this->modelpdf)) { // deprecated
  3971. $modele = $this->modelpdf;
  3972. } elseif (!empty($conf->global->$thisTypeConfName)) {
  3973. $modele = $conf->global->$thisTypeConfName;
  3974. } elseif (!empty($conf->global->FACTURE_ADDON_PDF)) {
  3975. $modele = $conf->global->FACTURE_ADDON_PDF;
  3976. }
  3977. }
  3978. $modelpath = "core/modules/facture/doc/";
  3979. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  3980. }
  3981. /**
  3982. * Gets the smallest reference available for a new cycle
  3983. *
  3984. * @return int >= 1 if OK, -1 if error
  3985. */
  3986. public function newCycle()
  3987. {
  3988. $sql = 'SELECT max(situation_cycle_ref) FROM '.MAIN_DB_PREFIX.'facture as f';
  3989. $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")";
  3990. $resql = $this->db->query($sql);
  3991. if ($resql) {
  3992. if ($resql->num_rows > 0) {
  3993. $res = $this->db->fetch_array($resql);
  3994. $ref = $res['max(situation_cycle_ref)'];
  3995. $ref++;
  3996. } else {
  3997. $ref = 1;
  3998. }
  3999. $this->db->free($resql);
  4000. return $ref;
  4001. } else {
  4002. $this->error = $this->db->lasterror();
  4003. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4004. return -1;
  4005. }
  4006. }
  4007. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4008. /**
  4009. * Checks if the invoice is the first of a cycle
  4010. *
  4011. * @return boolean
  4012. */
  4013. public function is_first()
  4014. {
  4015. // phpcs:enable
  4016. return ($this->situation_counter == 1);
  4017. }
  4018. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4019. /**
  4020. * Returns an array containing the previous situations as Facture objects
  4021. *
  4022. * @return mixed -1 if error, array of previous situations
  4023. */
  4024. public function get_prev_sits()
  4025. {
  4026. // phpcs:enable
  4027. global $conf;
  4028. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'facture';
  4029. $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
  4030. $sql .= ' AND situation_counter < '.((int) $this->situation_counter);
  4031. $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
  4032. $resql = $this->db->query($sql);
  4033. $res = array();
  4034. if ($resql && $resql->num_rows > 0) {
  4035. while ($row = $this->db->fetch_object($resql)) {
  4036. $id = $row->rowid;
  4037. $situation = new Facture($this->db);
  4038. $situation->fetch($id);
  4039. $res[] = $situation;
  4040. }
  4041. } else {
  4042. $this->error = $this->db->error();
  4043. dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
  4044. return -1;
  4045. }
  4046. return $res;
  4047. }
  4048. /**
  4049. * Sets the invoice as a final situation
  4050. *
  4051. * @param User $user Object user
  4052. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  4053. * @return int <0 if KO, >0 if OK
  4054. */
  4055. public function setFinal(User $user, $notrigger = 0)
  4056. {
  4057. $error = 0;
  4058. $this->db->begin();
  4059. $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET situation_final = '.((int) $this->situation_final).' WHERE rowid = '.((int) $this->id);
  4060. dol_syslog(__METHOD__, LOG_DEBUG);
  4061. $resql = $this->db->query($sql);
  4062. if (!$resql) {
  4063. $this->errors[] = $this->db->error();
  4064. $error++;
  4065. }
  4066. if (!$notrigger && empty($error)) {
  4067. // Call trigger
  4068. $result = $this->call_trigger('BILL_MODIFY', $user);
  4069. if ($result < 0) {
  4070. $error++;
  4071. }
  4072. // End call triggers
  4073. }
  4074. if (!$error) {
  4075. $this->db->commit();
  4076. return 1;
  4077. } else {
  4078. foreach ($this->errors as $errmsg) {
  4079. dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR);
  4080. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  4081. }
  4082. $this->db->rollback();
  4083. return -1 * $error;
  4084. }
  4085. }
  4086. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4087. /**
  4088. * Checks if the invoice is the last in its cycle
  4089. *
  4090. * @return bool Last of the cycle status
  4091. */
  4092. public function is_last_in_cycle()
  4093. {
  4094. // phpcs:enable
  4095. global $conf;
  4096. if (!empty($this->situation_cycle_ref)) {
  4097. // No point in testing anything if we're not inside a cycle
  4098. $sql = 'SELECT max(situation_counter) FROM '.MAIN_DB_PREFIX.'facture';
  4099. $sql .= ' WHERE situation_cycle_ref = '.((int) $this->situation_cycle_ref);
  4100. $sql .= ' AND entity = '.($this->entity > 0 ? $this->entity : $conf->entity);
  4101. $resql = $this->db->query($sql);
  4102. if ($resql && $resql->num_rows > 0) {
  4103. $res = $this->db->fetch_array($resql);
  4104. $last = $res['max(situation_counter)'];
  4105. return ($last == $this->situation_counter);
  4106. } else {
  4107. $this->error = $this->db->lasterror();
  4108. dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
  4109. return false;
  4110. }
  4111. } else {
  4112. return true;
  4113. }
  4114. }
  4115. /**
  4116. * Function used to replace a thirdparty id with another one.
  4117. *
  4118. * @param DoliDB $db Database handler
  4119. * @param int $origin_id Old third-party id
  4120. * @param int $dest_id New third-party id
  4121. * @return bool
  4122. */
  4123. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  4124. {
  4125. $tables = array(
  4126. 'facture'
  4127. );
  4128. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  4129. }
  4130. /**
  4131. * Is the customer invoice delayed?
  4132. *
  4133. * @return bool
  4134. */
  4135. public function hasDelay()
  4136. {
  4137. global $conf;
  4138. $now = dol_now();
  4139. // Paid invoices have status STATUS_CLOSED
  4140. if ($this->statut != Facture::STATUS_VALIDATED) {
  4141. return false;
  4142. }
  4143. $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
  4144. if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) {
  4145. $totalpaye = $this->getSommePaiement();
  4146. $totalpaye = floatval($totalpaye);
  4147. $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount();
  4148. if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) {
  4149. if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) {
  4150. $hasDelay = 1;
  4151. } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) {
  4152. $hasDelay = 1;
  4153. } else {
  4154. $hasDelay = 0;
  4155. }
  4156. }
  4157. }
  4158. return $hasDelay;
  4159. }
  4160. /**
  4161. * Currently used for documents generation : to know if retained warranty need to be displayed
  4162. * @return bool
  4163. */
  4164. public function displayRetainedWarranty()
  4165. {
  4166. global $conf;
  4167. // TODO : add a flag on invoices to store this conf : INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION
  4168. // note : we dont need to test INVOICE_USE_RETAINED_WARRANTY because if $this->retained_warranty is not empty it's because it was set when this conf was active
  4169. $displayWarranty = false;
  4170. if (!empty($this->retained_warranty)) {
  4171. $displayWarranty = true;
  4172. if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
  4173. // Check if this situation invoice is 100% for real
  4174. $displayWarranty = false;
  4175. if (!empty($this->situation_final)) {
  4176. $displayWarranty = true;
  4177. } elseif (!empty($this->lines) && $this->status == Facture::STATUS_DRAFT) {
  4178. // $object->situation_final need validation to be done so this test is need for draft
  4179. $displayWarranty = true;
  4180. foreach ($this->lines as $i => $line) {
  4181. if ($line->product_type < 2 && $line->situation_percent < 100) {
  4182. $displayWarranty = false;
  4183. break;
  4184. }
  4185. }
  4186. }
  4187. }
  4188. }
  4189. return $displayWarranty;
  4190. }
  4191. /**
  4192. * @param int $rounding Minimum number of decimal to show. If 0, no change, if -1, we use min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT)
  4193. * @return number or -1 if not available
  4194. */
  4195. public function getRetainedWarrantyAmount($rounding = -1)
  4196. {
  4197. global $conf;
  4198. if (empty($this->retained_warranty)) {
  4199. return -1;
  4200. }
  4201. $retainedWarrantyAmount = 0;
  4202. // Billed - retained warranty
  4203. if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) {
  4204. $displayWarranty = true;
  4205. // Check if this situation invoice is 100% for real
  4206. if (!empty($this->lines)) {
  4207. foreach ($this->lines as $i => $line) {
  4208. if ($line->product_type < 2 && $line->situation_percent < 100) {
  4209. $displayWarranty = false;
  4210. break;
  4211. }
  4212. }
  4213. }
  4214. if ($displayWarranty && !empty($this->situation_final)) {
  4215. $this->fetchPreviousNextSituationInvoice();
  4216. $TPreviousIncoice = $this->tab_previous_situation_invoice;
  4217. $total2BillWT = 0;
  4218. foreach ($TPreviousIncoice as &$fac) {
  4219. $total2BillWT += $fac->total_ttc;
  4220. }
  4221. $total2BillWT += $this->total_ttc;
  4222. $retainedWarrantyAmount = $total2BillWT * $this->retained_warranty / 100;
  4223. } else {
  4224. return -1;
  4225. }
  4226. } else {
  4227. // Because one day retained warranty could be used on standard invoices
  4228. $retainedWarrantyAmount = $this->total_ttc * $this->retained_warranty / 100;
  4229. }
  4230. if ($rounding < 0) {
  4231. $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
  4232. }
  4233. if ($rounding > 0) {
  4234. return round($retainedWarrantyAmount, $rounding);
  4235. }
  4236. return $retainedWarrantyAmount;
  4237. }
  4238. /**
  4239. * Change the retained warranty
  4240. *
  4241. * @param float $value value of retained warranty
  4242. * @return int >0 if OK, <0 if KO
  4243. */
  4244. public function setRetainedWarranty($value)
  4245. {
  4246. dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')');
  4247. if ($this->statut >= 0) {
  4248. $fieldname = 'retained_warranty';
  4249. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  4250. $sql .= " SET ".$fieldname." = ".((float) $value);
  4251. $sql .= ' WHERE rowid='.((int) $this->id);
  4252. if ($this->db->query($sql)) {
  4253. $this->retained_warranty = floatval($value);
  4254. return 1;
  4255. } else {
  4256. dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error());
  4257. $this->error = $this->db->error();
  4258. return -1;
  4259. }
  4260. } else {
  4261. dol_syslog(get_class($this).'::setRetainedWarranty, status of the object is incompatible');
  4262. $this->error = 'Status of the object is incompatible '.$this->statut;
  4263. return -2;
  4264. }
  4265. }
  4266. /**
  4267. * Change the retained_warranty_date_limit
  4268. *
  4269. * @param int $timestamp date limit of retained warranty in timestamp format
  4270. * @param string $dateYmd date limit of retained warranty in Y m d format
  4271. * @return int >0 if OK, <0 if KO
  4272. */
  4273. public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false)
  4274. {
  4275. if (!$timestamp && $dateYmd) {
  4276. $timestamp = $this->db->jdate($dateYmd);
  4277. }
  4278. dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')');
  4279. if ($this->statut >= 0) {
  4280. $fieldname = 'retained_warranty_date_limit';
  4281. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
  4282. $sql .= " SET ".$fieldname." = ".(strval($timestamp) != '' ? "'".$this->db->idate($timestamp)."'" : 'null');
  4283. $sql .= ' WHERE rowid = '.((int) $this->id);
  4284. if ($this->db->query($sql)) {
  4285. $this->retained_warranty_date_limit = $timestamp;
  4286. return 1;
  4287. } else {
  4288. dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit Erreur '.$sql.' - '.$this->db->error());
  4289. $this->error = $this->db->error();
  4290. return -1;
  4291. }
  4292. } else {
  4293. dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit, status of the object is incompatible');
  4294. $this->error = 'Status of the object is incompatible '.$this->statut;
  4295. return -2;
  4296. }
  4297. }
  4298. /**
  4299. * Send reminders by emails for ivoices that are due
  4300. * CAN BE A CRON TASK
  4301. *
  4302. * @param int $nbdays Delay after due date (or before if delay is negative)
  4303. * @param string $paymentmode '' or 'all' by default (no filter), or 'LIQ', 'CHQ', CB', ...
  4304. * @param int|string $template Name (or id) of email template (Must be a template of type 'facture_send')
  4305. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  4306. */
  4307. public function sendEmailsRemindersOnInvoiceDueDate($nbdays = 0, $paymentmode = 'all', $template = '')
  4308. {
  4309. global $conf, $langs, $user;
  4310. $error = 0;
  4311. $this->output = '';
  4312. $this->error = '';
  4313. $nbMailSend = 0;
  4314. $errorsMsg = array();
  4315. $langs->load("bills");
  4316. if (empty($conf->facture->enabled)) { // Should not happen. If module disabled, cron job should not be visible.
  4317. $this->output .= $langs->trans('ModuleNotEnabled', $langs->transnoentitiesnoconv("Facture"));
  4318. return 0;
  4319. }
  4320. /*if (empty($conf->global->FACTURE_REMINDER_EMAIL)) {
  4321. $langs->load("bills");
  4322. $this->output .= $langs->trans('EventRemindersByEmailNotEnabled', $langs->transnoentitiesnoconv("Facture"));
  4323. return 0;
  4324. }
  4325. */
  4326. require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
  4327. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
  4328. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  4329. $formmail = new FormMail($this->db);
  4330. $now = dol_now();
  4331. $tmpidate = dol_get_first_hour(dol_time_plus_duree($now, $nbdays, 'd'), 'gmt');
  4332. $tmpinvoice = new Facture($this->db);
  4333. dol_syslog(__METHOD__, LOG_DEBUG);
  4334. $this->db->begin();
  4335. //Select all action comm reminder
  4336. $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."facture as f";
  4337. if (!empty($paymentmode) && $paymentmode != 'all') {
  4338. $sql .= ", ".MAIN_DB_PREFIX."c_paiement as cp";
  4339. }
  4340. $sql .= " WHERE f.paye = 0";
  4341. $sql .= " AND f.date_lim_reglement = '".$this->db->idate($tmpidate, 'gmt')."'";
  4342. $sql .= " AND f.entity IN (".getEntity('facture').")";
  4343. if (!empty($paymentmode) && $paymentmode != 'all') {
  4344. $sql .= " AND f.fk_mode_reglement = cp.id AND cp.code = '".$this->db->escape($paymentmode)."'";
  4345. }
  4346. // TODO Add filter to check there is no payment started
  4347. $sql .= $this->db->order("date_lim_reglement", "ASC");
  4348. $resql = $this->db->query($sql);
  4349. $stmpidate = dol_print_date($tmpidate, 'day', 'gmt');
  4350. $this->output .= $langs->transnoentitiesnoconv("SearchUnpaidInvoicesWithDueDate", $stmpidate);
  4351. if (!empty($paymentmode) && $paymentmode != 'all') {
  4352. $this->output .= ' ('.$langs->transnoentitiesnoconv("PaymentMode").' '.$paymentmode.')';
  4353. }
  4354. $this->output .= '<br>';
  4355. if ($resql) {
  4356. while ($obj = $this->db->fetch_object($resql)) {
  4357. if (!$error) {
  4358. // Load event
  4359. $res = $tmpinvoice->fetch($obj->id);
  4360. if ($res > 0) {
  4361. $tmpinvoice->fetch_thirdparty();
  4362. $outputlangs = new Translate('', $conf);
  4363. if ($tmpinvoice->thirdparty->default_lang) {
  4364. $outputlangs->setDefaultLang($tmpinvoice->thirdparty->default_lang);
  4365. $outputlangs->loadLangs(array("main", "bills"));
  4366. } else {
  4367. $outputlangs = $langs;
  4368. }
  4369. // Select email template
  4370. $arraymessage = $formmail->getEMailTemplate($this->db, 'facture_send', $user, $outputlangs, (is_numeric($template) ? $template : 0), 1, (is_numeric($template) ? '' : $template));
  4371. if (is_numeric($arraymessage) && $arraymessage <= 0) {
  4372. $langs->load("errors");
  4373. $this->output .= $langs->trans('ErrorFailedToFindEmailTemplate', $template);
  4374. return 0;
  4375. }
  4376. // PREPARE EMAIL
  4377. $errormesg = '';
  4378. // Make substitution in email content
  4379. $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, '', $tmpinvoice);
  4380. complete_substitutions_array($substitutionarray, $outputlangs, $tmpinvoice);
  4381. // Topic
  4382. $sendTopic = make_substitutions(empty($arraymessage->topic) ? $outputlangs->transnoentitiesnoconv('InformationMessage') : $arraymessage->topic, $substitutionarray, $outputlangs, 1);
  4383. // Content
  4384. $content = $outputlangs->transnoentitiesnoconv($arraymessage->content);
  4385. $sendContent = make_substitutions($content, $substitutionarray, $outputlangs, 1);
  4386. // Recipient
  4387. $res = $tmpinvoice->fetch_thirdparty();
  4388. $recipient = $tmpinvoice->thirdparty;
  4389. if ($res > 0) {
  4390. if (!empty($recipient->email)) {
  4391. $to = $recipient->email;
  4392. } else {
  4393. $errormesg = "Failed to send remind to thirdparty id=".$tmpinvoice->fk_soc.". No email defined for user.";
  4394. $error++;
  4395. }
  4396. } else {
  4397. $errormesg = "Failed to load recipient with thirdparty id=".$tmpinvoice->fk_soc;
  4398. $error++;
  4399. }
  4400. // Sender
  4401. $from = $conf->global->MAIN_MAIL_EMAIL_FROM;
  4402. if (empty($from)) {
  4403. $errormesg = "Failed to get sender into global setup MAIN_MAIL_EMAIL_FROM";
  4404. $error++;
  4405. }
  4406. if (!$error) {
  4407. // Errors Recipient
  4408. $errors_to = $conf->global->MAIN_MAIL_ERRORS_TO;
  4409. $trackid = 'inv'.$tmpinvoice->id;
  4410. // Mail Creation
  4411. $cMailFile = new CMailFile($sendTopic, $to, $from, $sendContent, array(), array(), array(), '', "", 0, 1, $errors_to, '', $trackid, '', '', '');
  4412. // Sending Mail
  4413. if ($cMailFile->sendfile()) {
  4414. $nbMailSend++;
  4415. } else {
  4416. $errormesg = $cMailFile->error.' : '.$to;
  4417. $error++;
  4418. }
  4419. }
  4420. if ($errormesg) {
  4421. $errorsMsg[] = $errormesg;
  4422. }
  4423. } else {
  4424. $errorsMsg[] = 'Failed to fetch record invoice with ID = '.$obj->id;
  4425. $error++;
  4426. }
  4427. }
  4428. }
  4429. } else {
  4430. $error++;
  4431. }
  4432. if (!$error) {
  4433. $this->output .= 'Nb of emails sent : '.$nbMailSend;
  4434. $this->db->commit();
  4435. return 0;
  4436. } else {
  4437. $this->db->commit(); // We commit also on error, to have the error message recorded.
  4438. $this->error = 'Nb of emails sent : '.$nbMailSend.', '.(!empty($errorsMsg)) ? join(', ', $errorsMsg) : $error;
  4439. return $error;
  4440. }
  4441. }
  4442. }
  4443. /**
  4444. * Class to manage invoice lines.
  4445. * Saved into database table llx_facturedet
  4446. */
  4447. class FactureLigne extends CommonInvoiceLine
  4448. {
  4449. /**
  4450. * @var string ID to identify managed object
  4451. */
  4452. public $element = 'facturedet';
  4453. /**
  4454. * @var string Name of table without prefix where object is stored
  4455. */
  4456. public $table_element = 'facturedet';
  4457. public $oldline;
  4458. //! From llx_facturedet
  4459. //! Id facture
  4460. public $fk_facture;
  4461. //! Id parent line
  4462. public $fk_parent_line;
  4463. //! Description ligne
  4464. public $desc;
  4465. public $ref_ext; // External reference of the line
  4466. public $localtax1_type; // Local tax 1 type
  4467. public $localtax2_type; // Local tax 2 type
  4468. public $fk_remise_except; // Link to line into llx_remise_except
  4469. public $rang = 0;
  4470. public $fk_fournprice;
  4471. public $pa_ht;
  4472. public $marge_tx;
  4473. public $marque_tx;
  4474. public $remise_percent;
  4475. public $special_code; // Liste d'options non cumulabels:
  4476. // 1: frais de port
  4477. // 2: ecotaxe
  4478. // 3: ??
  4479. public $origin;
  4480. public $origin_id;
  4481. public $fk_code_ventilation = 0;
  4482. public $date_start;
  4483. public $date_end;
  4484. public $skip_update_total; // Skip update price total for special lines
  4485. /**
  4486. * @var int Situation advance percentage
  4487. */
  4488. public $situation_percent;
  4489. /**
  4490. * @var int Previous situation line id reference
  4491. */
  4492. public $fk_prev_id;
  4493. // Multicurrency
  4494. public $fk_multicurrency;
  4495. public $multicurrency_code;
  4496. public $multicurrency_subprice;
  4497. public $multicurrency_total_ht;
  4498. public $multicurrency_total_tva;
  4499. public $multicurrency_total_ttc;
  4500. /**
  4501. * Load invoice line from database
  4502. *
  4503. * @param int $rowid id of invoice line to get
  4504. * @return int <0 if KO, >0 if OK
  4505. */
  4506. public function fetch($rowid)
  4507. {
  4508. $sql = 'SELECT fd.rowid, fd.fk_facture, fd.fk_parent_line, fd.fk_product, fd.product_type, fd.label as custom_label, fd.description, fd.price, fd.qty, fd.vat_src_code, fd.tva_tx,';
  4509. $sql .= ' fd.localtax1_tx, fd. localtax2_tx, fd.remise, fd.remise_percent, fd.fk_remise_except, fd.subprice, fd.ref_ext,';
  4510. $sql .= ' fd.date_start as date_start, fd.date_end as date_end, fd.fk_product_fournisseur_price as fk_fournprice, fd.buy_price_ht as pa_ht,';
  4511. $sql .= ' fd.info_bits, fd.special_code, fd.total_ht, fd.total_tva, fd.total_ttc, fd.total_localtax1, fd.total_localtax2, fd.rang,';
  4512. $sql .= ' fd.fk_code_ventilation,';
  4513. $sql .= ' fd.fk_unit, fd.fk_user_author, fd.fk_user_modif,';
  4514. $sql .= ' fd.situation_percent, fd.fk_prev_id,';
  4515. $sql .= ' fd.multicurrency_subprice,';
  4516. $sql .= ' fd.multicurrency_total_ht,';
  4517. $sql .= ' fd.multicurrency_total_tva,';
  4518. $sql .= ' fd.multicurrency_total_ttc,';
  4519. $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc';
  4520. $sql .= ' FROM '.MAIN_DB_PREFIX.'facturedet as fd';
  4521. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON fd.fk_product = p.rowid';
  4522. $sql .= ' WHERE fd.rowid = '.((int) $rowid);
  4523. $result = $this->db->query($sql);
  4524. if ($result) {
  4525. $objp = $this->db->fetch_object($result);
  4526. $this->rowid = $objp->rowid;
  4527. $this->id = $objp->rowid;
  4528. $this->fk_facture = $objp->fk_facture;
  4529. $this->fk_parent_line = $objp->fk_parent_line;
  4530. $this->label = $objp->custom_label;
  4531. $this->desc = $objp->description;
  4532. $this->qty = $objp->qty;
  4533. $this->subprice = $objp->subprice;
  4534. $this->ref_ext = $objp->ref_ext;
  4535. $this->vat_src_code = $objp->vat_src_code;
  4536. $this->tva_tx = $objp->tva_tx;
  4537. $this->localtax1_tx = $objp->localtax1_tx;
  4538. $this->localtax2_tx = $objp->localtax2_tx;
  4539. $this->remise_percent = $objp->remise_percent;
  4540. $this->fk_remise_except = $objp->fk_remise_except;
  4541. $this->fk_product = $objp->fk_product;
  4542. $this->product_type = $objp->product_type;
  4543. $this->date_start = $this->db->jdate($objp->date_start);
  4544. $this->date_end = $this->db->jdate($objp->date_end);
  4545. $this->info_bits = $objp->info_bits;
  4546. $this->tva_npr = ($objp->info_bits & 1 == 1) ? 1 : 0;
  4547. $this->special_code = $objp->special_code;
  4548. $this->total_ht = $objp->total_ht;
  4549. $this->total_tva = $objp->total_tva;
  4550. $this->total_localtax1 = $objp->total_localtax1;
  4551. $this->total_localtax2 = $objp->total_localtax2;
  4552. $this->total_ttc = $objp->total_ttc;
  4553. $this->fk_code_ventilation = $objp->fk_code_ventilation;
  4554. $this->rang = $objp->rang;
  4555. $this->fk_fournprice = $objp->fk_fournprice;
  4556. $marginInfos = getMarginInfos($objp->subprice, $objp->remise_percent, $objp->tva_tx, $objp->localtax1_tx, $objp->localtax2_tx, $this->fk_fournprice, $objp->pa_ht);
  4557. $this->pa_ht = $marginInfos[0];
  4558. $this->marge_tx = $marginInfos[1];
  4559. $this->marque_tx = $marginInfos[2];
  4560. $this->ref = $objp->product_ref; // deprecated
  4561. $this->product_ref = $objp->product_ref;
  4562. $this->product_label = $objp->product_label;
  4563. $this->product_desc = $objp->product_desc;
  4564. $this->fk_unit = $objp->fk_unit;
  4565. $this->fk_user_modif = $objp->fk_user_modif;
  4566. $this->fk_user_author = $objp->fk_user_author;
  4567. $this->situation_percent = $objp->situation_percent;
  4568. $this->fk_prev_id = $objp->fk_prev_id;
  4569. $this->multicurrency_subprice = $objp->multicurrency_subprice;
  4570. $this->multicurrency_total_ht = $objp->multicurrency_total_ht;
  4571. $this->multicurrency_total_tva = $objp->multicurrency_total_tva;
  4572. $this->multicurrency_total_ttc = $objp->multicurrency_total_ttc;
  4573. $this->db->free($result);
  4574. return 1;
  4575. } else {
  4576. $this->error = $this->db->lasterror();
  4577. return -1;
  4578. }
  4579. }
  4580. /**
  4581. * Insert line into database
  4582. *
  4583. * @param int $notrigger 1 no triggers
  4584. * @param int $noerrorifdiscountalreadylinked 1=Do not make error if lines is linked to a discount and discount already linked to another
  4585. * @return int <0 if KO, >0 if OK
  4586. */
  4587. public function insert($notrigger = 0, $noerrorifdiscountalreadylinked = 0)
  4588. {
  4589. global $langs, $user, $conf;
  4590. $error = 0;
  4591. $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
  4592. dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
  4593. // Clean parameters
  4594. $this->desc = trim($this->desc);
  4595. if (empty($this->tva_tx)) {
  4596. $this->tva_tx = 0;
  4597. }
  4598. if (empty($this->localtax1_tx)) {
  4599. $this->localtax1_tx = 0;
  4600. }
  4601. if (empty($this->localtax2_tx)) {
  4602. $this->localtax2_tx = 0;
  4603. }
  4604. if (empty($this->localtax1_type)) {
  4605. $this->localtax1_type = 0;
  4606. }
  4607. if (empty($this->localtax2_type)) {
  4608. $this->localtax2_type = 0;
  4609. }
  4610. if (empty($this->total_localtax1)) {
  4611. $this->total_localtax1 = 0;
  4612. }
  4613. if (empty($this->total_localtax2)) {
  4614. $this->total_localtax2 = 0;
  4615. }
  4616. if (empty($this->rang)) {
  4617. $this->rang = 0;
  4618. }
  4619. if (empty($this->remise_percent)) {
  4620. $this->remise_percent = 0;
  4621. }
  4622. if (empty($this->info_bits)) {
  4623. $this->info_bits = 0;
  4624. }
  4625. if (empty($this->subprice)) {
  4626. $this->subprice = 0;
  4627. }
  4628. if (empty($this->ref_ext)) {
  4629. $this->ref_ext = '';
  4630. }
  4631. if (empty($this->special_code)) {
  4632. $this->special_code = 0;
  4633. }
  4634. if (empty($this->fk_parent_line)) {
  4635. $this->fk_parent_line = 0;
  4636. }
  4637. if (empty($this->fk_prev_id)) {
  4638. $this->fk_prev_id = 0;
  4639. }
  4640. if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
  4641. $this->situation_percent = 100;
  4642. }
  4643. if (empty($this->pa_ht)) {
  4644. $this->pa_ht = 0;
  4645. }
  4646. if (empty($this->multicurrency_subprice)) {
  4647. $this->multicurrency_subprice = 0;
  4648. }
  4649. if (empty($this->multicurrency_total_ht)) {
  4650. $this->multicurrency_total_ht = 0;
  4651. }
  4652. if (empty($this->multicurrency_total_tva)) {
  4653. $this->multicurrency_total_tva = 0;
  4654. }
  4655. if (empty($this->multicurrency_total_ttc)) {
  4656. $this->multicurrency_total_ttc = 0;
  4657. }
  4658. // if buy price not defined, define buyprice as configured in margin admin
  4659. if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
  4660. if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) {
  4661. return $result;
  4662. } else {
  4663. $this->pa_ht = $result;
  4664. }
  4665. }
  4666. // Check parameters
  4667. if ($this->product_type < 0) {
  4668. $this->error = 'ErrorProductTypeMustBe0orMore';
  4669. return -1;
  4670. }
  4671. if (!empty($this->fk_product) && $this->fk_product > 0) {
  4672. // Check product exists
  4673. $result = Product::isExistingObject('product', $this->fk_product);
  4674. if ($result <= 0) {
  4675. $this->error = 'ErrorProductIdDoesNotExists';
  4676. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  4677. return -1;
  4678. }
  4679. }
  4680. $this->db->begin();
  4681. // Insertion dans base de la ligne
  4682. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facturedet';
  4683. $sql .= ' (fk_facture, fk_parent_line, label, description, qty,';
  4684. $sql .= ' vat_src_code, tva_tx, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type,';
  4685. $sql .= ' fk_product, product_type, remise_percent, subprice, ref_ext, fk_remise_except,';
  4686. $sql .= ' date_start, date_end, fk_code_ventilation, ';
  4687. $sql .= ' rang, special_code, fk_product_fournisseur_price, buy_price_ht,';
  4688. $sql .= ' info_bits, total_ht, total_tva, total_ttc, total_localtax1, total_localtax2,';
  4689. $sql .= ' situation_percent, fk_prev_id,';
  4690. $sql .= ' fk_unit, fk_user_author, fk_user_modif,';
  4691. $sql .= ' fk_multicurrency, multicurrency_code, multicurrency_subprice, multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
  4692. $sql .= ')';
  4693. $sql .= " VALUES (".$this->fk_facture.",";
  4694. $sql .= " ".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null").",";
  4695. $sql .= " ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
  4696. $sql .= " '".$this->db->escape($this->desc)."',";
  4697. $sql .= " ".price2num($this->qty).",";
  4698. $sql .= " ".(empty($this->vat_src_code) ? "''" : "'".$this->db->escape($this->vat_src_code)."'").",";
  4699. $sql .= " ".price2num($this->tva_tx).",";
  4700. $sql .= " ".price2num($this->localtax1_tx).",";
  4701. $sql .= " ".price2num($this->localtax2_tx).",";
  4702. $sql .= " '".$this->db->escape($this->localtax1_type)."',";
  4703. $sql .= " '".$this->db->escape($this->localtax2_type)."',";
  4704. $sql .= ' '.((!empty($this->fk_product) && $this->fk_product > 0) ? $this->fk_product : "null").',';
  4705. $sql .= " ".((int) $this->product_type).",";
  4706. $sql .= " ".price2num($this->remise_percent).",";
  4707. $sql .= " ".price2num($this->subprice).",";
  4708. $sql .= " '".$this->db->escape($this->ref_ext)."',";
  4709. $sql .= ' '.(!empty($this->fk_remise_except) ? $this->fk_remise_except : "null").',';
  4710. $sql .= " ".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null").",";
  4711. $sql .= " ".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null").",";
  4712. $sql .= ' '.((int) $this->fk_code_ventilation).',';
  4713. $sql .= ' '.((int) $this->rang).',';
  4714. $sql .= ' '.((int) $this->special_code).',';
  4715. $sql .= ' '.(!empty($this->fk_fournprice) ? $this->fk_fournprice : "null").',';
  4716. $sql .= ' '.price2num($this->pa_ht).',';
  4717. $sql .= " '".$this->db->escape($this->info_bits)."',";
  4718. $sql .= " ".price2num($this->total_ht).",";
  4719. $sql .= " ".price2num($this->total_tva).",";
  4720. $sql .= " ".price2num($this->total_ttc).",";
  4721. $sql .= " ".price2num($this->total_localtax1).",";
  4722. $sql .= " ".price2num($this->total_localtax2);
  4723. $sql .= ", ".((float) $this->situation_percent);
  4724. $sql .= ", ".(!empty($this->fk_prev_id) ? $this->fk_prev_id : "null");
  4725. $sql .= ", ".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  4726. $sql .= ", ".((int) $user->id);
  4727. $sql .= ", ".((int) $user->id);
  4728. $sql .= ", ".(int) $this->fk_multicurrency;
  4729. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  4730. $sql .= ", ".price2num($this->multicurrency_subprice);
  4731. $sql .= ", ".price2num($this->multicurrency_total_ht);
  4732. $sql .= ", ".price2num($this->multicurrency_total_tva);
  4733. $sql .= ", ".price2num($this->multicurrency_total_ttc);
  4734. $sql .= ')';
  4735. dol_syslog(get_class($this)."::insert", LOG_DEBUG);
  4736. $resql = $this->db->query($sql);
  4737. if ($resql) {
  4738. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet');
  4739. $this->rowid = $this->id; // For backward compatibility
  4740. if (!$error) {
  4741. $result = $this->insertExtraFields();
  4742. if ($result < 0) {
  4743. $error++;
  4744. }
  4745. }
  4746. // Si fk_remise_except defini, on lie la remise a la facture
  4747. // ce qui la flague comme "consommee".
  4748. if ($this->fk_remise_except) {
  4749. $discount = new DiscountAbsolute($this->db);
  4750. $result = $discount->fetch($this->fk_remise_except);
  4751. if ($result >= 0) {
  4752. // Check if discount was found
  4753. if ($result > 0) {
  4754. // Check if discount not already affected to another invoice
  4755. if ($discount->fk_facture_line > 0) {
  4756. if (empty($noerrorifdiscountalreadylinked)) {
  4757. $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id);
  4758. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  4759. $this->db->rollback();
  4760. return -3;
  4761. }
  4762. } else {
  4763. $result = $discount->link_to_invoice($this->rowid, 0);
  4764. if ($result < 0) {
  4765. $this->error = $discount->error;
  4766. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  4767. $this->db->rollback();
  4768. return -3;
  4769. }
  4770. }
  4771. } else {
  4772. $this->error = $langs->trans("ErrorADiscountThatHasBeenRemovedIsIncluded");
  4773. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  4774. $this->db->rollback();
  4775. return -3;
  4776. }
  4777. } else {
  4778. $this->error = $discount->error;
  4779. dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR);
  4780. $this->db->rollback();
  4781. return -3;
  4782. }
  4783. }
  4784. if (!$notrigger) {
  4785. // Call trigger
  4786. $result = $this->call_trigger('LINEBILL_INSERT', $user);
  4787. if ($result < 0) {
  4788. $this->db->rollback();
  4789. return -2;
  4790. }
  4791. // End call triggers
  4792. }
  4793. $this->db->commit();
  4794. return $this->id;
  4795. } else {
  4796. $this->error = $this->db->lasterror();
  4797. $this->db->rollback();
  4798. return -2;
  4799. }
  4800. }
  4801. /**
  4802. * Update line into database
  4803. *
  4804. * @param User $user User object
  4805. * @param int $notrigger Disable triggers
  4806. * @return int <0 if KO, >0 if OK
  4807. */
  4808. public function update($user = '', $notrigger = 0)
  4809. {
  4810. global $user, $conf;
  4811. $error = 0;
  4812. $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
  4813. // Clean parameters
  4814. $this->desc = trim($this->desc);
  4815. if (empty($this->ref_ext)) {
  4816. $this->ref_ext = '';
  4817. }
  4818. if (empty($this->tva_tx)) {
  4819. $this->tva_tx = 0;
  4820. }
  4821. if (empty($this->localtax1_tx)) {
  4822. $this->localtax1_tx = 0;
  4823. }
  4824. if (empty($this->localtax2_tx)) {
  4825. $this->localtax2_tx = 0;
  4826. }
  4827. if (empty($this->localtax1_type)) {
  4828. $this->localtax1_type = 0;
  4829. }
  4830. if (empty($this->localtax2_type)) {
  4831. $this->localtax2_type = 0;
  4832. }
  4833. if (empty($this->total_localtax1)) {
  4834. $this->total_localtax1 = 0;
  4835. }
  4836. if (empty($this->total_localtax2)) {
  4837. $this->total_localtax2 = 0;
  4838. }
  4839. if (empty($this->remise_percent)) {
  4840. $this->remise_percent = 0;
  4841. }
  4842. if (empty($this->info_bits)) {
  4843. $this->info_bits = 0;
  4844. }
  4845. if (empty($this->special_code)) {
  4846. $this->special_code = 0;
  4847. }
  4848. if (empty($this->product_type)) {
  4849. $this->product_type = 0;
  4850. }
  4851. if (empty($this->fk_parent_line)) {
  4852. $this->fk_parent_line = 0;
  4853. }
  4854. if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') {
  4855. $this->situation_percent = 100;
  4856. }
  4857. if (empty($this->pa_ht)) {
  4858. $this->pa_ht = 0;
  4859. }
  4860. if (empty($this->multicurrency_subprice)) {
  4861. $this->multicurrency_subprice = 0;
  4862. }
  4863. if (empty($this->multicurrency_total_ht)) {
  4864. $this->multicurrency_total_ht = 0;
  4865. }
  4866. if (empty($this->multicurrency_total_tva)) {
  4867. $this->multicurrency_total_tva = 0;
  4868. }
  4869. if (empty($this->multicurrency_total_ttc)) {
  4870. $this->multicurrency_total_ttc = 0;
  4871. }
  4872. // Check parameters
  4873. if ($this->product_type < 0) {
  4874. return -1;
  4875. }
  4876. // if buy price not provided, define buyprice as configured in margin admin
  4877. if ($this->pa_ht == 0 && $pa_ht_isemptystring) {
  4878. // We call defineBuyPrice only if data was not provided (if input was '0', we will not go here and value will remaine '0')
  4879. $result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product);
  4880. if ($result < 0) {
  4881. return $result;
  4882. } else {
  4883. $this->pa_ht = $result;
  4884. }
  4885. }
  4886. $this->db->begin();
  4887. // Update line in database
  4888. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
  4889. $sql .= " description='".$this->db->escape($this->desc)."'";
  4890. $sql .= ", ref_ext='".$this->db->escape($this->ref_ext)."'";
  4891. $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
  4892. $sql .= ", subprice=".price2num($this->subprice)."";
  4893. $sql .= ", remise_percent=".price2num($this->remise_percent)."";
  4894. if ($this->fk_remise_except) {
  4895. $sql .= ", fk_remise_except=".$this->fk_remise_except;
  4896. } else {
  4897. $sql .= ", fk_remise_except=null";
  4898. }
  4899. $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'";
  4900. $sql .= ", tva_tx=".price2num($this->tva_tx)."";
  4901. $sql .= ", localtax1_tx=".price2num($this->localtax1_tx)."";
  4902. $sql .= ", localtax2_tx=".price2num($this->localtax2_tx)."";
  4903. $sql .= ", localtax1_type='".$this->db->escape($this->localtax1_type)."'";
  4904. $sql .= ", localtax2_type='".$this->db->escape($this->localtax2_type)."'";
  4905. $sql .= ", qty=".price2num($this->qty);
  4906. $sql .= ", date_start=".(!empty($this->date_start) ? "'".$this->db->idate($this->date_start)."'" : "null");
  4907. $sql .= ", date_end=".(!empty($this->date_end) ? "'".$this->db->idate($this->date_end)."'" : "null");
  4908. $sql .= ", product_type=".$this->product_type;
  4909. $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'";
  4910. $sql .= ", special_code='".$this->db->escape($this->special_code)."'";
  4911. if (empty($this->skip_update_total)) {
  4912. $sql .= ", total_ht=".price2num($this->total_ht);
  4913. $sql .= ", total_tva=".price2num($this->total_tva);
  4914. $sql .= ", total_ttc=".price2num($this->total_ttc);
  4915. $sql .= ", total_localtax1=".price2num($this->total_localtax1);
  4916. $sql .= ", total_localtax2=".price2num($this->total_localtax2);
  4917. }
  4918. $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null");
  4919. $sql .= ", buy_price_ht=".(($this->pa_ht || $this->pa_ht === 0 || $this->pa_ht === '0') ? price2num($this->pa_ht) : "null"); // $this->pa_ht should always be defined (set to 0 or to sell price depending on option)
  4920. $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null");
  4921. if (!empty($this->rang)) {
  4922. $sql .= ", rang=".((int) $this->rang);
  4923. }
  4924. $sql .= ", situation_percent=".$this->situation_percent;
  4925. $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
  4926. $sql .= ", fk_user_modif =".$user->id;
  4927. // Multicurrency
  4928. $sql .= ", multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
  4929. $sql .= ", multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
  4930. $sql .= ", multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
  4931. $sql .= ", multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
  4932. $sql .= " WHERE rowid = ".((int) $this->rowid);
  4933. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  4934. $resql = $this->db->query($sql);
  4935. if ($resql) {
  4936. if (!$error) {
  4937. $this->id = $this->rowid;
  4938. $result = $this->insertExtraFields();
  4939. if ($result < 0) {
  4940. $error++;
  4941. }
  4942. }
  4943. if (!$error && !$notrigger) {
  4944. // Call trigger
  4945. $result = $this->call_trigger('LINEBILL_UPDATE', $user);
  4946. if ($result < 0) {
  4947. $this->db->rollback();
  4948. return -2;
  4949. }
  4950. // End call triggers
  4951. }
  4952. $this->db->commit();
  4953. return 1;
  4954. } else {
  4955. $this->error = $this->db->error();
  4956. $this->db->rollback();
  4957. return -2;
  4958. }
  4959. }
  4960. /**
  4961. * Delete line in database
  4962. * TODO Add param User $user and notrigger (see skeleton)
  4963. *
  4964. * @return int <0 if KO, >0 if OK
  4965. */
  4966. public function delete()
  4967. {
  4968. global $user;
  4969. $this->db->begin();
  4970. // Call trigger
  4971. $result = $this->call_trigger('LINEBILL_DELETE', $user);
  4972. if ($result < 0) {
  4973. $this->db->rollback();
  4974. return -1;
  4975. }
  4976. // End call triggers
  4977. // extrafields
  4978. $result = $this->deleteExtraFields();
  4979. if ($result < 0) {
  4980. $this->db->rollback();
  4981. return -1;
  4982. }
  4983. $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".((int) $this->rowid);
  4984. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  4985. if ($this->db->query($sql)) {
  4986. $this->db->commit();
  4987. return 1;
  4988. } else {
  4989. $this->error = $this->db->error()." sql=".$sql;
  4990. $this->db->rollback();
  4991. return -1;
  4992. }
  4993. }
  4994. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4995. /**
  4996. * Update DB line fields total_xxx
  4997. * Used by migration
  4998. *
  4999. * @return int <0 if KO, >0 if OK
  5000. */
  5001. public function update_total()
  5002. {
  5003. // phpcs:enable
  5004. $this->db->begin();
  5005. dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
  5006. // Clean parameters
  5007. if (empty($this->total_localtax1)) {
  5008. $this->total_localtax1 = 0;
  5009. }
  5010. if (empty($this->total_localtax2)) {
  5011. $this->total_localtax2 = 0;
  5012. }
  5013. // Mise a jour ligne en base
  5014. $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET";
  5015. $sql .= " total_ht=".price2num($this->total_ht)."";
  5016. $sql .= ",total_tva=".price2num($this->total_tva)."";
  5017. $sql .= ",total_localtax1=".price2num($this->total_localtax1)."";
  5018. $sql .= ",total_localtax2=".price2num($this->total_localtax2)."";
  5019. $sql .= ",total_ttc=".price2num($this->total_ttc)."";
  5020. $sql .= " WHERE rowid = ".((int) $this->rowid);
  5021. dol_syslog(get_class($this)."::update_total", LOG_DEBUG);
  5022. $resql = $this->db->query($sql);
  5023. if ($resql) {
  5024. $this->db->commit();
  5025. return 1;
  5026. } else {
  5027. $this->error = $this->db->error();
  5028. $this->db->rollback();
  5029. return -2;
  5030. }
  5031. }
  5032. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5033. /**
  5034. * Returns situation_percent of the previous line.
  5035. * Warning: If invoice is a replacement invoice, this->fk_prev_id is id of the replaced line.
  5036. *
  5037. * @param int $invoiceid Invoice id
  5038. * @param bool $include_credit_note Include credit note or not
  5039. * @return int >= 0
  5040. */
  5041. public function get_prev_progress($invoiceid, $include_credit_note = true)
  5042. {
  5043. // phpcs:enable
  5044. global $invoicecache;
  5045. if (is_null($this->fk_prev_id) || empty($this->fk_prev_id) || $this->fk_prev_id == "") {
  5046. return 0;
  5047. } else {
  5048. // If invoice is not a situation invoice, this->fk_prev_id is used for something else
  5049. if (!isset($invoicecache[$invoiceid])) {
  5050. $invoicecache[$invoiceid] = new Facture($this->db);
  5051. $invoicecache[$invoiceid]->fetch($invoiceid);
  5052. }
  5053. if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) {
  5054. return 0;
  5055. }
  5056. $sql = 'SELECT situation_percent FROM '.MAIN_DB_PREFIX.'facturedet WHERE rowid='.((int) $this->fk_prev_id);
  5057. $resql = $this->db->query($sql);
  5058. if ($resql && $resql->num_rows > 0) {
  5059. $res = $this->db->fetch_array($resql);
  5060. $returnPercent = floatval($res['situation_percent']);
  5061. if ($include_credit_note) {
  5062. $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd';
  5063. $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture f ON (f.rowid = fd.fk_facture) ';
  5064. $sql .= ' WHERE fd.fk_prev_id = '.((int) $this->fk_prev_id);
  5065. $sql .= ' AND f.situation_cycle_ref = '.((int) $invoicecache[$invoiceid]->situation_cycle_ref); // Prevent cycle outed
  5066. $sql .= ' AND f.type = '.Facture::TYPE_CREDIT_NOTE;
  5067. $res = $this->db->query($sql);
  5068. if ($res) {
  5069. while ($obj = $this->db->fetch_object($res)) {
  5070. $returnPercent = $returnPercent + floatval($obj->situation_percent);
  5071. }
  5072. } else {
  5073. dol_print_error($this->db);
  5074. }
  5075. }
  5076. return $returnPercent;
  5077. } else {
  5078. $this->error = $this->db->error();
  5079. dol_syslog(get_class($this)."::select Error ".$this->error, LOG_ERR);
  5080. $this->db->rollback();
  5081. return -1;
  5082. }
  5083. }
  5084. }
  5085. }