facture.class.php 164 KB

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