product.class.php 241 KB

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