facture.class.php 245 KB

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