facture.class.php 196 KB

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