facture.class.php 169 KB

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