facture.class.php 232 KB

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