facture.class.php 161 KB

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