facture.class.php 243 KB

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