product.class.php 225 KB

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