product.class.php 235 KB

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