facture.class.php 245 KB

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