product.class.php 230 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315
  1. <?php
  2. /* Copyright (C) 2001-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  6. * Copyright (C) 2007-2011 Jean Heimburger <jean@tiaris.info>
  7. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  9. * Copyright (C) 2013-2014 Cedric GROSS <c.gross@kreiz-it.fr>
  10. * Copyright (C) 2013-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2011-2021 Open-DSI <support@open-dsi.fr>
  12. * Copyright (C) 2014 Henry Florian <florian.henry@open-concept.pro>
  13. * Copyright (C) 2014-2016 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2014 Ion agorria <ion@agorria.com>
  15. * Copyright (C) 2016-2018 Ferran Marcet <fmarcet@2byte.es>
  16. * Copyright (C) 2017 Gustavo Novaro
  17. * Copyright (C) 2019-2022 Frédéric France <frederic.france@netlogic.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/product/class/product.class.php
  34. * \ingroup produit
  35. * \brief File of class to manage predefined products or services
  36. */
  37. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  38. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  41. /**
  42. * Class to manage products or services
  43. */
  44. class Product extends CommonObject
  45. {
  46. /**
  47. * @var string ID to identify managed object
  48. */
  49. public $element = 'product';
  50. /**
  51. * @var string Name of table without prefix where object is stored
  52. */
  53. public $table_element = 'product';
  54. /**
  55. * @var string Field with ID of parent key if this field has a parent
  56. */
  57. public $fk_element = 'fk_product';
  58. /**
  59. * @var array List of child tables. To test if we can delete object.
  60. */
  61. protected $childtables = array(
  62. 'supplier_proposaldet' => array('name' => 'SupplierProposal', 'parent' => 'supplier_proposal', 'parentkey' => 'fk_supplier_proposal'),
  63. 'propaldet' => array('name' => 'Proposal', 'parent' => 'propal', 'parentkey' => 'fk_propal'),
  64. 'commandedet' => array('name' => 'Order', 'parent' => 'commande', 'parentkey' => 'fk_commande'),
  65. 'facturedet' => array('name' => 'Invoice', 'parent' => 'facture', 'parentkey' => 'fk_facture'),
  66. 'contratdet' => array('name' => 'Contract', 'parent' => 'contrat', 'parentkey' => 'fk_contrat'),
  67. 'facture_fourn_det' => array('name' => 'SupplierInvoice', 'parent' => 'facture_fourn', 'parentkey' => 'fk_facture_fourn'),
  68. 'commande_fournisseurdet' => array('name' => 'SupplierOrder', 'parent' => 'commande_fournisseur', 'parentkey' => 'fk_commande')
  69. );
  70. /**
  71. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  72. *
  73. * @var int
  74. */
  75. public $ismultientitymanaged = 1;
  76. /**
  77. * @var string picto
  78. */
  79. public $picto = 'product';
  80. /**
  81. * {@inheritdoc}
  82. */
  83. protected $table_ref_field = 'ref';
  84. public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm'; // See also into images.lib.php
  85. /**
  86. * @deprecated
  87. * @see $label
  88. */
  89. public $libelle;
  90. /**
  91. * Product label
  92. *
  93. * @var string
  94. */
  95. public $label;
  96. /**
  97. * Product description
  98. *
  99. * @var string
  100. */
  101. public $description;
  102. /**
  103. * Product other fields PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION
  104. *
  105. * @var string
  106. */
  107. public $other;
  108. /**
  109. * Check TYPE constants
  110. *
  111. * @var int
  112. */
  113. public $type = self::TYPE_PRODUCT;
  114. /**
  115. * Selling price without tax
  116. *
  117. * @var float
  118. */
  119. public $price;
  120. public $price_formated; // used by takepos/ajax/ajax.php
  121. /**
  122. * Selling price with tax
  123. *
  124. * @var float
  125. */
  126. public $price_ttc;
  127. public $price_ttc_formated; // used by takepos/ajax/ajax.php
  128. /**
  129. * Minimum price net
  130. *
  131. * @var float
  132. */
  133. public $price_min;
  134. /**
  135. * Minimum price with tax
  136. *
  137. * @var float
  138. */
  139. public $price_min_ttc;
  140. /**
  141. * Base price ('TTC' for price including tax or 'HT' for net price)
  142. * @var string
  143. */
  144. public $price_base_type;
  145. //! Arrays for multiprices
  146. public $multiprices = array();
  147. public $multiprices_ttc = array();
  148. public $multiprices_base_type = array();
  149. public $multiprices_min = array();
  150. public $multiprices_min_ttc = array();
  151. public $multiprices_tva_tx = array();
  152. public $multiprices_recuperableonly = array();
  153. //! Price by quantity arrays
  154. public $price_by_qty;
  155. public $prices_by_qty = array();
  156. public $prices_by_qty_id = array();
  157. public $prices_by_qty_list = array();
  158. //! Array for multilangs
  159. public $multilangs = array();
  160. //! Default VAT code for product (link to code into llx_c_tva but without foreign keys)
  161. public $default_vat_code;
  162. //! Default VAT rate of product
  163. public $tva_tx;
  164. //! French VAT NPR (0 or 1)
  165. public $tva_npr = 0;
  166. //! Default discount percent
  167. public $remise_percent;
  168. //! Other local taxes
  169. public $localtax1_tx;
  170. public $localtax2_tx;
  171. public $localtax1_type;
  172. public $localtax2_type;
  173. // Properties set by get_buyprice() for return
  174. public $desc_supplier;
  175. public $vatrate_supplier;
  176. public $default_vat_code_supplier;
  177. public $fourn_multicurrency_price;
  178. public $fourn_multicurrency_unitprice;
  179. public $fourn_multicurrency_tx;
  180. public $fourn_multicurrency_id;
  181. public $fourn_multicurrency_code;
  182. public $packaging;
  183. public $lifetime;
  184. public $qc_frequency;
  185. /**
  186. * Stock real
  187. *
  188. * @var int
  189. */
  190. public $stock_reel = 0;
  191. /**
  192. * Stock virtual
  193. *
  194. * @var int
  195. */
  196. public $stock_theorique;
  197. /**
  198. * Cost price
  199. *
  200. * @var float
  201. */
  202. public $cost_price;
  203. //! Average price value for product entry into stock (PMP)
  204. public $pmp;
  205. /**
  206. * Stock alert
  207. *
  208. * @var float
  209. */
  210. public $seuil_stock_alerte = 0;
  211. /**
  212. * Ask for replenishment when $desiredstock < $stock_reel
  213. */
  214. public $desiredstock = 0;
  215. /*
  216. * Service expiration
  217. */
  218. public $duration_value;
  219. /*
  220. * Service Workstation
  221. */
  222. public $fk_default_workstation;
  223. /**
  224. * Exoiration unit
  225. */
  226. public $duration_unit;
  227. /**
  228. * Status indicates whether the product is on sale '1' or not '0'
  229. *
  230. * @var int
  231. */
  232. public $status = 0;
  233. /**
  234. * Status indicates whether the product is on sale '1' or not '0'
  235. * @var int
  236. * @deprecated
  237. * @see $status
  238. */
  239. public $tosell;
  240. /**
  241. * Status indicate whether the product is available for purchase '1' or not '0'
  242. *
  243. * @var int
  244. */
  245. public $status_buy = 0;
  246. /**
  247. * Status indicate whether the product is available for purchase '1' or not '0'
  248. * @var int
  249. * @deprecated
  250. * @see $status_buy
  251. */
  252. public $tobuy;
  253. /**
  254. * Status indicates whether the product is a finished product '1' or a raw material '0'
  255. *
  256. * @var int
  257. */
  258. public $finished;
  259. /**
  260. * fk_default_bom indicates the default bom
  261. *
  262. * @var int
  263. */
  264. public $fk_default_bom;
  265. /**
  266. * We must manage lot/batch number, sell-by date and so on : '0':no, '1':yes, '2": yes with unique serial number
  267. *
  268. * @var int
  269. */
  270. public $status_batch = 0;
  271. /**
  272. * If allowed, we can edit batch or serial number mask for each product
  273. *
  274. * @var string
  275. */
  276. public $batch_mask = '';
  277. /**
  278. * Customs code
  279. *
  280. * @var string
  281. */
  282. public $customcode;
  283. /**
  284. * Product URL
  285. *
  286. * @var string
  287. */
  288. public $url;
  289. //! Metric of products
  290. public $weight;
  291. public $weight_units; // scale -3, 0, 3, 6
  292. public $length;
  293. public $length_units; // scale -3, 0, 3, 6
  294. public $width;
  295. public $width_units; // scale -3, 0, 3, 6
  296. public $height;
  297. public $height_units; // scale -3, 0, 3, 6
  298. public $surface;
  299. public $surface_units; // scale -3, 0, 3, 6
  300. public $volume;
  301. public $volume_units; // scale -3, 0, 3, 6
  302. public $net_measure;
  303. public $net_measure_units; // scale -3, 0, 3, 6
  304. public $accountancy_code_sell;
  305. public $accountancy_code_sell_intra;
  306. public $accountancy_code_sell_export;
  307. public $accountancy_code_buy;
  308. public $accountancy_code_buy_intra;
  309. public $accountancy_code_buy_export;
  310. /**
  311. * Main Barcode value
  312. *
  313. * @var string
  314. */
  315. public $barcode;
  316. /**
  317. * Main Barcode type ID
  318. *
  319. * @var int
  320. */
  321. public $barcode_type;
  322. /**
  323. * Main Barcode type code
  324. *
  325. * @var string
  326. */
  327. public $barcode_type_code;
  328. public $stats_propale = array();
  329. public $stats_commande = array();
  330. public $stats_contrat = array();
  331. public $stats_facture = array();
  332. public $stats_commande_fournisseur = array();
  333. public $stats_reception = array();
  334. public $stats_mrptoconsume = array();
  335. public $stats_mrptoproduce = array();
  336. //! Size of image
  337. public $imgWidth;
  338. public $imgHeight;
  339. /**
  340. * @var integer|string date_creation
  341. */
  342. public $date_creation;
  343. /**
  344. * @var integer|string date_modification
  345. */
  346. public $date_modification;
  347. //! Id du fournisseur
  348. public $product_fourn_id;
  349. //! Product ID already linked to a reference supplier
  350. public $product_id_already_linked;
  351. public $nbphoto = 0;
  352. //! Contains detail of stock of product into each warehouse
  353. public $stock_warehouse = array();
  354. public $oldcopy;
  355. /**
  356. * @var int Default warehouse Id
  357. */
  358. public $fk_default_warehouse;
  359. /**
  360. * @var int ID
  361. */
  362. public $fk_price_expression;
  363. /* To store supplier price found */
  364. public $fourn_qty;
  365. public $fourn_pu;
  366. public $fourn_price_base_type;
  367. public $fourn_socid;
  368. /**
  369. * @deprecated
  370. * @see $ref_supplier
  371. */
  372. public $ref_fourn;
  373. /**
  374. * @var string ref supplier
  375. */
  376. public $ref_supplier;
  377. /**
  378. * Unit code ('km', 'm', 'l', 'p', ...)
  379. *
  380. * @var string
  381. */
  382. public $fk_unit;
  383. /**
  384. * Price is generated using multiprice rules
  385. *
  386. * @var int
  387. */
  388. public $price_autogen = 0;
  389. /**
  390. * Array with list of supplier prices of product
  391. *
  392. * @var array
  393. */
  394. public $supplierprices;
  395. /**
  396. * Property set to save result of isObjectUsed(). Used for example by Product API.
  397. *
  398. * @var boolean
  399. */
  400. public $is_object_used;
  401. /**
  402. *
  403. *
  404. *
  405. */
  406. public $mandatory_period;
  407. /**
  408. * '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')
  409. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  410. * 'label' the translation key.
  411. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  412. * 'position' is the sort order of field.
  413. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  414. * '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)
  415. * 'noteditable' says if field is not editable (1 or 0)
  416. * '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.
  417. * 'index' if we want an index in database.
  418. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  419. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  420. * '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).
  421. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  422. * 'help' is a string visible as a tooltip on field
  423. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  424. * '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.
  425. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  426. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  427. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  428. *
  429. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  430. */
  431. /**
  432. * @var array fields of object product
  433. */
  434. public $fields = array(
  435. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
  436. 'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
  437. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>5),
  438. 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>2, 'position'=>15),
  439. 'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>'isModEnabled("barcode")', 'position'=>20, 'visible'=>-1, 'showoncombobox'=>3),
  440. 'fk_barcode_type' => array('type'=>'integer', 'label'=>'BarcodeType', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>-1,),
  441. 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61),
  442. 'note' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62),
  443. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
  444. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
  445. //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
  446. 'fk_user_author'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'),
  447. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
  448. //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
  449. 'localtax1_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax1tx', 'enabled'=>'1', 'position'=>150, 'notnull'=>0, 'visible'=>-1,),
  450. 'localtax1_type' => array('type'=>'varchar(10)', 'label'=>'Localtax1type', 'enabled'=>'1', 'position'=>155, 'notnull'=>1, 'visible'=>-1,),
  451. 'localtax2_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax2tx', 'enabled'=>'1', 'position'=>160, 'notnull'=>0, 'visible'=>-1,),
  452. 'localtax2_type' => array('type'=>'varchar(10)', 'label'=>'Localtax2type', 'enabled'=>'1', 'position'=>165, 'notnull'=>1, 'visible'=>-1,),
  453. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
  454. //'tosell' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
  455. //'tobuy' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
  456. 'mandatory_period' => array('type'=>'integer', 'label'=>'mandatory_period', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000),
  457. );
  458. /**
  459. * Regular product
  460. */
  461. const TYPE_PRODUCT = 0;
  462. /**
  463. * Service
  464. */
  465. const TYPE_SERVICE = 1;
  466. /**
  467. * Advanced feature: assembly kit
  468. */
  469. const TYPE_ASSEMBLYKIT = 2;
  470. /**
  471. * Advanced feature: stock kit
  472. */
  473. const TYPE_STOCKKIT = 3;
  474. /**
  475. * Constructor
  476. *
  477. * @param DoliDB $db Database handler
  478. */
  479. public function __construct($db)
  480. {
  481. $this->db = $db;
  482. $this->canvas = '';
  483. }
  484. /**
  485. * Check that ref and label are ok
  486. *
  487. * @return int >1 if OK, <=0 if KO
  488. */
  489. public function check()
  490. {
  491. $this->ref = dol_sanitizeFileName(stripslashes($this->ref));
  492. $err = 0;
  493. if (dol_strlen(trim($this->ref)) == 0) {
  494. $err++;
  495. }
  496. if (dol_strlen(trim($this->label)) == 0) {
  497. $err++;
  498. }
  499. if ($err > 0) {
  500. return 0;
  501. } else {
  502. return 1;
  503. }
  504. }
  505. /**
  506. * Insert product into database
  507. *
  508. * @param User $user User making insert
  509. * @param int $notrigger Disable triggers
  510. * @return int Id of product/service if OK, < 0 if KO
  511. */
  512. public function create($user, $notrigger = 0)
  513. {
  514. global $conf, $langs;
  515. $error = 0;
  516. // Clean parameters
  517. $this->ref = dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)));
  518. $this->label = trim($this->label);
  519. $this->price_ttc = price2num($this->price_ttc);
  520. $this->price = price2num($this->price);
  521. $this->price_min_ttc = price2num($this->price_min_ttc);
  522. $this->price_min = price2num($this->price_min);
  523. if (empty($this->tva_tx)) {
  524. $this->tva_tx = 0;
  525. }
  526. if (empty($this->tva_npr)) {
  527. $this->tva_npr = 0;
  528. }
  529. //Local taxes
  530. if (empty($this->localtax1_tx)) {
  531. $this->localtax1_tx = 0;
  532. }
  533. if (empty($this->localtax2_tx)) {
  534. $this->localtax2_tx = 0;
  535. }
  536. if (empty($this->localtax1_type)) {
  537. $this->localtax1_type = '0';
  538. }
  539. if (empty($this->localtax2_type)) {
  540. $this->localtax2_type = '0';
  541. }
  542. if (empty($this->price)) {
  543. $this->price = 0;
  544. }
  545. if (empty($this->price_min)) {
  546. $this->price_min = 0;
  547. }
  548. // Price by quantity
  549. if (empty($this->price_by_qty)) {
  550. $this->price_by_qty = 0;
  551. }
  552. if (empty($this->status)) {
  553. $this->status = 0;
  554. }
  555. if (empty($this->status_buy)) {
  556. $this->status_buy = 0;
  557. }
  558. $price_ht = 0;
  559. $price_ttc = 0;
  560. $price_min_ht = 0;
  561. $price_min_ttc = 0;
  562. //
  563. if ($this->price_base_type == 'TTC' && $this->price_ttc > 0) {
  564. $price_ttc = price2num($this->price_ttc, 'MU');
  565. $price_ht = price2num($this->price_ttc / (1 + ($this->tva_tx / 100)), 'MU');
  566. }
  567. //
  568. if ($this->price_base_type != 'TTC' && $this->price > 0) {
  569. $price_ht = price2num($this->price, 'MU');
  570. $price_ttc = price2num($this->price * (1 + ($this->tva_tx / 100)), 'MU');
  571. }
  572. //
  573. if (($this->price_min_ttc > 0) && ($this->price_base_type == 'TTC')) {
  574. $price_min_ttc = price2num($this->price_min_ttc, 'MU');
  575. $price_min_ht = price2num($this->price_min_ttc / (1 + ($this->tva_tx / 100)), 'MU');
  576. }
  577. //
  578. if (($this->price_min > 0) && ($this->price_base_type != 'TTC')) {
  579. $price_min_ht = price2num($this->price_min, 'MU');
  580. $price_min_ttc = price2num($this->price_min * (1 + ($this->tva_tx / 100)), 'MU');
  581. }
  582. $this->accountancy_code_buy = trim($this->accountancy_code_buy);
  583. $this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
  584. $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
  585. $this->accountancy_code_sell = trim($this->accountancy_code_sell);
  586. $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
  587. $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
  588. // Barcode value
  589. $this->barcode = trim($this->barcode);
  590. $this->mandatory_period = empty($this->mandatory_period) ? 0 : $this->mandatory_period;
  591. // Check parameters
  592. if (empty($this->label)) {
  593. $this->error = 'ErrorMandatoryParametersNotProvided';
  594. return -1;
  595. }
  596. if (empty($this->ref) || $this->ref == 'auto') {
  597. // Load object modCodeProduct
  598. $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard');
  599. if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard
  600. if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') {
  601. $module = substr($module, 0, dol_strlen($module) - 4);
  602. }
  603. dol_include_once('/core/modules/product/'.$module.'.php');
  604. $modCodeProduct = new $module;
  605. if (!empty($modCodeProduct->code_auto)) {
  606. $this->ref = $modCodeProduct->getNextValue($this, $this->type);
  607. }
  608. unset($modCodeProduct);
  609. }
  610. if (empty($this->ref)) {
  611. $this->error = 'ProductModuleNotSetupForAutoRef';
  612. return -2;
  613. }
  614. }
  615. dol_syslog(get_class($this)."::create ref=".$this->ref." price=".$this->price." price_ttc=".$this->price_ttc." tva_tx=".$this->tva_tx." price_base_type=".$this->price_base_type, LOG_DEBUG);
  616. $now = dol_now();
  617. $this->db->begin();
  618. // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
  619. if ($this->barcode == -1) {
  620. $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
  621. }
  622. // Check more parameters
  623. // If error, this->errors[] is filled
  624. $result = $this->verify();
  625. if ($result >= 0) {
  626. $sql = "SELECT count(*) as nb";
  627. $sql .= " FROM ".$this->db->prefix()."product";
  628. $sql .= " WHERE entity IN (".getEntity('product').")";
  629. $sql .= " AND ref = '".$this->db->escape($this->ref)."'";
  630. $result = $this->db->query($sql);
  631. if ($result) {
  632. $obj = $this->db->fetch_object($result);
  633. if ($obj->nb == 0) {
  634. // Produit non deja existant
  635. $sql = "INSERT INTO ".$this->db->prefix()."product (";
  636. $sql .= "datec";
  637. $sql .= ", entity";
  638. $sql .= ", ref";
  639. $sql .= ", ref_ext";
  640. $sql .= ", price_min";
  641. $sql .= ", price_min_ttc";
  642. $sql .= ", label";
  643. $sql .= ", fk_user_author";
  644. $sql .= ", fk_product_type";
  645. $sql .= ", price";
  646. $sql .= ", price_ttc";
  647. $sql .= ", price_base_type";
  648. $sql .= ", tobuy";
  649. $sql .= ", tosell";
  650. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  651. $sql .= ", accountancy_code_buy";
  652. $sql .= ", accountancy_code_buy_intra";
  653. $sql .= ", accountancy_code_buy_export";
  654. $sql .= ", accountancy_code_sell";
  655. $sql .= ", accountancy_code_sell_intra";
  656. $sql .= ", accountancy_code_sell_export";
  657. }
  658. $sql .= ", canvas";
  659. $sql .= ", finished";
  660. $sql .= ", tobatch";
  661. $sql .= ", batch_mask";
  662. $sql .= ", fk_unit";
  663. $sql .= ", mandatory_period";
  664. $sql .= ") VALUES (";
  665. $sql .= "'".$this->db->idate($now)."'";
  666. $sql .= ", ".((int) $conf->entity);
  667. $sql .= ", '".$this->db->escape($this->ref)."'";
  668. $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  669. $sql .= ", ".price2num($price_min_ht);
  670. $sql .= ", ".price2num($price_min_ttc);
  671. $sql .= ", ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
  672. $sql .= ", ".((int) $user->id);
  673. $sql .= ", ".((int) $this->type);
  674. $sql .= ", ".price2num($price_ht, 'MT');
  675. $sql .= ", ".price2num($price_ttc, 'MT');
  676. $sql .= ", '".$this->db->escape($this->price_base_type)."'";
  677. $sql .= ", ".((int) $this->status);
  678. $sql .= ", ".((int) $this->status_buy);
  679. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  680. $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
  681. $sql .= ", '".$this->db->escape($this->accountancy_code_buy_intra)."'";
  682. $sql .= ", '".$this->db->escape($this->accountancy_code_buy_export)."'";
  683. $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
  684. $sql .= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'";
  685. $sql .= ", '".$this->db->escape($this->accountancy_code_sell_export)."'";
  686. }
  687. $sql .= ", '".$this->db->escape($this->canvas)."'";
  688. $sql .= ", ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'NULL' : (int) $this->finished);
  689. $sql .= ", ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : ((int) $this->status_batch));
  690. $sql .= ", '".$this->db->escape($this->batch_mask)."'";
  691. $sql .= ", ".($this->fk_unit > 0 ? ((int) $this->fk_unit) : 'NULL');
  692. $sql .= ", '".$this->db->escape($this->mandatory_period)."'";
  693. $sql .= ")";
  694. dol_syslog(get_class($this)."::Create", LOG_DEBUG);
  695. $result = $this->db->query($sql);
  696. if ($result) {
  697. $id = $this->db->last_insert_id($this->db->prefix()."product");
  698. if ($id > 0) {
  699. $this->id = $id;
  700. $this->price = $price_ht;
  701. $this->price_ttc = $price_ttc;
  702. $this->price_min = $price_min_ht;
  703. $this->price_min_ttc = $price_min_ttc;
  704. $result = $this->_log_price($user);
  705. if ($result > 0) {
  706. if ($this->update($id, $user, true, 'add') <= 0) {
  707. $error++;
  708. }
  709. } else {
  710. $error++;
  711. $this->error = $this->db->lasterror();
  712. }
  713. // update accountancy for this entity
  714. if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  715. $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " .((int) $this->id) . " AND entity = " . ((int) $conf->entity));
  716. $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
  717. $sql .= " fk_product";
  718. $sql .= ", entity";
  719. $sql .= ", accountancy_code_buy";
  720. $sql .= ", accountancy_code_buy_intra";
  721. $sql .= ", accountancy_code_buy_export";
  722. $sql .= ", accountancy_code_sell";
  723. $sql .= ", accountancy_code_sell_intra";
  724. $sql .= ", accountancy_code_sell_export";
  725. $sql .= ") VALUES (";
  726. $sql .= $this->id;
  727. $sql .= ", " . $conf->entity;
  728. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
  729. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
  730. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
  731. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
  732. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
  733. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
  734. $sql .= ")";
  735. $result = $this->db->query($sql);
  736. if (!$result) {
  737. $error++;
  738. $this->error = 'ErrorFailedToInsertAccountancyForEntity';
  739. }
  740. }
  741. } else {
  742. $error++;
  743. $this->error = 'ErrorFailedToGetInsertedId';
  744. }
  745. } else {
  746. $error++;
  747. $this->error = $this->db->lasterror();
  748. }
  749. } else {
  750. // Product already exists with this ref
  751. $langs->load("products");
  752. $error++;
  753. $this->error = "ErrorProductAlreadyExists";
  754. }
  755. } else {
  756. $error++;
  757. $this->error = $this->db->lasterror();
  758. }
  759. if (!$error && !$notrigger) {
  760. // Call trigger
  761. $result = $this->call_trigger('PRODUCT_CREATE', $user);
  762. if ($result < 0) {
  763. $error++;
  764. }
  765. // End call triggers
  766. }
  767. if (!$error) {
  768. $this->db->commit();
  769. return $this->id;
  770. } else {
  771. $this->db->rollback();
  772. return -$error;
  773. }
  774. } else {
  775. $this->db->rollback();
  776. dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
  777. return -3;
  778. }
  779. }
  780. /**
  781. * Check properties of product are ok (like name, barcode, ...).
  782. * All properties must be already loaded on object (this->barcode, this->barcode_type_code, ...).
  783. *
  784. * @return int 0 if OK, <0 if KO
  785. */
  786. public function verify()
  787. {
  788. global $langs;
  789. $this->errors = array();
  790. $result = 0;
  791. $this->ref = trim($this->ref);
  792. if (!$this->ref) {
  793. $this->errors[] = 'ErrorBadRef';
  794. $result = -2;
  795. }
  796. $arrayofnonnegativevalue = array('weight'=>'Weight', 'width'=>'Width', 'height'=>'Height', 'length'=>'Length', 'surface'=>'Surface', 'volume'=>'Volume');
  797. foreach ($arrayofnonnegativevalue as $key => $value) {
  798. if (property_exists($this, $key) && !empty($this->$key) && ($this->$key < 0)) {
  799. $langs->loadLangs(array("main", "other"));
  800. $this->error = $langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv($value));
  801. $this->errors[] = $this->error;
  802. $result = -4;
  803. }
  804. }
  805. $rescode = $this->check_barcode($this->barcode, $this->barcode_type_code);
  806. if ($rescode) {
  807. if ($rescode == -1) {
  808. $this->errors[] = 'ErrorBadBarCodeSyntax';
  809. } elseif ($rescode == -2) {
  810. $this->errors[] = 'ErrorBarCodeRequired';
  811. } elseif ($rescode == -3) {
  812. // Note: Common usage is to have barcode unique. For variants, we should have a different barcode.
  813. $this->errors[] = 'ErrorBarCodeAlreadyUsed';
  814. }
  815. $result = -3;
  816. }
  817. return $result;
  818. }
  819. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  820. /**
  821. * Check barcode
  822. *
  823. * @param string $valuetotest Value to test
  824. * @param string $typefortest Type of barcode (ISBN, EAN, ...)
  825. * @return int 0 if OK
  826. * -1 ErrorBadBarCodeSyntax
  827. * -2 ErrorBarCodeRequired
  828. * -3 ErrorBarCodeAlreadyUsed
  829. */
  830. public function check_barcode($valuetotest, $typefortest)
  831. {
  832. // phpcs:enable
  833. global $conf;
  834. if (isModEnabled('barcode') && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
  835. $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM);
  836. $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
  837. foreach ($dirsociete as $dirroot) {
  838. $res = dol_include_once($dirroot.$module.'.php');
  839. if ($res) {
  840. break;
  841. }
  842. }
  843. $mod = new $module();
  844. dol_syslog(get_class($this)."::check_barcode value=".$valuetotest." type=".$typefortest." module=".$module);
  845. $result = $mod->verif($this->db, $valuetotest, $this, 0, $typefortest);
  846. return $result;
  847. } else {
  848. return 0;
  849. }
  850. }
  851. /**
  852. * Update a record into database.
  853. * If batch flag is set to on, we create records into llx_product_batch
  854. *
  855. * @param int $id Id of product
  856. * @param User $user Object user making update
  857. * @param int $notrigger Disable triggers
  858. * @param string $action Current action for hookmanager ('add' or 'update')
  859. * @param boolean $updatetype Update product type
  860. * @return int 1 if OK, -1 if ref already exists, -2 if other error
  861. */
  862. public function update($id, $user, $notrigger = false, $action = 'update', $updatetype = false)
  863. {
  864. global $langs, $conf, $hookmanager;
  865. $error = 0;
  866. // Check parameters
  867. if (!$this->label) {
  868. $this->label = 'MISSING LABEL';
  869. }
  870. // Clean parameters
  871. $this->ref = dol_string_nospecial(trim($this->ref));
  872. $this->label = trim($this->label);
  873. $this->description = trim($this->description);
  874. $this->note_private = (isset($this->note_private) ? trim($this->note_private) : null);
  875. $this->note_public = (isset($this->note_public) ? trim($this->note_public) : null);
  876. $this->net_measure = price2num($this->net_measure);
  877. $this->net_measure_units = trim($this->net_measure_units);
  878. $this->weight = price2num($this->weight);
  879. $this->weight_units = trim($this->weight_units);
  880. $this->length = price2num($this->length);
  881. $this->length_units = trim($this->length_units);
  882. $this->width = price2num($this->width);
  883. $this->width_units = trim($this->width_units);
  884. $this->height = price2num($this->height);
  885. $this->height_units = trim($this->height_units);
  886. $this->surface = price2num($this->surface);
  887. $this->surface_units = trim($this->surface_units);
  888. $this->volume = price2num($this->volume);
  889. $this->volume_units = trim($this->volume_units);
  890. // set unit not defined
  891. if (is_numeric($this->length_units)) {
  892. $this->width_units = $this->length_units; // Not used yet
  893. }
  894. if (is_numeric($this->length_units)) {
  895. $this->height_units = $this->length_units; // Not used yet
  896. }
  897. // Automated compute surface and volume if not filled
  898. if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) {
  899. $this->surface = $this->length * $this->width;
  900. $this->surface_units = measuring_units_squared($this->length_units);
  901. }
  902. if (empty($this->volume) && !empty($this->surface) && !empty($this->height) && $this->length_units == $this->height_units) {
  903. $this->volume = $this->surface * $this->height;
  904. $this->volume_units = measuring_units_cubed($this->height_units);
  905. }
  906. if (empty($this->tva_tx)) {
  907. $this->tva_tx = 0;
  908. }
  909. if (empty($this->tva_npr)) {
  910. $this->tva_npr = 0;
  911. }
  912. if (empty($this->localtax1_tx)) {
  913. $this->localtax1_tx = 0;
  914. }
  915. if (empty($this->localtax2_tx)) {
  916. $this->localtax2_tx = 0;
  917. }
  918. if (empty($this->localtax1_type)) {
  919. $this->localtax1_type = '0';
  920. }
  921. if (empty($this->localtax2_type)) {
  922. $this->localtax2_type = '0';
  923. }
  924. if (empty($this->status)) {
  925. $this->status = 0;
  926. }
  927. if (empty($this->status_buy)) {
  928. $this->status_buy = 0;
  929. }
  930. if (empty($this->country_id)) {
  931. $this->country_id = 0;
  932. }
  933. if (empty($this->state_id)) {
  934. $this->state_id = 0;
  935. }
  936. // Barcode value
  937. $this->barcode = trim($this->barcode);
  938. $this->accountancy_code_buy = trim($this->accountancy_code_buy);
  939. $this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
  940. $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
  941. $this->accountancy_code_sell = trim($this->accountancy_code_sell);
  942. $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
  943. $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
  944. $this->db->begin();
  945. $result = 0;
  946. // Check name is required and codes are ok or unique. If error, this->errors[] is filled
  947. if ($action != 'add') {
  948. $result = $this->verify(); // We don't check when update called during a create because verify was already done
  949. } else {
  950. // we can continue
  951. $result = 0;
  952. }
  953. if ($result >= 0) {
  954. // $this->oldcopy should have been set by the caller of update (here properties were already modified)
  955. if (empty($this->oldcopy)) {
  956. $this->oldcopy = dol_clone($this);
  957. }
  958. // Test if batch management is activated on existing product
  959. // If yes, we create missing entries into product_batch
  960. if ($this->hasbatch() && !$this->oldcopy->hasbatch()) {
  961. //$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower
  962. $valueforundefinedlot = '000000';
  963. if (!empty($conf->global->STOCK_DEFAULT_BATCH)) {
  964. $valueforundefinedlot = $conf->global->STOCK_DEFAULT_BATCH;
  965. }
  966. dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch");
  967. $this->load_stock();
  968. foreach ($this->stock_warehouse as $idW => $ObjW) { // For each warehouse where we have stocks defined for this product (for each lines in product_stock)
  969. $qty_batch = 0;
  970. foreach ($ObjW->detail_batch as $detail) { // Each lines of detail in product_batch of the current $ObjW = product_stock
  971. if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') {
  972. // We discard this line, we will create it later
  973. $sqlclean = "DELETE FROM ".$this->db->prefix()."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".((int) $ObjW->id);
  974. $result = $this->db->query($sqlclean);
  975. if (!$result) {
  976. dol_print_error($this->db);
  977. exit;
  978. }
  979. continue;
  980. }
  981. $qty_batch += $detail->qty;
  982. }
  983. // Quantities in batch details are not same as stock quantity,
  984. // so we add a default batch record to complete and get same qty in parent and child table
  985. if ($ObjW->real <> $qty_batch) {
  986. $ObjBatch = new Productbatch($this->db);
  987. $ObjBatch->batch = $valueforundefinedlot;
  988. $ObjBatch->qty = ($ObjW->real - $qty_batch);
  989. $ObjBatch->fk_product_stock = $ObjW->id;
  990. if ($ObjBatch->create($user, 1) < 0) {
  991. $error++;
  992. $this->errors = $ObjBatch->errors;
  993. }
  994. }
  995. }
  996. }
  997. // For automatic creation
  998. if ($this->barcode == -1) {
  999. $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
  1000. }
  1001. $sql = "UPDATE ".$this->db->prefix()."product";
  1002. $sql .= " SET label = '".$this->db->escape($this->label)."'";
  1003. if ($updatetype && ($this->isProduct() || $this->isService())) {
  1004. $sql .= ", fk_product_type = ".((int) $this->type);
  1005. }
  1006. $sql .= ", ref = '".$this->db->escape($this->ref)."'";
  1007. $sql .= ", ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  1008. $sql .= ", default_vat_code = ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null");
  1009. $sql .= ", tva_tx = ".((float) $this->tva_tx);
  1010. $sql .= ", recuperableonly = ".((int) $this->tva_npr);
  1011. $sql .= ", localtax1_tx = ".((float) $this->localtax1_tx);
  1012. $sql .= ", localtax2_tx = ".((float) $this->localtax2_tx);
  1013. $sql .= ", localtax1_type = ".($this->localtax1_type != '' ? "'".$this->db->escape($this->localtax1_type)."'" : "'0'");
  1014. $sql .= ", localtax2_type = ".($this->localtax2_type != '' ? "'".$this->db->escape($this->localtax2_type)."'" : "'0'");
  1015. $sql .= ", barcode = ".(empty($this->barcode) ? "null" : "'".$this->db->escape($this->barcode)."'");
  1016. $sql .= ", fk_barcode_type = ".(empty($this->barcode_type) ? "null" : $this->db->escape($this->barcode_type));
  1017. $sql .= ", tosell = ".(int) $this->status;
  1018. $sql .= ", tobuy = ".(int) $this->status_buy;
  1019. $sql .= ", tobatch = ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : (int) $this->status_batch);
  1020. $sql .= ", batch_mask = '".$this->db->escape($this->batch_mask)."'";
  1021. $sql .= ", finished = ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? "null" : (int) $this->finished);
  1022. $sql .= ", fk_default_bom = ".((!isset($this->fk_default_bom) || $this->fk_default_bom < 0 || $this->fk_default_bom == '') ? "null" : (int) $this->fk_default_bom);
  1023. $sql .= ", net_measure = ".($this->net_measure != '' ? "'".$this->db->escape($this->net_measure)."'" : 'null');
  1024. $sql .= ", net_measure_units = ".($this->net_measure_units != '' ? "'".$this->db->escape($this->net_measure_units)."'" : 'null');
  1025. $sql .= ", weight = ".($this->weight != '' ? "'".$this->db->escape($this->weight)."'" : 'null');
  1026. $sql .= ", weight_units = ".($this->weight_units != '' ? "'".$this->db->escape($this->weight_units)."'" : 'null');
  1027. $sql .= ", length = ".($this->length != '' ? "'".$this->db->escape($this->length)."'" : 'null');
  1028. $sql .= ", length_units = ".($this->length_units != '' ? "'".$this->db->escape($this->length_units)."'" : 'null');
  1029. $sql .= ", width= ".($this->width != '' ? "'".$this->db->escape($this->width)."'" : 'null');
  1030. $sql .= ", width_units = ".($this->width_units != '' ? "'".$this->db->escape($this->width_units)."'" : 'null');
  1031. $sql .= ", height = ".($this->height != '' ? "'".$this->db->escape($this->height)."'" : 'null');
  1032. $sql .= ", height_units = ".($this->height_units != '' ? "'".$this->db->escape($this->height_units)."'" : 'null');
  1033. $sql .= ", surface = ".($this->surface != '' ? "'".$this->db->escape($this->surface)."'" : 'null');
  1034. $sql .= ", surface_units = ".($this->surface_units != '' ? "'".$this->db->escape($this->surface_units)."'" : 'null');
  1035. $sql .= ", volume = ".($this->volume != '' ? "'".$this->db->escape($this->volume)."'" : 'null');
  1036. $sql .= ", volume_units = ".($this->volume_units != '' ? "'".$this->db->escape($this->volume_units)."'" : 'null');
  1037. $sql .= ", fk_default_warehouse = ".($this->fk_default_warehouse > 0 ? $this->db->escape($this->fk_default_warehouse) : 'null');
  1038. $sql .= ", fk_default_workstation = ".($this->fk_default_workstation > 0 ? $this->db->escape($this->fk_default_workstation) : 'null');
  1039. $sql .= ", seuil_stock_alerte = ".((isset($this->seuil_stock_alerte) && is_numeric($this->seuil_stock_alerte)) ? (float) $this->seuil_stock_alerte : 'null');
  1040. $sql .= ", description = '".$this->db->escape($this->description)."'";
  1041. $sql .= ", url = ".($this->url ? "'".$this->db->escape($this->url)."'" : 'null');
  1042. $sql .= ", customcode = '".$this->db->escape($this->customcode)."'";
  1043. $sql .= ", fk_country = ".($this->country_id > 0 ? (int) $this->country_id : 'null');
  1044. $sql .= ", fk_state = ".($this->state_id > 0 ? (int) $this->state_id : 'null');
  1045. $sql .= ", lifetime = ".($this->lifetime > 0 ? (int) $this->lifetime : 'null');
  1046. $sql .= ", qc_frequency = ".($this->qc_frequency > 0 ? (int) $this->qc_frequency : 'null');
  1047. $sql .= ", note = ".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : 'null');
  1048. $sql .= ", note_public = ".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : 'null');
  1049. $sql .= ", duration = '".$this->db->escape($this->duration_value.$this->duration_unit)."'";
  1050. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  1051. $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
  1052. $sql .= ", accountancy_code_buy_intra = '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
  1053. $sql .= ", accountancy_code_buy_export = '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
  1054. $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
  1055. $sql .= ", accountancy_code_sell_intra= '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
  1056. $sql .= ", accountancy_code_sell_export= '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
  1057. }
  1058. $sql .= ", desiredstock = ".((isset($this->desiredstock) && is_numeric($this->desiredstock)) ? (float) $this->desiredstock : "null");
  1059. $sql .= ", cost_price = ".($this->cost_price != '' ? $this->db->escape($this->cost_price) : 'null');
  1060. $sql .= ", fk_unit= ".(!$this->fk_unit ? 'NULL' : (int) $this->fk_unit);
  1061. $sql .= ", price_autogen = ".(!$this->price_autogen ? 0 : 1);
  1062. $sql .= ", fk_price_expression = ".($this->fk_price_expression != 0 ? (int) $this->fk_price_expression : 'NULL');
  1063. $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : 'NULL');
  1064. $sql .= ", mandatory_period = ".($this->mandatory_period );
  1065. // stock field is not here because it is a denormalized value from product_stock.
  1066. $sql .= " WHERE rowid = ".((int) $id);
  1067. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1068. $resql = $this->db->query($sql);
  1069. if ($resql) {
  1070. $this->id = $id;
  1071. // Multilangs
  1072. if (getDolGlobalInt('MAIN_MULTILANGS')) {
  1073. if ($this->setMultiLangs($user) < 0) {
  1074. $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
  1075. return -2;
  1076. }
  1077. }
  1078. $action = 'update';
  1079. // update accountancy for this entity
  1080. if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  1081. $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " . ((int) $this->id) . " AND entity = " . ((int) $conf->entity));
  1082. $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
  1083. $sql .= " fk_product";
  1084. $sql .= ", entity";
  1085. $sql .= ", accountancy_code_buy";
  1086. $sql .= ", accountancy_code_buy_intra";
  1087. $sql .= ", accountancy_code_buy_export";
  1088. $sql .= ", accountancy_code_sell";
  1089. $sql .= ", accountancy_code_sell_intra";
  1090. $sql .= ", accountancy_code_sell_export";
  1091. $sql .= ") VALUES (";
  1092. $sql .= $this->id;
  1093. $sql .= ", " . $conf->entity;
  1094. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
  1095. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
  1096. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
  1097. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
  1098. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
  1099. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
  1100. $sql .= ")";
  1101. $result = $this->db->query($sql);
  1102. if (!$result) {
  1103. $error++;
  1104. $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
  1105. }
  1106. }
  1107. // Actions on extra fields
  1108. if (!$error) {
  1109. $result = $this->insertExtraFields();
  1110. if ($result < 0) {
  1111. $error++;
  1112. }
  1113. }
  1114. if (!$error && !$notrigger) {
  1115. // Call trigger
  1116. $result = $this->call_trigger('PRODUCT_MODIFY', $user);
  1117. if ($result < 0) {
  1118. $error++;
  1119. }
  1120. // End call triggers
  1121. }
  1122. if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
  1123. // We remove directory
  1124. if ($conf->product->dir_output) {
  1125. $olddir = $conf->product->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
  1126. $newdir = $conf->product->dir_output."/".dol_sanitizeFileName($this->ref);
  1127. if (file_exists($olddir)) {
  1128. //include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  1129. //$res = dol_move($olddir, $newdir);
  1130. // do not use dol_move with directory
  1131. $res = @rename($olddir, $newdir);
  1132. if (!$res) {
  1133. $langs->load("errors");
  1134. $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
  1135. $error++;
  1136. }
  1137. }
  1138. }
  1139. }
  1140. if (!$error) {
  1141. if (isModEnabled('variants')) {
  1142. include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  1143. $comb = new ProductCombination($this->db);
  1144. foreach ($comb->fetchAllByFkProductParent($this->id) as $currcomb) {
  1145. $currcomb->updateProperties($this, $user);
  1146. }
  1147. }
  1148. $this->db->commit();
  1149. return 1;
  1150. } else {
  1151. $this->db->rollback();
  1152. return -$error;
  1153. }
  1154. } else {
  1155. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1156. $langs->load("errors");
  1157. if (empty($conf->barcode->enabled) || empty($this->barcode)) {
  1158. $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists", $this->ref);
  1159. } else {
  1160. $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductBarCodeAlreadyExists", $this->barcode);
  1161. }
  1162. $this->errors[] = $this->error;
  1163. $this->db->rollback();
  1164. return -1;
  1165. } else {
  1166. $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
  1167. $this->errors[] = $this->error;
  1168. $this->db->rollback();
  1169. return -2;
  1170. }
  1171. }
  1172. } else {
  1173. $this->db->rollback();
  1174. dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
  1175. return -3;
  1176. }
  1177. }
  1178. /**
  1179. * Delete a product from database (if not used)
  1180. *
  1181. * @param User $user User (object) deleting product
  1182. * @param int $notrigger Do not execute trigger
  1183. * @return int < 0 if KO, 0 = Not possible, > 0 if OK
  1184. */
  1185. public function delete(User $user, $notrigger = 0)
  1186. {
  1187. global $conf, $langs;
  1188. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1189. $error = 0;
  1190. // Check parameters
  1191. if (empty($this->id)) {
  1192. $this->error = "Object must be fetched before calling delete";
  1193. return -1;
  1194. }
  1195. if (($this->type == Product::TYPE_PRODUCT && empty($user->rights->produit->supprimer)) || ($this->type == Product::TYPE_SERVICE && empty($user->rights->service->supprimer))) {
  1196. $this->error = "ErrorForbidden";
  1197. return 0;
  1198. }
  1199. $objectisused = $this->isObjectUsed($this->id);
  1200. if (empty($objectisused)) {
  1201. $this->db->begin();
  1202. if (!$error && empty($notrigger)) {
  1203. // Call trigger
  1204. $result = $this->call_trigger('PRODUCT_DELETE', $user);
  1205. if ($result < 0) {
  1206. $error++;
  1207. }
  1208. // End call triggers
  1209. }
  1210. // Delete from product_batch on product delete
  1211. if (!$error) {
  1212. $sql = "DELETE FROM ".$this->db->prefix().'product_batch';
  1213. $sql .= " WHERE fk_product_stock IN (";
  1214. $sql .= "SELECT rowid FROM ".$this->db->prefix().'product_stock';
  1215. $sql .= " WHERE fk_product = ".((int) $this->id).")";
  1216. $result = $this->db->query($sql);
  1217. if (!$result) {
  1218. $error++;
  1219. $this->errors[] = $this->db->lasterror();
  1220. }
  1221. }
  1222. // Delete all child tables
  1223. if (!$error) {
  1224. $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before
  1225. foreach ($elements as $table) {
  1226. if (!$error) {
  1227. $sql = "DELETE FROM ".$this->db->prefix().$table;
  1228. $sql .= " WHERE fk_product = ".(int) $this->id;
  1229. $result = $this->db->query($sql);
  1230. if (!$result) {
  1231. $error++;
  1232. $this->errors[] = $this->db->lasterror();
  1233. }
  1234. }
  1235. }
  1236. }
  1237. if (!$error) {
  1238. include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  1239. include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
  1240. //If it is a parent product, then we remove the association with child products
  1241. $prodcomb = new ProductCombination($this->db);
  1242. if ($prodcomb->deleteByFkProductParent($user, $this->id) < 0) {
  1243. $error++;
  1244. $this->errors[] = 'Error deleting combinations';
  1245. }
  1246. //We also check if it is a child product
  1247. if (!$error && ($prodcomb->fetchByFkProductChild($this->id) > 0) && ($prodcomb->delete($user) < 0)) {
  1248. $error++;
  1249. $this->errors[] = 'Error deleting child combination';
  1250. }
  1251. }
  1252. // Delete from product_association
  1253. if (!$error) {
  1254. $sql = "DELETE FROM ".$this->db->prefix()."product_association";
  1255. $sql .= " WHERE fk_product_pere = ".(int) $this->id." OR fk_product_fils = ".(int) $this->id;
  1256. $result = $this->db->query($sql);
  1257. if (!$result) {
  1258. $error++;
  1259. $this->errors[] = $this->db->lasterror();
  1260. }
  1261. }
  1262. // Remove extrafields
  1263. if (!$error) {
  1264. $result = $this->deleteExtraFields();
  1265. if ($result < 0) {
  1266. $error++;
  1267. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  1268. }
  1269. }
  1270. // Delete product
  1271. if (!$error) {
  1272. $sqlz = "DELETE FROM ".$this->db->prefix()."product";
  1273. $sqlz .= " WHERE rowid = ".(int) $this->id;
  1274. $resultz = $this->db->query($sqlz);
  1275. if (!$resultz) {
  1276. $error++;
  1277. $this->errors[] = $this->db->lasterror();
  1278. }
  1279. }
  1280. // Delete record into ECM index and physically
  1281. if (!$error) {
  1282. $res = $this->deleteEcmFiles(0); // Deleting files physically is done later with the dol_delete_dir_recursive
  1283. if (!$res) {
  1284. $error++;
  1285. }
  1286. }
  1287. if (!$error) {
  1288. // We remove directory
  1289. $ref = dol_sanitizeFileName($this->ref);
  1290. if ($conf->product->dir_output) {
  1291. $dir = $conf->product->dir_output."/".$ref;
  1292. if (file_exists($dir)) {
  1293. $res = @dol_delete_dir_recursive($dir);
  1294. if (!$res) {
  1295. $this->errors[] = 'ErrorFailToDeleteDir';
  1296. $error++;
  1297. }
  1298. }
  1299. }
  1300. }
  1301. if (!$error) {
  1302. $this->db->commit();
  1303. return 1;
  1304. } else {
  1305. foreach ($this->errors as $errmsg) {
  1306. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  1307. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1308. }
  1309. $this->db->rollback();
  1310. return -$error;
  1311. }
  1312. } else {
  1313. $this->error = "ErrorRecordIsUsedCantDelete";
  1314. return 0;
  1315. }
  1316. }
  1317. /**
  1318. * Update or add a translation for a product
  1319. *
  1320. * @param User $user Object user making update
  1321. * @return int <0 if KO, >0 if OK
  1322. */
  1323. public function setMultiLangs($user)
  1324. {
  1325. global $conf, $langs;
  1326. $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
  1327. $current_lang = $langs->getDefaultLang();
  1328. foreach ($langs_available as $key => $value) {
  1329. if ($key == $current_lang) {
  1330. $sql = "SELECT rowid";
  1331. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1332. $sql .= " WHERE fk_product = ".((int) $this->id);
  1333. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1334. $result = $this->db->query($sql);
  1335. if ($this->db->num_rows($result)) { // if there is already a description line for this language
  1336. $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
  1337. $sql2 .= " SET ";
  1338. $sql2 .= " label='".$this->db->escape($this->label)."',";
  1339. $sql2 .= " description='".$this->db->escape($this->description)."'";
  1340. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1341. $sql2 .= ", note='".$this->db->escape($this->other)."'";
  1342. }
  1343. $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1344. } else {
  1345. $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
  1346. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1347. $sql2 .= ", note";
  1348. }
  1349. $sql2 .= ")";
  1350. $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
  1351. $sql2 .= " '".$this->db->escape($this->description)."'";
  1352. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1353. $sql2 .= ", '".$this->db->escape($this->other)."'";
  1354. }
  1355. $sql2 .= ")";
  1356. }
  1357. dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key);
  1358. if (!$this->db->query($sql2)) {
  1359. $this->error = $this->db->lasterror();
  1360. return -1;
  1361. }
  1362. } elseif (isset($this->multilangs[$key])) {
  1363. if (empty($this->multilangs["$key"]["label"])) {
  1364. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
  1365. return -1;
  1366. }
  1367. $sql = "SELECT rowid";
  1368. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1369. $sql .= " WHERE fk_product = ".((int) $this->id);
  1370. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1371. $result = $this->db->query($sql);
  1372. if ($this->db->num_rows($result)) { // if there is already a description line for this language
  1373. $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
  1374. $sql2 .= " SET ";
  1375. $sql2 .= " label = '".$this->db->escape($this->multilangs["$key"]["label"])."',";
  1376. $sql2 .= " description = '".$this->db->escape($this->multilangs["$key"]["description"])."'";
  1377. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1378. $sql2 .= ", note = '".$this->db->escape($this->multilangs["$key"]["other"])."'";
  1379. }
  1380. $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1381. } else {
  1382. $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
  1383. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1384. $sql2 .= ", note";
  1385. }
  1386. $sql2 .= ")";
  1387. $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
  1388. $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'";
  1389. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1390. $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'";
  1391. }
  1392. $sql2 .= ")";
  1393. }
  1394. // We do not save if main fields are empty
  1395. if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) {
  1396. if (!$this->db->query($sql2)) {
  1397. $this->error = $this->db->lasterror();
  1398. return -1;
  1399. }
  1400. }
  1401. } else {
  1402. // language is not current language and we didn't provide a multilang description for this language
  1403. }
  1404. }
  1405. // Call trigger
  1406. $result = $this->call_trigger('PRODUCT_SET_MULTILANGS', $user);
  1407. if ($result < 0) {
  1408. $this->error = $this->db->lasterror();
  1409. return -1;
  1410. }
  1411. // End call triggers
  1412. return 1;
  1413. }
  1414. /**
  1415. * Delete a language for this product
  1416. *
  1417. * @param string $langtodelete Language code to delete
  1418. * @param User $user Object user making delete
  1419. *
  1420. * @return int <0 if KO, >0 if OK
  1421. */
  1422. public function delMultiLangs($langtodelete, $user)
  1423. {
  1424. $sql = "DELETE FROM ".$this->db->prefix()."product_lang";
  1425. $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
  1426. dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
  1427. $result = $this->db->query($sql);
  1428. if ($result) {
  1429. // Call trigger
  1430. $result = $this->call_trigger('PRODUCT_DEL_MULTILANGS', $user);
  1431. if ($result < 0) {
  1432. $this->error = $this->db->lasterror();
  1433. dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
  1434. return -1;
  1435. }
  1436. // End call triggers
  1437. return 1;
  1438. } else {
  1439. $this->error = $this->db->lasterror();
  1440. dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
  1441. return -1;
  1442. }
  1443. }
  1444. /**
  1445. * Sets an accountancy code for a product.
  1446. * Also calls PRODUCT_MODIFY trigger when modified
  1447. *
  1448. * @param string $type It can be 'buy', 'buy_intra', 'buy_export', 'sell', 'sell_intra' or 'sell_export'
  1449. * @param string $value Accountancy code
  1450. * @return int <0 KO >0 OK
  1451. */
  1452. public function setAccountancyCode($type, $value)
  1453. {
  1454. global $user, $langs, $conf;
  1455. $error = 0;
  1456. $this->db->begin();
  1457. if ($type == 'buy') {
  1458. $field = 'accountancy_code_buy';
  1459. } elseif ($type == 'buy_intra') {
  1460. $field = 'accountancy_code_buy_intra';
  1461. } elseif ($type == 'buy_export') {
  1462. $field = 'accountancy_code_buy_export';
  1463. } elseif ($type == 'sell') {
  1464. $field = 'accountancy_code_sell';
  1465. } elseif ($type == 'sell_intra') {
  1466. $field = 'accountancy_code_sell_intra';
  1467. } elseif ($type == 'sell_export') {
  1468. $field = 'accountancy_code_sell_export';
  1469. } else {
  1470. return -1;
  1471. }
  1472. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ";
  1473. $sql .= "$field = '".$this->db->escape($value)."'";
  1474. $sql .= " WHERE rowid = ".((int) $this->id);
  1475. dol_syslog(__METHOD__."", LOG_DEBUG);
  1476. $resql = $this->db->query($sql);
  1477. if ($resql) {
  1478. // Call trigger
  1479. $result = $this->call_trigger('PRODUCT_MODIFY', $user);
  1480. if ($result < 0) {
  1481. $error++;
  1482. }
  1483. // End call triggers
  1484. if ($error) {
  1485. $this->db->rollback();
  1486. return -1;
  1487. }
  1488. $this->$field = $value;
  1489. $this->db->commit();
  1490. return 1;
  1491. } else {
  1492. $this->error = $this->db->lasterror();
  1493. $this->db->rollback();
  1494. return -1;
  1495. }
  1496. }
  1497. /**
  1498. * Load array this->multilangs
  1499. *
  1500. * @return int <0 if KO, >0 if OK
  1501. */
  1502. public function getMultiLangs()
  1503. {
  1504. global $langs;
  1505. $current_lang = $langs->getDefaultLang();
  1506. $sql = "SELECT lang, label, description, note as other";
  1507. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1508. $sql .= " WHERE fk_product = ".((int) $this->id);
  1509. $result = $this->db->query($sql);
  1510. if ($result) {
  1511. while ($obj = $this->db->fetch_object($result)) {
  1512. //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
  1513. if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
  1514. $this->label = $obj->label;
  1515. $this->description = $obj->description;
  1516. $this->other = $obj->other;
  1517. }
  1518. $this->multilangs["$obj->lang"]["label"] = $obj->label;
  1519. $this->multilangs["$obj->lang"]["description"] = $obj->description;
  1520. $this->multilangs["$obj->lang"]["other"] = $obj->other;
  1521. }
  1522. return 1;
  1523. } else {
  1524. $this->error = "Error: ".$this->db->lasterror()." - ".$sql;
  1525. return -1;
  1526. }
  1527. }
  1528. /**
  1529. * used to check if price have really change to avoid log pollution
  1530. *
  1531. * @param int $level price level to change
  1532. * @return array
  1533. */
  1534. private function getArrayForPriceCompare($level = 0)
  1535. {
  1536. $testExit = array('multiprices','multiprices_ttc','multiprices_base_type','multiprices_min','multiprices_min_ttc','multiprices_tva_tx','multiprices_recuperableonly');
  1537. foreach ($testExit as $field) {
  1538. if (!isset($this->$field)) {
  1539. return array();
  1540. }
  1541. $tmparray = $this->$field;
  1542. if (!isset($tmparray[$level])) {
  1543. return array();
  1544. }
  1545. }
  1546. $lastPrice = array(
  1547. 'level' => $level ? $level : 1,
  1548. 'multiprices' => doubleval($this->multiprices[$level]),
  1549. 'multiprices_ttc' => doubleval($this->multiprices_ttc[$level]),
  1550. 'multiprices_base_type' => $this->multiprices_base_type[$level],
  1551. 'multiprices_min' => doubleval($this->multiprices_min[$level]),
  1552. 'multiprices_min_ttc' => doubleval($this->multiprices_min_ttc[$level]),
  1553. 'multiprices_tva_tx' => doubleval($this->multiprices_tva_tx[$level]),
  1554. 'multiprices_recuperableonly' => doubleval($this->multiprices_recuperableonly[$level]),
  1555. );
  1556. return $lastPrice;
  1557. }
  1558. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1559. /**
  1560. * Insert a track that we changed a customer price
  1561. *
  1562. * @param User $user User making change
  1563. * @param int $level price level to change
  1564. * @return int <0 if KO, >0 if OK
  1565. */
  1566. private function _log_price($user, $level = 0)
  1567. {
  1568. // phpcs:enable
  1569. global $conf;
  1570. $now = dol_now();
  1571. // Clean parameters
  1572. if (empty($this->price_by_qty)) {
  1573. $this->price_by_qty = 0;
  1574. }
  1575. // Add new price
  1576. $sql = "INSERT INTO ".$this->db->prefix()."product_price(price_level,date_price, fk_product, fk_user_author, price, price_ttc, price_base_type,tosell, tva_tx, default_vat_code, recuperableonly,";
  1577. $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) ";
  1578. $sql .= " VALUES(".($level ? ((int) $level) : 1).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $user->id).", ".((float) price2num($this->price)).", ".((float) price2num($this->price_ttc)).",'".$this->db->escape($this->price_base_type)."',".((int) $this->status).", ".((float) price2num($this->tva_tx)).", ".($this->default_vat_code ? ("'".$this->db->escape($this->default_vat_code)."'") : "null").", ".((int) $this->tva_npr).",";
  1579. $sql .= " ".price2num($this->localtax1_tx).", ".price2num($this->localtax2_tx).", '".$this->db->escape($this->localtax1_type)."', '".$this->db->escape($this->localtax2_type)."', ".price2num($this->price_min).", ".price2num($this->price_min_ttc).", ".price2num($this->price_by_qty).", ".((int) $conf->entity).",".($this->fk_price_expression > 0 ? ((int) $this->fk_price_expression) : 'null');
  1580. $sql .= ")";
  1581. dol_syslog(get_class($this)."::_log_price", LOG_DEBUG);
  1582. $resql = $this->db->query($sql);
  1583. if (!$resql) {
  1584. $this->error = $this->db->lasterror();
  1585. dol_print_error($this->db);
  1586. return -1;
  1587. } else {
  1588. return 1;
  1589. }
  1590. }
  1591. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1592. /**
  1593. * Delete a price line
  1594. *
  1595. * @param User $user Object user
  1596. * @param int $rowid Line id to delete
  1597. * @return int <0 if KO, >0 if OK
  1598. */
  1599. public function log_price_delete($user, $rowid)
  1600. {
  1601. // phpcs:enable
  1602. $sql = "DELETE FROM ".$this->db->prefix()."product_price_by_qty";
  1603. $sql .= " WHERE fk_product_price = ".((int) $rowid);
  1604. $resql = $this->db->query($sql);
  1605. $sql = "DELETE FROM ".$this->db->prefix()."product_price";
  1606. $sql .= " WHERE rowid=".((int) $rowid);
  1607. $resql = $this->db->query($sql);
  1608. if ($resql) {
  1609. return 1;
  1610. } else {
  1611. $this->error = $this->db->lasterror();
  1612. return -1;
  1613. }
  1614. }
  1615. /**
  1616. * Return price of sell of a product for a seller/buyer/product.
  1617. *
  1618. * @param Societe $thirdparty_seller Seller
  1619. * @param Societe $thirdparty_buyer Buyer
  1620. * @param int $pqp Id of product price per quantity if a selection was done of such a price
  1621. * @return array Array of price information array('pu_ht'=> , 'pu_ttc'=> , 'tva_tx'=>'X.Y (code)', ...), 'tva_npr'=>0, ...)
  1622. * @see get_buyprice(), find_min_price_product_fournisseur()
  1623. */
  1624. public function getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp = 0)
  1625. {
  1626. global $conf, $db, $hookmanager, $action;
  1627. // Call hook if any
  1628. if (is_object($hookmanager)) {
  1629. $parameters = array('thirdparty_seller'=>$thirdparty_seller, 'thirdparty_buyer' => $thirdparty_buyer, 'pqp' => $pqp);
  1630. // Note that $action and $object may have been modified by some hooks
  1631. $reshook = $hookmanager->executeHooks('getSellPrice', $parameters, $this, $action);
  1632. if ($reshook > 0) {
  1633. return $hookmanager->resArray;
  1634. }
  1635. }
  1636. // Update if prices fields are defined
  1637. $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
  1638. $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
  1639. if (empty($tva_tx)) {
  1640. $tva_npr = 0;
  1641. }
  1642. $pu_ht = $this->price;
  1643. $pu_ttc = $this->price_ttc;
  1644. $price_min = $this->price_min;
  1645. $price_base_type = $this->price_base_type;
  1646. // If price per segment
  1647. if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($thirdparty_buyer->price_level)) {
  1648. $pu_ht = $this->multiprices[$thirdparty_buyer->price_level];
  1649. $pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level];
  1650. $price_min = $this->multiprices_min[$thirdparty_buyer->price_level];
  1651. $price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level];
  1652. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  1653. if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
  1654. $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
  1655. }
  1656. if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
  1657. $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
  1658. }
  1659. if (empty($tva_tx)) {
  1660. $tva_npr = 0;
  1661. }
  1662. }
  1663. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  1664. // If price per customer
  1665. require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
  1666. $prodcustprice = new Productcustomerprice($this->db);
  1667. $filter = array('t.fk_product' => $this->id, 't.fk_soc' => $thirdparty_buyer->id);
  1668. $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
  1669. if ($result) {
  1670. if (count($prodcustprice->lines) > 0) {
  1671. $pu_ht = price($prodcustprice->lines[0]->price);
  1672. $price_min = price($prodcustprice->lines[0]->price_min);
  1673. $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
  1674. $price_base_type = $prodcustprice->lines[0]->price_base_type;
  1675. $tva_tx = $prodcustprice->lines[0]->tva_tx;
  1676. if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
  1677. $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
  1678. }
  1679. $tva_npr = $prodcustprice->lines[0]->recuperableonly;
  1680. if (empty($tva_tx)) {
  1681. $tva_npr = 0;
  1682. }
  1683. }
  1684. }
  1685. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
  1686. // If price per quantity
  1687. if ($this->prices_by_qty[0]) {
  1688. // yes, this product has some prices per quantity
  1689. // Search price into product_price_by_qty from $this->id
  1690. foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
  1691. if ($priceforthequantityarray['rowid'] != $pqp) {
  1692. continue;
  1693. }
  1694. // We found the price
  1695. if ($priceforthequantityarray['price_base_type'] == 'HT') {
  1696. $pu_ht = $priceforthequantityarray['unitprice'];
  1697. } else {
  1698. $pu_ttc = $priceforthequantityarray['unitprice'];
  1699. }
  1700. break;
  1701. }
  1702. }
  1703. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  1704. // If price per quantity and customer
  1705. if ($this->prices_by_qty[$thirdparty_buyer->price_level]) {
  1706. // yes, this product has some prices per quantity
  1707. // Search price into product_price_by_qty from $this->id
  1708. foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
  1709. if ($priceforthequantityarray['rowid'] != $pqp) {
  1710. continue;
  1711. }
  1712. // We found the price
  1713. if ($priceforthequantityarray['price_base_type'] == 'HT') {
  1714. $pu_ht = $priceforthequantityarray['unitprice'];
  1715. } else {
  1716. $pu_ttc = $priceforthequantityarray['unitprice'];
  1717. }
  1718. break;
  1719. }
  1720. }
  1721. }
  1722. return array('pu_ht'=>$pu_ht, 'pu_ttc'=>$pu_ttc, 'price_min'=>$price_min, 'price_base_type'=>$price_base_type, 'tva_tx'=>$tva_tx, 'tva_npr'=>$tva_npr);
  1723. }
  1724. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1725. /**
  1726. * Read price used by a provider.
  1727. * We enter as input couple prodfournprice/qty or triplet qty/product_id/fourn_ref.
  1728. * This also set some properties on product like ->buyprice, ->fourn_pu, ...
  1729. *
  1730. * @param int $prodfournprice Id du tarif = rowid table product_fournisseur_price
  1731. * @param double $qty Quantity asked or -1 to get first entry found
  1732. * @param int $product_id Filter on a particular product id
  1733. * @param string $fourn_ref Filter on a supplier price ref. 'none' to exclude ref in search.
  1734. * @param int $fk_soc If of supplier
  1735. * @return int <-1 if KO, -1 if qty not enough, 0 if OK but nothing found, id_product if OK and found. May also initialize some properties like (->ref_supplier, buyprice, fourn_pu, vatrate_supplier...)
  1736. * @see getSellPrice(), find_min_price_product_fournisseur()
  1737. */
  1738. public function get_buyprice($prodfournprice, $qty, $product_id = 0, $fourn_ref = '', $fk_soc = 0)
  1739. {
  1740. // phpcs:enable
  1741. global $conf;
  1742. $result = 0;
  1743. // We do a first search with a select by searching with couple prodfournprice and qty only (later we will search on triplet qty/product_id/fourn_ref)
  1744. $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
  1745. $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.default_vat_code, pfp.fk_supplier_price_expression,";
  1746. $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
  1747. $sql .= " pfp.packaging";
  1748. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
  1749. $sql .= " WHERE pfp.rowid = ".((int) $prodfournprice);
  1750. if ($qty > 0) {
  1751. $sql .= " AND pfp.quantity <= ".((float) $qty);
  1752. }
  1753. $sql .= " ORDER BY pfp.quantity DESC";
  1754. dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG);
  1755. $resql = $this->db->query($sql);
  1756. if ($resql) {
  1757. $obj = $this->db->fetch_object($resql);
  1758. if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
  1759. if (isModEnabled('dynamicprices') && !empty($obj->fk_supplier_price_expression)) {
  1760. $prod_supplier = new ProductFournisseur($this->db);
  1761. $prod_supplier->product_fourn_price_id = $obj->rowid;
  1762. $prod_supplier->id = $obj->fk_product;
  1763. $prod_supplier->fourn_qty = $obj->quantity;
  1764. $prod_supplier->fourn_tva_tx = $obj->tva_tx;
  1765. $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
  1766. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1767. $priceparser = new PriceParser($this->db);
  1768. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  1769. if ($price_result >= 0) {
  1770. $obj->price = $price_result;
  1771. }
  1772. }
  1773. $this->product_fourn_price_id = $obj->rowid;
  1774. $this->buyprice = $obj->price; // deprecated
  1775. $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier
  1776. $this->fourn_price_base_type = 'HT'; // Price base type
  1777. $this->fourn_socid = $obj->fk_soc; // Company that offer this price
  1778. $this->ref_fourn = $obj->ref_supplier; // deprecated
  1779. $this->ref_supplier = $obj->ref_supplier; // Ref supplier
  1780. $this->desc_supplier = $obj->desc_supplier; // desc supplier
  1781. $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
  1782. $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
  1783. $this->default_vat_code_supplier = $obj->default_vat_code; // Vat code supplier
  1784. $this->fourn_multicurrency_price = $obj->multicurrency_price;
  1785. $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
  1786. $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
  1787. $this->fourn_multicurrency_id = $obj->fk_multicurrency;
  1788. $this->fourn_multicurrency_code = $obj->multicurrency_code;
  1789. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  1790. $this->packaging = $obj->packaging;
  1791. }
  1792. $result = $obj->fk_product;
  1793. return $result;
  1794. } else { // If not found
  1795. // We do a second search by doing a select again but searching with less reliable criteria: couple qty/id product, and if set fourn_ref or fk_soc.
  1796. $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
  1797. $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.default_vat_code, pfp.fk_supplier_price_expression,";
  1798. $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
  1799. $sql .= " pfp.packaging";
  1800. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
  1801. $sql .= " WHERE 1 = 1";
  1802. if ($product_id > 0) {
  1803. $sql .= " AND pfp.fk_product = ".((int) $product_id);
  1804. }
  1805. if ($fourn_ref != 'none') {
  1806. $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
  1807. }
  1808. if ($fk_soc > 0) {
  1809. $sql .= " AND pfp.fk_soc = ".((int) $fk_soc);
  1810. }
  1811. if ($qty > 0) {
  1812. $sql .= " AND pfp.quantity <= ".((float) $qty);
  1813. }
  1814. $sql .= " ORDER BY pfp.quantity DESC";
  1815. $sql .= " LIMIT 1";
  1816. dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG);
  1817. $resql = $this->db->query($sql);
  1818. if ($resql) {
  1819. $obj = $this->db->fetch_object($resql);
  1820. if ($obj && $obj->quantity > 0) { // If found
  1821. if (isModEnabled('dynamicprices') && !empty($obj->fk_supplier_price_expression)) {
  1822. $prod_supplier = new ProductFournisseur($this->db);
  1823. $prod_supplier->product_fourn_price_id = $obj->rowid;
  1824. $prod_supplier->id = $obj->fk_product;
  1825. $prod_supplier->fourn_qty = $obj->quantity;
  1826. $prod_supplier->fourn_tva_tx = $obj->tva_tx;
  1827. $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
  1828. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1829. $priceparser = new PriceParser($this->db);
  1830. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  1831. if ($result >= 0) {
  1832. $obj->price = $price_result;
  1833. }
  1834. }
  1835. $this->product_fourn_price_id = $obj->rowid;
  1836. $this->buyprice = $obj->price; // deprecated
  1837. $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier
  1838. $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier
  1839. $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier
  1840. $this->fourn_socid = $obj->fk_soc; // Company that offer this price
  1841. $this->ref_fourn = $obj->ref_supplier; // deprecated
  1842. $this->ref_supplier = $obj->ref_supplier; // Ref supplier
  1843. $this->desc_supplier = $obj->desc_supplier; // desc supplier
  1844. $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
  1845. $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
  1846. $this->default_vat_code_supplier = $obj->default_vat_code; // Vat code supplier
  1847. $this->fourn_multicurrency_price = $obj->multicurrency_price;
  1848. $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
  1849. $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
  1850. $this->fourn_multicurrency_id = $obj->fk_multicurrency;
  1851. $this->fourn_multicurrency_code = $obj->multicurrency_code;
  1852. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  1853. $this->packaging = $obj->packaging;
  1854. }
  1855. $result = $obj->fk_product;
  1856. return $result;
  1857. } else {
  1858. return -1; // Ce produit n'existe pas avec cet id tarif fournisseur ou existe mais qte insuffisante, ni pour le couple produit/ref fournisseur dans la quantité.
  1859. }
  1860. } else {
  1861. $this->error = $this->db->lasterror();
  1862. return -3;
  1863. }
  1864. }
  1865. } else {
  1866. $this->error = $this->db->lasterror();
  1867. return -2;
  1868. }
  1869. }
  1870. /**
  1871. * Modify customer price of a product/Service for a given level
  1872. *
  1873. * @param double $newprice New price
  1874. * @param string $newpricebase HT or TTC
  1875. * @param User $user Object user that make change
  1876. * @param double $newvat New VAT Rate (For example 8.5. Should not be a string)
  1877. * @param double $newminprice New price min
  1878. * @param int $level 0=standard, >0 = level if multilevel prices
  1879. * @param int $newnpr 0=Standard vat rate, 1=Special vat rate for French NPR VAT
  1880. * @param int $newpbq 1 if it has price by quantity
  1881. * @param int $ignore_autogen Used to avoid infinite loops
  1882. * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function).
  1883. * @param string $newdefaultvatcode Default vat code
  1884. * @return int <0 if KO, >0 if OK
  1885. */
  1886. public function updatePrice($newprice, $newpricebase, $user, $newvat = '', $newminprice = 0, $level = 0, $newnpr = 0, $newpbq = 0, $ignore_autogen = 0, $localtaxes_array = array(), $newdefaultvatcode = '')
  1887. {
  1888. global $conf, $langs;
  1889. $lastPriceData = $this->getArrayForPriceCompare($level); // temporary store current price before update
  1890. $id = $this->id;
  1891. dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode);
  1892. // Clean parameters
  1893. if (empty($this->tva_tx)) {
  1894. $this->tva_tx = 0;
  1895. }
  1896. if (empty($newnpr)) {
  1897. $newnpr = 0;
  1898. }
  1899. if (empty($newminprice)) {
  1900. $newminprice = 0;
  1901. }
  1902. if (empty($newminprice)) {
  1903. $newminprice = 0;
  1904. }
  1905. // Check parameters
  1906. if ($newvat == '') {
  1907. $newvat = $this->tva_tx;
  1908. }
  1909. // If multiprices are enabled, then we check if the current product is subject to price autogeneration
  1910. // Price will be modified ONLY when the first one is the one that is being modified
  1911. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !$ignore_autogen && $this->price_autogen && ($level == 1)) {
  1912. return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq);
  1913. }
  1914. if (!empty($newminprice) && ($newminprice > $newprice)) {
  1915. $this->error = 'ErrorPriceCantBeLowerThanMinPrice';
  1916. return -1;
  1917. }
  1918. if ($newprice !== '' || $newprice === 0) {
  1919. if ($newpricebase == 'TTC') {
  1920. $price_ttc = price2num($newprice, 'MU');
  1921. $price = price2num($newprice) / (1 + ($newvat / 100));
  1922. $price = price2num($price, 'MU');
  1923. if ($newminprice != '' || $newminprice == 0) {
  1924. $price_min_ttc = price2num($newminprice, 'MU');
  1925. $price_min = price2num($newminprice) / (1 + ($newvat / 100));
  1926. $price_min = price2num($price_min, 'MU');
  1927. } else {
  1928. $price_min = 0;
  1929. $price_min_ttc = 0;
  1930. }
  1931. } else {
  1932. $price = price2num($newprice, 'MU');
  1933. $price_ttc = ($newnpr != 1) ? (float) price2num($newprice) * (1 + ($newvat / 100)) : $price;
  1934. $price_ttc = price2num($price_ttc, 'MU');
  1935. if ($newminprice !== '' || $newminprice === 0) {
  1936. $price_min = price2num($newminprice, 'MU');
  1937. $price_min_ttc = price2num($newminprice) * (1 + ($newvat / 100));
  1938. $price_min_ttc = price2num($price_min_ttc, 'MU');
  1939. //print 'X'.$newminprice.'-'.$price_min;
  1940. } else {
  1941. $price_min = 0;
  1942. $price_min_ttc = 0;
  1943. }
  1944. }
  1945. //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc;
  1946. if (count($localtaxes_array) > 0) {
  1947. $localtaxtype1 = $localtaxes_array['0'];
  1948. $localtax1 = $localtaxes_array['1'];
  1949. $localtaxtype2 = $localtaxes_array['2'];
  1950. $localtax2 = $localtaxes_array['3'];
  1951. } else {
  1952. // if array empty, we try to use the vat code
  1953. if (!empty($newdefaultvatcode)) {
  1954. global $mysoc;
  1955. // Get record from code
  1956. $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
  1957. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  1958. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($mysoc->country_code)."'";
  1959. $sql .= " AND t.taux = ".((float) $newdefaultvatcode)." AND t.active = 1";
  1960. $sql .= " AND t.code = '".$this->db->escape($newdefaultvatcode)."'";
  1961. $resql = $this->db->query($sql);
  1962. if ($resql) {
  1963. $obj = $this->db->fetch_object($resql);
  1964. if ($obj) {
  1965. $npr = $obj->recuperableonly;
  1966. $localtax1 = $obj->localtax1;
  1967. $localtax2 = $obj->localtax2;
  1968. $localtaxtype1 = $obj->localtax1_type;
  1969. $localtaxtype2 = $obj->localtax2_type;
  1970. }
  1971. }
  1972. } else {
  1973. // old method. deprecated because we can't retrieve type
  1974. $localtaxtype1 = '0';
  1975. $localtax1 = get_localtax($newvat, 1);
  1976. $localtaxtype2 = '0';
  1977. $localtax2 = get_localtax($newvat, 2);
  1978. }
  1979. }
  1980. if (empty($localtax1)) {
  1981. $localtax1 = 0; // If = '' then = 0
  1982. }
  1983. if (empty($localtax2)) {
  1984. $localtax2 = 0; // If = '' then = 0
  1985. }
  1986. $this->db->begin();
  1987. // Ne pas mettre de quote sur les numeriques decimaux.
  1988. // Ceci provoque des stockages avec arrondis en base au lieu des valeurs exactes.
  1989. $sql = "UPDATE ".$this->db->prefix()."product SET";
  1990. $sql .= " price_base_type='".$this->db->escape($newpricebase)."',";
  1991. $sql .= " price=".$price.",";
  1992. $sql .= " price_ttc=".$price_ttc.",";
  1993. $sql .= " price_min=".$price_min.",";
  1994. $sql .= " price_min_ttc=".$price_min_ttc.",";
  1995. $sql .= " localtax1_tx=".($localtax1 >= 0 ? $localtax1 : 'NULL').",";
  1996. $sql .= " localtax2_tx=".($localtax2 >= 0 ? $localtax2 : 'NULL').",";
  1997. $sql .= " localtax1_type=".($localtaxtype1 != '' ? "'".$this->db->escape($localtaxtype1)."'" : "'0'").",";
  1998. $sql .= " localtax2_type=".($localtaxtype2 != '' ? "'".$this->db->escape($localtaxtype2)."'" : "'0'").",";
  1999. $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
  2000. $sql .= " tva_tx='".price2num($newvat)."',";
  2001. $sql .= " recuperableonly='".$this->db->escape($newnpr)."'";
  2002. $sql .= " WHERE rowid = ".((int) $id);
  2003. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  2004. $resql = $this->db->query($sql);
  2005. if ($resql) {
  2006. $this->multiprices[$level] = $price;
  2007. $this->multiprices_ttc[$level] = $price_ttc;
  2008. $this->multiprices_min[$level] = $price_min;
  2009. $this->multiprices_min_ttc[$level] = $price_min_ttc;
  2010. $this->multiprices_base_type[$level] = $newpricebase;
  2011. $this->multiprices_default_vat_code[$level] = $newdefaultvatcode;
  2012. $this->multiprices_tva_tx[$level] = $newvat;
  2013. $this->multiprices_recuperableonly[$level] = $newnpr;
  2014. $this->price = $price;
  2015. $this->price_ttc = $price_ttc;
  2016. $this->price_min = $price_min;
  2017. $this->price_min_ttc = $price_min_ttc;
  2018. $this->price_base_type = $newpricebase;
  2019. $this->default_vat_code = $newdefaultvatcode;
  2020. $this->tva_tx = $newvat;
  2021. $this->tva_npr = $newnpr;
  2022. //Local taxes
  2023. $this->localtax1_tx = $localtax1;
  2024. $this->localtax2_tx = $localtax2;
  2025. $this->localtax1_type = $localtaxtype1;
  2026. $this->localtax2_type = $localtaxtype2;
  2027. // Price by quantity
  2028. $this->price_by_qty = $newpbq;
  2029. // check if price have really change before log
  2030. $newPriceData = $this->getArrayForPriceCompare($level);
  2031. if (!empty(array_diff_assoc($newPriceData, $lastPriceData)) || empty($conf->global->PRODUIT_MULTIPRICES)) {
  2032. $this->_log_price($user, $level); // Save price for level into table product_price
  2033. }
  2034. $this->level = $level; // Store level of price edited for trigger
  2035. // Call trigger
  2036. $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user);
  2037. if ($result < 0) {
  2038. $this->db->rollback();
  2039. return -1;
  2040. }
  2041. // End call triggers
  2042. $this->db->commit();
  2043. } else {
  2044. $this->db->rollback();
  2045. $this->error = $this->db->lasterror();
  2046. return -1;
  2047. }
  2048. }
  2049. return 1;
  2050. }
  2051. /**
  2052. * Sets the supplier price expression
  2053. *
  2054. * @param int $expression_id Expression
  2055. * @return int <0 if KO, >0 if OK
  2056. * @deprecated Use Product::update instead
  2057. */
  2058. public function setPriceExpression($expression_id)
  2059. {
  2060. global $user;
  2061. $this->fk_price_expression = $expression_id;
  2062. return $this->update($this->id, $user);
  2063. }
  2064. /**
  2065. * Load a product in memory from database
  2066. *
  2067. * @param int $id Id of product/service to load
  2068. * @param string $ref Ref of product/service to load
  2069. * @param string $ref_ext Ref ext of product/service to load
  2070. * @param string $barcode Barcode of product/service to load
  2071. * @param int $ignore_expression When module dynamicprices is on, ignores the math expression for calculating price and uses the db value instead
  2072. * @param int $ignore_price_load Load product without loading $this->multiprices... array (when we are sure we don't need them)
  2073. * @param int $ignore_lang_load Load product without loading $this->multilangs language arrays (when we are sure we don't need them)
  2074. * @return int <0 if KO, 0 if not found, >0 if OK
  2075. */
  2076. public function fetch($id = '', $ref = '', $ref_ext = '', $barcode = '', $ignore_expression = 0, $ignore_price_load = 0, $ignore_lang_load = 0)
  2077. {
  2078. include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2079. global $langs, $conf;
  2080. dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref." ref_ext=".$ref_ext);
  2081. // Check parameters
  2082. if (!$id && !$ref && !$ref_ext && !$barcode) {
  2083. $this->error = 'ErrorWrongParameters';
  2084. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  2085. return -1;
  2086. }
  2087. $sql = "SELECT p.rowid, p.ref, p.ref_ext, p.label, p.description, p.url, p.note_public, p.note as note_private, p.customcode, p.fk_country, p.fk_state, p.lifetime, p.qc_frequency, p.price, p.price_ttc,";
  2088. $sql .= " p.price_min, p.price_min_ttc, p.price_base_type, p.cost_price, p.default_vat_code, p.tva_tx, p.recuperableonly as tva_npr, p.localtax1_tx, p.localtax2_tx, p.localtax1_type, p.localtax2_type, p.tosell,";
  2089. $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.fk_default_workstation, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
  2090. $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
  2091. $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished, p.fk_default_bom, p.mandatory_period,";
  2092. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  2093. $sql .= " p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,";
  2094. } else {
  2095. $sql .= " ppe.accountancy_code_buy, ppe.accountancy_code_buy_intra, ppe.accountancy_code_buy_export, ppe.accountancy_code_sell, ppe.accountancy_code_sell_intra, ppe.accountancy_code_sell_export,";
  2096. }
  2097. //For MultiCompany
  2098. //PMP per entity & Stocks Sharings stock_reel includes only stocks shared with this entity
  2099. $separatedEntityPMP = false; // Set to true to get the AWP from table llx_product_perentity instead of field 'pmp' into llx_product.
  2100. $separatedStock = false; // Set to true will count stock from subtable llx_product_stock. It is slower than using denormalized field 'stock', but it is required when using multientity and shared warehouses.
  2101. $visibleWarehousesEntities = $conf->entity;
  2102. if (!empty($conf->global->MULTICOMPANY_PRODUCT_SHARING_ENABLED)) {
  2103. if (!empty($conf->global->MULTICOMPANY_PMP_PER_ENTITY_ENABLED)) {
  2104. $checkPMPPerEntity = $this->db->query("SELECT pmp FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = ".((int) $id)." AND entity = ".(int) $conf->entity);
  2105. if ($this->db->num_rows($checkPMPPerEntity)>0) {
  2106. $separatedEntityPMP = true;
  2107. }
  2108. }
  2109. global $mc;
  2110. $separatedStock = true;
  2111. if (isset($mc->sharings['stock']) && !empty($mc->sharings['stock'])) {
  2112. $visibleWarehousesEntities .= "," . implode(",", $mc->sharings['stock']);
  2113. }
  2114. }
  2115. if ($separatedEntityPMP) {
  2116. $sql .= " ppe.pmp,";
  2117. } else {
  2118. $sql .= " p.pmp,";
  2119. }
  2120. $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
  2121. $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf,";
  2122. if ($separatedStock) {
  2123. $sql .= " SUM(sp.reel) as stock";
  2124. } else {
  2125. $sql .= " p.stock";
  2126. }
  2127. $sql .= " FROM ".$this->db->prefix()."product as p";
  2128. if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED) || $separatedEntityPMP) {
  2129. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
  2130. }
  2131. if ($separatedStock) {
  2132. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as sp ON sp.fk_product = p.rowid AND sp.fk_entrepot IN (SELECT rowid FROM ".$this->db->prefix()."entrepot WHERE entity IN (".$this->db->sanitize($visibleWarehousesEntities)."))";
  2133. }
  2134. if ($id) {
  2135. $sql .= " WHERE p.rowid = ".((int) $id);
  2136. } else {
  2137. $sql .= " WHERE p.entity IN (".getEntity($this->element).")";
  2138. if ($ref) {
  2139. $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
  2140. } elseif ($ref_ext) {
  2141. $sql .= " AND p.ref_ext = '".$this->db->escape($ref_ext)."'";
  2142. } elseif ($barcode) {
  2143. $sql .= " AND p.barcode = '".$this->db->escape($barcode)."'";
  2144. }
  2145. }
  2146. if ($separatedStock) {
  2147. $sql .= " GROUP BY p.rowid, p.ref, p.ref_ext, p.label, p.description, p.url, p.note_public, p.note, p.customcode, p.fk_country, p.fk_state, p.lifetime, p.qc_frequency, p.price, p.price_ttc,";
  2148. $sql .= " p.price_min, p.price_min_ttc, p.price_base_type, p.cost_price, p.default_vat_code, p.tva_tx, p.recuperableonly, p.localtax1_tx, p.localtax2_tx, p.localtax1_type, p.localtax2_type, p.tosell,";
  2149. $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.fk_default_workstation, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
  2150. $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
  2151. $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished,";
  2152. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  2153. $sql .= " p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,";
  2154. } else {
  2155. $sql .= " ppe.accountancy_code_buy, ppe.accountancy_code_buy_intra, ppe.accountancy_code_buy_export, ppe.accountancy_code_sell, ppe.accountancy_code_sell_intra, ppe.accountancy_code_sell_export,";
  2156. }
  2157. if ($separatedEntityPMP) {
  2158. $sql .= " ppe.pmp,";
  2159. } else {
  2160. $sql .= " p.pmp,";
  2161. }
  2162. $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
  2163. $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf";
  2164. if (!$separatedStock) {
  2165. $sql .= ", p.stock";
  2166. }
  2167. }
  2168. $resql = $this->db->query($sql);
  2169. if ($resql) {
  2170. unset($this->oldcopy);
  2171. if ($this->db->num_rows($resql) > 0) {
  2172. $obj = $this->db->fetch_object($resql);
  2173. $this->id = $obj->rowid;
  2174. $this->ref = $obj->ref;
  2175. $this->ref_ext = $obj->ref_ext;
  2176. $this->label = $obj->label;
  2177. $this->description = $obj->description;
  2178. $this->url = $obj->url;
  2179. $this->note_public = $obj->note_public;
  2180. $this->note_private = $obj->note_private;
  2181. $this->note = $obj->note_private; // deprecated
  2182. $this->type = $obj->fk_product_type;
  2183. $this->status = $obj->tosell;
  2184. $this->status_buy = $obj->tobuy;
  2185. $this->status_batch = $obj->tobatch;
  2186. $this->batch_mask = $obj->batch_mask;
  2187. $this->customcode = $obj->customcode;
  2188. $this->country_id = $obj->fk_country;
  2189. $this->country_code = getCountry($this->country_id, 2, $this->db);
  2190. $this->state_id = $obj->fk_state;
  2191. $this->lifetime = $obj->lifetime;
  2192. $this->qc_frequency = $obj->qc_frequency;
  2193. $this->price = $obj->price;
  2194. $this->price_ttc = $obj->price_ttc;
  2195. $this->price_min = $obj->price_min;
  2196. $this->price_min_ttc = $obj->price_min_ttc;
  2197. $this->price_base_type = $obj->price_base_type;
  2198. $this->cost_price = $obj->cost_price;
  2199. $this->default_vat_code = $obj->default_vat_code;
  2200. $this->tva_tx = $obj->tva_tx;
  2201. //! French VAT NPR
  2202. $this->tva_npr = $obj->tva_npr;
  2203. $this->recuperableonly = $obj->tva_npr; // For backward compatibility
  2204. //! Local taxes
  2205. $this->localtax1_tx = $obj->localtax1_tx;
  2206. $this->localtax2_tx = $obj->localtax2_tx;
  2207. $this->localtax1_type = $obj->localtax1_type;
  2208. $this->localtax2_type = $obj->localtax2_type;
  2209. $this->finished = $obj->finished;
  2210. $this->fk_default_bom = $obj->fk_default_bom;
  2211. $this->duration = $obj->duration;
  2212. $this->duration_value = substr($obj->duration, 0, dol_strlen($obj->duration) - 1);
  2213. $this->duration_unit = substr($obj->duration, -1);
  2214. $this->canvas = $obj->canvas;
  2215. $this->net_measure = $obj->net_measure;
  2216. $this->net_measure_units = $obj->net_measure_units;
  2217. $this->weight = $obj->weight;
  2218. $this->weight_units = $obj->weight_units;
  2219. $this->length = $obj->length;
  2220. $this->length_units = $obj->length_units;
  2221. $this->width = $obj->width;
  2222. $this->width_units = $obj->width_units;
  2223. $this->height = $obj->height;
  2224. $this->height_units = $obj->height_units;
  2225. $this->surface = $obj->surface;
  2226. $this->surface_units = $obj->surface_units;
  2227. $this->volume = $obj->volume;
  2228. $this->volume_units = $obj->volume_units;
  2229. $this->barcode = $obj->barcode;
  2230. $this->barcode_type = $obj->fk_barcode_type;
  2231. $this->accountancy_code_buy = $obj->accountancy_code_buy;
  2232. $this->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra;
  2233. $this->accountancy_code_buy_export = $obj->accountancy_code_buy_export;
  2234. $this->accountancy_code_sell = $obj->accountancy_code_sell;
  2235. $this->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra;
  2236. $this->accountancy_code_sell_export = $obj->accountancy_code_sell_export;
  2237. $this->fk_default_warehouse = $obj->fk_default_warehouse;
  2238. $this->fk_default_workstation = $obj->fk_default_workstation;
  2239. $this->seuil_stock_alerte = $obj->seuil_stock_alerte;
  2240. $this->desiredstock = $obj->desiredstock;
  2241. $this->stock_reel = $obj->stock;
  2242. $this->pmp = $obj->pmp;
  2243. $this->date_creation = $obj->datec;
  2244. $this->date_modification = $obj->tms;
  2245. $this->import_key = $obj->import_key;
  2246. $this->entity = $obj->entity;
  2247. $this->ref_ext = $obj->ref_ext;
  2248. $this->fk_price_expression = $obj->fk_price_expression;
  2249. $this->fk_unit = $obj->fk_unit;
  2250. $this->price_autogen = $obj->price_autogen;
  2251. $this->model_pdf = $obj->model_pdf;
  2252. $this->mandatory_period = $obj->mandatory_period;
  2253. $this->db->free($resql);
  2254. // fetch optionals attributes and labels
  2255. $this->fetch_optionals();
  2256. // Multilangs
  2257. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($ignore_lang_load)) {
  2258. $this->getMultiLangs();
  2259. }
  2260. // Load multiprices array
  2261. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) { // prices per segment
  2262. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  2263. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2264. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
  2265. $sql .= " FROM ".$this->db->prefix()."product_price";
  2266. $sql .= " WHERE entity IN (".getEntity('productprice').")";
  2267. $sql .= " AND price_level=".((int) $i);
  2268. $sql .= " AND fk_product = ".((int) $this->id);
  2269. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Get the most recent line
  2270. $sql .= " LIMIT 1"; // Only the first one
  2271. $resql = $this->db->query($sql);
  2272. if ($resql) {
  2273. $result = $this->db->fetch_array($resql);
  2274. $this->multiprices[$i] = $result ? $result["price"] : null;
  2275. $this->multiprices_ttc[$i] = $result ? $result["price_ttc"] : null;
  2276. $this->multiprices_min[$i] = $result ? $result["price_min"] : null;
  2277. $this->multiprices_min_ttc[$i] = $result ? $result["price_min_ttc"] : null;
  2278. $this->multiprices_base_type[$i] = $result ? $result["price_base_type"] : null;
  2279. // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
  2280. $this->multiprices_tva_tx[$i] = $result ? $result["tva_tx"].($result ? ' ('.$result['default_vat_code'].')' : '') : null;
  2281. $this->multiprices_recuperableonly[$i] = $result ? $result["recuperableonly"] : null;
  2282. // Price by quantity
  2283. /*
  2284. $this->prices_by_qty[$i]=$result["price_by_qty"];
  2285. $this->prices_by_qty_id[$i]=$result["rowid"];
  2286. // Récuperation de la liste des prix selon qty si flag positionné
  2287. if ($this->prices_by_qty[$i] == 1)
  2288. {
  2289. $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
  2290. $sql.= " FROM ".$this->db->prefix()."product_price_by_qty";
  2291. $sql.= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
  2292. $sql.= " ORDER BY quantity ASC";
  2293. $resultat=array();
  2294. $resql = $this->db->query($sql);
  2295. if ($resql)
  2296. {
  2297. $ii=0;
  2298. while ($result= $this->db->fetch_array($resql)) {
  2299. $resultat[$ii]=array();
  2300. $resultat[$ii]["rowid"]=$result["rowid"];
  2301. $resultat[$ii]["price"]= $result["price"];
  2302. $resultat[$ii]["unitprice"]= $result["unitprice"];
  2303. $resultat[$ii]["quantity"]= $result["quantity"];
  2304. $resultat[$ii]["remise_percent"]= $result["remise_percent"];
  2305. $resultat[$ii]["remise"]= $result["remise"]; // deprecated
  2306. $resultat[$ii]["price_base_type"]= $result["price_base_type"];
  2307. $ii++;
  2308. }
  2309. $this->prices_by_qty_list[$i]=$resultat;
  2310. }
  2311. else
  2312. {
  2313. dol_print_error($this->db);
  2314. return -1;
  2315. }
  2316. }*/
  2317. } else {
  2318. $this->error = $this->db->lasterror;
  2319. return -1;
  2320. }
  2321. }
  2322. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) { // prices per customers
  2323. // Nothing loaded by default. List may be very long.
  2324. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) { // prices per quantity
  2325. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2326. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
  2327. $sql .= " FROM ".$this->db->prefix()."product_price";
  2328. $sql .= " WHERE fk_product = ".((int) $this->id);
  2329. $sql .= " ORDER BY date_price DESC, rowid DESC";
  2330. $sql .= " LIMIT 1";
  2331. $resql = $this->db->query($sql);
  2332. if ($resql) {
  2333. $result = $this->db->fetch_array($resql);
  2334. // Price by quantity
  2335. $this->prices_by_qty[0] = $result["price_by_qty"];
  2336. $this->prices_by_qty_id[0] = $result["rowid"];
  2337. // Récuperation de la liste des prix selon qty si flag positionné
  2338. if ($this->prices_by_qty[0] == 1) {
  2339. $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type";
  2340. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2341. $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[0]);
  2342. $sql .= " ORDER BY quantity ASC";
  2343. $resultat = array();
  2344. $resql = $this->db->query($sql);
  2345. if ($resql) {
  2346. $ii = 0;
  2347. while ($result = $this->db->fetch_array($resql)) {
  2348. $resultat[$ii] = array();
  2349. $resultat[$ii]["rowid"] = $result["rowid"];
  2350. $resultat[$ii]["price"] = $result["price"];
  2351. $resultat[$ii]["unitprice"] = $result["unitprice"];
  2352. $resultat[$ii]["quantity"] = $result["quantity"];
  2353. $resultat[$ii]["remise_percent"] = $result["remise_percent"];
  2354. //$resultat[$ii]["remise"]= $result["remise"]; // deprecated
  2355. $resultat[$ii]["price_base_type"] = $result["price_base_type"];
  2356. $ii++;
  2357. }
  2358. $this->prices_by_qty_list[0] = $resultat;
  2359. } else {
  2360. $this->error = $this->db->lasterror;
  2361. return -1;
  2362. }
  2363. }
  2364. } else {
  2365. $this->error = $this->db->lasterror;
  2366. return -1;
  2367. }
  2368. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) { // prices per customer and quantity
  2369. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  2370. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2371. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
  2372. $sql .= " FROM ".$this->db->prefix()."product_price";
  2373. $sql .= " WHERE entity IN (".getEntity('productprice').")";
  2374. $sql .= " AND price_level=".((int) $i);
  2375. $sql .= " AND fk_product = ".((int) $this->id);
  2376. $sql .= " ORDER BY date_price DESC, rowid DESC";
  2377. $sql .= " LIMIT 1";
  2378. $resql = $this->db->query($sql);
  2379. if ($resql) {
  2380. $result = $this->db->fetch_array($resql);
  2381. $this->multiprices[$i] = $result["price"];
  2382. $this->multiprices_ttc[$i] = $result["price_ttc"];
  2383. $this->multiprices_min[$i] = $result["price_min"];
  2384. $this->multiprices_min_ttc[$i] = $result["price_min_ttc"];
  2385. $this->multiprices_base_type[$i] = $result["price_base_type"];
  2386. // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
  2387. $this->multiprices_tva_tx[$i] = $result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')'
  2388. $this->multiprices_recuperableonly[$i] = $result["recuperableonly"];
  2389. // Price by quantity
  2390. $this->prices_by_qty[$i] = $result["price_by_qty"];
  2391. $this->prices_by_qty_id[$i] = $result["rowid"];
  2392. // Récuperation de la liste des prix selon qty si flag positionné
  2393. if ($this->prices_by_qty[$i] == 1) {
  2394. $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
  2395. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2396. $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
  2397. $sql .= " ORDER BY quantity ASC";
  2398. $resultat = array();
  2399. $resql = $this->db->query($sql);
  2400. if ($resql) {
  2401. $ii = 0;
  2402. while ($result = $this->db->fetch_array($resql)) {
  2403. $resultat[$ii] = array();
  2404. $resultat[$ii]["rowid"] = $result["rowid"];
  2405. $resultat[$ii]["price"] = $result["price"];
  2406. $resultat[$ii]["unitprice"] = $result["unitprice"];
  2407. $resultat[$ii]["quantity"] = $result["quantity"];
  2408. $resultat[$ii]["remise_percent"] = $result["remise_percent"];
  2409. $resultat[$ii]["remise"] = $result["remise"]; // deprecated
  2410. $resultat[$ii]["price_base_type"] = $result["price_base_type"];
  2411. $ii++;
  2412. }
  2413. $this->prices_by_qty_list[$i] = $resultat;
  2414. } else {
  2415. $this->error = $this->db->lasterror;
  2416. return -1;
  2417. }
  2418. }
  2419. } else {
  2420. $this->error = $this->db->lasterror;
  2421. return -1;
  2422. }
  2423. }
  2424. }
  2425. if (isModEnabled('dynamicprices') && !empty($this->fk_price_expression) && empty($ignore_expression)) {
  2426. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2427. $priceparser = new PriceParser($this->db);
  2428. $price_result = $priceparser->parseProduct($this);
  2429. if ($price_result >= 0) {
  2430. $this->price = $price_result;
  2431. // Calculate the VAT
  2432. $this->price_ttc = price2num($this->price) * (1 + ($this->tva_tx / 100));
  2433. $this->price_ttc = price2num($this->price_ttc, 'MU');
  2434. }
  2435. }
  2436. // We should not load stock during the fetch. If someone need stock of product, he must call load_stock after fetching product.
  2437. // Instead we just init the stock_warehouse array
  2438. $this->stock_warehouse = array();
  2439. return 1;
  2440. } else {
  2441. return 0;
  2442. }
  2443. } else {
  2444. $this->error = $this->db->lasterror();
  2445. return -1;
  2446. }
  2447. }
  2448. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2449. /**
  2450. * Charge tableau des stats OF pour le produit/service
  2451. *
  2452. * @param int $socid Id societe
  2453. * @return int Array of stats in $this->stats_mo, <0 if ko or >0 if ok
  2454. */
  2455. public function load_stats_mo($socid = 0)
  2456. {
  2457. // phpcs:enable
  2458. global $user, $hookmanager, $action;
  2459. $error = 0;
  2460. foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
  2461. $this->stats_mo['customers_'.$role] = 0;
  2462. $this->stats_mo['nb_'.$role] = 0;
  2463. $this->stats_mo['qty_'.$role] = 0;
  2464. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  2465. $sql .= " SUM(mp.qty) as qty";
  2466. $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
  2467. $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
  2468. if (empty($user->rights->societe->client->voir) && !$socid) {
  2469. $sql .= "INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".((int) $user->id);
  2470. }
  2471. $sql .= " WHERE ";
  2472. $sql .= " c.entity IN (".getEntity('mo').")";
  2473. $sql .= " AND mp.fk_product = ".((int) $this->id);
  2474. $sql .= " AND mp.role ='".$this->db->escape($role)."'";
  2475. if ($socid > 0) {
  2476. $sql .= " AND c.fk_soc = ".((int) $socid);
  2477. }
  2478. $result = $this->db->query($sql);
  2479. if ($result) {
  2480. $obj = $this->db->fetch_object($result);
  2481. $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
  2482. $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
  2483. $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
  2484. } else {
  2485. $this->error = $this->db->error();
  2486. $error++;
  2487. }
  2488. }
  2489. if (!empty($error)) {
  2490. return -1;
  2491. }
  2492. $parameters = array('socid' => $socid);
  2493. $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
  2494. if ($reshook > 0) {
  2495. $this->stats_mo = $hookmanager->resArray['stats_mo'];
  2496. }
  2497. return 1;
  2498. }
  2499. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2500. /**
  2501. * Charge tableau des stats OF pour le produit/service
  2502. *
  2503. * @param int $socid Id societe
  2504. * @return int Array of stats in $this->stats_bom, <0 if ko or >0 if ok
  2505. */
  2506. public function load_stats_bom($socid = 0)
  2507. {
  2508. // phpcs:enable
  2509. global $user, $hookmanager, $action;
  2510. $error = 0;
  2511. $this->stats_bom['nb_toproduce'] = 0;
  2512. $this->stats_bom['nb_toconsume'] = 0;
  2513. $this->stats_bom['qty_toproduce'] = 0;
  2514. $this->stats_bom['qty_toconsume'] = 0;
  2515. $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,";
  2516. $sql .= " SUM(b.qty) as qty_toproduce";
  2517. $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
  2518. $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
  2519. $sql .= " WHERE ";
  2520. $sql .= " b.entity IN (".getEntity('bom').")";
  2521. $sql .= " AND b.fk_product =".((int) $this->id);
  2522. $sql .= " GROUP BY b.rowid";
  2523. $result = $this->db->query($sql);
  2524. if ($result) {
  2525. $obj = $this->db->fetch_object($result);
  2526. $this->stats_bom['nb_toproduce'] = !empty($obj->nb_toproduce) ? $obj->nb_toproduce : 0;
  2527. $this->stats_bom['qty_toproduce'] = !empty($obj->qty_toproduce) ? price2num($obj->qty_toproduce) : 0;
  2528. } else {
  2529. $this->error = $this->db->error();
  2530. $error++;
  2531. }
  2532. $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,";
  2533. $sql .= " SUM(bl.qty) as qty_toconsume";
  2534. $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
  2535. $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
  2536. $sql .= " WHERE ";
  2537. $sql .= " b.entity IN (".getEntity('bom').")";
  2538. $sql .= " AND bl.fk_product =".((int) $this->id);
  2539. $result = $this->db->query($sql);
  2540. if ($result) {
  2541. $obj = $this->db->fetch_object($result);
  2542. $this->stats_bom['nb_toconsume'] = !empty($obj->nb_toconsume) ? $obj->nb_toconsume : 0;
  2543. $this->stats_bom['qty_toconsume'] = !empty($obj->qty_toconsume) ? price2num($obj->qty_toconsume) : 0;
  2544. } else {
  2545. $this->error = $this->db->error();
  2546. $error++;
  2547. }
  2548. if (!empty($error)) {
  2549. return -1;
  2550. }
  2551. $parameters = array('socid' => $socid);
  2552. $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
  2553. if ($reshook > 0) {
  2554. $this->stats_bom = $hookmanager->resArray['stats_bom'];
  2555. }
  2556. return 1;
  2557. }
  2558. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2559. /**
  2560. * Charge tableau des stats propale pour le produit/service
  2561. *
  2562. * @param int $socid Id societe
  2563. * @return int Array of stats in $this->stats_propale, <0 if ko or >0 if ok
  2564. */
  2565. public function load_stats_propale($socid = 0)
  2566. {
  2567. // phpcs:enable
  2568. global $conf, $user, $hookmanager, $action;
  2569. $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_customers, COUNT(DISTINCT p.rowid) as nb,";
  2570. $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
  2571. $sql .= " FROM ".$this->db->prefix()."propaldet as pd";
  2572. $sql .= ", ".$this->db->prefix()."propal as p";
  2573. $sql .= ", ".$this->db->prefix()."societe as s";
  2574. if (empty($user->rights->societe->client->voir) && !$socid) {
  2575. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2576. }
  2577. $sql .= " WHERE p.rowid = pd.fk_propal";
  2578. $sql .= " AND p.fk_soc = s.rowid";
  2579. $sql .= " AND p.entity IN (".getEntity('propal').")";
  2580. $sql .= " AND pd.fk_product = ".((int) $this->id);
  2581. if (empty($user->rights->societe->client->voir) && !$socid) {
  2582. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2583. }
  2584. //$sql.= " AND pr.fk_statut != 0";
  2585. if ($socid > 0) {
  2586. $sql .= " AND p.fk_soc = ".((int) $socid);
  2587. }
  2588. $result = $this->db->query($sql);
  2589. if ($result) {
  2590. $obj = $this->db->fetch_object($result);
  2591. $this->stats_propale['customers'] = $obj->nb_customers;
  2592. $this->stats_propale['nb'] = $obj->nb;
  2593. $this->stats_propale['rows'] = $obj->nb_rows;
  2594. $this->stats_propale['qty'] = $obj->qty ? $obj->qty : 0;
  2595. // if it's a virtual product, maybe it is in proposal by extension
  2596. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2597. $TFather = $this->getFather();
  2598. if (is_array($TFather) && !empty($TFather)) {
  2599. foreach ($TFather as &$fatherData) {
  2600. $pFather = new Product($this->db);
  2601. $pFather->id = $fatherData['id'];
  2602. $qtyCoef = $fatherData['qty'];
  2603. if ($fatherData['incdec']) {
  2604. $pFather->load_stats_propale($socid);
  2605. $this->stats_propale['customers'] += $pFather->stats_propale['customers'];
  2606. $this->stats_propale['nb'] += $pFather->stats_propale['nb'];
  2607. $this->stats_propale['rows'] += $pFather->stats_propale['rows'];
  2608. $this->stats_propale['qty'] += $pFather->stats_propale['qty'] * $qtyCoef;
  2609. }
  2610. }
  2611. }
  2612. }
  2613. $parameters = array('socid' => $socid);
  2614. $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
  2615. if ($reshook > 0) {
  2616. $this->stats_propale = $hookmanager->resArray['stats_propale'];
  2617. }
  2618. return 1;
  2619. } else {
  2620. $this->error = $this->db->error();
  2621. return -1;
  2622. }
  2623. }
  2624. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2625. /**
  2626. * Charge tableau des stats propale pour le produit/service
  2627. *
  2628. * @param int $socid Id thirdparty
  2629. * @return int Array of stats in $this->stats_proposal_supplier, <0 if ko or >0 if ok
  2630. */
  2631. public function load_stats_proposal_supplier($socid = 0)
  2632. {
  2633. // phpcs:enable
  2634. global $conf, $user, $hookmanager, $action;
  2635. $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,";
  2636. $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
  2637. $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as pd";
  2638. $sql .= ", ".$this->db->prefix()."supplier_proposal as p";
  2639. $sql .= ", ".$this->db->prefix()."societe as s";
  2640. if (empty($user->rights->societe->client->voir) && !$socid) {
  2641. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2642. }
  2643. $sql .= " WHERE p.rowid = pd.fk_supplier_proposal";
  2644. $sql .= " AND p.fk_soc = s.rowid";
  2645. $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
  2646. $sql .= " AND pd.fk_product = ".((int) $this->id);
  2647. if (empty($user->rights->societe->client->voir) && !$socid) {
  2648. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2649. }
  2650. //$sql.= " AND pr.fk_statut != 0";
  2651. if ($socid > 0) {
  2652. $sql .= " AND p.fk_soc = ".((int) $socid);
  2653. }
  2654. $result = $this->db->query($sql);
  2655. if ($result) {
  2656. $obj = $this->db->fetch_object($result);
  2657. $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers;
  2658. $this->stats_proposal_supplier['nb'] = $obj->nb;
  2659. $this->stats_proposal_supplier['rows'] = $obj->nb_rows;
  2660. $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0;
  2661. $parameters = array('socid' => $socid);
  2662. $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
  2663. if ($reshook > 0) {
  2664. $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
  2665. }
  2666. return 1;
  2667. } else {
  2668. $this->error = $this->db->error();
  2669. return -1;
  2670. }
  2671. }
  2672. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2673. /**
  2674. * Charge tableau des stats commande client pour le produit/service
  2675. *
  2676. * @param int $socid Id societe pour filtrer sur une societe
  2677. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2678. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation. Set when load_stats_commande is used for virtual stock calculation.
  2679. * @return integer Array of stats in $this->stats_commande (nb=nb of order, qty=qty ordered), <0 if ko or >0 if ok
  2680. */
  2681. public function load_stats_commande($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2682. {
  2683. // phpcs:enable
  2684. global $conf, $user, $hookmanager, $action;
  2685. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  2686. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  2687. $sql .= " FROM ".$this->db->prefix()."commandedet as cd";
  2688. $sql .= ", ".$this->db->prefix()."commande as c";
  2689. $sql .= ", ".$this->db->prefix()."societe as s";
  2690. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2691. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2692. }
  2693. $sql .= " WHERE c.rowid = cd.fk_commande";
  2694. $sql .= " AND c.fk_soc = s.rowid";
  2695. $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'commande').")";
  2696. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2697. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2698. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2699. }
  2700. if ($socid > 0) {
  2701. $sql .= " AND c.fk_soc = ".((int) $socid);
  2702. }
  2703. if ($filtrestatut <> '') {
  2704. $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")";
  2705. }
  2706. $result = $this->db->query($sql);
  2707. if ($result) {
  2708. $obj = $this->db->fetch_object($result);
  2709. $this->stats_commande['customers'] = $obj->nb_customers;
  2710. $this->stats_commande['nb'] = $obj->nb;
  2711. $this->stats_commande['rows'] = $obj->nb_rows;
  2712. $this->stats_commande['qty'] = $obj->qty ? $obj->qty : 0;
  2713. // if it's a virtual product, maybe it is in order by extension
  2714. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2715. $TFather = $this->getFather();
  2716. if (is_array($TFather) && !empty($TFather)) {
  2717. foreach ($TFather as &$fatherData) {
  2718. $pFather = new Product($this->db);
  2719. $pFather->id = $fatherData['id'];
  2720. $qtyCoef = $fatherData['qty'];
  2721. if ($fatherData['incdec']) {
  2722. $pFather->load_stats_commande($socid, $filtrestatut);
  2723. $this->stats_commande['customers'] += $pFather->stats_commande['customers'];
  2724. $this->stats_commande['nb'] += $pFather->stats_commande['nb'];
  2725. $this->stats_commande['rows'] += $pFather->stats_commande['rows'];
  2726. $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef;
  2727. }
  2728. }
  2729. }
  2730. }
  2731. // If stock decrease is on invoice validation, the theorical stock continue to
  2732. // count the orders to ship in theorical stock when some are already removed by invoice validation.
  2733. if ($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  2734. if (!empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) {
  2735. // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation but only if order not yet invoice.
  2736. $adeduire = 0;
  2737. $sql = "SELECT sum(fd.qty) as count FROM ".$this->db->prefix()."facturedet as fd ";
  2738. $sql .= " JOIN ".$this->db->prefix()."facture as f ON fd.fk_facture = f.rowid ";
  2739. $sql .= " JOIN ".$this->db->prefix()."element_element as el ON ((el.fk_target = f.rowid AND el.targettype = 'facture' AND sourcetype = 'commande') OR (el.fk_source = f.rowid AND el.targettype = 'commande' AND sourcetype = 'facture'))";
  2740. $sql .= " JOIN ".$this->db->prefix()."commande as c ON el.fk_source = c.rowid ";
  2741. $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
  2742. dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
  2743. $resql = $this->db->query($sql);
  2744. if ($resql) {
  2745. if ($this->db->num_rows($resql) > 0) {
  2746. $obj = $this->db->fetch_object($resql);
  2747. $adeduire += $obj->count;
  2748. }
  2749. }
  2750. $this->stats_commande['qty'] -= $adeduire;
  2751. } else {
  2752. // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is off, we make a compensation with lines of invoices linked to the order
  2753. include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  2754. // For every order having invoice already validated we need to decrease stock cause it's in physical stock
  2755. $adeduire = 0;
  2756. $sql = 'SELECT sum(fd.qty) as count FROM '.MAIN_DB_PREFIX.'facturedet as fd ';
  2757. $sql .= ' JOIN '.MAIN_DB_PREFIX.'facture as f ON fd.fk_facture = f.rowid ';
  2758. $sql .= ' JOIN '.MAIN_DB_PREFIX."element_element as el ON ((el.fk_target = f.rowid AND el.targettype = 'facture' AND sourcetype = 'commande') OR (el.fk_source = f.rowid AND el.targettype = 'commande' AND sourcetype = 'facture'))";
  2759. $sql .= ' JOIN '.MAIN_DB_PREFIX.'commande as c ON el.fk_source = c.rowid ';
  2760. $sql .= ' WHERE c.fk_statut IN ('.$this->db->sanitize($filtrestatut).') AND f.fk_statut > '.Facture::STATUS_DRAFT.' AND fd.fk_product = '.((int) $this->id);
  2761. dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
  2762. $resql = $this->db->query($sql);
  2763. if ($resql) {
  2764. if ($this->db->num_rows($resql) > 0) {
  2765. $obj = $this->db->fetch_object($resql);
  2766. $adeduire += $obj->count;
  2767. }
  2768. }
  2769. $this->stats_commande['qty'] -= $adeduire;
  2770. }
  2771. }
  2772. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2773. $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
  2774. if ($reshook > 0) {
  2775. $this->stats_commande = $hookmanager->resArray['stats_commande'];
  2776. }
  2777. return 1;
  2778. } else {
  2779. $this->error = $this->db->error();
  2780. return -1;
  2781. }
  2782. }
  2783. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2784. /**
  2785. * Charge tableau des stats commande fournisseur pour le produit/service
  2786. *
  2787. * @param int $socid Id societe pour filtrer sur une societe
  2788. * @param string $filtrestatut Id des statuts pour filtrer sur des statuts
  2789. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2790. * @param int $dateofvirtualstock Date of virtual stock
  2791. * @return int Array of stats in $this->stats_commande_fournisseur, <0 if ko or >0 if ok
  2792. */
  2793. public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null)
  2794. {
  2795. // phpcs:enable
  2796. global $conf, $user, $hookmanager, $action;
  2797. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,";
  2798. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  2799. $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as cd";
  2800. $sql .= ", ".$this->db->prefix()."commande_fournisseur as c";
  2801. $sql .= ", ".$this->db->prefix()."societe as s";
  2802. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2803. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2804. }
  2805. $sql .= " WHERE c.rowid = cd.fk_commande";
  2806. $sql .= " AND c.fk_soc = s.rowid";
  2807. $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
  2808. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2809. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2810. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2811. }
  2812. if ($socid > 0) {
  2813. $sql .= " AND c.fk_soc = ".((int) $socid);
  2814. }
  2815. if ($filtrestatut != '') {
  2816. $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")"; // Peut valoir 0
  2817. }
  2818. if (!empty($dateofvirtualstock)) {
  2819. $sql .= " AND c.date_livraison <= '".$this->db->idate($dateofvirtualstock)."'";
  2820. }
  2821. $result = $this->db->query($sql);
  2822. if ($result) {
  2823. $obj = $this->db->fetch_object($result);
  2824. $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers;
  2825. $this->stats_commande_fournisseur['nb'] = $obj->nb;
  2826. $this->stats_commande_fournisseur['rows'] = $obj->nb_rows;
  2827. $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
  2828. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2829. $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
  2830. if ($reshook > 0) {
  2831. $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
  2832. }
  2833. return 1;
  2834. } else {
  2835. $this->error = $this->db->error().' sql='.$sql;
  2836. return -1;
  2837. }
  2838. }
  2839. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2840. /**
  2841. * Charge tableau des stats expedition client pour le produit/service
  2842. *
  2843. * @param int $socid Id societe pour filtrer sur une societe
  2844. * @param string $filtrestatut [=''] Ids order status separated by comma
  2845. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2846. * @param string $filterShipmentStatus [=''] Ids shipment status separated by comma
  2847. * @return int Array of stats in $this->stats_expedition, <0 if ko or >0 if ok
  2848. */
  2849. public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '')
  2850. {
  2851. // phpcs:enable
  2852. global $conf, $user, $hookmanager, $action;
  2853. $sql = "SELECT COUNT(DISTINCT e.fk_soc) as nb_customers, COUNT(DISTINCT e.rowid) as nb,";
  2854. $sql .= " COUNT(ed.rowid) as nb_rows, SUM(ed.qty) as qty";
  2855. $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
  2856. $sql .= ", ".$this->db->prefix()."commandedet as cd";
  2857. $sql .= ", ".$this->db->prefix()."commande as c";
  2858. $sql .= ", ".$this->db->prefix()."expedition as e";
  2859. $sql .= ", ".$this->db->prefix()."societe as s";
  2860. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2861. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2862. }
  2863. $sql .= " WHERE e.rowid = ed.fk_expedition";
  2864. $sql .= " AND c.rowid = cd.fk_commande";
  2865. $sql .= " AND e.fk_soc = s.rowid";
  2866. $sql .= " AND e.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'expedition').")";
  2867. $sql .= " AND ed.fk_origin_line = cd.rowid";
  2868. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2869. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2870. $sql .= " AND e.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2871. }
  2872. if ($socid > 0) {
  2873. $sql .= " AND e.fk_soc = ".((int) $socid);
  2874. }
  2875. if ($filtrestatut <> '') {
  2876. $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
  2877. }
  2878. if (!empty($filterShipmentStatus)) {
  2879. $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
  2880. }
  2881. $result = $this->db->query($sql);
  2882. if ($result) {
  2883. $obj = $this->db->fetch_object($result);
  2884. $this->stats_expedition['customers'] = $obj->nb_customers;
  2885. $this->stats_expedition['nb'] = $obj->nb;
  2886. $this->stats_expedition['rows'] = $obj->nb_rows;
  2887. $this->stats_expedition['qty'] = $obj->qty ? $obj->qty : 0;
  2888. // if it's a virtual product, maybe it is in sending by extension
  2889. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2890. $TFather = $this->getFather();
  2891. if (is_array($TFather) && !empty($TFather)) {
  2892. foreach ($TFather as &$fatherData) {
  2893. $pFather = new Product($this->db);
  2894. $pFather->id = $fatherData['id'];
  2895. $qtyCoef = $fatherData['qty'];
  2896. if ($fatherData['incdec']) {
  2897. $pFather->load_stats_sending($socid, $filtrestatut, $forVirtualStock);
  2898. $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
  2899. $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
  2900. $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
  2901. $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
  2902. }
  2903. }
  2904. }
  2905. }
  2906. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
  2907. $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
  2908. if ($reshook > 0) {
  2909. $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
  2910. }
  2911. return 1;
  2912. } else {
  2913. $this->error = $this->db->error();
  2914. return -1;
  2915. }
  2916. }
  2917. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2918. /**
  2919. * Charge tableau des stats réception fournisseur pour le produit/service
  2920. *
  2921. * @param int $socid Id societe pour filtrer sur une societe
  2922. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2923. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2924. * @param int $dateofvirtualstock Date of virtual stock
  2925. * @return int Array of stats in $this->stats_reception, <0 if ko or >0 if ok
  2926. */
  2927. public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null)
  2928. {
  2929. // phpcs:enable
  2930. global $conf, $user, $hookmanager, $action;
  2931. $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_suppliers, COUNT(DISTINCT cf.rowid) as nb,";
  2932. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
  2933. $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as fd";
  2934. $sql .= ", ".$this->db->prefix()."commande_fournisseur as cf";
  2935. $sql .= ", ".$this->db->prefix()."societe as s";
  2936. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2937. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2938. }
  2939. $sql .= " WHERE cf.rowid = fd.fk_commande";
  2940. $sql .= " AND cf.fk_soc = s.rowid";
  2941. $sql .= " AND cf.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
  2942. $sql .= " AND fd.fk_product = ".((int) $this->id);
  2943. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2944. $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2945. }
  2946. if ($socid > 0) {
  2947. $sql .= " AND cf.fk_soc = ".((int) $socid);
  2948. }
  2949. if ($filtrestatut <> '') {
  2950. $sql .= " AND cf.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
  2951. }
  2952. if (!empty($dateofvirtualstock)) {
  2953. $sql .= " AND fd.datec <= '".$this->db->idate($dateofvirtualstock)."'";
  2954. }
  2955. $result = $this->db->query($sql);
  2956. if ($result) {
  2957. $obj = $this->db->fetch_object($result);
  2958. $this->stats_reception['suppliers'] = $obj->nb_suppliers;
  2959. $this->stats_reception['nb'] = $obj->nb;
  2960. $this->stats_reception['rows'] = $obj->nb_rows;
  2961. $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
  2962. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2963. $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
  2964. if ($reshook > 0) {
  2965. $this->stats_reception = $hookmanager->resArray['stats_reception'];
  2966. }
  2967. return 1;
  2968. } else {
  2969. $this->error = $this->db->error();
  2970. return -1;
  2971. }
  2972. }
  2973. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2974. /**
  2975. * Charge tableau des stats production pour le produit/service
  2976. *
  2977. * @param int $socid Id societe pour filtrer sur une societe
  2978. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2979. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2980. * @param int $dateofvirtualstock Date of virtual stock
  2981. * @return integer Array of stats in $this->stats_mrptoproduce (nb=nb of order, qty=qty ordered), <0 if ko or >0 if ok
  2982. */
  2983. public function load_stats_inproduction($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $dateofvirtualstock = null)
  2984. {
  2985. // phpcs:enable
  2986. global $conf, $user, $hookmanager, $action;
  2987. $sql = "SELECT COUNT(DISTINCT m.fk_soc) as nb_customers, COUNT(DISTINCT m.rowid) as nb,";
  2988. $sql .= " COUNT(mp.rowid) as nb_rows, SUM(mp.qty) as qty, role";
  2989. $sql .= " FROM ".$this->db->prefix()."mrp_production as mp";
  2990. $sql .= ", ".$this->db->prefix()."mrp_mo as m";
  2991. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON s.rowid = m.fk_soc";
  2992. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2993. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2994. }
  2995. $sql .= " WHERE m.rowid = mp.fk_mo";
  2996. $sql .= " AND m.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'mrp').")";
  2997. $sql .= " AND mp.fk_product = ".((int) $this->id);
  2998. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2999. $sql .= " AND m.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3000. }
  3001. if ($socid > 0) {
  3002. $sql .= " AND m.fk_soc = ".((int) $socid);
  3003. }
  3004. if ($filtrestatut <> '') {
  3005. $sql .= " AND m.status IN (".$this->db->sanitize($filtrestatut).")";
  3006. }
  3007. if (!empty($dateofvirtualstock)) {
  3008. $sql .= " AND m.date_valid <= '".$this->db->idate($dateofvirtualstock)."'"; // better date to code ? end of production ?
  3009. }
  3010. $sql .= " GROUP BY role";
  3011. $this->stats_mrptoconsume['customers'] = 0;
  3012. $this->stats_mrptoconsume['nb'] = 0;
  3013. $this->stats_mrptoconsume['rows'] = 0;
  3014. $this->stats_mrptoconsume['qty'] = 0;
  3015. $this->stats_mrptoproduce['customers'] = 0;
  3016. $this->stats_mrptoproduce['nb'] = 0;
  3017. $this->stats_mrptoproduce['rows'] = 0;
  3018. $this->stats_mrptoproduce['qty'] = 0;
  3019. $result = $this->db->query($sql);
  3020. if ($result) {
  3021. while ($obj = $this->db->fetch_object($result)) {
  3022. if ($obj->role == 'toconsume') {
  3023. $this->stats_mrptoconsume['customers'] += $obj->nb_customers;
  3024. $this->stats_mrptoconsume['nb'] += $obj->nb;
  3025. $this->stats_mrptoconsume['rows'] += $obj->nb_rows;
  3026. $this->stats_mrptoconsume['qty'] += ($obj->qty ? $obj->qty : 0);
  3027. }
  3028. if ($obj->role == 'consumed') {
  3029. //$this->stats_mrptoconsume['customers'] += $obj->nb_customers;
  3030. //$this->stats_mrptoconsume['nb'] += $obj->nb;
  3031. //$this->stats_mrptoconsume['rows'] += $obj->nb_rows;
  3032. $this->stats_mrptoconsume['qty'] -= ($obj->qty ? $obj->qty : 0);
  3033. }
  3034. if ($obj->role == 'toproduce') {
  3035. $this->stats_mrptoproduce['customers'] += $obj->nb_customers;
  3036. $this->stats_mrptoproduce['nb'] += $obj->nb;
  3037. $this->stats_mrptoproduce['rows'] += $obj->nb_rows;
  3038. $this->stats_mrptoproduce['qty'] += ($obj->qty ? $obj->qty : 0);
  3039. }
  3040. if ($obj->role == 'produced') {
  3041. //$this->stats_mrptoproduce['customers'] += $obj->nb_customers;
  3042. //$this->stats_mrptoproduce['nb'] += $obj->nb;
  3043. //$this->stats_mrptoproduce['rows'] += $obj->nb_rows;
  3044. $this->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
  3045. }
  3046. }
  3047. // Clean data
  3048. if ($this->stats_mrptoconsume['qty'] < 0) {
  3049. $this->stats_mrptoconsume['qty'] = 0;
  3050. }
  3051. if ($this->stats_mrptoproduce['qty'] < 0) {
  3052. $this->stats_mrptoproduce['qty'] = 0;
  3053. }
  3054. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  3055. $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
  3056. if ($reshook > 0) {
  3057. $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
  3058. }
  3059. return 1;
  3060. } else {
  3061. $this->error = $this->db->error();
  3062. return -1;
  3063. }
  3064. }
  3065. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3066. /**
  3067. * Charge tableau des stats contrat pour le produit/service
  3068. *
  3069. * @param int $socid Id societe
  3070. * @return int Array of stats in $this->stats_contrat, <0 if ko or >0 if ok
  3071. */
  3072. public function load_stats_contrat($socid = 0)
  3073. {
  3074. // phpcs:enable
  3075. global $conf, $user, $hookmanager, $action;
  3076. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  3077. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  3078. $sql .= " FROM ".$this->db->prefix()."contratdet as cd";
  3079. $sql .= ", ".$this->db->prefix()."contrat as c";
  3080. $sql .= ", ".$this->db->prefix()."societe as s";
  3081. if (empty($user->rights->societe->client->voir) && !$socid) {
  3082. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3083. }
  3084. $sql .= " WHERE c.rowid = cd.fk_contrat";
  3085. $sql .= " AND c.fk_soc = s.rowid";
  3086. $sql .= " AND c.entity IN (".getEntity('contract').")";
  3087. $sql .= " AND cd.fk_product = ".((int) $this->id);
  3088. if (empty($user->rights->societe->client->voir) && !$socid) {
  3089. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3090. }
  3091. //$sql.= " AND c.statut != 0";
  3092. if ($socid > 0) {
  3093. $sql .= " AND c.fk_soc = ".((int) $socid);
  3094. }
  3095. $result = $this->db->query($sql);
  3096. if ($result) {
  3097. $obj = $this->db->fetch_object($result);
  3098. $this->stats_contrat['customers'] = $obj->nb_customers;
  3099. $this->stats_contrat['nb'] = $obj->nb;
  3100. $this->stats_contrat['rows'] = $obj->nb_rows;
  3101. $this->stats_contrat['qty'] = $obj->qty ? $obj->qty : 0;
  3102. // if it's a virtual product, maybe it is in contract by extension
  3103. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  3104. $TFather = $this->getFather();
  3105. if (is_array($TFather) && !empty($TFather)) {
  3106. foreach ($TFather as &$fatherData) {
  3107. $pFather = new Product($this->db);
  3108. $pFather->id = $fatherData['id'];
  3109. $qtyCoef = $fatherData['qty'];
  3110. if ($fatherData['incdec']) {
  3111. $pFather->load_stats_contrat($socid);
  3112. $this->stats_contrat['customers'] += $pFather->stats_contrat['customers'];
  3113. $this->stats_contrat['nb'] += $pFather->stats_contrat['nb'];
  3114. $this->stats_contrat['rows'] += $pFather->stats_contrat['rows'];
  3115. $this->stats_contrat['qty'] += $pFather->stats_contrat['qty'] * $qtyCoef;
  3116. }
  3117. }
  3118. }
  3119. }
  3120. $parameters = array('socid' => $socid);
  3121. $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
  3122. if ($reshook > 0) {
  3123. $this->stats_contrat = $hookmanager->resArray['stats_contrat'];
  3124. }
  3125. return 1;
  3126. } else {
  3127. $this->error = $this->db->error().' sql='.$sql;
  3128. return -1;
  3129. }
  3130. }
  3131. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3132. /**
  3133. * Charge tableau des stats facture pour le produit/service
  3134. *
  3135. * @param int $socid Id societe
  3136. * @return int Array of stats in $this->stats_facture, <0 if ko or >0 if ok
  3137. */
  3138. public function load_stats_facture($socid = 0)
  3139. {
  3140. // phpcs:enable
  3141. global $db, $conf, $user, $hookmanager, $action;
  3142. $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
  3143. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(".$this->db->ifsql('f.type != 2', 'fd.qty', 'fd.qty * -1').") as qty";
  3144. $sql .= " FROM ".$this->db->prefix()."facturedet as fd";
  3145. $sql .= ", ".$this->db->prefix()."facture as f";
  3146. $sql .= ", ".$this->db->prefix()."societe as s";
  3147. if (empty($user->rights->societe->client->voir) && !$socid) {
  3148. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3149. }
  3150. $sql .= " WHERE f.rowid = fd.fk_facture";
  3151. $sql .= " AND f.fk_soc = s.rowid";
  3152. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3153. $sql .= " AND fd.fk_product = ".((int) $this->id);
  3154. if (empty($user->rights->societe->client->voir) && !$socid) {
  3155. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3156. }
  3157. //$sql.= " AND f.fk_statut != 0";
  3158. if ($socid > 0) {
  3159. $sql .= " AND f.fk_soc = ".((int) $socid);
  3160. }
  3161. $result = $this->db->query($sql);
  3162. if ($result) {
  3163. $obj = $this->db->fetch_object($result);
  3164. $this->stats_facture['customers'] = $obj->nb_customers;
  3165. $this->stats_facture['nb'] = $obj->nb;
  3166. $this->stats_facture['rows'] = $obj->nb_rows;
  3167. $this->stats_facture['qty'] = $obj->qty ? $obj->qty : 0;
  3168. // if it's a virtual product, maybe it is in invoice by extension
  3169. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  3170. $TFather = $this->getFather();
  3171. if (is_array($TFather) && !empty($TFather)) {
  3172. foreach ($TFather as &$fatherData) {
  3173. $pFather = new Product($this->db);
  3174. $pFather->id = $fatherData['id'];
  3175. $qtyCoef = $fatherData['qty'];
  3176. if ($fatherData['incdec']) {
  3177. $pFather->load_stats_facture($socid);
  3178. $this->stats_facture['customers'] += $pFather->stats_facture['customers'];
  3179. $this->stats_facture['nb'] += $pFather->stats_facture['nb'];
  3180. $this->stats_facture['rows'] += $pFather->stats_facture['rows'];
  3181. $this->stats_facture['qty'] += $pFather->stats_facture['qty'] * $qtyCoef;
  3182. }
  3183. }
  3184. }
  3185. }
  3186. $parameters = array('socid' => $socid);
  3187. $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
  3188. if ($reshook > 0) {
  3189. $this->stats_facture = $hookmanager->resArray['stats_facture'];
  3190. }
  3191. return 1;
  3192. } else {
  3193. $this->error = $this->db->error();
  3194. return -1;
  3195. }
  3196. }
  3197. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3198. /**
  3199. * Charge tableau des stats facture recurrentes pour le produit/service
  3200. *
  3201. * @param int $socid Id societe
  3202. * @return int Array of stats in $this->stats_facture, <0 if ko or >0 if ok
  3203. */
  3204. public function load_stats_facturerec($socid = 0)
  3205. {
  3206. // phpcs:enable
  3207. global $db, $conf, $user, $hookmanager;
  3208. $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
  3209. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
  3210. $sql .= " FROM ".MAIN_DB_PREFIX."facturedet_rec as fd";
  3211. $sql .= ", ".MAIN_DB_PREFIX."facture_rec as f";
  3212. $sql .= ", ".MAIN_DB_PREFIX."societe as s";
  3213. if (empty($user->rights->societe->client->voir) && !$socid) {
  3214. $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
  3215. }
  3216. $sql .= " WHERE f.rowid = fd.fk_facture";
  3217. $sql .= " AND f.fk_soc = s.rowid";
  3218. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3219. $sql .= " AND fd.fk_product = ".((int) $this->id);
  3220. if (empty($user->rights->societe->client->voir) && !$socid) {
  3221. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3222. }
  3223. //$sql.= " AND f.fk_statut != 0";
  3224. if ($socid > 0) {
  3225. $sql .= " AND f.fk_soc = ".((int) $socid);
  3226. }
  3227. $result = $this->db->query($sql);
  3228. if ($result) {
  3229. $obj = $this->db->fetch_object($result);
  3230. $this->stats_facturerec['customers'] = $obj->nb_customers;
  3231. $this->stats_facturerec['nb'] = $obj->nb;
  3232. $this->stats_facturerec['rows'] = $obj->nb_rows;
  3233. $this->stats_facturerec['qty'] = $obj->qty ? $obj->qty : 0;
  3234. // if it's a virtual product, maybe it is in invoice by extension
  3235. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  3236. $TFather = $this->getFather();
  3237. if (is_array($TFather) && !empty($TFather)) {
  3238. foreach ($TFather as &$fatherData) {
  3239. $pFather = new Product($this->db);
  3240. $pFather->id = $fatherData['id'];
  3241. $qtyCoef = $fatherData['qty'];
  3242. if ($fatherData['incdec']) {
  3243. $pFather->load_stats_facture($socid);
  3244. $this->stats_facturerec['customers'] += $pFather->stats_facturerec['customers'];
  3245. $this->stats_facturerec['nb'] += $pFather->stats_facturerec['nb'];
  3246. $this->stats_facturerec['rows'] += $pFather->stats_facturerec['rows'];
  3247. $this->stats_facturerec['qty'] += $pFather->stats_facturerec['qty'] * $qtyCoef;
  3248. }
  3249. }
  3250. }
  3251. }
  3252. $parameters = array('socid' => $socid);
  3253. $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoiceRec', $parameters, $this, $action);
  3254. if ($reshook > 0) {
  3255. $this->stats_facturerec = $hookmanager->resArray['stats_facturerec'];
  3256. }
  3257. return 1;
  3258. } else {
  3259. $this->error = $this->db->error();
  3260. return -1;
  3261. }
  3262. }
  3263. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3264. /**
  3265. * Charge tableau des stats facture pour le produit/service
  3266. *
  3267. * @param int $socid Id societe
  3268. * @return int Array of stats in $this->stats_facture_fournisseur, <0 if ko or >0 if ok
  3269. */
  3270. public function load_stats_facture_fournisseur($socid = 0)
  3271. {
  3272. // phpcs:enable
  3273. global $conf, $user, $hookmanager, $action;
  3274. $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
  3275. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
  3276. $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as fd";
  3277. $sql .= ", ".$this->db->prefix()."facture_fourn as f";
  3278. $sql .= ", ".$this->db->prefix()."societe as s";
  3279. if (empty($user->rights->societe->client->voir) && !$socid) {
  3280. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3281. }
  3282. $sql .= " WHERE f.rowid = fd.fk_facture_fourn";
  3283. $sql .= " AND f.fk_soc = s.rowid";
  3284. $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
  3285. $sql .= " AND fd.fk_product = ".((int) $this->id);
  3286. if (empty($user->rights->societe->client->voir) && !$socid) {
  3287. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3288. }
  3289. //$sql.= " AND f.fk_statut != 0";
  3290. if ($socid > 0) {
  3291. $sql .= " AND f.fk_soc = ".((int) $socid);
  3292. }
  3293. $result = $this->db->query($sql);
  3294. if ($result) {
  3295. $obj = $this->db->fetch_object($result);
  3296. $this->stats_facture_fournisseur['suppliers'] = $obj->nb_suppliers;
  3297. $this->stats_facture_fournisseur['nb'] = $obj->nb;
  3298. $this->stats_facture_fournisseur['rows'] = $obj->nb_rows;
  3299. $this->stats_facture_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
  3300. $parameters = array('socid' => $socid);
  3301. $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
  3302. if ($reshook > 0) {
  3303. $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
  3304. }
  3305. return 1;
  3306. } else {
  3307. $this->error = $this->db->error();
  3308. return -1;
  3309. }
  3310. }
  3311. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3312. /**
  3313. * Return an array formated for showing graphs
  3314. *
  3315. * @param string $sql Request to execute
  3316. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3317. * @param int $year Year (0=current year, -1=all years)
  3318. * @return array|int <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3319. */
  3320. private function _get_stats($sql, $mode, $year = 0)
  3321. {
  3322. // phpcs:enable
  3323. $tab = array();
  3324. $resql = $this->db->query($sql);
  3325. if ($resql) {
  3326. $num = $this->db->num_rows($resql);
  3327. $i = 0;
  3328. while ($i < $num) {
  3329. $arr = $this->db->fetch_array($resql);
  3330. $keyfortab = (string) $arr[1];
  3331. if ($year == -1) {
  3332. $keyfortab = substr($keyfortab, -2);
  3333. }
  3334. if ($mode == 'byunit') {
  3335. $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[0]; // 1st field
  3336. } elseif ($mode == 'bynumber') {
  3337. $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
  3338. }
  3339. $i++;
  3340. }
  3341. } else {
  3342. $this->error = $this->db->error().' sql='.$sql;
  3343. return -1;
  3344. }
  3345. if (empty($year)) {
  3346. $year = strftime('%Y', time());
  3347. $month = strftime('%m', time());
  3348. } elseif ($year == -1) {
  3349. $year = '';
  3350. $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
  3351. } else {
  3352. $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
  3353. }
  3354. $result = array();
  3355. for ($j = 0; $j < 12; $j++) {
  3356. // $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
  3357. $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
  3358. //print $idx.'-'.$year.'-'.$month.'<br>';
  3359. $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0);
  3360. // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0);
  3361. $month = "0".($month - 1);
  3362. if (dol_strlen($month) == 3) {
  3363. $month = substr($month, 1);
  3364. }
  3365. if ($month == 0) {
  3366. $month = 12;
  3367. $year = $year - 1;
  3368. }
  3369. }
  3370. return array_reverse($result);
  3371. }
  3372. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3373. /**
  3374. * Return nb of units or customers invoices in which product is included
  3375. *
  3376. * @param int $socid Limit count on a particular third party id
  3377. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3378. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3379. * @param int $year Year (0=last 12 month, -1=all years)
  3380. * @param string $morefilter More sql filters
  3381. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3382. */
  3383. public function get_nb_vente($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3384. {
  3385. // phpcs:enable
  3386. global $conf;
  3387. global $user;
  3388. $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
  3389. if ($mode == 'bynumber') {
  3390. $sql .= ", count(DISTINCT f.rowid)";
  3391. }
  3392. $sql .= " FROM ".$this->db->prefix()."facturedet as d, ".$this->db->prefix()."facture as f, ".$this->db->prefix()."societe as s";
  3393. if ($filteronproducttype >= 0) {
  3394. $sql .= ", ".$this->db->prefix()."product as p";
  3395. }
  3396. if (empty($user->rights->societe->client->voir) && !$socid) {
  3397. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3398. }
  3399. $sql .= " WHERE f.rowid = d.fk_facture";
  3400. if ($this->id > 0) {
  3401. $sql .= " AND d.fk_product = ".((int) $this->id);
  3402. } else {
  3403. $sql .= " AND d.fk_product > 0";
  3404. }
  3405. if ($filteronproducttype >= 0) {
  3406. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3407. }
  3408. $sql .= " AND f.fk_soc = s.rowid";
  3409. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3410. if (empty($user->rights->societe->client->voir) && !$socid) {
  3411. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3412. }
  3413. if ($socid > 0) {
  3414. $sql .= " AND f.fk_soc = $socid";
  3415. }
  3416. $sql .= $morefilter;
  3417. $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
  3418. $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
  3419. return $this->_get_stats($sql, $mode, $year);
  3420. }
  3421. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3422. /**
  3423. * Return nb of units or supplier invoices in which product is included
  3424. *
  3425. * @param int $socid Limit count on a particular third party id
  3426. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3427. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3428. * @param int $year Year (0=last 12 month, -1=all years)
  3429. * @param string $morefilter More sql filters
  3430. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3431. */
  3432. public function get_nb_achat($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3433. {
  3434. // phpcs:enable
  3435. global $conf;
  3436. global $user;
  3437. $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
  3438. if ($mode == 'bynumber') {
  3439. $sql .= ", count(DISTINCT f.rowid)";
  3440. }
  3441. $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as d, ".$this->db->prefix()."facture_fourn as f, ".$this->db->prefix()."societe as s";
  3442. if ($filteronproducttype >= 0) {
  3443. $sql .= ", ".$this->db->prefix()."product as p";
  3444. }
  3445. if (empty($user->rights->societe->client->voir) && !$socid) {
  3446. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3447. }
  3448. $sql .= " WHERE f.rowid = d.fk_facture_fourn";
  3449. if ($this->id > 0) {
  3450. $sql .= " AND d.fk_product = ".((int) $this->id);
  3451. } else {
  3452. $sql .= " AND d.fk_product > 0";
  3453. }
  3454. if ($filteronproducttype >= 0) {
  3455. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3456. }
  3457. $sql .= " AND f.fk_soc = s.rowid";
  3458. $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
  3459. if (empty($user->rights->societe->client->voir) && !$socid) {
  3460. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3461. }
  3462. if ($socid > 0) {
  3463. $sql .= " AND f.fk_soc = $socid";
  3464. }
  3465. $sql .= $morefilter;
  3466. $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
  3467. $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
  3468. return $this->_get_stats($sql, $mode, $year);
  3469. }
  3470. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3471. /**
  3472. * Return nb of units in proposals in which product is included
  3473. *
  3474. * @param int $socid Limit count on a particular third party id
  3475. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3476. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3477. * @param int $year Year (0=last 12 month, -1=all years)
  3478. * @param string $morefilter More sql filters
  3479. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3480. */
  3481. public function get_nb_propal($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3482. {
  3483. // phpcs:enable
  3484. global $conf, $user;
  3485. $sql = "SELECT sum(d.qty), date_format(p.datep, '%Y%m')";
  3486. if ($mode == 'bynumber') {
  3487. $sql .= ", count(DISTINCT p.rowid)";
  3488. }
  3489. $sql .= " FROM ".$this->db->prefix()."propaldet as d, ".$this->db->prefix()."propal as p, ".$this->db->prefix()."societe as s";
  3490. if ($filteronproducttype >= 0) {
  3491. $sql .= ", ".$this->db->prefix()."product as prod";
  3492. }
  3493. if (empty($user->rights->societe->client->voir) && !$socid) {
  3494. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3495. }
  3496. $sql .= " WHERE p.rowid = d.fk_propal";
  3497. if ($this->id > 0) {
  3498. $sql .= " AND d.fk_product = ".((int) $this->id);
  3499. } else {
  3500. $sql .= " AND d.fk_product > 0";
  3501. }
  3502. if ($filteronproducttype >= 0) {
  3503. $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
  3504. }
  3505. $sql .= " AND p.fk_soc = s.rowid";
  3506. $sql .= " AND p.entity IN (".getEntity('propal').")";
  3507. if (empty($user->rights->societe->client->voir) && !$socid) {
  3508. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3509. }
  3510. if ($socid > 0) {
  3511. $sql .= " AND p.fk_soc = ".((int) $socid);
  3512. }
  3513. $sql .= $morefilter;
  3514. $sql .= " GROUP BY date_format(p.datep,'%Y%m')";
  3515. $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC";
  3516. return $this->_get_stats($sql, $mode, $year);
  3517. }
  3518. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3519. /**
  3520. * Return nb of units in proposals in which product is included
  3521. *
  3522. * @param int $socid Limit count on a particular third party id
  3523. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3524. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3525. * @param int $year Year (0=last 12 month, -1=all years)
  3526. * @param string $morefilter More sql filters
  3527. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3528. */
  3529. public function get_nb_propalsupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3530. {
  3531. // phpcs:enable
  3532. global $conf;
  3533. global $user;
  3534. $sql = "SELECT sum(d.qty), date_format(p.date_valid, '%Y%m')";
  3535. if ($mode == 'bynumber') {
  3536. $sql .= ", count(DISTINCT p.rowid)";
  3537. }
  3538. $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as d, ".$this->db->prefix()."supplier_proposal as p, ".$this->db->prefix()."societe as s";
  3539. if ($filteronproducttype >= 0) {
  3540. $sql .= ", ".$this->db->prefix()."product as prod";
  3541. }
  3542. if (empty($user->rights->societe->client->voir) && !$socid) {
  3543. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3544. }
  3545. $sql .= " WHERE p.rowid = d.fk_supplier_proposal";
  3546. if ($this->id > 0) {
  3547. $sql .= " AND d.fk_product = ".((int) $this->id);
  3548. } else {
  3549. $sql .= " AND d.fk_product > 0";
  3550. }
  3551. if ($filteronproducttype >= 0) {
  3552. $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
  3553. }
  3554. $sql .= " AND p.fk_soc = s.rowid";
  3555. $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
  3556. if (empty($user->rights->societe->client->voir) && !$socid) {
  3557. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3558. }
  3559. if ($socid > 0) {
  3560. $sql .= " AND p.fk_soc = ".((int) $socid);
  3561. }
  3562. $sql .= $morefilter;
  3563. $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')";
  3564. $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC";
  3565. return $this->_get_stats($sql, $mode, $year);
  3566. }
  3567. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3568. /**
  3569. * Return nb of units in orders in which product is included
  3570. *
  3571. * @param int $socid Limit count on a particular third party id
  3572. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3573. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3574. * @param int $year Year (0=last 12 month, -1=all years)
  3575. * @param string $morefilter More sql filters
  3576. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3577. */
  3578. public function get_nb_order($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3579. {
  3580. // phpcs:enable
  3581. global $conf, $user;
  3582. $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
  3583. if ($mode == 'bynumber') {
  3584. $sql .= ", count(DISTINCT c.rowid)";
  3585. }
  3586. $sql .= " FROM ".$this->db->prefix()."commandedet as d, ".$this->db->prefix()."commande as c, ".$this->db->prefix()."societe as s";
  3587. if ($filteronproducttype >= 0) {
  3588. $sql .= ", ".$this->db->prefix()."product as p";
  3589. }
  3590. if (empty($user->rights->societe->client->voir) && !$socid) {
  3591. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3592. }
  3593. $sql .= " WHERE c.rowid = d.fk_commande";
  3594. if ($this->id > 0) {
  3595. $sql .= " AND d.fk_product = ".((int) $this->id);
  3596. } else {
  3597. $sql .= " AND d.fk_product > 0";
  3598. }
  3599. if ($filteronproducttype >= 0) {
  3600. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3601. }
  3602. $sql .= " AND c.fk_soc = s.rowid";
  3603. $sql .= " AND c.entity IN (".getEntity('commande').")";
  3604. if (empty($user->rights->societe->client->voir) && !$socid) {
  3605. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3606. }
  3607. if ($socid > 0) {
  3608. $sql .= " AND c.fk_soc = ".((int) $socid);
  3609. }
  3610. $sql .= $morefilter;
  3611. $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
  3612. $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
  3613. return $this->_get_stats($sql, $mode, $year);
  3614. }
  3615. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3616. /**
  3617. * Return nb of units in orders in which product is included
  3618. *
  3619. * @param int $socid Limit count on a particular third party id
  3620. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3621. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3622. * @param int $year Year (0=last 12 month, -1=all years)
  3623. * @param string $morefilter More sql filters
  3624. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3625. */
  3626. public function get_nb_ordersupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3627. {
  3628. // phpcs:enable
  3629. global $conf, $user;
  3630. $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
  3631. if ($mode == 'bynumber') {
  3632. $sql .= ", count(DISTINCT c.rowid)";
  3633. }
  3634. $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as d, ".$this->db->prefix()."commande_fournisseur as c, ".$this->db->prefix()."societe as s";
  3635. if ($filteronproducttype >= 0) {
  3636. $sql .= ", ".$this->db->prefix()."product as p";
  3637. }
  3638. if (empty($user->rights->societe->client->voir) && !$socid) {
  3639. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3640. }
  3641. $sql .= " WHERE c.rowid = d.fk_commande";
  3642. if ($this->id > 0) {
  3643. $sql .= " AND d.fk_product = ".((int) $this->id);
  3644. } else {
  3645. $sql .= " AND d.fk_product > 0";
  3646. }
  3647. if ($filteronproducttype >= 0) {
  3648. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3649. }
  3650. $sql .= " AND c.fk_soc = s.rowid";
  3651. $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
  3652. if (empty($user->rights->societe->client->voir) && !$socid) {
  3653. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3654. }
  3655. if ($socid > 0) {
  3656. $sql .= " AND c.fk_soc = ".((int) $socid);
  3657. }
  3658. $sql .= $morefilter;
  3659. $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
  3660. $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
  3661. return $this->_get_stats($sql, $mode, $year);
  3662. }
  3663. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3664. /**
  3665. * Return nb of units in orders in which product is included
  3666. *
  3667. * @param int $socid Limit count on a particular third party id
  3668. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3669. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3670. * @param int $year Year (0=last 12 month, -1=all years)
  3671. * @param string $morefilter More sql filters
  3672. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3673. */
  3674. public function get_nb_contract($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3675. {
  3676. // phpcs:enable
  3677. global $conf, $user;
  3678. $sql = "SELECT sum(d.qty), date_format(c.date_contrat, '%Y%m')";
  3679. if ($mode == 'bynumber') {
  3680. $sql .= ", count(DISTINCT c.rowid)";
  3681. }
  3682. $sql .= " FROM ".$this->db->prefix()."contratdet as d, ".$this->db->prefix()."contrat as c, ".$this->db->prefix()."societe as s";
  3683. if ($filteronproducttype >= 0) {
  3684. $sql .= ", ".$this->db->prefix()."product as p";
  3685. }
  3686. if (empty($user->rights->societe->client->voir) && !$socid) {
  3687. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3688. }
  3689. $sql .= " WHERE c.entity IN (".getEntity('contract').")";
  3690. $sql .= " AND c.rowid = d.fk_contrat";
  3691. if ($this->id > 0) {
  3692. $sql .= " AND d.fk_product = ".((int) $this->id);
  3693. } else {
  3694. $sql .= " AND d.fk_product > 0";
  3695. }
  3696. if ($filteronproducttype >= 0) {
  3697. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3698. }
  3699. $sql .= " AND c.fk_soc = s.rowid";
  3700. if (empty($user->rights->societe->client->voir) && !$socid) {
  3701. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3702. }
  3703. if ($socid > 0) {
  3704. $sql .= " AND c.fk_soc = ".((int) $socid);
  3705. }
  3706. $sql .= $morefilter;
  3707. $sql .= " GROUP BY date_format(c.date_contrat,'%Y%m')";
  3708. $sql .= " ORDER BY date_format(c.date_contrat,'%Y%m') DESC";
  3709. return $this->_get_stats($sql, $mode, $year);
  3710. }
  3711. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3712. /**
  3713. * Return nb of units in orders in which product is included
  3714. *
  3715. * @param int $socid Limit count on a particular third party id
  3716. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3717. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3718. * @param int $year Year (0=last 12 month, -1=all years)
  3719. * @param string $morefilter More sql filters
  3720. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3721. */
  3722. public function get_nb_mos($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3723. {
  3724. // phpcs:enable
  3725. global $conf, $user;
  3726. $sql = "SELECT sum(d.qty), date_format(d.date_valid, '%Y%m')";
  3727. if ($mode == 'bynumber') {
  3728. $sql .= ", count(DISTINCT d.rowid)";
  3729. }
  3730. $sql .= " FROM ".$this->db->prefix()."mrp_mo as d LEFT JOIN ".$this->db->prefix()."societe as s ON d.fk_soc = s.rowid";
  3731. if ($filteronproducttype >= 0) {
  3732. $sql .= ", ".$this->db->prefix()."product as p";
  3733. }
  3734. if (empty($user->rights->societe->client->voir) && !$socid) {
  3735. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3736. }
  3737. $sql .= " WHERE d.entity IN (".getEntity('mo').")";
  3738. $sql .= " AND d.status > 0";
  3739. if ($this->id > 0) {
  3740. $sql .= " AND d.fk_product = ".((int) $this->id);
  3741. } else {
  3742. $sql .= " AND d.fk_product > 0";
  3743. }
  3744. if ($filteronproducttype >= 0) {
  3745. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3746. }
  3747. if (empty($user->rights->societe->client->voir) && !$socid) {
  3748. $sql .= " AND d.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3749. }
  3750. if ($socid > 0) {
  3751. $sql .= " AND d.fk_soc = ".((int) $socid);
  3752. }
  3753. $sql .= $morefilter;
  3754. $sql .= " GROUP BY date_format(d.date_valid,'%Y%m')";
  3755. $sql .= " ORDER BY date_format(d.date_valid,'%Y%m') DESC";
  3756. return $this->_get_stats($sql, $mode, $year);
  3757. }
  3758. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3759. /**
  3760. * Link a product/service to a parent product/service
  3761. *
  3762. * @param int $id_pere Id of parent product/service
  3763. * @param int $id_fils Id of child product/service
  3764. * @param int $qty Quantity
  3765. * @param int $incdec 1=Increase/decrease stock of child when parent stock increase/decrease
  3766. * @return int < 0 if KO, > 0 if OK
  3767. */
  3768. public function add_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
  3769. {
  3770. // phpcs:enable
  3771. // Clean parameters
  3772. if (!is_numeric($id_pere)) {
  3773. $id_pere = 0;
  3774. }
  3775. if (!is_numeric($id_fils)) {
  3776. $id_fils = 0;
  3777. }
  3778. if (!is_numeric($incdec)) {
  3779. $incdec = 0;
  3780. }
  3781. $result = $this->del_sousproduit($id_pere, $id_fils);
  3782. if ($result < 0) {
  3783. return $result;
  3784. }
  3785. // Check not already father of id_pere (to avoid father -> child -> father links)
  3786. $sql = "SELECT fk_product_pere from ".$this->db->prefix()."product_association";
  3787. $sql .= " WHERE fk_product_pere = ".((int) $id_fils)." AND fk_product_fils = ".((int) $id_pere);
  3788. if (!$this->db->query($sql)) {
  3789. dol_print_error($this->db);
  3790. return -1;
  3791. } else {
  3792. //Selection of the highest row
  3793. $sql = "SELECT MAX(rang) as max_rank FROM ".$this->db->prefix()."product_association";
  3794. $sql .= " WHERE fk_product_pere = ".((int) $id_pere);
  3795. $resql = $this->db->query($sql);
  3796. if ($resql) {
  3797. $obj = $this->db->fetch_object($resql);
  3798. $rank = $obj->max_rank + 1;
  3799. //Addition of a product with the highest rank +1
  3800. $sql = "INSERT INTO ".$this->db->prefix()."product_association(fk_product_pere,fk_product_fils,qty,incdec,rang)";
  3801. $sql .= " VALUES (".((int) $id_pere).", ".((int) $id_fils).", ".price2num($qty, 'MS').", ".price2num($incdec, 'MS').", ".((int) $rank).")";
  3802. if (! $this->db->query($sql)) {
  3803. dol_print_error($this->db);
  3804. return -1;
  3805. } else {
  3806. return 1;
  3807. }
  3808. } else {
  3809. dol_print_error($this->db);
  3810. return -1;
  3811. }
  3812. }
  3813. }
  3814. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3815. /**
  3816. * Modify composed product
  3817. *
  3818. * @param int $id_pere Id of parent product/service
  3819. * @param int $id_fils Id of child product/service
  3820. * @param int $qty Quantity
  3821. * @param int $incdec 1=Increase/decrease stock of child when parent stock increase/decrease
  3822. * @return int < 0 if KO, > 0 if OK
  3823. */
  3824. public function update_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
  3825. {
  3826. // phpcs:enable
  3827. // Clean parameters
  3828. if (!is_numeric($id_pere)) {
  3829. $id_pere = 0;
  3830. }
  3831. if (!is_numeric($id_fils)) {
  3832. $id_fils = 0;
  3833. }
  3834. if (!is_numeric($incdec)) {
  3835. $incdec = 1;
  3836. }
  3837. if (!is_numeric($qty)) {
  3838. $qty = 1;
  3839. }
  3840. $sql = 'UPDATE '.$this->db->prefix().'product_association SET ';
  3841. $sql .= 'qty = '.price2num($qty, 'MS');
  3842. $sql .= ',incdec = '.price2num($incdec, 'MS');
  3843. $sql .= ' WHERE fk_product_pere = '.((int) $id_pere).' AND fk_product_fils = '.((int) $id_fils);
  3844. if (!$this->db->query($sql)) {
  3845. dol_print_error($this->db);
  3846. return -1;
  3847. } else {
  3848. return 1;
  3849. }
  3850. }
  3851. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3852. /**
  3853. * Remove a link between a subproduct and a parent product/service
  3854. *
  3855. * @param int $fk_parent Id of parent product (child will no more be linked to it)
  3856. * @param int $fk_child Id of child product
  3857. * @return int < 0 if KO, > 0 if OK
  3858. */
  3859. public function del_sousproduit($fk_parent, $fk_child)
  3860. {
  3861. // phpcs:enable
  3862. if (!is_numeric($fk_parent)) {
  3863. $fk_parent = 0;
  3864. }
  3865. if (!is_numeric($fk_child)) {
  3866. $fk_child = 0;
  3867. }
  3868. $sql = "DELETE FROM ".$this->db->prefix()."product_association";
  3869. $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
  3870. $sql .= " AND fk_product_fils = ".((int) $fk_child);
  3871. dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG);
  3872. if (!$this->db->query($sql)) {
  3873. dol_print_error($this->db);
  3874. return -1;
  3875. }
  3876. // Updated ranks so that none are missing
  3877. $sqlrank = "SELECT rowid, rang FROM ".$this->db->prefix()."product_association";
  3878. $sqlrank.= " WHERE fk_product_pere = ".((int) $fk_parent);
  3879. $sqlrank.= " ORDER BY rang";
  3880. $resqlrank = $this->db->query($sqlrank);
  3881. if ($resqlrank) {
  3882. $cpt = 0;
  3883. while ($objrank = $this->db->fetch_object($resqlrank)) {
  3884. $cpt++;
  3885. $sql = "UPDATE ".$this->db->prefix()."product_association";
  3886. $sql.= " SET rang = ".((int) $cpt);
  3887. $sql.= " WHERE rowid = ".((int) $objrank->rowid);
  3888. if (! $this->db->query($sql)) {
  3889. dol_print_error($this->db);
  3890. return -1;
  3891. }
  3892. }
  3893. }
  3894. return 1;
  3895. }
  3896. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3897. /**
  3898. * Check if it is a sub-product into a kit
  3899. *
  3900. * @param int $fk_parent Id of parent kit product
  3901. * @param int $fk_child Id of child product
  3902. * @return int <0 if KO, >0 if OK
  3903. */
  3904. public function is_sousproduit($fk_parent, $fk_child)
  3905. {
  3906. // phpcs:enable
  3907. $sql = "SELECT fk_product_pere, qty, incdec";
  3908. $sql .= " FROM ".$this->db->prefix()."product_association";
  3909. $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
  3910. $sql .= " AND fk_product_fils = ".((int) $fk_child);
  3911. $result = $this->db->query($sql);
  3912. if ($result) {
  3913. $num = $this->db->num_rows($result);
  3914. if ($num > 0) {
  3915. $obj = $this->db->fetch_object($result);
  3916. $this->is_sousproduit_qty = $obj->qty;
  3917. $this->is_sousproduit_incdec = $obj->incdec;
  3918. return true;
  3919. } else {
  3920. return false;
  3921. }
  3922. } else {
  3923. dol_print_error($this->db);
  3924. return -1;
  3925. }
  3926. }
  3927. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3928. /**
  3929. * Add a supplier price for the product.
  3930. * Note: Duplicate ref is accepted for different quantity only, or for different companies.
  3931. *
  3932. * @param User $user User that make link
  3933. * @param int $id_fourn Supplier id
  3934. * @param string $ref_fourn Supplier ref
  3935. * @param float $quantity Quantity minimum for price
  3936. * @return int < 0 if KO, 0 if link already exists for this product, > 0 if OK
  3937. */
  3938. public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
  3939. {
  3940. // phpcs:enable
  3941. global $conf;
  3942. $now = dol_now();
  3943. dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG);
  3944. // Clean parameters
  3945. $quantity = price2num($quantity, 'MS');
  3946. if ($ref_fourn) {
  3947. $sql = "SELECT rowid, fk_product";
  3948. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  3949. $sql .= " WHERE fk_soc = ".((int) $id_fourn);
  3950. $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
  3951. $sql .= " AND fk_product <> ".((int) $this->id);
  3952. $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
  3953. $resql = $this->db->query($sql);
  3954. if ($resql) {
  3955. $obj = $this->db->fetch_object($resql);
  3956. if ($obj) {
  3957. // If the supplier ref already exists but for another product (duplicate ref is accepted for different quantity only or different companies)
  3958. $this->product_id_already_linked = $obj->fk_product;
  3959. return -3;
  3960. }
  3961. $this->db->free($resql);
  3962. }
  3963. }
  3964. $sql = "SELECT rowid";
  3965. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  3966. $sql .= " WHERE fk_soc = ".((int) $id_fourn);
  3967. if ($ref_fourn) {
  3968. $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
  3969. } else {
  3970. $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
  3971. }
  3972. $sql .= " AND quantity = ".((float) $quantity);
  3973. $sql .= " AND fk_product = ".((int) $this->id);
  3974. $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
  3975. $resql = $this->db->query($sql);
  3976. if ($resql) {
  3977. $obj = $this->db->fetch_object($resql);
  3978. // The reference supplier does not exist, we create it for this product.
  3979. if (empty($obj)) {
  3980. $sql = "INSERT INTO ".$this->db->prefix()."product_fournisseur_price(";
  3981. $sql .= "datec";
  3982. $sql .= ", entity";
  3983. $sql .= ", fk_product";
  3984. $sql .= ", fk_soc";
  3985. $sql .= ", ref_fourn";
  3986. $sql .= ", quantity";
  3987. $sql .= ", fk_user";
  3988. $sql .= ", tva_tx";
  3989. $sql .= ") VALUES (";
  3990. $sql .= "'".$this->db->idate($now)."'";
  3991. $sql .= ", ".$conf->entity;
  3992. $sql .= ", ".$this->id;
  3993. $sql .= ", ".$id_fourn;
  3994. $sql .= ", '".$this->db->escape($ref_fourn)."'";
  3995. $sql .= ", ".$quantity;
  3996. $sql .= ", ".$user->id;
  3997. $sql .= ", 0";
  3998. $sql .= ")";
  3999. if ($this->db->query($sql)) {
  4000. $this->product_fourn_price_id = $this->db->last_insert_id($this->db->prefix()."product_fournisseur_price");
  4001. return 1;
  4002. } else {
  4003. $this->error = $this->db->lasterror();
  4004. return -1;
  4005. }
  4006. } else {
  4007. // If the supplier price already exists for this product and quantity
  4008. $this->product_fourn_price_id = $obj->rowid;
  4009. return 0;
  4010. }
  4011. } else {
  4012. $this->error = $this->db->lasterror();
  4013. return -2;
  4014. }
  4015. }
  4016. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4017. /**
  4018. * Return list of suppliers providing the product or service
  4019. *
  4020. * @return array Array of vendor ids
  4021. */
  4022. public function list_suppliers()
  4023. {
  4024. // phpcs:enable
  4025. global $conf;
  4026. $list = array();
  4027. $sql = "SELECT DISTINCT p.fk_soc";
  4028. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as p";
  4029. $sql .= " WHERE p.fk_product = ".((int) $this->id);
  4030. $sql .= " AND p.entity = ".((int) $conf->entity);
  4031. $result = $this->db->query($sql);
  4032. if ($result) {
  4033. $num = $this->db->num_rows($result);
  4034. $i = 0;
  4035. while ($i < $num) {
  4036. $obj = $this->db->fetch_object($result);
  4037. $list[$i] = $obj->fk_soc;
  4038. $i++;
  4039. }
  4040. }
  4041. return $list;
  4042. }
  4043. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4044. /**
  4045. * Recopie les prix d'un produit/service sur un autre
  4046. *
  4047. * @param int $fromId Id product source
  4048. * @param int $toId Id product target
  4049. * @return int < 0 if KO, > 0 if OK
  4050. */
  4051. public function clone_price($fromId, $toId)
  4052. {
  4053. global $conf, $user;
  4054. $now = dol_now();
  4055. $this->db->begin();
  4056. // prices
  4057. $sql = "INSERT INTO ".$this->db->prefix()."product_price (";
  4058. $sql .= " entity";
  4059. $sql .= ", fk_product";
  4060. $sql .= ", date_price";
  4061. $sql .= ", price_level";
  4062. $sql .= ", price";
  4063. $sql .= ", price_ttc";
  4064. $sql .= ", price_min";
  4065. $sql .= ", price_min_ttc";
  4066. $sql .= ", price_base_type";
  4067. $sql .= ", default_vat_code";
  4068. $sql .= ", tva_tx";
  4069. $sql .= ", recuperableonly";
  4070. $sql .= ", localtax1_tx";
  4071. $sql .= ", localtax1_type";
  4072. $sql .= ", localtax2_tx";
  4073. $sql .= ", localtax2_type";
  4074. $sql .= ", fk_user_author";
  4075. $sql .= ", tosell";
  4076. $sql .= ", price_by_qty";
  4077. $sql .= ", fk_price_expression";
  4078. $sql .= ", fk_multicurrency";
  4079. $sql .= ", multicurrency_code";
  4080. $sql .= ", multicurrency_tx";
  4081. $sql .= ", multicurrency_price";
  4082. $sql .= ", multicurrency_price_ttc";
  4083. $sql .= ")";
  4084. $sql .= " SELECT";
  4085. $sql .= " entity";
  4086. $sql .= ", ".$toId;
  4087. $sql .= ", '".$this->db->idate($now)."'";
  4088. $sql .= ", price_level";
  4089. $sql .= ", price";
  4090. $sql .= ", price_ttc";
  4091. $sql .= ", price_min";
  4092. $sql .= ", price_min_ttc";
  4093. $sql .= ", price_base_type";
  4094. $sql .= ", default_vat_code";
  4095. $sql .= ", tva_tx";
  4096. $sql .= ", recuperableonly";
  4097. $sql .= ", localtax1_tx";
  4098. $sql .= ", localtax1_type";
  4099. $sql .= ", localtax2_tx";
  4100. $sql .= ", localtax2_type";
  4101. $sql .= ", ".$user->id;
  4102. $sql .= ", tosell";
  4103. $sql .= ", price_by_qty";
  4104. $sql .= ", fk_price_expression";
  4105. $sql .= ", fk_multicurrency";
  4106. $sql .= ", multicurrency_code";
  4107. $sql .= ", multicurrency_tx";
  4108. $sql .= ", multicurrency_price";
  4109. $sql .= ", multicurrency_price_ttc";
  4110. $sql .= " FROM ".$this->db->prefix()."product_price";
  4111. $sql .= " WHERE fk_product = ".((int) $fromId);
  4112. $sql .= " ORDER BY date_price DESC";
  4113. if ($conf->global->PRODUIT_MULTIPRICES_LIMIT > 0) {
  4114. $sql .= " LIMIT ".$conf->global->PRODUIT_MULTIPRICES_LIMIT;
  4115. }
  4116. dol_syslog(__METHOD__, LOG_DEBUG);
  4117. $resql = $this->db->query($sql);
  4118. if (!$resql) {
  4119. $this->db->rollback();
  4120. return -1;
  4121. }
  4122. $this->db->commit();
  4123. return 1;
  4124. }
  4125. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4126. /**
  4127. * Clone links between products
  4128. *
  4129. * @param int $fromId Product id
  4130. * @param int $toId Product id
  4131. * @return int <0 if KO, >0 if OK
  4132. */
  4133. public function clone_associations($fromId, $toId)
  4134. {
  4135. // phpcs:enable
  4136. $this->db->begin();
  4137. $sql = 'INSERT INTO '.$this->db->prefix().'product_association (fk_product_pere, fk_product_fils, qty)';
  4138. $sql .= " SELECT ".$toId.", fk_product_fils, qty FROM ".$this->db->prefix()."product_association";
  4139. $sql .= " WHERE fk_product_pere = ".((int) $fromId);
  4140. dol_syslog(get_class($this).'::clone_association', LOG_DEBUG);
  4141. if (!$this->db->query($sql)) {
  4142. $this->db->rollback();
  4143. return -1;
  4144. }
  4145. $this->db->commit();
  4146. return 1;
  4147. }
  4148. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4149. /**
  4150. * Recopie les fournisseurs et prix fournisseurs d'un produit/service sur un autre
  4151. *
  4152. * @param int $fromId Id produit source
  4153. * @param int $toId Id produit cible
  4154. * @return int < 0 si erreur, > 0 si ok
  4155. */
  4156. public function clone_fournisseurs($fromId, $toId)
  4157. {
  4158. // phpcs:enable
  4159. $this->db->begin();
  4160. $now = dol_now();
  4161. // les fournisseurs
  4162. /*$sql = "INSERT ".$this->db->prefix()."product_fournisseur ("
  4163. . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )"
  4164. . " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, ref_fourn, fk_user_author"
  4165. . " FROM ".$this->db->prefix()."product_fournisseur"
  4166. . " WHERE fk_product = ".((int) $fromId);
  4167. if ( ! $this->db->query($sql ) )
  4168. {
  4169. $this->db->rollback();
  4170. return -1;
  4171. }*/
  4172. // les prix de fournisseurs.
  4173. $sql = "INSERT ".$this->db->prefix()."product_fournisseur_price (";
  4174. $sql .= " datec, fk_product, fk_soc, price, quantity, fk_user)";
  4175. $sql .= " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, price, quantity, fk_user";
  4176. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  4177. $sql .= " WHERE fk_product = ".((int) $fromId);
  4178. dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG);
  4179. $resql = $this->db->query($sql);
  4180. if (!$resql) {
  4181. $this->db->rollback();
  4182. return -1;
  4183. } else {
  4184. $this->db->commit();
  4185. return 1;
  4186. }
  4187. }
  4188. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4189. /**
  4190. * Fonction recursive uniquement utilisee par get_arbo_each_prod, recompose l'arborescence des sousproduits
  4191. * Define value of this->res
  4192. *
  4193. * @param array $prod Products array
  4194. * @param string $compl_path Directory path of parents to add before
  4195. * @param int $multiply Because each sublevel must be multiplicated by parent nb
  4196. * @param int $level Init level
  4197. * @param int $id_parent Id parent
  4198. * @param int $ignore_stock_load Ignore stock load
  4199. * @return void
  4200. */
  4201. public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0)
  4202. {
  4203. // phpcs:enable
  4204. global $conf, $langs;
  4205. $tmpproduct = null;
  4206. //var_dump($prod);
  4207. foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
  4208. if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
  4209. $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
  4210. $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
  4211. $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
  4212. $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
  4213. $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0);
  4214. if ($multiply < 1) {
  4215. $multiply = 1;
  4216. }
  4217. //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
  4218. if (is_null($tmpproduct)) {
  4219. $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
  4220. }
  4221. $tmpproduct->fetch($id); // Load product to get ->ref
  4222. if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  4223. $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
  4224. }
  4225. $this->res[] = array(
  4226. 'id'=>$id, // Id product
  4227. 'id_parent'=>$id_parent,
  4228. 'ref'=>$tmpproduct->ref, // Ref product
  4229. 'nb'=>$nb, // Nb of units that compose parent product
  4230. 'nb_total'=>$nb * $multiply, // Nb of units for all nb of product
  4231. 'stock'=>$tmpproduct->stock_reel, // Stock
  4232. 'stock_alert'=>$tmpproduct->seuil_stock_alerte, // Stock alert
  4233. 'label'=>$label,
  4234. 'fullpath'=>$compl_path.$label, // Label
  4235. 'type'=>$type, // Nb of units that compose parent product
  4236. 'desiredstock'=>$tmpproduct->desiredstock,
  4237. 'level'=>$level,
  4238. 'incdec'=>$incdec,
  4239. 'entity'=>$tmpproduct->entity
  4240. );
  4241. // Recursive call if there is childs to child
  4242. if (isset($desc_pere['childs']) && is_array($desc_pere['childs'])) {
  4243. //print 'YYY We go down for '.$desc_pere[3]." -> \n";
  4244. $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id, $ignore_stock_load);
  4245. }
  4246. }
  4247. }
  4248. }
  4249. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4250. /**
  4251. * Build the tree of subproducts into an array ->res and return it.
  4252. * this->sousprods must have been loaded by this->get_sousproduits_arbo()
  4253. *
  4254. * @param int $multiply Because each sublevel must be multiplicated by parent nb
  4255. * @param int $ignore_stock_load Ignore stock load
  4256. * @return array $this->res
  4257. */
  4258. public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0)
  4259. {
  4260. // phpcs:enable
  4261. $this->res = array();
  4262. if (isset($this->sousprods) && is_array($this->sousprods)) {
  4263. foreach ($this->sousprods as $prod_name => $desc_product) {
  4264. if (is_array($desc_product)) {
  4265. $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load);
  4266. }
  4267. }
  4268. }
  4269. //var_dump($this->res);
  4270. return $this->res;
  4271. }
  4272. /**
  4273. * Count all parent and children products for current product (first level only)
  4274. *
  4275. * @param int $mode 0=Both parent and child, -1=Parents only, 1=Children only
  4276. * @return int Nb of father + child
  4277. * @see getFather(), get_sousproduits_arbo()
  4278. */
  4279. public function hasFatherOrChild($mode = 0)
  4280. {
  4281. $nb = 0;
  4282. $sql = "SELECT COUNT(pa.rowid) as nb";
  4283. $sql .= " FROM ".$this->db->prefix()."product_association as pa";
  4284. if ($mode == 0) {
  4285. $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id)." OR pa.fk_product_pere = ".((int) $this->id);
  4286. } elseif ($mode == -1) {
  4287. $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id); // We are a child, so we found lines that link to parents (can have several parents)
  4288. } elseif ($mode == 1) {
  4289. $sql .= " WHERE pa.fk_product_pere = ".((int) $this->id); // We are a parent, so we found lines that link to children (can have several children)
  4290. }
  4291. $resql = $this->db->query($sql);
  4292. if ($resql) {
  4293. $obj = $this->db->fetch_object($resql);
  4294. if ($obj) {
  4295. $nb = $obj->nb;
  4296. }
  4297. } else {
  4298. return -1;
  4299. }
  4300. return $nb;
  4301. }
  4302. /**
  4303. * Return if a product has variants or not
  4304. *
  4305. * @return int Number of variants
  4306. */
  4307. public function hasVariants()
  4308. {
  4309. $nb = 0;
  4310. $sql = "SELECT count(rowid) as nb FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_parent = ".((int) $this->id);
  4311. $sql .= " AND entity IN (".getEntity('product').")";
  4312. $resql = $this->db->query($sql);
  4313. if ($resql) {
  4314. $obj = $this->db->fetch_object($resql);
  4315. if ($obj) {
  4316. $nb = $obj->nb;
  4317. }
  4318. }
  4319. return $nb;
  4320. }
  4321. /**
  4322. * Return if loaded product is a variant
  4323. *
  4324. * @return int
  4325. */
  4326. public function isVariant()
  4327. {
  4328. global $conf;
  4329. if (isModEnabled('variants')) {
  4330. $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_child = ".((int) $this->id)." AND entity IN (".getEntity('product').")";
  4331. $query = $this->db->query($sql);
  4332. if ($query) {
  4333. if (!$this->db->num_rows($query)) {
  4334. return false;
  4335. }
  4336. return true;
  4337. } else {
  4338. dol_print_error($this->db);
  4339. return -1;
  4340. }
  4341. } else {
  4342. return false;
  4343. }
  4344. }
  4345. /**
  4346. * Return all parent products for current product (first level only)
  4347. *
  4348. * @return array Array of product
  4349. * @see hasFatherOrChild()
  4350. */
  4351. public function getFather()
  4352. {
  4353. $sql = "SELECT p.rowid, p.label as label, p.ref as ref, pa.fk_product_pere as id, p.fk_product_type, pa.qty, pa.incdec, p.entity";
  4354. $sql .= ", p.tosell as status, p.tobuy as status_buy";
  4355. $sql .= " FROM ".$this->db->prefix()."product_association as pa,";
  4356. $sql .= " ".$this->db->prefix()."product as p";
  4357. $sql .= " WHERE p.rowid = pa.fk_product_pere";
  4358. $sql .= " AND pa.fk_product_fils = ".((int) $this->id);
  4359. $res = $this->db->query($sql);
  4360. if ($res) {
  4361. $prods = array();
  4362. while ($record = $this->db->fetch_array($res)) {
  4363. // $record['id'] = $record['rowid'] = id of father
  4364. $prods[$record['id']]['id'] = $record['rowid'];
  4365. $prods[$record['id']]['ref'] = $record['ref'];
  4366. $prods[$record['id']]['label'] = $record['label'];
  4367. $prods[$record['id']]['qty'] = $record['qty'];
  4368. $prods[$record['id']]['incdec'] = $record['incdec'];
  4369. $prods[$record['id']]['fk_product_type'] = $record['fk_product_type'];
  4370. $prods[$record['id']]['entity'] = $record['entity'];
  4371. $prods[$record['id']]['status'] = $record['status'];
  4372. $prods[$record['id']]['status_buy'] = $record['status_buy'];
  4373. }
  4374. return $prods;
  4375. } else {
  4376. dol_print_error($this->db);
  4377. return -1;
  4378. }
  4379. }
  4380. /**
  4381. * Return childs of product $id
  4382. *
  4383. * @param int $id Id of product to search childs of
  4384. * @param int $firstlevelonly Return only direct child
  4385. * @param int $level Level of recursing call (start to 1)
  4386. * @param array $parents Array of all parents of $id
  4387. * @return array Return array(prodid=>array(0=prodid, 1=>qty, 2=>product type, 3=>label, 4=>incdec, 5=>product ref)
  4388. */
  4389. public function getChildsArbo($id, $firstlevelonly = 0, $level = 1, $parents = array())
  4390. {
  4391. global $alreadyfound;
  4392. if (empty($id)) {
  4393. return array();
  4394. }
  4395. $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,";
  4396. $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec,";
  4397. $sql .= " pa.rowid as fk_association, pa.rang";
  4398. $sql .= " FROM ".$this->db->prefix()."product as p,";
  4399. $sql .= " ".$this->db->prefix()."product_association as pa";
  4400. $sql .= " WHERE p.rowid = pa.fk_product_fils";
  4401. $sql .= " AND pa.fk_product_pere = ".((int) $id);
  4402. $sql .= " AND pa.fk_product_fils <> ".((int) $id); // This should not happens, it is to avoid infinite loop if it happens
  4403. $sql.= " ORDER BY pa.rang";
  4404. dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level. ' parents='.(is_array($parents)?implode(',', $parents):$parents), LOG_DEBUG);
  4405. if ($level == 1) {
  4406. $alreadyfound = array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly
  4407. }
  4408. // Protection against infinite loop
  4409. if ($level > 30) {
  4410. return array();
  4411. }
  4412. $res = $this->db->query($sql);
  4413. if ($res) {
  4414. $prods = array();
  4415. while ($rec = $this->db->fetch_array($res)) {
  4416. if (!empty($alreadyfound[$rec['rowid']])) {
  4417. dol_syslog(get_class($this).'::getChildsArbo the product id='.$rec['rowid'].' was already found at a higher level in tree. We discard to avoid infinite loop', LOG_WARNING);
  4418. if (in_array($rec['id'], $parents)) {
  4419. continue; // We discard this child if it is already found at a higher level in tree in the same branch.
  4420. }
  4421. }
  4422. $alreadyfound[$rec['rowid']] = 1;
  4423. $prods[$rec['rowid']] = array(
  4424. 0=>$rec['rowid'],
  4425. 1=>$rec['qty'],
  4426. 2=>$rec['fk_product_type'],
  4427. 3=>$this->db->escape($rec['label']),
  4428. 4=>$rec['incdec'],
  4429. 5=>$rec['ref'],
  4430. 6=>$rec['fk_association'],
  4431. 7=>$rec['rang']
  4432. );
  4433. //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']);
  4434. //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
  4435. if (empty($firstlevelonly)) {
  4436. $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1, array_push($parents, $rec['rowid']));
  4437. foreach ($listofchilds as $keyChild => $valueChild) {
  4438. $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
  4439. }
  4440. }
  4441. }
  4442. return $prods;
  4443. } else {
  4444. dol_print_error($this->db);
  4445. return -1;
  4446. }
  4447. }
  4448. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4449. /**
  4450. * Return tree of all subproducts for product. Tree contains array of array(0=prodid, 1=>qty, 2=>product type, 3=>label, 4=>incdec, 5=>product ref)
  4451. * Set this->sousprods
  4452. *
  4453. * @return void
  4454. */
  4455. public function get_sousproduits_arbo()
  4456. {
  4457. // phpcs:enable
  4458. $parent = array();
  4459. foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
  4460. $parent[$this->label][$keyChild] = $valueChild;
  4461. }
  4462. foreach ($parent as $key => $value) { // key=label, value is array of childs
  4463. $this->sousprods[$key] = $value;
  4464. }
  4465. }
  4466. /**
  4467. * Return clicable link of object (with eventually picto)
  4468. *
  4469. * @param int $withpicto Add picto into link
  4470. * @param string $option Where point the link ('stock', 'composition', 'category', 'supplier', '')
  4471. * @param int $maxlength Maxlength of ref
  4472. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  4473. * @param int $notooltip No tooltip
  4474. * @param string $morecss ''=Add more css on link
  4475. * @param int $add_label 0=Default, 1=Add label into string, >1=Add first chars into string
  4476. * @param string $sep ' - '=Separator between ref and label if option 'add_label' is set
  4477. * @return string String with URL
  4478. */
  4479. public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ')
  4480. {
  4481. global $conf, $langs, $hookmanager;
  4482. include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4483. $result = ''; $label = '';
  4484. $newref = $this->ref;
  4485. if ($maxlength) {
  4486. $newref = dol_trunc($newref, $maxlength, 'middle');
  4487. }
  4488. if (!empty($this->entity)) {
  4489. $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
  4490. if ($this->nbphoto > 0) {
  4491. $label .= '<div class="photointooltip floatright">';
  4492. $label .= $tmpphoto;
  4493. $label .= '</div>';
  4494. //$label .= '<div style="clear: both;"></div>';
  4495. }
  4496. }
  4497. if ($this->type == Product::TYPE_PRODUCT) {
  4498. $label .= img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
  4499. } elseif ($this->type == Product::TYPE_SERVICE) {
  4500. $label .= img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
  4501. }
  4502. if (isset($this->status) && isset($this->status_buy)) {
  4503. $label .= ' '.$this->getLibStatut(5, 0);
  4504. $label .= ' '.$this->getLibStatut(5, 1);
  4505. }
  4506. if (!empty($this->ref)) {
  4507. $label .= '<br><b>'.$langs->trans('ProductRef').':</b> '.$this->ref;
  4508. }
  4509. if (!empty($this->label)) {
  4510. $label .= '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label;
  4511. }
  4512. if ($this->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4513. if (isModEnabled('productbatch')) {
  4514. $langs->load("productbatch");
  4515. $label .= "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
  4516. }
  4517. }
  4518. if (isModEnabled('barcode')) {
  4519. $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
  4520. }
  4521. if ($this->type == Product::TYPE_PRODUCT) {
  4522. if ($this->weight) {
  4523. $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
  4524. }
  4525. $labelsize = "";
  4526. if ($this->length) {
  4527. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
  4528. }
  4529. if ($this->width) {
  4530. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
  4531. }
  4532. if ($this->height) {
  4533. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
  4534. }
  4535. if ($labelsize) {
  4536. $label .= "<br>".$labelsize;
  4537. }
  4538. $labelsurfacevolume = "";
  4539. if ($this->surface) {
  4540. $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
  4541. }
  4542. if ($this->volume) {
  4543. $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
  4544. }
  4545. if ($labelsurfacevolume) {
  4546. $label .= "<br>".$labelsurfacevolume;
  4547. }
  4548. }
  4549. if (!empty($this->pmp) && $this->pmp) {
  4550. $label .= "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency);
  4551. }
  4552. if (isModEnabled('accounting')) {
  4553. if ($this->status && isset($this->accountancy_code_sell)) {
  4554. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  4555. $label .= '<br>';
  4556. $label .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
  4557. $label .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
  4558. $label .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
  4559. }
  4560. if ($this->status_buy && isset($this->accountancy_code_buy)) {
  4561. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  4562. if (empty($this->status)) {
  4563. $label .= '<br>';
  4564. }
  4565. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
  4566. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
  4567. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
  4568. }
  4569. }
  4570. $linkclose = '';
  4571. if (empty($notooltip)) {
  4572. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4573. $label = $langs->trans("ShowProduct");
  4574. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  4575. }
  4576. $linkclose .= ' title="'.dol_escape_htmltag($label, 1, 1).'"';
  4577. $linkclose .= ' class="nowraponall classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  4578. } else {
  4579. $linkclose = ' class="nowraponall'.($morecss ? ' '.$morecss : '').'"';
  4580. }
  4581. if ($option == 'supplier' || $option == 'category') {
  4582. $url = DOL_URL_ROOT.'/product/fournisseurs.php?id='.$this->id;
  4583. } elseif ($option == 'stock') {
  4584. $url = DOL_URL_ROOT.'/product/stock/product.php?id='.$this->id;
  4585. } elseif ($option == 'composition') {
  4586. $url = DOL_URL_ROOT.'/product/composition/card.php?id='.$this->id;
  4587. } else {
  4588. $url = DOL_URL_ROOT.'/product/card.php?id='.$this->id;
  4589. }
  4590. if ($option !== 'nolink') {
  4591. // Add param to save lastsearch_values or not
  4592. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  4593. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  4594. $add_save_lastsearch_values = 1;
  4595. }
  4596. if ($add_save_lastsearch_values) {
  4597. $url .= '&save_lastsearch_values=1';
  4598. }
  4599. }
  4600. $linkstart = '<a href="'.$url.'"';
  4601. $linkstart .= $linkclose.'>';
  4602. $linkend = '</a>';
  4603. $result .= $linkstart;
  4604. if ($withpicto) {
  4605. if ($this->type == Product::TYPE_PRODUCT) {
  4606. $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
  4607. }
  4608. if ($this->type == Product::TYPE_SERVICE) {
  4609. $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
  4610. }
  4611. }
  4612. $result .= dol_escape_htmltag($newref);
  4613. $result .= $linkend;
  4614. if ($withpicto != 2) {
  4615. $result .= (($add_label && $this->label) ? $sep.dol_trunc($this->label, ($add_label > 1 ? $add_label : 0)) : '');
  4616. }
  4617. global $action;
  4618. $hookmanager->initHooks(array('productdao'));
  4619. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  4620. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4621. if ($reshook > 0) {
  4622. $result = $hookmanager->resPrint;
  4623. } else {
  4624. $result .= $hookmanager->resPrint;
  4625. }
  4626. return $result;
  4627. }
  4628. /**
  4629. * Create a document onto disk according to template module.
  4630. *
  4631. * @param string $modele Force model to use ('' to not force)
  4632. * @param Translate $outputlangs Object langs to use for output
  4633. * @param int $hidedetails Hide details of lines
  4634. * @param int $hidedesc Hide description
  4635. * @param int $hideref Hide ref
  4636. * @return int 0 if KO, 1 if OK
  4637. */
  4638. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  4639. {
  4640. global $conf, $user, $langs;
  4641. $langs->load("products");
  4642. $outputlangs->load("products");
  4643. // Positionne le modele sur le nom du modele a utiliser
  4644. if (!dol_strlen($modele)) {
  4645. $modele = getDolGlobalString('PRODUCT_ADDON_PDF', 'strato');
  4646. }
  4647. $modelpath = "core/modules/product/doc/";
  4648. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  4649. }
  4650. /**
  4651. * Return label of status of object
  4652. *
  4653. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  4654. * @param int $type 0=Sell, 1=Buy, 2=Batch Number management
  4655. * @return string Label of status
  4656. */
  4657. public function getLibStatut($mode = 0, $type = 0)
  4658. {
  4659. switch ($type) {
  4660. case 0:
  4661. return $this->LibStatut($this->status, $mode, $type);
  4662. case 1:
  4663. return $this->LibStatut($this->status_buy, $mode, $type);
  4664. case 2:
  4665. return $this->LibStatut($this->status_batch, $mode, $type);
  4666. default:
  4667. //Simulate previous behavior but should return an error string
  4668. return $this->LibStatut($this->status_buy, $mode, $type);
  4669. }
  4670. }
  4671. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4672. /**
  4673. * Return label of a given status
  4674. *
  4675. * @param int $status Statut
  4676. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  4677. * @param int $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4678. * @return string Label of status
  4679. */
  4680. public function LibStatut($status, $mode = 0, $type = 0)
  4681. {
  4682. // phpcs:enable
  4683. global $conf, $langs;
  4684. $labelStatus = $labelStatusShort = '';
  4685. $langs->load('products');
  4686. if (isModEnabled('productbatch')) {
  4687. $langs->load("productbatch");
  4688. }
  4689. if ($type == 2) {
  4690. switch ($mode) {
  4691. case 0:
  4692. $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatch') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial')));
  4693. return dolGetStatus($label);
  4694. case 1:
  4695. $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort')));
  4696. return dolGetStatus($label);
  4697. case 2:
  4698. return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2);
  4699. case 3:
  4700. return dolGetStatus($langs->transnoentitiesnoconv('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot');
  4701. case 4:
  4702. return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2);
  4703. case 5:
  4704. return $this->LibStatut($status, 1, 2).' '.$this->LibStatut($status, 3, 2);
  4705. default:
  4706. return dolGetStatus($langs->transnoentitiesnoconv('Unknown'));
  4707. }
  4708. }
  4709. $statuttrans = empty($status) ? 'status5' : 'status4';
  4710. if ($status == 0) {
  4711. // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4712. if ($type == 0) {
  4713. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnSellShort');
  4714. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnSell');
  4715. } elseif ($type == 1) {
  4716. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBuyShort');
  4717. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBuy');
  4718. } elseif ($type == 2) {
  4719. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBatch');
  4720. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort');
  4721. }
  4722. } elseif ($status == 1) {
  4723. // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4724. if ($type == 0) {
  4725. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSellShort');
  4726. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSell');
  4727. } elseif ($type == 1) {
  4728. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBuyShort');
  4729. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBuy');
  4730. } elseif ($type == 2) {
  4731. $labelStatus = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial'));
  4732. $labelStatusShort = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort'));
  4733. }
  4734. } elseif ( $type == 2 && $status == 2 ) {
  4735. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSerial');
  4736. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSerialShort');
  4737. }
  4738. if ($mode > 6) {
  4739. return dolGetStatus($langs->transnoentitiesnoconv('Unknown'), '', '', 'status0', 0);
  4740. } else {
  4741. return dolGetStatus($labelStatus, $labelStatusShort, '', $statuttrans, $mode);
  4742. }
  4743. }
  4744. /**
  4745. * Retour label of nature of product
  4746. *
  4747. * @return string Label
  4748. */
  4749. public function getLibFinished()
  4750. {
  4751. global $langs;
  4752. $langs->load('products');
  4753. if (isset($this->finished) && $this->finished >= 0) {
  4754. $sql = "SELECT label, code FROM ".$this->db->prefix()."c_product_nature where code = ".((int) $this->finished)." AND active=1";
  4755. $resql = $this->db->query($sql);
  4756. if ($resql && $this->db->num_rows($resql) > 0) {
  4757. $res = $this->db->fetch_array($resql);
  4758. $label = $langs->trans($res['label']);
  4759. $this->db->free($resql);
  4760. return $label;
  4761. } else {
  4762. $this->error = $this->db->error().' sql='.$sql;
  4763. dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR);
  4764. return -1;
  4765. }
  4766. }
  4767. return '';
  4768. }
  4769. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4770. /**
  4771. * Adjust stock in a warehouse for product
  4772. *
  4773. * @param User $user user asking change
  4774. * @param int $id_entrepot id of warehouse
  4775. * @param double $nbpiece nb of units (should be always positive, use $movement to decide if we add or remove)
  4776. * @param int $movement 0 = add, 1 = remove
  4777. * @param string $label Label of stock movement
  4778. * @param double $price Unit price HT of product, used to calculate average weighted price (PMP in french). If 0, average weighted price is not changed.
  4779. * @param string $inventorycode Inventory code
  4780. * @param string $origin_element Origin element type
  4781. * @param int $origin_id Origin id of element
  4782. * @param int $disablestockchangeforsubproduct Disable stock change for sub-products of kit (usefull only if product is a subproduct)
  4783. * @param Extrafields $extrafields Array of extrafields
  4784. * @return int <0 if KO, >0 if OK
  4785. */
  4786. public function correct_stock($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
  4787. {
  4788. // phpcs:enable
  4789. if ($id_entrepot) {
  4790. $this->db->begin();
  4791. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  4792. if ($nbpiece < 0) {
  4793. if (!$movement) {
  4794. $movement = 1;
  4795. }
  4796. $nbpiece = abs($nbpiece);
  4797. }
  4798. $op[0] = "+".trim($nbpiece);
  4799. $op[1] = "-".trim($nbpiece);
  4800. $movementstock = new MouvementStock($this->db);
  4801. $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->origin_id
  4802. $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', '', '', '', false, 0, $disablestockchangeforsubproduct);
  4803. if ($result >= 0) {
  4804. if ($extrafields) {
  4805. $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
  4806. $movementstock->array_options = $array_options;
  4807. $movementstock->insertExtraFields();
  4808. }
  4809. $this->db->commit();
  4810. return 1;
  4811. } else {
  4812. $this->error = $movementstock->error;
  4813. $this->errors = $movementstock->errors;
  4814. $this->db->rollback();
  4815. return -1;
  4816. }
  4817. }
  4818. }
  4819. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4820. /**
  4821. * Adjust stock in a warehouse for product with batch number
  4822. *
  4823. * @param User $user user asking change
  4824. * @param int $id_entrepot id of warehouse
  4825. * @param double $nbpiece nb of units (should be always positive, use $movement to decide if we add or remove)
  4826. * @param int $movement 0 = add, 1 = remove
  4827. * @param string $label Label of stock movement
  4828. * @param double $price Price to use for stock eval
  4829. * @param integer $dlc eat-by date
  4830. * @param integer $dluo sell-by date
  4831. * @param string $lot Lot number
  4832. * @param string $inventorycode Inventory code
  4833. * @param string $origin_element Origin element type
  4834. * @param int $origin_id Origin id of element
  4835. * @param int $disablestockchangeforsubproduct Disable stock change for sub-products of kit (usefull only if product is a subproduct)
  4836. * @param Extrafields $extrafields Array of extrafields
  4837. * @return int <0 if KO, >0 if OK
  4838. */
  4839. public function correct_stock_batch($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $dlc = '', $dluo = '', $lot = '', $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
  4840. {
  4841. // phpcs:enable
  4842. if ($id_entrepot) {
  4843. $this->db->begin();
  4844. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  4845. if ($nbpiece < 0) {
  4846. if (!$movement) {
  4847. $movement = 1;
  4848. }
  4849. $nbpiece = abs($nbpiece);
  4850. }
  4851. $op[0] = "+".trim($nbpiece);
  4852. $op[1] = "-".trim($nbpiece);
  4853. $movementstock = new MouvementStock($this->db);
  4854. $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->fk_origin
  4855. $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot, false, 0, $disablestockchangeforsubproduct);
  4856. if ($result >= 0) {
  4857. if ($extrafields) {
  4858. $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
  4859. $movementstock->array_options = $array_options;
  4860. $movementstock->insertExtraFields();
  4861. }
  4862. $this->db->commit();
  4863. return 1;
  4864. } else {
  4865. $this->error = $movementstock->error;
  4866. $this->errors = $movementstock->errors;
  4867. $this->db->rollback();
  4868. return -1;
  4869. }
  4870. }
  4871. }
  4872. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4873. /**
  4874. * Load information about stock of a product into ->stock_reel, ->stock_warehouse[] (including stock_warehouse[idwarehouse]->detail_batch for batch products)
  4875. * This function need a lot of load. If you use it on list, use a cache to execute it once for each product id.
  4876. * If ENTREPOT_EXTRA_STATUS is set, filtering on warehouse status is possible.
  4877. *
  4878. * @param string $option '' = Load all stock info, also from closed and internal warehouses, 'nobatch', 'novirtual'
  4879. * You can also filter on 'warehouseclosed', 'warehouseopen', 'warehouseinternal'
  4880. * @param int $includedraftpoforvirtual Include draft status of PO for virtual stock calculation
  4881. * @param int $dateofvirtualstock Date of virtual stock
  4882. * @return int < 0 if KO, > 0 if OK
  4883. * @see load_virtual_stock(), loadBatchInfo()
  4884. */
  4885. public function load_stock($option = '', $includedraftpoforvirtual = null, $dateofvirtualstock = null)
  4886. {
  4887. // phpcs:enable
  4888. global $conf;
  4889. $this->stock_reel = 0;
  4890. $this->stock_warehouse = array();
  4891. $this->stock_theorique = 0;
  4892. // Set filter on warehouse status
  4893. $warehouseStatus = array();
  4894. if (preg_match('/warehouseclosed/', $option)) {
  4895. $warehouseStatus[Entrepot::STATUS_CLOSED] = Entrepot::STATUS_CLOSED;
  4896. }
  4897. if (preg_match('/warehouseopen/', $option)) {
  4898. $warehouseStatus[Entrepot::STATUS_OPEN_ALL] = Entrepot::STATUS_OPEN_ALL;
  4899. }
  4900. if (preg_match('/warehouseinternal/', $option)) {
  4901. if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
  4902. $warehouseStatus[Entrepot::STATUS_OPEN_INTERNAL] = Entrepot::STATUS_OPEN_INTERNAL;
  4903. } else {
  4904. $warehouseStatus[Entrepot::STATUS_OPEN_ALL] = Entrepot::STATUS_OPEN_ALL;
  4905. }
  4906. }
  4907. $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot";
  4908. $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
  4909. $sql .= ", ".$this->db->prefix()."entrepot as w";
  4910. $sql .= " WHERE w.entity IN (".getEntity('stock').")";
  4911. $sql .= " AND w.rowid = ps.fk_entrepot";
  4912. $sql .= " AND ps.fk_product = ".((int) $this->id);
  4913. if (count($warehouseStatus)) {
  4914. $sql .= " AND w.statut IN (".$this->db->sanitize(implode(',', $warehouseStatus)).")";
  4915. }
  4916. $sql .= " ORDER BY ps.reel ".(!empty($conf->global->DO_NOT_TRY_TO_DEFRAGMENT_STOCKS_WAREHOUSE)?'DESC':'ASC'); // Note : qty ASC is important for expedition card, to avoid stock fragmentation;
  4917. dol_syslog(get_class($this)."::load_stock", LOG_DEBUG);
  4918. $result = $this->db->query($sql);
  4919. if ($result) {
  4920. $num = $this->db->num_rows($result);
  4921. $i = 0;
  4922. if ($num > 0) {
  4923. while ($i < $num) {
  4924. $row = $this->db->fetch_object($result);
  4925. $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
  4926. $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
  4927. $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid;
  4928. if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) {
  4929. $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id);
  4930. }
  4931. $this->stock_reel += $row->reel;
  4932. $i++;
  4933. }
  4934. }
  4935. $this->db->free($result);
  4936. if (!preg_match('/novirtual/', $option)) {
  4937. $this->load_virtual_stock($includedraftpoforvirtual, $dateofvirtualstock); // This also load all arrays stats_xxx...
  4938. }
  4939. return 1;
  4940. } else {
  4941. $this->error = $this->db->lasterror();
  4942. return -1;
  4943. }
  4944. }
  4945. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4946. /**
  4947. * Load value ->stock_theorique of a product. Property this->id must be defined.
  4948. * This function need a lot of load. If you use it on list, use a cache to execute it one for each product id.
  4949. *
  4950. * @param int $includedraftpoforvirtual Include draft status and not yet approved Purchase Orders for virtual stock calculation
  4951. * @param int $dateofvirtualstock Date of virtual stock
  4952. * @return int < 0 if KO, > 0 if OK
  4953. * @see load_stock(), loadBatchInfo()
  4954. */
  4955. public function load_virtual_stock($includedraftpoforvirtual = null, $dateofvirtualstock = null)
  4956. {
  4957. // phpcs:enable
  4958. global $conf, $hookmanager, $action;
  4959. $stock_commande_client = 0;
  4960. $stock_commande_fournisseur = 0;
  4961. $stock_sending_client = 0;
  4962. $stock_reception_fournisseur = 0;
  4963. $stock_inproduction = 0;
  4964. //dol_syslog("load_virtual_stock");
  4965. if (isModEnabled('commande')) {
  4966. $result = $this->load_stats_commande(0, '1,2', 1);
  4967. if ($result < 0) {
  4968. dol_print_error($this->db, $this->error);
  4969. }
  4970. $stock_commande_client = $this->stats_commande['qty'];
  4971. }
  4972. if (isModEnabled("expedition")) {
  4973. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  4974. $filterShipmentStatus = '';
  4975. if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
  4976. $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
  4977. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
  4978. $filterShipmentStatus = Expedition::STATUS_CLOSED;
  4979. }
  4980. $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
  4981. if ($result < 0) {
  4982. dol_print_error($this->db, $this->error);
  4983. }
  4984. $stock_sending_client = $this->stats_expedition['qty'];
  4985. }
  4986. if ((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order")) {
  4987. $filterStatus = empty($conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK) ? '3,4' : $conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK;
  4988. if (isset($includedraftpoforvirtual)) {
  4989. $filterStatus = '0,1,2,'.$filterStatus; // 1,2 may have already been inside $filterStatus but it is better to have twice than missing $filterStatus does not include them
  4990. }
  4991. $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1, $dateofvirtualstock);
  4992. if ($result < 0) {
  4993. dol_print_error($this->db, $this->error);
  4994. }
  4995. $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
  4996. }
  4997. if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && empty($conf->reception->enabled)) {
  4998. // Case module reception is not used
  4999. $filterStatus = '4';
  5000. if (isset($includedraftpoforvirtual)) {
  5001. $filterStatus = '0,'.$filterStatus;
  5002. }
  5003. $result = $this->load_stats_reception(0, $filterStatus, 1, $dateofvirtualstock);
  5004. if ($result < 0) {
  5005. dol_print_error($this->db, $this->error);
  5006. }
  5007. $stock_reception_fournisseur = $this->stats_reception['qty'];
  5008. }
  5009. if (((isModEnabled("fournisseur") && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && isModEnabled("reception")) {
  5010. // Case module reception is used
  5011. $filterStatus = '4';
  5012. if (isset($includedraftpoforvirtual)) {
  5013. $filterStatus = '0,'.$filterStatus;
  5014. }
  5015. $result = $this->load_stats_reception(0, $filterStatus, 1, $dateofvirtualstock); // Use same tables than when module reception is not used.
  5016. if ($result < 0) {
  5017. dol_print_error($this->db, $this->error);
  5018. }
  5019. $stock_reception_fournisseur = $this->stats_reception['qty'];
  5020. }
  5021. if (isModEnabled('mrp')) {
  5022. $result = $this->load_stats_inproduction(0, '1,2', 1, $dateofvirtualstock);
  5023. if ($result < 0) {
  5024. dol_print_error($this->db, $this->error);
  5025. }
  5026. $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
  5027. }
  5028. $this->stock_theorique = $this->stock_reel + $stock_inproduction;
  5029. // Stock decrease mode
  5030. if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
  5031. $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
  5032. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER)) {
  5033. $this->stock_theorique += 0;
  5034. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  5035. $this->stock_theorique -= $stock_commande_client;
  5036. }
  5037. // Stock Increase mode
  5038. if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  5039. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  5040. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) {
  5041. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  5042. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) {
  5043. $this->stock_theorique -= $stock_reception_fournisseur;
  5044. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  5045. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  5046. }
  5047. if (!is_object($hookmanager)) {
  5048. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  5049. $hookmanager = new HookManager($this->db);
  5050. }
  5051. $hookmanager->initHooks(array('productdao'));
  5052. $parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
  5053. // Note that $action and $object may have been modified by some hooks
  5054. $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
  5055. if ($reshook > 0) {
  5056. $this->stock_theorique = $hookmanager->resArray['stock_theorique'];
  5057. }
  5058. return 1;
  5059. }
  5060. /**
  5061. * Load existing information about a serial
  5062. *
  5063. * @param string $batch Lot/serial number
  5064. * @return array Array with record into product_batch
  5065. * @see load_stock(), load_virtual_stock()
  5066. */
  5067. public function loadBatchInfo($batch)
  5068. {
  5069. $result = array();
  5070. $sql = "SELECT pb.batch, pb.eatby, pb.sellby, SUM(pb.qty) AS qty FROM ".$this->db->prefix()."product_batch as pb, ".$this->db->prefix()."product_stock as ps";
  5071. $sql .= " WHERE pb.fk_product_stock = ps.rowid AND ps.fk_product = ".((int) $this->id)." AND pb.batch = '".$this->db->escape($batch)."'";
  5072. $sql .= " GROUP BY pb.batch, pb.eatby, pb.sellby";
  5073. dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG);
  5074. $resql = $this->db->query($sql);
  5075. if ($resql) {
  5076. $num = $this->db->num_rows($resql);
  5077. $i = 0;
  5078. while ($i < $num) {
  5079. $obj = $this->db->fetch_object($resql);
  5080. $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty);
  5081. $i++;
  5082. }
  5083. return $result;
  5084. } else {
  5085. dol_print_error($this->db);
  5086. $this->db->rollback();
  5087. return array();
  5088. }
  5089. }
  5090. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5091. /**
  5092. * Move an uploaded file described into $file array into target directory $sdir.
  5093. *
  5094. * @param string $sdir Target directory
  5095. * @param string $file Array of file info of file to upload: array('name'=>..., 'tmp_name'=>...)
  5096. * @return int <0 if KO, >0 if OK
  5097. */
  5098. public function add_photo($sdir, $file)
  5099. {
  5100. // phpcs:enable
  5101. global $conf;
  5102. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5103. $result = 0;
  5104. $dir = $sdir;
  5105. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  5106. $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos";
  5107. } else {
  5108. $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref);
  5109. }
  5110. dol_mkdir($dir);
  5111. $dir_osencoded = $dir;
  5112. if (is_dir($dir_osencoded)) {
  5113. $originImage = $dir.'/'.$file['name'];
  5114. // Cree fichier en taille origine
  5115. $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1);
  5116. if (file_exists(dol_osencode($originImage))) {
  5117. // Create thumbs
  5118. $this->addThumbs($originImage);
  5119. }
  5120. }
  5121. if (is_numeric($result) && $result > 0) {
  5122. return 1;
  5123. } else {
  5124. return -1;
  5125. }
  5126. }
  5127. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5128. /**
  5129. * Return if at least one photo is available
  5130. *
  5131. * @param string $sdir Directory to scan
  5132. * @return boolean True if at least one photo is available, False if not
  5133. */
  5134. public function is_photo_available($sdir)
  5135. {
  5136. // phpcs:enable
  5137. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5138. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5139. global $conf;
  5140. $dir = $sdir;
  5141. if (getDolGlobalInt('PRODUCT_USE_OLD_PATH_FOR_PHOTO')) {
  5142. $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/";
  5143. } else {
  5144. $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product');
  5145. }
  5146. $nbphoto = 0;
  5147. $dir_osencoded = dol_osencode($dir);
  5148. if (file_exists($dir_osencoded)) {
  5149. $handle = opendir($dir_osencoded);
  5150. if (is_resource($handle)) {
  5151. while (($file = readdir($handle)) !== false) {
  5152. if (!utf8_check($file)) {
  5153. $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory
  5154. }
  5155. if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
  5156. return true;
  5157. }
  5158. }
  5159. }
  5160. }
  5161. return false;
  5162. }
  5163. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5164. /**
  5165. * Return an array with all photos of product found on disk. There is no sorting criteria.
  5166. *
  5167. * @param string $dir Directory to scan
  5168. * @param int $nbmax Number maxium of photos (0=no maximum)
  5169. * @return array Array of photos
  5170. */
  5171. public function liste_photos($dir, $nbmax = 0)
  5172. {
  5173. // phpcs:enable
  5174. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5175. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5176. $nbphoto = 0;
  5177. $tabobj = array();
  5178. $dir_osencoded = dol_osencode($dir);
  5179. $handle = @opendir($dir_osencoded);
  5180. if (is_resource($handle)) {
  5181. while (($file = readdir($handle)) !== false) {
  5182. if (!utf8_check($file)) {
  5183. $file = utf8_encode($file); // readdir returns ISO
  5184. }
  5185. if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
  5186. $nbphoto++;
  5187. // We forge name of thumb.
  5188. $photo = $file;
  5189. $photo_vignette = '';
  5190. $regs = array();
  5191. if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) {
  5192. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
  5193. }
  5194. $dirthumb = $dir.'thumbs/';
  5195. // Objet
  5196. $obj = array();
  5197. $obj['photo'] = $photo;
  5198. if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
  5199. $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
  5200. } else {
  5201. $obj['photo_vignette'] = "";
  5202. }
  5203. $tabobj[$nbphoto - 1] = $obj;
  5204. // Do we have to continue with next photo ?
  5205. if ($nbmax && $nbphoto >= $nbmax) {
  5206. break;
  5207. }
  5208. }
  5209. }
  5210. closedir($handle);
  5211. }
  5212. return $tabobj;
  5213. }
  5214. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5215. /**
  5216. * Delete a photo and its thumbs
  5217. *
  5218. * @param string $file Path to image file
  5219. * @return void
  5220. */
  5221. public function delete_photo($file)
  5222. {
  5223. // phpcs:enable
  5224. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5225. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5226. $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
  5227. $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
  5228. $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
  5229. // On efface l'image d'origine
  5230. dol_delete_file($file, 0, 0, 0, $this); // For triggers
  5231. // Si elle existe, on efface la vignette
  5232. if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) {
  5233. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
  5234. if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
  5235. dol_delete_file($dirthumb.$photo_vignette);
  5236. }
  5237. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0];
  5238. if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
  5239. dol_delete_file($dirthumb.$photo_vignette);
  5240. }
  5241. }
  5242. }
  5243. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5244. /**
  5245. * Load size of image file
  5246. *
  5247. * @param string $file Path to file
  5248. * @return void
  5249. */
  5250. public function get_image_size($file)
  5251. {
  5252. // phpcs:enable
  5253. $file_osencoded = dol_osencode($file);
  5254. $infoImg = getimagesize($file_osencoded); // Get information on image
  5255. $this->imgWidth = $infoImg[0]; // Largeur de l'image
  5256. $this->imgHeight = $infoImg[1]; // Hauteur de l'image
  5257. }
  5258. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5259. /**
  5260. * Load indicators this->nb for the dashboard
  5261. *
  5262. * @return int <0 if KO, >0 if OK
  5263. */
  5264. public function load_state_board()
  5265. {
  5266. // phpcs:enable
  5267. global $hookmanager;
  5268. $this->nb = array();
  5269. $sql = "SELECT count(p.rowid) as nb, fk_product_type";
  5270. $sql .= " FROM ".$this->db->prefix()."product as p";
  5271. $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')';
  5272. // Add where from hooks
  5273. if (is_object($hookmanager)) {
  5274. $parameters = array();
  5275. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
  5276. $sql .= $hookmanager->resPrint;
  5277. }
  5278. $sql .= ' GROUP BY fk_product_type';
  5279. $resql = $this->db->query($sql);
  5280. if ($resql) {
  5281. while ($obj = $this->db->fetch_object($resql)) {
  5282. if ($obj->fk_product_type == 1) {
  5283. $this->nb["services"] = $obj->nb;
  5284. } else {
  5285. $this->nb["products"] = $obj->nb;
  5286. }
  5287. }
  5288. $this->db->free($resql);
  5289. return 1;
  5290. } else {
  5291. dol_print_error($this->db);
  5292. $this->error = $this->db->error();
  5293. return -1;
  5294. }
  5295. }
  5296. /**
  5297. * Return if object is a product
  5298. *
  5299. * @return boolean True if it's a product
  5300. */
  5301. public function isProduct()
  5302. {
  5303. return ($this->type == Product::TYPE_PRODUCT ? true : false);
  5304. }
  5305. /**
  5306. * Return if object is a product
  5307. *
  5308. * @return boolean True if it's a service
  5309. */
  5310. public function isService()
  5311. {
  5312. return ($this->type == Product::TYPE_SERVICE ? true : false);
  5313. }
  5314. /**
  5315. * Return if object have a constraint on mandatory_period
  5316. *
  5317. * @return boolean True if mandatory_period setted to 1
  5318. */
  5319. public function isMandatoryPeriod()
  5320. {
  5321. return ($this->mandatory_period == 1 ? true : false);
  5322. }
  5323. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5324. /**
  5325. * Get a barcode from the module to generate barcode values.
  5326. * Return value is stored into this->barcode
  5327. *
  5328. * @param Product $object Object product or service
  5329. * @param string $type Barcode type (ean, isbn, ...)
  5330. * @return string
  5331. */
  5332. public function get_barcode($object, $type = '')
  5333. {
  5334. // phpcs:enable
  5335. global $conf;
  5336. $result = '';
  5337. if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
  5338. $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
  5339. foreach ($dirsociete as $dirroot) {
  5340. $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php');
  5341. if ($res) {
  5342. break;
  5343. }
  5344. }
  5345. $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM;
  5346. $mod = new $var;
  5347. $result = $mod->getNextValue($object, $type);
  5348. dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var);
  5349. }
  5350. return $result;
  5351. }
  5352. /**
  5353. * Initialise an instance with random values.
  5354. * Used to build previews or test instances.
  5355. * id must be 0 if object instance is a specimen.
  5356. *
  5357. * @return void
  5358. */
  5359. public function initAsSpecimen()
  5360. {
  5361. global $user, $langs, $conf, $mysoc;
  5362. $now = dol_now();
  5363. // Initialize parameters
  5364. $this->specimen = 1;
  5365. $this->id = 0;
  5366. $this->ref = 'PRODUCT_SPEC';
  5367. $this->label = 'PRODUCT SPECIMEN';
  5368. $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.';
  5369. $this->specimen = 1;
  5370. $this->country_id = 1;
  5371. $this->status = 1;
  5372. $this->status_buy = 1;
  5373. $this->tobatch = 0;
  5374. $this->note_private = 'This is a comment (private)';
  5375. $this->note_public = 'This is a comment (public)';
  5376. $this->date_creation = $now;
  5377. $this->date_modification = $now;
  5378. $this->weight = 4;
  5379. $this->weight_units = 3;
  5380. $this->length = 5;
  5381. $this->length_units = 1;
  5382. $this->width = 6;
  5383. $this->width_units = 0;
  5384. $this->height = null;
  5385. $this->height_units = null;
  5386. $this->surface = 30;
  5387. $this->surface_units = 0;
  5388. $this->volume = 300;
  5389. $this->volume_units = 0;
  5390. $this->barcode = -1; // Create barcode automatically
  5391. }
  5392. /**
  5393. * Returns the text label from units dictionary
  5394. *
  5395. * @param string $type Label type (long or short)
  5396. * @return string|int <0 if ko, label if ok
  5397. */
  5398. public function getLabelOfUnit($type = 'long')
  5399. {
  5400. global $langs;
  5401. if (!$this->fk_unit) {
  5402. return '';
  5403. }
  5404. $langs->load('products');
  5405. $label_type = 'label';
  5406. if ($type == 'short') {
  5407. $label_type = 'short_label';
  5408. }
  5409. $sql = "SELECT ".$label_type.", code from ".$this->db->prefix()."c_units where rowid = ".((int) $this->fk_unit);
  5410. $resql = $this->db->query($sql);
  5411. if ($resql && $this->db->num_rows($resql) > 0) {
  5412. $res = $this->db->fetch_array($resql);
  5413. $label = ($label_type == 'short_label' ? $res[$label_type] : 'unit'.$res['code']);
  5414. $this->db->free($resql);
  5415. return $label;
  5416. } else {
  5417. $this->error = $this->db->error();
  5418. dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
  5419. return -1;
  5420. }
  5421. }
  5422. /**
  5423. * Return if object has a sell-by date or eat-by date
  5424. *
  5425. * @return boolean True if it's has
  5426. */
  5427. public function hasbatch()
  5428. {
  5429. return ($this->status_batch > 0 ? true : false);
  5430. }
  5431. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5432. /**
  5433. * Return minimum product recommended price
  5434. *
  5435. * @return int Minimum recommanded price that is higher price among all suppliers * PRODUCT_MINIMUM_RECOMMENDED_PRICE
  5436. */
  5437. public function min_recommended_price()
  5438. {
  5439. // phpcs:enable
  5440. global $conf;
  5441. $maxpricesupplier = 0;
  5442. if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) {
  5443. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5444. $product_fourn = new ProductFournisseur($this->db);
  5445. $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
  5446. if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
  5447. foreach ($product_fourn_list as $productfourn) {
  5448. if ($productfourn->fourn_unitprice > $maxpricesupplier) {
  5449. $maxpricesupplier = $productfourn->fourn_unitprice;
  5450. }
  5451. }
  5452. $maxpricesupplier *= $conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE;
  5453. }
  5454. }
  5455. return $maxpricesupplier;
  5456. }
  5457. /**
  5458. * Sets object to supplied categories.
  5459. *
  5460. * Deletes object from existing categories not supplied.
  5461. * Adds it to non existing supplied categories.
  5462. * Existing categories are left untouch.
  5463. *
  5464. * @param int[]|int $categories Category or categories IDs
  5465. * @return int <0 if KO, >0 if OK
  5466. */
  5467. public function setCategories($categories)
  5468. {
  5469. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  5470. return parent::setCategoriesCommon($categories, Categorie::TYPE_PRODUCT);
  5471. }
  5472. /**
  5473. * Function used to replace a thirdparty id with another one.
  5474. *
  5475. * @param DoliDB $db Database handler
  5476. * @param int $origin_id Old thirdparty id
  5477. * @param int $dest_id New thirdparty id
  5478. * @return bool
  5479. */
  5480. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  5481. {
  5482. $tables = array(
  5483. 'product_customer_price',
  5484. 'product_customer_price_log'
  5485. );
  5486. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  5487. }
  5488. /**
  5489. * Generates prices for a product based on product multiprice generation rules
  5490. *
  5491. * @param User $user User that updates the prices
  5492. * @param float $baseprice Base price
  5493. * @param string $price_type Base price type
  5494. * @param float $price_vat VAT % tax
  5495. * @param int $npr NPR
  5496. * @param string $psq ¿?
  5497. * @return int -1 KO, 1 OK
  5498. */
  5499. public function generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
  5500. {
  5501. global $conf, $db;
  5502. $sql = "SELECT rowid, level, fk_level, var_percent, var_min_percent FROM ".$this->db->prefix()."product_pricerules";
  5503. $query = $this->db->query($sql);
  5504. $rules = array();
  5505. while ($result = $this->db->fetch_object($query)) {
  5506. $rules[$result->level] = $result;
  5507. }
  5508. //Because prices can be based on other level's prices, we temporarily store them
  5509. $prices = array(
  5510. 1 => $baseprice
  5511. );
  5512. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  5513. $price = $baseprice;
  5514. $price_min = $baseprice;
  5515. //We have to make sure it does exist and it is > 0
  5516. //First price level only allows changing min_price
  5517. if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) {
  5518. $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100));
  5519. }
  5520. $prices[$i] = $price;
  5521. //We have to make sure it does exist and it is > 0
  5522. if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) {
  5523. $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100));
  5524. }
  5525. //Little check to make sure the price is modified before triggering generation
  5526. $check_amount = (($price == $this->multiprices[$i]) && ($price_min == $this->multiprices_min[$i]));
  5527. $check_type = ($baseprice == $this->multiprices_base_type[$i]);
  5528. if ($check_amount && $check_type) {
  5529. continue;
  5530. }
  5531. if ($this->updatePrice($price, $price_type, $user, $price_vat, $price_min, $i, $npr, $psq, true) < 0) {
  5532. return -1;
  5533. }
  5534. }
  5535. return 1;
  5536. }
  5537. /**
  5538. * Returns the rights used for this class
  5539. *
  5540. * @return Object
  5541. */
  5542. public function getRights()
  5543. {
  5544. global $user;
  5545. if ($this->isProduct()) {
  5546. return $user->rights->produit;
  5547. } else {
  5548. return $user->rights->service;
  5549. }
  5550. }
  5551. /**
  5552. * Load information for tab info
  5553. *
  5554. * @param int $id Id of thirdparty to load
  5555. * @return void
  5556. */
  5557. public function info($id)
  5558. {
  5559. $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, p.tms as date_modification,";
  5560. $sql .= " p.fk_user_author, p.fk_user_modif";
  5561. $sql .= " FROM ".$this->db->prefix().$this->table_element." as p";
  5562. $sql .= " WHERE p.rowid = ".((int) $id);
  5563. $result = $this->db->query($sql);
  5564. if ($result) {
  5565. if ($this->db->num_rows($result)) {
  5566. $obj = $this->db->fetch_object($result);
  5567. $this->id = $obj->rowid;
  5568. if ($obj->fk_user_author) {
  5569. $cuser = new User($this->db);
  5570. $cuser->fetch($obj->fk_user_author);
  5571. $this->user_creation = $cuser;
  5572. }
  5573. if ($obj->fk_user_modif) {
  5574. $muser = new User($this->db);
  5575. $muser->fetch($obj->fk_user_modif);
  5576. $this->user_modification = $muser;
  5577. }
  5578. $this->ref = $obj->ref;
  5579. $this->date_creation = $this->db->jdate($obj->date_creation);
  5580. $this->date_modification = $this->db->jdate($obj->date_modification);
  5581. }
  5582. $this->db->free($result);
  5583. } else {
  5584. dol_print_error($this->db);
  5585. }
  5586. }
  5587. /**
  5588. * Return the duration in Hours of a service base on duration fields
  5589. * @return int -1 KO, >= 0 is the duration in hours
  5590. */
  5591. public function getProductDurationHours()
  5592. {
  5593. global $langs;
  5594. if (empty($this->duration_value)) {
  5595. $this->errors[]='ErrorDurationForServiceNotDefinedCantCalculateHourlyPrice';
  5596. return -1;
  5597. }
  5598. if ($this->duration_unit == 'i') {
  5599. $prodDurationHours = 1. / 60;
  5600. }
  5601. if ($this->duration_unit == 'h') {
  5602. $prodDurationHours = 1.;
  5603. }
  5604. if ($this->duration_unit == 'd') {
  5605. $prodDurationHours = 24.;
  5606. }
  5607. if ($this->duration_unit == 'w') {
  5608. $prodDurationHours = 24. * 7;
  5609. }
  5610. if ($this->duration_unit == 'm') {
  5611. $prodDurationHours = 24. * 30;
  5612. }
  5613. if ($this->duration_unit == 'y') {
  5614. $prodDurationHours = 24. * 365;
  5615. }
  5616. $prodDurationHours *= $this->duration_value;
  5617. return $prodDurationHours;
  5618. }
  5619. }
  5620. /**
  5621. * Class to manage products or services.
  5622. * Do not use 'Service' as class name since it is already used by APIs.
  5623. */
  5624. class ProductService extends Product
  5625. {
  5626. public $picto = 'service';
  5627. }