facture.class.php 232 KB

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