product.class.php 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092
  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. if (!$error) {
  1246. // We remove directory
  1247. $ref = dol_sanitizeFileName($this->ref);
  1248. if ($conf->product->dir_output) {
  1249. $dir = $conf->product->dir_output."/".$ref;
  1250. if (file_exists($dir)) {
  1251. $res = @dol_delete_dir_recursive($dir);
  1252. if (!$res) {
  1253. $this->errors[] = 'ErrorFailToDeleteDir';
  1254. $error++;
  1255. }
  1256. }
  1257. }
  1258. }
  1259. if (!$error) {
  1260. $this->db->commit();
  1261. return 1;
  1262. } else {
  1263. foreach ($this->errors as $errmsg) {
  1264. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  1265. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1266. }
  1267. $this->db->rollback();
  1268. return -$error;
  1269. }
  1270. } else {
  1271. $this->error = "ErrorRecordIsUsedCantDelete";
  1272. return 0;
  1273. }
  1274. }
  1275. /**
  1276. * Update or add a translation for a product
  1277. *
  1278. * @param User $user Object user making update
  1279. * @return int <0 if KO, >0 if OK
  1280. */
  1281. public function setMultiLangs($user)
  1282. {
  1283. global $conf, $langs;
  1284. $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
  1285. $current_lang = $langs->getDefaultLang();
  1286. foreach ($langs_available as $key => $value) {
  1287. if ($key == $current_lang) {
  1288. $sql = "SELECT rowid";
  1289. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1290. $sql .= " WHERE fk_product = ".((int) $this->id);
  1291. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1292. $result = $this->db->query($sql);
  1293. if ($this->db->num_rows($result)) { // if there is already a description line for this language
  1294. $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
  1295. $sql2 .= " SET ";
  1296. $sql2 .= " label='".$this->db->escape($this->label)."',";
  1297. $sql2 .= " description='".$this->db->escape($this->description)."'";
  1298. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1299. $sql2 .= ", note='".$this->db->escape($this->other)."'";
  1300. }
  1301. $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1302. } else {
  1303. $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
  1304. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1305. $sql2 .= ", note";
  1306. }
  1307. $sql2 .= ")";
  1308. $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
  1309. $sql2 .= " '".$this->db->escape($this->description)."'";
  1310. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1311. $sql2 .= ", '".$this->db->escape($this->other)."'";
  1312. }
  1313. $sql2 .= ")";
  1314. }
  1315. dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key);
  1316. if (!$this->db->query($sql2)) {
  1317. $this->error = $this->db->lasterror();
  1318. return -1;
  1319. }
  1320. } elseif (isset($this->multilangs[$key])) {
  1321. if (empty($this->multilangs["$key"]["label"])) {
  1322. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
  1323. return -1;
  1324. }
  1325. $sql = "SELECT rowid";
  1326. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1327. $sql .= " WHERE fk_product = ".((int) $this->id);
  1328. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1329. $result = $this->db->query($sql);
  1330. if ($this->db->num_rows($result)) { // if there is already a description line for this language
  1331. $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
  1332. $sql2 .= " SET ";
  1333. $sql2 .= " label = '".$this->db->escape($this->multilangs["$key"]["label"])."',";
  1334. $sql2 .= " description = '".$this->db->escape($this->multilangs["$key"]["description"])."'";
  1335. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1336. $sql2 .= ", note = '".$this->db->escape($this->multilangs["$key"]["other"])."'";
  1337. }
  1338. $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1339. } else {
  1340. $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
  1341. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1342. $sql2 .= ", note";
  1343. }
  1344. $sql2 .= ")";
  1345. $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
  1346. $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'";
  1347. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1348. $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'";
  1349. }
  1350. $sql2 .= ")";
  1351. }
  1352. // We do not save if main fields are empty
  1353. if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) {
  1354. if (!$this->db->query($sql2)) {
  1355. $this->error = $this->db->lasterror();
  1356. return -1;
  1357. }
  1358. }
  1359. } else {
  1360. // language is not current language and we didn't provide a multilang description for this language
  1361. }
  1362. }
  1363. // Call trigger
  1364. $result = $this->call_trigger('PRODUCT_SET_MULTILANGS', $user);
  1365. if ($result < 0) {
  1366. $this->error = $this->db->lasterror();
  1367. return -1;
  1368. }
  1369. // End call triggers
  1370. return 1;
  1371. }
  1372. /**
  1373. * Delete a language for this product
  1374. *
  1375. * @param string $langtodelete Language code to delete
  1376. * @param User $user Object user making delete
  1377. *
  1378. * @return int <0 if KO, >0 if OK
  1379. */
  1380. public function delMultiLangs($langtodelete, $user)
  1381. {
  1382. $sql = "DELETE FROM ".$this->db->prefix()."product_lang";
  1383. $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
  1384. dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
  1385. $result = $this->db->query($sql);
  1386. if ($result) {
  1387. // Call trigger
  1388. $result = $this->call_trigger('PRODUCT_DEL_MULTILANGS', $user);
  1389. if ($result < 0) {
  1390. $this->error = $this->db->lasterror();
  1391. dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
  1392. return -1;
  1393. }
  1394. // End call triggers
  1395. return 1;
  1396. } else {
  1397. $this->error = $this->db->lasterror();
  1398. dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
  1399. return -1;
  1400. }
  1401. }
  1402. /**
  1403. * Sets an accountancy code for a product.
  1404. * Also calls PRODUCT_MODIFY trigger when modified
  1405. *
  1406. * @param string $type It can be 'buy', 'buy_intra', 'buy_export', 'sell', 'sell_intra' or 'sell_export'
  1407. * @param string $value Accountancy code
  1408. * @return int <0 KO >0 OK
  1409. */
  1410. public function setAccountancyCode($type, $value)
  1411. {
  1412. global $user, $langs, $conf;
  1413. $error = 0;
  1414. $this->db->begin();
  1415. if ($type == 'buy') {
  1416. $field = 'accountancy_code_buy';
  1417. } elseif ($type == 'buy_intra') {
  1418. $field = 'accountancy_code_buy_intra';
  1419. } elseif ($type == 'buy_export') {
  1420. $field = 'accountancy_code_buy_export';
  1421. } elseif ($type == 'sell') {
  1422. $field = 'accountancy_code_sell';
  1423. } elseif ($type == 'sell_intra') {
  1424. $field = 'accountancy_code_sell_intra';
  1425. } elseif ($type == 'sell_export') {
  1426. $field = 'accountancy_code_sell_export';
  1427. } else {
  1428. return -1;
  1429. }
  1430. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ";
  1431. $sql .= "$field = '".$this->db->escape($value)."'";
  1432. $sql .= " WHERE rowid = ".((int) $this->id);
  1433. dol_syslog(__METHOD__."", LOG_DEBUG);
  1434. $resql = $this->db->query($sql);
  1435. if ($resql) {
  1436. // Call trigger
  1437. $result = $this->call_trigger('PRODUCT_MODIFY', $user);
  1438. if ($result < 0) {
  1439. $error++;
  1440. }
  1441. // End call triggers
  1442. if ($error) {
  1443. $this->db->rollback();
  1444. return -1;
  1445. }
  1446. $this->$field = $value;
  1447. $this->db->commit();
  1448. return 1;
  1449. } else {
  1450. $this->error = $this->db->lasterror();
  1451. $this->db->rollback();
  1452. return -1;
  1453. }
  1454. }
  1455. /**
  1456. * Load array this->multilangs
  1457. *
  1458. * @return int <0 if KO, >0 if OK
  1459. */
  1460. public function getMultiLangs()
  1461. {
  1462. global $langs;
  1463. $current_lang = $langs->getDefaultLang();
  1464. $sql = "SELECT lang, label, description, note as other";
  1465. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1466. $sql .= " WHERE fk_product = ".((int) $this->id);
  1467. $result = $this->db->query($sql);
  1468. if ($result) {
  1469. while ($obj = $this->db->fetch_object($result)) {
  1470. //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
  1471. if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
  1472. $this->label = $obj->label;
  1473. $this->description = $obj->description;
  1474. $this->other = $obj->other;
  1475. }
  1476. $this->multilangs["$obj->lang"]["label"] = $obj->label;
  1477. $this->multilangs["$obj->lang"]["description"] = $obj->description;
  1478. $this->multilangs["$obj->lang"]["other"] = $obj->other;
  1479. }
  1480. return 1;
  1481. } else {
  1482. $this->error = "Error: ".$this->db->lasterror()." - ".$sql;
  1483. return -1;
  1484. }
  1485. }
  1486. /**
  1487. * used to check if price have really change to avoid log pollution
  1488. *
  1489. * @param int $level price level to change
  1490. * @return array
  1491. */
  1492. private function getArrayForPriceCompare($level = 0)
  1493. {
  1494. $testExit = array('multiprices','multiprices_ttc','multiprices_base_type','multiprices_min','multiprices_min_ttc','multiprices_tva_tx','multiprices_recuperableonly');
  1495. foreach ($testExit as $field) {
  1496. if (!isset($this->$field)) {
  1497. return array();
  1498. }
  1499. $tmparray = $this->$field;
  1500. if (!isset($tmparray[$level])) {
  1501. return array();
  1502. }
  1503. }
  1504. $lastPrice = array(
  1505. 'level' => $level ? $level : 1,
  1506. 'multiprices' => doubleval($this->multiprices[$level]),
  1507. 'multiprices_ttc' => doubleval($this->multiprices_ttc[$level]),
  1508. 'multiprices_base_type' => $this->multiprices_base_type[$level],
  1509. 'multiprices_min' => doubleval($this->multiprices_min[$level]),
  1510. 'multiprices_min_ttc' => doubleval($this->multiprices_min_ttc[$level]),
  1511. 'multiprices_tva_tx' => doubleval($this->multiprices_tva_tx[$level]),
  1512. 'multiprices_recuperableonly' => doubleval($this->multiprices_recuperableonly[$level]),
  1513. );
  1514. return $lastPrice;
  1515. }
  1516. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1517. /**
  1518. * Insert a track that we changed a customer price
  1519. *
  1520. * @param User $user User making change
  1521. * @param int $level price level to change
  1522. * @return int <0 if KO, >0 if OK
  1523. */
  1524. private function _log_price($user, $level = 0)
  1525. {
  1526. // phpcs:enable
  1527. global $conf;
  1528. $now = dol_now();
  1529. // Clean parameters
  1530. if (empty($this->price_by_qty)) {
  1531. $this->price_by_qty = 0;
  1532. }
  1533. // Add new price
  1534. $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,";
  1535. $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) ";
  1536. $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).",";
  1537. $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');
  1538. $sql .= ")";
  1539. dol_syslog(get_class($this)."::_log_price", LOG_DEBUG);
  1540. $resql = $this->db->query($sql);
  1541. if (!$resql) {
  1542. $this->error = $this->db->lasterror();
  1543. dol_print_error($this->db);
  1544. return -1;
  1545. } else {
  1546. return 1;
  1547. }
  1548. }
  1549. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1550. /**
  1551. * Delete a price line
  1552. *
  1553. * @param User $user Object user
  1554. * @param int $rowid Line id to delete
  1555. * @return int <0 if KO, >0 if OK
  1556. */
  1557. public function log_price_delete($user, $rowid)
  1558. {
  1559. // phpcs:enable
  1560. $sql = "DELETE FROM ".$this->db->prefix()."product_price_by_qty";
  1561. $sql .= " WHERE fk_product_price = ".((int) $rowid);
  1562. $resql = $this->db->query($sql);
  1563. $sql = "DELETE FROM ".$this->db->prefix()."product_price";
  1564. $sql .= " WHERE rowid=".((int) $rowid);
  1565. $resql = $this->db->query($sql);
  1566. if ($resql) {
  1567. return 1;
  1568. } else {
  1569. $this->error = $this->db->lasterror();
  1570. return -1;
  1571. }
  1572. }
  1573. /**
  1574. * Return price of sell of a product for a seller/buyer/product.
  1575. *
  1576. * @param Societe $thirdparty_seller Seller
  1577. * @param Societe $thirdparty_buyer Buyer
  1578. * @param int $pqp Id of product price per quantity if a selection was done of such a price
  1579. * @return array Array of price information array('pu_ht'=> , 'pu_ttc'=> , 'tva_tx'=>'X.Y (code)', ...), 'tva_npr'=>0, ...)
  1580. * @see get_buyprice(), find_min_price_product_fournisseur()
  1581. */
  1582. public function getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp = 0)
  1583. {
  1584. global $conf, $db, $hookmanager, $action;
  1585. // Call hook if any
  1586. if (is_object($hookmanager)) {
  1587. $parameters = array('thirdparty_seller'=>$thirdparty_seller, 'thirdparty_buyer' => $thirdparty_buyer, 'pqp' => $pqp);
  1588. // Note that $action and $object may have been modified by some hooks
  1589. $reshook = $hookmanager->executeHooks('getSellPrice', $parameters, $this, $action);
  1590. if ($reshook > 0) {
  1591. return $hookmanager->resArray;
  1592. }
  1593. }
  1594. // Update if prices fields are defined
  1595. $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
  1596. $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
  1597. if (empty($tva_tx)) {
  1598. $tva_npr = 0;
  1599. }
  1600. $pu_ht = $this->price;
  1601. $pu_ttc = $this->price_ttc;
  1602. $price_min = $this->price_min;
  1603. $price_base_type = $this->price_base_type;
  1604. // If price per segment
  1605. if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($thirdparty_buyer->price_level)) {
  1606. $pu_ht = $this->multiprices[$thirdparty_buyer->price_level];
  1607. $pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level];
  1608. $price_min = $this->multiprices_min[$thirdparty_buyer->price_level];
  1609. $price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level];
  1610. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  1611. if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
  1612. $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
  1613. }
  1614. if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
  1615. $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
  1616. }
  1617. if (empty($tva_tx)) {
  1618. $tva_npr = 0;
  1619. }
  1620. }
  1621. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  1622. // If price per customer
  1623. require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
  1624. $prodcustprice = new Productcustomerprice($this->db);
  1625. $filter = array('t.fk_product' => $this->id, 't.fk_soc' => $thirdparty_buyer->id);
  1626. $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
  1627. if ($result) {
  1628. if (count($prodcustprice->lines) > 0) {
  1629. $pu_ht = price($prodcustprice->lines[0]->price);
  1630. $price_min = price($prodcustprice->lines[0]->price_min);
  1631. $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
  1632. $price_base_type = $prodcustprice->lines[0]->price_base_type;
  1633. $tva_tx = $prodcustprice->lines[0]->tva_tx;
  1634. if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
  1635. $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
  1636. }
  1637. $tva_npr = $prodcustprice->lines[0]->recuperableonly;
  1638. if (empty($tva_tx)) {
  1639. $tva_npr = 0;
  1640. }
  1641. }
  1642. }
  1643. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
  1644. // If price per quantity
  1645. if ($this->prices_by_qty[0]) {
  1646. // yes, this product has some prices per quantity
  1647. // Search price into product_price_by_qty from $this->id
  1648. foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
  1649. if ($priceforthequantityarray['rowid'] != $pqp) {
  1650. continue;
  1651. }
  1652. // We found the price
  1653. if ($priceforthequantityarray['price_base_type'] == 'HT') {
  1654. $pu_ht = $priceforthequantityarray['unitprice'];
  1655. } else {
  1656. $pu_ttc = $priceforthequantityarray['unitprice'];
  1657. }
  1658. break;
  1659. }
  1660. }
  1661. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  1662. // If price per quantity and customer
  1663. if ($this->prices_by_qty[$thirdparty_buyer->price_level]) {
  1664. // yes, this product has some prices per quantity
  1665. // Search price into product_price_by_qty from $this->id
  1666. foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
  1667. if ($priceforthequantityarray['rowid'] != $pqp) {
  1668. continue;
  1669. }
  1670. // We found the price
  1671. if ($priceforthequantityarray['price_base_type'] == 'HT') {
  1672. $pu_ht = $priceforthequantityarray['unitprice'];
  1673. } else {
  1674. $pu_ttc = $priceforthequantityarray['unitprice'];
  1675. }
  1676. break;
  1677. }
  1678. }
  1679. }
  1680. 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);
  1681. }
  1682. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1683. /**
  1684. * Read price used by a provider.
  1685. * We enter as input couple prodfournprice/qty or triplet qty/product_id/fourn_ref.
  1686. * This also set some properties on product like ->buyprice, ->fourn_pu, ...
  1687. *
  1688. * @param int $prodfournprice Id du tarif = rowid table product_fournisseur_price
  1689. * @param double $qty Quantity asked or -1 to get first entry found
  1690. * @param int $product_id Filter on a particular product id
  1691. * @param string $fourn_ref Filter on a supplier price ref. 'none' to exclude ref in search.
  1692. * @param int $fk_soc If of supplier
  1693. * @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...)
  1694. * @see getSellPrice(), find_min_price_product_fournisseur()
  1695. */
  1696. public function get_buyprice($prodfournprice, $qty, $product_id = 0, $fourn_ref = '', $fk_soc = 0)
  1697. {
  1698. // phpcs:enable
  1699. global $conf;
  1700. $result = 0;
  1701. // 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)
  1702. $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent,";
  1703. $sql .= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression,";
  1704. $sql .= " pfp.default_vat_code,";
  1705. $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code";
  1706. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  1707. $sql .= ", pfp.packaging";
  1708. }
  1709. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
  1710. $sql .= " WHERE pfp.rowid = ".((int) $prodfournprice);
  1711. if ($qty > 0) {
  1712. $sql .= " AND pfp.quantity <= ".((float) $qty);
  1713. }
  1714. $sql .= " ORDER BY pfp.quantity DESC";
  1715. dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG);
  1716. $resql = $this->db->query($sql);
  1717. if ($resql) {
  1718. $obj = $this->db->fetch_object($resql);
  1719. if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
  1720. if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
  1721. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1722. $prod_supplier = new ProductFournisseur($this->db);
  1723. $prod_supplier->product_fourn_price_id = $obj->rowid;
  1724. $prod_supplier->id = $obj->fk_product;
  1725. $prod_supplier->fourn_qty = $obj->quantity;
  1726. $prod_supplier->fourn_tva_tx = $obj->tva_tx;
  1727. $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
  1728. $priceparser = new PriceParser($this->db);
  1729. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  1730. if ($price_result >= 0) {
  1731. $obj->price = $price_result;
  1732. }
  1733. }
  1734. $this->product_fourn_price_id = $obj->rowid;
  1735. $this->buyprice = $obj->price; // deprecated
  1736. $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier
  1737. $this->fourn_price_base_type = 'HT'; // Price base type
  1738. $this->fourn_socid = $obj->fk_soc; // Company that offer this price
  1739. $this->ref_fourn = $obj->ref_fourn; // deprecated
  1740. $this->ref_supplier = $obj->ref_fourn; // Ref supplier
  1741. $this->desc_supplier = $obj->desc_fourn; // desc supplier
  1742. $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
  1743. $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
  1744. $this->default_vat_code = $obj->default_vat_code; // Vat code supplier
  1745. $this->fourn_multicurrency_price = $obj->multicurrency_price;
  1746. $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
  1747. $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
  1748. $this->fourn_multicurrency_id = $obj->fk_multicurrency;
  1749. $this->fourn_multicurrency_code = $obj->multicurrency_code;
  1750. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  1751. $this->packaging = $obj->packaging;
  1752. }
  1753. $result = $obj->fk_product;
  1754. return $result;
  1755. } else { // If not found
  1756. // 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.
  1757. $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
  1758. $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.fk_supplier_price_expression,";
  1759. $sql .= " pfp.default_vat_code,";
  1760. $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
  1761. $sql .= " pfp.packaging";
  1762. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
  1763. $sql .= " WHERE 1 = 1";
  1764. if ($product_id > 0) {
  1765. $sql .= " AND pfp.fk_product = ".((int) $product_id);
  1766. }
  1767. if ($fourn_ref != 'none') {
  1768. $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
  1769. }
  1770. if ($fk_soc > 0) {
  1771. $sql .= " AND pfp.fk_soc = ".((int) $fk_soc);
  1772. }
  1773. if ($qty > 0) {
  1774. $sql .= " AND pfp.quantity <= ".((float) $qty);
  1775. }
  1776. $sql .= " ORDER BY pfp.quantity DESC";
  1777. $sql .= " LIMIT 1";
  1778. dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG);
  1779. $resql = $this->db->query($sql);
  1780. if ($resql) {
  1781. $obj = $this->db->fetch_object($resql);
  1782. if ($obj && $obj->quantity > 0) { // If found
  1783. if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
  1784. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1785. $prod_supplier = new ProductFournisseur($this->db);
  1786. $prod_supplier->product_fourn_price_id = $obj->rowid;
  1787. $prod_supplier->id = $obj->fk_product;
  1788. $prod_supplier->fourn_qty = $obj->quantity;
  1789. $prod_supplier->fourn_tva_tx = $obj->tva_tx;
  1790. $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
  1791. $priceparser = new PriceParser($this->db);
  1792. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  1793. if ($result >= 0) {
  1794. $obj->price = $price_result;
  1795. }
  1796. }
  1797. $this->product_fourn_price_id = $obj->rowid;
  1798. $this->buyprice = $obj->price; // deprecated
  1799. $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier
  1800. $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier
  1801. $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier
  1802. $this->fourn_socid = $obj->fk_soc; // Company that offer this price
  1803. $this->ref_fourn = $obj->ref_supplier; // deprecated
  1804. $this->ref_supplier = $obj->ref_supplier; // Ref supplier
  1805. $this->desc_supplier = $obj->desc_supplier; // desc supplier
  1806. $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
  1807. $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
  1808. $this->default_vat_code = $obj->default_vat_code; // Vat code supplier
  1809. $this->fourn_multicurrency_price = $obj->multicurrency_price;
  1810. $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
  1811. $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
  1812. $this->fourn_multicurrency_id = $obj->fk_multicurrency;
  1813. $this->fourn_multicurrency_code = $obj->multicurrency_code;
  1814. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  1815. $this->packaging = $obj->packaging;
  1816. }
  1817. $result = $obj->fk_product;
  1818. return $result;
  1819. } else {
  1820. 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é.
  1821. }
  1822. } else {
  1823. $this->error = $this->db->lasterror();
  1824. return -3;
  1825. }
  1826. }
  1827. } else {
  1828. $this->error = $this->db->lasterror();
  1829. return -2;
  1830. }
  1831. }
  1832. /**
  1833. * Modify customer price of a product/Service for a given level
  1834. *
  1835. * @param double $newprice New price
  1836. * @param string $newpricebase HT or TTC
  1837. * @param User $user Object user that make change
  1838. * @param double $newvat New VAT Rate (For example 8.5. Should not be a string)
  1839. * @param double $newminprice New price min
  1840. * @param int $level 0=standard, >0 = level if multilevel prices
  1841. * @param int $newnpr 0=Standard vat rate, 1=Special vat rate for French NPR VAT
  1842. * @param int $newpbq 1 if it has price by quantity
  1843. * @param int $ignore_autogen Used to avoid infinite loops
  1844. * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function).
  1845. * @param string $newdefaultvatcode Default vat code
  1846. * @return int <0 if KO, >0 if OK
  1847. */
  1848. public function updatePrice($newprice, $newpricebase, $user, $newvat = '', $newminprice = 0, $level = 0, $newnpr = 0, $newpbq = 0, $ignore_autogen = 0, $localtaxes_array = array(), $newdefaultvatcode = '')
  1849. {
  1850. global $conf, $langs;
  1851. $lastPriceData = $this->getArrayForPriceCompare($level); // temporary store current price before update
  1852. $id = $this->id;
  1853. dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode);
  1854. // Clean parameters
  1855. if (empty($this->tva_tx)) {
  1856. $this->tva_tx = 0;
  1857. }
  1858. if (empty($newnpr)) {
  1859. $newnpr = 0;
  1860. }
  1861. if (empty($newminprice)) {
  1862. $newminprice = 0;
  1863. }
  1864. if (empty($newminprice)) {
  1865. $newminprice = 0;
  1866. }
  1867. // Check parameters
  1868. if ($newvat == '') {
  1869. $newvat = $this->tva_tx;
  1870. }
  1871. // If multiprices are enabled, then we check if the current product is subject to price autogeneration
  1872. // Price will be modified ONLY when the first one is the one that is being modified
  1873. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !$ignore_autogen && $this->price_autogen && ($level == 1)) {
  1874. return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq);
  1875. }
  1876. if (!empty($newminprice) && ($newminprice > $newprice)) {
  1877. $this->error = 'ErrorPriceCantBeLowerThanMinPrice';
  1878. return -1;
  1879. }
  1880. if ($newprice !== '' || $newprice === 0) {
  1881. if ($newpricebase == 'TTC') {
  1882. $price_ttc = price2num($newprice, 'MU');
  1883. $price = price2num($newprice) / (1 + ($newvat / 100));
  1884. $price = price2num($price, 'MU');
  1885. if ($newminprice != '' || $newminprice == 0) {
  1886. $price_min_ttc = price2num($newminprice, 'MU');
  1887. $price_min = price2num($newminprice) / (1 + ($newvat / 100));
  1888. $price_min = price2num($price_min, 'MU');
  1889. } else {
  1890. $price_min = 0;
  1891. $price_min_ttc = 0;
  1892. }
  1893. } else {
  1894. $price = price2num($newprice, 'MU');
  1895. $price_ttc = ($newnpr != 1) ? price2num($newprice) * (1 + ($newvat / 100)) : $price;
  1896. $price_ttc = price2num($price_ttc, 'MU');
  1897. if ($newminprice !== '' || $newminprice === 0) {
  1898. $price_min = price2num($newminprice, 'MU');
  1899. $price_min_ttc = price2num($newminprice) * (1 + ($newvat / 100));
  1900. $price_min_ttc = price2num($price_min_ttc, 'MU');
  1901. //print 'X'.$newminprice.'-'.$price_min;
  1902. } else {
  1903. $price_min = 0;
  1904. $price_min_ttc = 0;
  1905. }
  1906. }
  1907. //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc;
  1908. if (count($localtaxes_array) > 0) {
  1909. $localtaxtype1 = $localtaxes_array['0'];
  1910. $localtax1 = $localtaxes_array['1'];
  1911. $localtaxtype2 = $localtaxes_array['2'];
  1912. $localtax2 = $localtaxes_array['3'];
  1913. } else // old method. deprecated because ot can't retrieve type
  1914. {
  1915. $localtaxtype1 = '0';
  1916. $localtax1 = get_localtax($newvat, 1);
  1917. $localtaxtype2 = '0';
  1918. $localtax2 = get_localtax($newvat, 2);
  1919. }
  1920. if (empty($localtax1)) {
  1921. $localtax1 = 0; // If = '' then = 0
  1922. }
  1923. if (empty($localtax2)) {
  1924. $localtax2 = 0; // If = '' then = 0
  1925. }
  1926. $this->db->begin();
  1927. // Ne pas mettre de quote sur les numeriques decimaux.
  1928. // Ceci provoque des stockages avec arrondis en base au lieu des valeurs exactes.
  1929. $sql = "UPDATE ".$this->db->prefix()."product SET";
  1930. $sql .= " price_base_type='".$this->db->escape($newpricebase)."',";
  1931. $sql .= " price=".$price.",";
  1932. $sql .= " price_ttc=".$price_ttc.",";
  1933. $sql .= " price_min=".$price_min.",";
  1934. $sql .= " price_min_ttc=".$price_min_ttc.",";
  1935. $sql .= " localtax1_tx=".($localtax1 >= 0 ? $localtax1 : 'NULL').",";
  1936. $sql .= " localtax2_tx=".($localtax2 >= 0 ? $localtax2 : 'NULL').",";
  1937. $sql .= " localtax1_type=".($localtaxtype1 != '' ? "'".$this->db->escape($localtaxtype1)."'" : "'0'").",";
  1938. $sql .= " localtax2_type=".($localtaxtype2 != '' ? "'".$this->db->escape($localtaxtype2)."'" : "'0'").",";
  1939. $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
  1940. $sql .= " tva_tx='".price2num($newvat)."',";
  1941. $sql .= " recuperableonly='".$this->db->escape($newnpr)."'";
  1942. $sql .= " WHERE rowid = ".((int) $id);
  1943. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  1944. $resql = $this->db->query($sql);
  1945. if ($resql) {
  1946. $this->multiprices[$level] = $price;
  1947. $this->multiprices_ttc[$level] = $price_ttc;
  1948. $this->multiprices_min[$level] = $price_min;
  1949. $this->multiprices_min_ttc[$level] = $price_min_ttc;
  1950. $this->multiprices_base_type[$level] = $newpricebase;
  1951. $this->multiprices_default_vat_code[$level] = $newdefaultvatcode;
  1952. $this->multiprices_tva_tx[$level] = $newvat;
  1953. $this->multiprices_recuperableonly[$level] = $newnpr;
  1954. $this->price = $price;
  1955. $this->price_ttc = $price_ttc;
  1956. $this->price_min = $price_min;
  1957. $this->price_min_ttc = $price_min_ttc;
  1958. $this->price_base_type = $newpricebase;
  1959. $this->default_vat_code = $newdefaultvatcode;
  1960. $this->tva_tx = $newvat;
  1961. $this->tva_npr = $newnpr;
  1962. //Local taxes
  1963. $this->localtax1_tx = $localtax1;
  1964. $this->localtax2_tx = $localtax2;
  1965. $this->localtax1_type = $localtaxtype1;
  1966. $this->localtax2_type = $localtaxtype2;
  1967. // Price by quantity
  1968. $this->price_by_qty = $newpbq;
  1969. // check if price have really change before log
  1970. $newPriceData = $this->getArrayForPriceCompare($level);
  1971. if (!empty(array_diff_assoc($newPriceData, $lastPriceData)) || empty($conf->global->PRODUIT_MULTIPRICES)) {
  1972. $this->_log_price($user, $level); // Save price for level into table product_price
  1973. }
  1974. $this->level = $level; // Store level of price edited for trigger
  1975. // Call trigger
  1976. $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user);
  1977. if ($result < 0) {
  1978. $this->db->rollback();
  1979. return -1;
  1980. }
  1981. // End call triggers
  1982. $this->db->commit();
  1983. } else {
  1984. $this->db->rollback();
  1985. $this->error = $this->db->lasterror();
  1986. return -1;
  1987. }
  1988. }
  1989. return 1;
  1990. }
  1991. /**
  1992. * Sets the supplier price expression
  1993. *
  1994. * @param int $expression_id Expression
  1995. * @return int <0 if KO, >0 if OK
  1996. * @deprecated Use Product::update instead
  1997. */
  1998. public function setPriceExpression($expression_id)
  1999. {
  2000. global $user;
  2001. $this->fk_price_expression = $expression_id;
  2002. return $this->update($this->id, $user);
  2003. }
  2004. /**
  2005. * Load a product in memory from database
  2006. *
  2007. * @param int $id Id of product/service to load
  2008. * @param string $ref Ref of product/service to load
  2009. * @param string $ref_ext Ref ext of product/service to load
  2010. * @param string $barcode Barcode of product/service to load
  2011. * @param int $ignore_expression When module dynamicprices is on, ignores the math expression for calculating price and uses the db value instead
  2012. * @param int $ignore_price_load Load product without loading $this->multiprices... array (when we are sure we don't need them)
  2013. * @param int $ignore_lang_load Load product without loading $this->multilangs language arrays (when we are sure we don't need them)
  2014. * @return int <0 if KO, 0 if not found, >0 if OK
  2015. */
  2016. public function fetch($id = '', $ref = '', $ref_ext = '', $barcode = '', $ignore_expression = 0, $ignore_price_load = 0, $ignore_lang_load = 0)
  2017. {
  2018. include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2019. global $langs, $conf;
  2020. dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref." ref_ext=".$ref_ext);
  2021. // Check parameters
  2022. if (!$id && !$ref && !$ref_ext && !$barcode) {
  2023. $this->error = 'ErrorWrongParameters';
  2024. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  2025. return -1;
  2026. }
  2027. $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,";
  2028. $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,";
  2029. $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,";
  2030. $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
  2031. $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,";
  2032. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  2033. $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,";
  2034. } else {
  2035. $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,";
  2036. }
  2037. //For MultiCompany
  2038. //PMP per entity & Stocks Sharings stock_reel includes only stocks shared with this entity
  2039. $separatedEntityPMP = false; // Set to true to get the AWP from table llx_product_perentity instead of field 'pmp' into llx_product.
  2040. $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.
  2041. if (!empty($conf->global->MULTICOMPANY_PRODUCT_SHARING_ENABLED)) {
  2042. if (!empty($conf->global->MULTICOMPANY_PMP_PER_ENTITY_ENABLED)) {
  2043. $checkPMPPerEntity = $this->db->query("SELECT pmp FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = ".((int) $id)." AND entity = ".(int) $conf->entity);
  2044. if ($this->db->num_rows($checkPMPPerEntity)>0) {
  2045. $separatedEntityPMP = true;
  2046. }
  2047. }
  2048. global $mc;
  2049. $separatedStock = true;
  2050. $visibleWarehousesEntities = $conf->entity;
  2051. if (isset($mc->sharings['stock']) && !empty($mc->sharings['stock'])) {
  2052. $visibleWarehousesEntities .= "," . implode(",", $mc->sharings['stock']);
  2053. }
  2054. }
  2055. if ($separatedEntityPMP) {
  2056. $sql .= " ppe.pmp,";
  2057. } else {
  2058. $sql .= " p.pmp,";
  2059. }
  2060. $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
  2061. $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf,";
  2062. if ($separatedStock) {
  2063. $sql .= " SUM(sp.reel) as stock";
  2064. } else {
  2065. $sql .= " p.stock";
  2066. }
  2067. $sql .= " FROM ".$this->db->prefix()."product as p";
  2068. if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED) || $separatedEntityPMP) {
  2069. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
  2070. }
  2071. if ($separatedStock) {
  2072. $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)."))";
  2073. }
  2074. if ($id) {
  2075. $sql .= " WHERE p.rowid = ".((int) $id);
  2076. } else {
  2077. $sql .= " WHERE p.entity IN (".getEntity($this->element).")";
  2078. if ($ref) {
  2079. $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
  2080. } elseif ($ref_ext) {
  2081. $sql .= " AND p.ref_ext = '".$this->db->escape($ref_ext)."'";
  2082. } elseif ($barcode) {
  2083. $sql .= " AND p.barcode = '".$this->db->escape($barcode)."'";
  2084. }
  2085. }
  2086. if ($separatedStock) {
  2087. $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,";
  2088. $sql .= " p.price_min, p.price_min_ttc, p.price_base_type, p.cost_price, p.default_vat_code, p.tva_tx, p.recuperableonly, p.localtax1_tx, p.localtax2_tx, p.localtax1_type, p.localtax2_type, p.tosell,";
  2089. $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
  2090. $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
  2091. $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished,";
  2092. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  2093. $sql .= " p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,";
  2094. } else {
  2095. $sql .= " ppe.accountancy_code_buy, ppe.accountancy_code_buy_intra, ppe.accountancy_code_buy_export, ppe.accountancy_code_sell, ppe.accountancy_code_sell_intra, ppe.accountancy_code_sell_export,";
  2096. }
  2097. if ($separatedEntityPMP) {
  2098. $sql .= " ppe.pmp,";
  2099. } else {
  2100. $sql .= " p.pmp,";
  2101. }
  2102. $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
  2103. $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf";
  2104. if (!$separatedStock) {
  2105. $sql .= ", p.stock";
  2106. }
  2107. }
  2108. $resql = $this->db->query($sql);
  2109. if ($resql) {
  2110. unset($this->oldcopy);
  2111. if ($this->db->num_rows($resql) > 0) {
  2112. $obj = $this->db->fetch_object($resql);
  2113. $this->id = $obj->rowid;
  2114. $this->ref = $obj->ref;
  2115. $this->ref_ext = $obj->ref_ext;
  2116. $this->label = $obj->label;
  2117. $this->description = $obj->description;
  2118. $this->url = $obj->url;
  2119. $this->note_public = $obj->note_public;
  2120. $this->note_private = $obj->note_private;
  2121. $this->note = $obj->note_private; // deprecated
  2122. $this->type = $obj->fk_product_type;
  2123. $this->status = $obj->tosell;
  2124. $this->status_buy = $obj->tobuy;
  2125. $this->status_batch = $obj->tobatch;
  2126. $this->batch_mask = $obj->batch_mask;
  2127. $this->customcode = $obj->customcode;
  2128. $this->country_id = $obj->fk_country;
  2129. $this->country_code = getCountry($this->country_id, 2, $this->db);
  2130. $this->state_id = $obj->fk_state;
  2131. $this->lifetime = $obj->lifetime;
  2132. $this->qc_frequency = $obj->qc_frequency;
  2133. $this->price = $obj->price;
  2134. $this->price_ttc = $obj->price_ttc;
  2135. $this->price_min = $obj->price_min;
  2136. $this->price_min_ttc = $obj->price_min_ttc;
  2137. $this->price_base_type = $obj->price_base_type;
  2138. $this->cost_price = $obj->cost_price;
  2139. $this->default_vat_code = $obj->default_vat_code;
  2140. $this->tva_tx = $obj->tva_tx;
  2141. //! French VAT NPR
  2142. $this->tva_npr = $obj->tva_npr;
  2143. $this->recuperableonly = $obj->tva_npr; // For backward compatibility
  2144. //! Local taxes
  2145. $this->localtax1_tx = $obj->localtax1_tx;
  2146. $this->localtax2_tx = $obj->localtax2_tx;
  2147. $this->localtax1_type = $obj->localtax1_type;
  2148. $this->localtax2_type = $obj->localtax2_type;
  2149. $this->finished = $obj->finished;
  2150. $this->fk_default_bom = $obj->fk_default_bom;
  2151. $this->duration = $obj->duration;
  2152. $this->duration_value = substr($obj->duration, 0, dol_strlen($obj->duration) - 1);
  2153. $this->duration_unit = substr($obj->duration, -1);
  2154. $this->canvas = $obj->canvas;
  2155. $this->net_measure = $obj->net_measure;
  2156. $this->net_measure_units = $obj->net_measure_units;
  2157. $this->weight = $obj->weight;
  2158. $this->weight_units = $obj->weight_units;
  2159. $this->length = $obj->length;
  2160. $this->length_units = $obj->length_units;
  2161. $this->width = $obj->width;
  2162. $this->width_units = $obj->width_units;
  2163. $this->height = $obj->height;
  2164. $this->height_units = $obj->height_units;
  2165. $this->surface = $obj->surface;
  2166. $this->surface_units = $obj->surface_units;
  2167. $this->volume = $obj->volume;
  2168. $this->volume_units = $obj->volume_units;
  2169. $this->barcode = $obj->barcode;
  2170. $this->barcode_type = $obj->fk_barcode_type;
  2171. $this->accountancy_code_buy = $obj->accountancy_code_buy;
  2172. $this->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra;
  2173. $this->accountancy_code_buy_export = $obj->accountancy_code_buy_export;
  2174. $this->accountancy_code_sell = $obj->accountancy_code_sell;
  2175. $this->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra;
  2176. $this->accountancy_code_sell_export = $obj->accountancy_code_sell_export;
  2177. $this->fk_default_warehouse = $obj->fk_default_warehouse;
  2178. $this->seuil_stock_alerte = $obj->seuil_stock_alerte;
  2179. $this->desiredstock = $obj->desiredstock;
  2180. $this->stock_reel = $obj->stock;
  2181. $this->pmp = $obj->pmp;
  2182. $this->date_creation = $obj->datec;
  2183. $this->date_modification = $obj->tms;
  2184. $this->import_key = $obj->import_key;
  2185. $this->entity = $obj->entity;
  2186. $this->ref_ext = $obj->ref_ext;
  2187. $this->fk_price_expression = $obj->fk_price_expression;
  2188. $this->fk_unit = $obj->fk_unit;
  2189. $this->price_autogen = $obj->price_autogen;
  2190. $this->model_pdf = $obj->model_pdf;
  2191. $this->mandatory_period = $obj->mandatory_period;
  2192. $this->db->free($resql);
  2193. // fetch optionals attributes and labels
  2194. $this->fetch_optionals();
  2195. // Multilangs
  2196. if (!empty($conf->global->MAIN_MULTILANGS) && empty($ignore_lang_load)) {
  2197. $this->getMultiLangs();
  2198. }
  2199. // Load multiprices array
  2200. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) { // prices per segment
  2201. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  2202. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2203. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
  2204. $sql .= " FROM ".$this->db->prefix()."product_price";
  2205. $sql .= " WHERE entity IN (".getEntity('productprice').")";
  2206. $sql .= " AND price_level=".((int) $i);
  2207. $sql .= " AND fk_product = ".((int) $this->id);
  2208. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Get the most recent line
  2209. $sql .= " LIMIT 1"; // Only the first one
  2210. $resql = $this->db->query($sql);
  2211. if ($resql) {
  2212. $result = $this->db->fetch_array($resql);
  2213. $this->multiprices[$i] = $result ? $result["price"] : null;
  2214. $this->multiprices_ttc[$i] = $result ? $result["price_ttc"] : null;
  2215. $this->multiprices_min[$i] = $result ? $result["price_min"] : null;
  2216. $this->multiprices_min_ttc[$i] = $result ? $result["price_min_ttc"] : null;
  2217. $this->multiprices_base_type[$i] = $result ? $result["price_base_type"] : null;
  2218. // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
  2219. $this->multiprices_tva_tx[$i] = $result ? $result["tva_tx"].($result ? ' ('.$result['default_vat_code'].')' : '') : null;
  2220. $this->multiprices_recuperableonly[$i] = $result ? $result["recuperableonly"] : null;
  2221. // Price by quantity
  2222. /*
  2223. $this->prices_by_qty[$i]=$result["price_by_qty"];
  2224. $this->prices_by_qty_id[$i]=$result["rowid"];
  2225. // Récuperation de la liste des prix selon qty si flag positionné
  2226. if ($this->prices_by_qty[$i] == 1)
  2227. {
  2228. $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
  2229. $sql.= " FROM ".$this->db->prefix()."product_price_by_qty";
  2230. $sql.= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
  2231. $sql.= " ORDER BY quantity ASC";
  2232. $resultat=array();
  2233. $resql = $this->db->query($sql);
  2234. if ($resql)
  2235. {
  2236. $ii=0;
  2237. while ($result= $this->db->fetch_array($resql)) {
  2238. $resultat[$ii]=array();
  2239. $resultat[$ii]["rowid"]=$result["rowid"];
  2240. $resultat[$ii]["price"]= $result["price"];
  2241. $resultat[$ii]["unitprice"]= $result["unitprice"];
  2242. $resultat[$ii]["quantity"]= $result["quantity"];
  2243. $resultat[$ii]["remise_percent"]= $result["remise_percent"];
  2244. $resultat[$ii]["remise"]= $result["remise"]; // deprecated
  2245. $resultat[$ii]["price_base_type"]= $result["price_base_type"];
  2246. $ii++;
  2247. }
  2248. $this->prices_by_qty_list[$i]=$resultat;
  2249. }
  2250. else
  2251. {
  2252. dol_print_error($this->db);
  2253. return -1;
  2254. }
  2255. }*/
  2256. } else {
  2257. $this->error = $this->db->lasterror;
  2258. return -1;
  2259. }
  2260. }
  2261. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) { // prices per customers
  2262. // Nothing loaded by default. List may be very long.
  2263. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) { // prices per quantity
  2264. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2265. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
  2266. $sql .= " FROM ".$this->db->prefix()."product_price";
  2267. $sql .= " WHERE fk_product = ".((int) $this->id);
  2268. $sql .= " ORDER BY date_price DESC, rowid DESC";
  2269. $sql .= " LIMIT 1";
  2270. $resql = $this->db->query($sql);
  2271. if ($resql) {
  2272. $result = $this->db->fetch_array($resql);
  2273. // Price by quantity
  2274. $this->prices_by_qty[0] = $result["price_by_qty"];
  2275. $this->prices_by_qty_id[0] = $result["rowid"];
  2276. // Récuperation de la liste des prix selon qty si flag positionné
  2277. if ($this->prices_by_qty[0] == 1) {
  2278. $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type";
  2279. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2280. $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[0]);
  2281. $sql .= " ORDER BY quantity ASC";
  2282. $resultat = array();
  2283. $resql = $this->db->query($sql);
  2284. if ($resql) {
  2285. $ii = 0;
  2286. while ($result = $this->db->fetch_array($resql)) {
  2287. $resultat[$ii] = array();
  2288. $resultat[$ii]["rowid"] = $result["rowid"];
  2289. $resultat[$ii]["price"] = $result["price"];
  2290. $resultat[$ii]["unitprice"] = $result["unitprice"];
  2291. $resultat[$ii]["quantity"] = $result["quantity"];
  2292. $resultat[$ii]["remise_percent"] = $result["remise_percent"];
  2293. //$resultat[$ii]["remise"]= $result["remise"]; // deprecated
  2294. $resultat[$ii]["price_base_type"] = $result["price_base_type"];
  2295. $ii++;
  2296. }
  2297. $this->prices_by_qty_list[0] = $resultat;
  2298. } else {
  2299. $this->error = $this->db->lasterror;
  2300. return -1;
  2301. }
  2302. }
  2303. } else {
  2304. $this->error = $this->db->lasterror;
  2305. return -1;
  2306. }
  2307. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) { // prices per customer and quantity
  2308. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  2309. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2310. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
  2311. $sql .= " FROM ".$this->db->prefix()."product_price";
  2312. $sql .= " WHERE entity IN (".getEntity('productprice').")";
  2313. $sql .= " AND price_level=".((int) $i);
  2314. $sql .= " AND fk_product = ".((int) $this->id);
  2315. $sql .= " ORDER BY date_price DESC, rowid DESC";
  2316. $sql .= " LIMIT 1";
  2317. $resql = $this->db->query($sql);
  2318. if ($resql) {
  2319. $result = $this->db->fetch_array($resql);
  2320. $this->multiprices[$i] = $result["price"];
  2321. $this->multiprices_ttc[$i] = $result["price_ttc"];
  2322. $this->multiprices_min[$i] = $result["price_min"];
  2323. $this->multiprices_min_ttc[$i] = $result["price_min_ttc"];
  2324. $this->multiprices_base_type[$i] = $result["price_base_type"];
  2325. // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
  2326. $this->multiprices_tva_tx[$i] = $result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')'
  2327. $this->multiprices_recuperableonly[$i] = $result["recuperableonly"];
  2328. // Price by quantity
  2329. $this->prices_by_qty[$i] = $result["price_by_qty"];
  2330. $this->prices_by_qty_id[$i] = $result["rowid"];
  2331. // Récuperation de la liste des prix selon qty si flag positionné
  2332. if ($this->prices_by_qty[$i] == 1) {
  2333. $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
  2334. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2335. $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
  2336. $sql .= " ORDER BY quantity ASC";
  2337. $resultat = array();
  2338. $resql = $this->db->query($sql);
  2339. if ($resql) {
  2340. $ii = 0;
  2341. while ($result = $this->db->fetch_array($resql)) {
  2342. $resultat[$ii] = array();
  2343. $resultat[$ii]["rowid"] = $result["rowid"];
  2344. $resultat[$ii]["price"] = $result["price"];
  2345. $resultat[$ii]["unitprice"] = $result["unitprice"];
  2346. $resultat[$ii]["quantity"] = $result["quantity"];
  2347. $resultat[$ii]["remise_percent"] = $result["remise_percent"];
  2348. $resultat[$ii]["remise"] = $result["remise"]; // deprecated
  2349. $resultat[$ii]["price_base_type"] = $result["price_base_type"];
  2350. $ii++;
  2351. }
  2352. $this->prices_by_qty_list[$i] = $resultat;
  2353. } else {
  2354. $this->error = $this->db->lasterror;
  2355. return -1;
  2356. }
  2357. }
  2358. } else {
  2359. $this->error = $this->db->lasterror;
  2360. return -1;
  2361. }
  2362. }
  2363. }
  2364. if (!empty($conf->dynamicprices->enabled) && !empty($this->fk_price_expression) && empty($ignore_expression)) {
  2365. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2366. $priceparser = new PriceParser($this->db);
  2367. $price_result = $priceparser->parseProduct($this);
  2368. if ($price_result >= 0) {
  2369. $this->price = $price_result;
  2370. // Calculate the VAT
  2371. $this->price_ttc = price2num($this->price) * (1 + ($this->tva_tx / 100));
  2372. $this->price_ttc = price2num($this->price_ttc, 'MU');
  2373. }
  2374. }
  2375. // We should not load stock during the fetch. If someone need stock of product, he must call load_stock after fetching product.
  2376. // Instead we just init the stock_warehouse array
  2377. $this->stock_warehouse = array();
  2378. return 1;
  2379. } else {
  2380. return 0;
  2381. }
  2382. } else {
  2383. $this->error = $this->db->lasterror();
  2384. return -1;
  2385. }
  2386. }
  2387. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2388. /**
  2389. * Charge tableau des stats OF pour le produit/service
  2390. *
  2391. * @param int $socid Id societe
  2392. * @return int Array of stats in $this->stats_mo, <0 if ko or >0 if ok
  2393. */
  2394. public function load_stats_mo($socid = 0)
  2395. {
  2396. // phpcs:enable
  2397. global $user, $hookmanager, $action;
  2398. $error = 0;
  2399. foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
  2400. $this->stats_mo['customers_'.$role] = 0;
  2401. $this->stats_mo['nb_'.$role] = 0;
  2402. $this->stats_mo['qty_'.$role] = 0;
  2403. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  2404. $sql .= " SUM(mp.qty) as qty";
  2405. $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
  2406. $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
  2407. if (empty($user->rights->societe->client->voir) && !$socid) {
  2408. $sql .= "INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".((int) $user->id);
  2409. }
  2410. $sql .= " WHERE ";
  2411. $sql .= " c.entity IN (".getEntity('mo').")";
  2412. $sql .= " AND mp.fk_product = ".((int) $this->id);
  2413. $sql .= " AND mp.role ='".$this->db->escape($role)."'";
  2414. if ($socid > 0) {
  2415. $sql .= " AND c.fk_soc = ".((int) $socid);
  2416. }
  2417. $result = $this->db->query($sql);
  2418. if ($result) {
  2419. $obj = $this->db->fetch_object($result);
  2420. $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
  2421. $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
  2422. $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
  2423. } else {
  2424. $this->error = $this->db->error();
  2425. $error++;
  2426. }
  2427. }
  2428. if (!empty($error)) {
  2429. return -1;
  2430. }
  2431. $parameters = array('socid' => $socid);
  2432. $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
  2433. if ($reshook > 0) {
  2434. $this->stats_mo = $hookmanager->resArray['stats_mo'];
  2435. }
  2436. return 1;
  2437. }
  2438. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2439. /**
  2440. * Charge tableau des stats OF pour le produit/service
  2441. *
  2442. * @param int $socid Id societe
  2443. * @return int Array of stats in $this->stats_bom, <0 if ko or >0 if ok
  2444. */
  2445. public function load_stats_bom($socid = 0)
  2446. {
  2447. // phpcs:enable
  2448. global $user, $hookmanager;
  2449. $error = 0;
  2450. $this->stats_bom['nb_toproduce'] = 0;
  2451. $this->stats_bom['nb_toconsume'] = 0;
  2452. $this->stats_bom['qty_toproduce'] = 0;
  2453. $this->stats_bom['qty_toconsume'] = 0;
  2454. $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,";
  2455. $sql .= " SUM(b.qty) as qty_toproduce";
  2456. $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
  2457. $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
  2458. $sql .= " WHERE ";
  2459. $sql .= " b.entity IN (".getEntity('bom').")";
  2460. $sql .= " AND b.fk_product =".((int) $this->id);
  2461. $sql .= " GROUP BY b.rowid";
  2462. $result = $this->db->query($sql);
  2463. if ($result) {
  2464. $obj = $this->db->fetch_object($result);
  2465. $this->stats_bom['nb_toproduce'] = !empty($obj->nb_toproduce) ? $obj->nb_toproduce : 0;
  2466. $this->stats_bom['qty_toproduce'] = !empty($obj->qty_toproduce) ? price2num($obj->qty_toproduce) : 0;
  2467. } else {
  2468. $this->error = $this->db->error();
  2469. $error++;
  2470. }
  2471. $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,";
  2472. $sql .= " SUM(bl.qty) as qty_toconsume";
  2473. $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
  2474. $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
  2475. $sql .= " WHERE ";
  2476. $sql .= " b.entity IN (".getEntity('bom').")";
  2477. $sql .= " AND bl.fk_product =".((int) $this->id);
  2478. $result = $this->db->query($sql);
  2479. if ($result) {
  2480. $obj = $this->db->fetch_object($result);
  2481. $this->stats_bom['nb_toconsume'] = !empty($obj->nb_toconsume) ? $obj->nb_toconsume : 0;
  2482. $this->stats_bom['qty_toconsume'] = !empty($obj->qty_toconsume) ? price2num($obj->qty_toconsume) : 0;
  2483. } else {
  2484. $this->error = $this->db->error();
  2485. $error++;
  2486. }
  2487. if (!empty($error)) {
  2488. return -1;
  2489. }
  2490. $parameters = array('socid' => $socid);
  2491. $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
  2492. if ($reshook > 0) {
  2493. $this->stats_bom = $hookmanager->resArray['stats_bom'];
  2494. }
  2495. return 1;
  2496. }
  2497. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2498. /**
  2499. * Charge tableau des stats propale pour le produit/service
  2500. *
  2501. * @param int $socid Id societe
  2502. * @return int Array of stats in $this->stats_propale, <0 if ko or >0 if ok
  2503. */
  2504. public function load_stats_propale($socid = 0)
  2505. {
  2506. // phpcs:enable
  2507. global $conf, $user, $hookmanager;
  2508. $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_customers, COUNT(DISTINCT p.rowid) as nb,";
  2509. $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
  2510. $sql .= " FROM ".$this->db->prefix()."propaldet as pd";
  2511. $sql .= ", ".$this->db->prefix()."propal as p";
  2512. $sql .= ", ".$this->db->prefix()."societe as s";
  2513. if (empty($user->rights->societe->client->voir) && !$socid) {
  2514. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2515. }
  2516. $sql .= " WHERE p.rowid = pd.fk_propal";
  2517. $sql .= " AND p.fk_soc = s.rowid";
  2518. $sql .= " AND p.entity IN (".getEntity('propal').")";
  2519. $sql .= " AND pd.fk_product = ".((int) $this->id);
  2520. if (empty($user->rights->societe->client->voir) && !$socid) {
  2521. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2522. }
  2523. //$sql.= " AND pr.fk_statut != 0";
  2524. if ($socid > 0) {
  2525. $sql .= " AND p.fk_soc = ".((int) $socid);
  2526. }
  2527. $result = $this->db->query($sql);
  2528. if ($result) {
  2529. $obj = $this->db->fetch_object($result);
  2530. $this->stats_propale['customers'] = $obj->nb_customers;
  2531. $this->stats_propale['nb'] = $obj->nb;
  2532. $this->stats_propale['rows'] = $obj->nb_rows;
  2533. $this->stats_propale['qty'] = $obj->qty ? $obj->qty : 0;
  2534. // if it's a virtual product, maybe it is in proposal by extension
  2535. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2536. $TFather = $this->getFather();
  2537. if (is_array($TFather) && !empty($TFather)) {
  2538. foreach ($TFather as &$fatherData) {
  2539. $pFather = new Product($this->db);
  2540. $pFather->id = $fatherData['id'];
  2541. $qtyCoef = $fatherData['qty'];
  2542. if ($fatherData['incdec']) {
  2543. $pFather->load_stats_propale($socid);
  2544. $this->stats_propale['customers'] += $pFather->stats_propale['customers'];
  2545. $this->stats_propale['nb'] += $pFather->stats_propale['nb'];
  2546. $this->stats_propale['rows'] += $pFather->stats_propale['rows'];
  2547. $this->stats_propale['qty'] += $pFather->stats_propale['qty'] * $qtyCoef;
  2548. }
  2549. }
  2550. }
  2551. }
  2552. $parameters = array('socid' => $socid);
  2553. $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
  2554. if ($reshook > 0) {
  2555. $this->stats_propale = $hookmanager->resArray['stats_propale'];
  2556. }
  2557. return 1;
  2558. } else {
  2559. $this->error = $this->db->error();
  2560. return -1;
  2561. }
  2562. }
  2563. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2564. /**
  2565. * Charge tableau des stats propale pour le produit/service
  2566. *
  2567. * @param int $socid Id thirdparty
  2568. * @return int Array of stats in $this->stats_proposal_supplier, <0 if ko or >0 if ok
  2569. */
  2570. public function load_stats_proposal_supplier($socid = 0)
  2571. {
  2572. // phpcs:enable
  2573. global $conf, $user, $hookmanager, $action;
  2574. $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,";
  2575. $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
  2576. $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as pd";
  2577. $sql .= ", ".$this->db->prefix()."supplier_proposal as p";
  2578. $sql .= ", ".$this->db->prefix()."societe as s";
  2579. if (empty($user->rights->societe->client->voir) && !$socid) {
  2580. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2581. }
  2582. $sql .= " WHERE p.rowid = pd.fk_supplier_proposal";
  2583. $sql .= " AND p.fk_soc = s.rowid";
  2584. $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
  2585. $sql .= " AND pd.fk_product = ".((int) $this->id);
  2586. if (empty($user->rights->societe->client->voir) && !$socid) {
  2587. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2588. }
  2589. //$sql.= " AND pr.fk_statut != 0";
  2590. if ($socid > 0) {
  2591. $sql .= " AND p.fk_soc = ".((int) $socid);
  2592. }
  2593. $result = $this->db->query($sql);
  2594. if ($result) {
  2595. $obj = $this->db->fetch_object($result);
  2596. $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers;
  2597. $this->stats_proposal_supplier['nb'] = $obj->nb;
  2598. $this->stats_proposal_supplier['rows'] = $obj->nb_rows;
  2599. $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0;
  2600. $parameters = array('socid' => $socid);
  2601. $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
  2602. if ($reshook > 0) {
  2603. $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
  2604. }
  2605. return 1;
  2606. } else {
  2607. $this->error = $this->db->error();
  2608. return -1;
  2609. }
  2610. }
  2611. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2612. /**
  2613. * Charge tableau des stats commande client pour le produit/service
  2614. *
  2615. * @param int $socid Id societe pour filtrer sur une societe
  2616. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2617. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2618. * @return integer Array of stats in $this->stats_commande (nb=nb of order, qty=qty ordered), <0 if ko or >0 if ok
  2619. */
  2620. public function load_stats_commande($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2621. {
  2622. // phpcs:enable
  2623. global $conf, $user, $hookmanager;
  2624. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  2625. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  2626. $sql .= " FROM ".$this->db->prefix()."commandedet as cd";
  2627. $sql .= ", ".$this->db->prefix()."commande as c";
  2628. $sql .= ", ".$this->db->prefix()."societe as s";
  2629. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2630. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2631. }
  2632. $sql .= " WHERE c.rowid = cd.fk_commande";
  2633. $sql .= " AND c.fk_soc = s.rowid";
  2634. $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'commande').")";
  2635. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2636. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2637. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2638. }
  2639. if ($socid > 0) {
  2640. $sql .= " AND c.fk_soc = ".((int) $socid);
  2641. }
  2642. if ($filtrestatut <> '') {
  2643. $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")";
  2644. }
  2645. $result = $this->db->query($sql);
  2646. if ($result) {
  2647. $obj = $this->db->fetch_object($result);
  2648. $this->stats_commande['customers'] = $obj->nb_customers;
  2649. $this->stats_commande['nb'] = $obj->nb;
  2650. $this->stats_commande['rows'] = $obj->nb_rows;
  2651. $this->stats_commande['qty'] = $obj->qty ? $obj->qty : 0;
  2652. // if it's a virtual product, maybe it is in order by extension
  2653. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2654. $TFather = $this->getFather();
  2655. if (is_array($TFather) && !empty($TFather)) {
  2656. foreach ($TFather as &$fatherData) {
  2657. $pFather = new Product($this->db);
  2658. $pFather->id = $fatherData['id'];
  2659. $qtyCoef = $fatherData['qty'];
  2660. if ($fatherData['incdec']) {
  2661. $pFather->load_stats_commande($socid, $filtrestatut);
  2662. $this->stats_commande['customers'] += $pFather->stats_commande['customers'];
  2663. $this->stats_commande['nb'] += $pFather->stats_commande['nb'];
  2664. $this->stats_commande['rows'] += $pFather->stats_commande['rows'];
  2665. $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef;
  2666. }
  2667. }
  2668. }
  2669. }
  2670. // If stock decrease is on invoice validation, the theorical stock continue to
  2671. // count the orders to ship in theorical stock when some are already removed b invoice validation.
  2672. // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation.
  2673. if (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  2674. if (!empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) {
  2675. $adeduire = 0;
  2676. $sql = "SELECT sum(fd.qty) as count FROM ".$this->db->prefix()."facturedet fd ";
  2677. $sql .= " JOIN ".$this->db->prefix()."facture f ON fd.fk_facture = f.rowid ";
  2678. $sql .= " JOIN ".$this->db->prefix()."element_element el ON el.fk_target = f.rowid and el.targettype = 'facture' and sourcetype = 'commande'";
  2679. $sql .= " JOIN ".$this->db->prefix()."commande c ON el.fk_source = c.rowid ";
  2680. $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
  2681. dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
  2682. $resql = $this->db->query($sql);
  2683. if ($resql) {
  2684. if ($this->db->num_rows($resql) > 0) {
  2685. $obj = $this->db->fetch_object($resql);
  2686. $adeduire += $obj->count;
  2687. }
  2688. }
  2689. $this->stats_commande['qty'] -= $adeduire;
  2690. }
  2691. }
  2692. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2693. $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
  2694. if ($reshook > 0) {
  2695. $this->stats_commande = $hookmanager->resArray['stats_commande'];
  2696. }
  2697. return 1;
  2698. } else {
  2699. $this->error = $this->db->error();
  2700. return -1;
  2701. }
  2702. }
  2703. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2704. /**
  2705. * Charge tableau des stats commande fournisseur pour le produit/service
  2706. *
  2707. * @param int $socid Id societe pour filtrer sur une societe
  2708. * @param string $filtrestatut Id des statuts pour filtrer sur des statuts
  2709. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2710. * @return int Array of stats in $this->stats_commande_fournisseur, <0 if ko or >0 if ok
  2711. */
  2712. public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2713. {
  2714. // phpcs:enable
  2715. global $conf, $user, $hookmanager, $action;
  2716. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,";
  2717. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  2718. $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as cd";
  2719. $sql .= ", ".$this->db->prefix()."commande_fournisseur as c";
  2720. $sql .= ", ".$this->db->prefix()."societe as s";
  2721. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2722. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2723. }
  2724. $sql .= " WHERE c.rowid = cd.fk_commande";
  2725. $sql .= " AND c.fk_soc = s.rowid";
  2726. $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
  2727. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2728. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2729. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2730. }
  2731. if ($socid > 0) {
  2732. $sql .= " AND c.fk_soc = ".((int) $socid);
  2733. }
  2734. if ($filtrestatut != '') {
  2735. $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")"; // Peut valoir 0
  2736. }
  2737. $result = $this->db->query($sql);
  2738. if ($result) {
  2739. $obj = $this->db->fetch_object($result);
  2740. $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers;
  2741. $this->stats_commande_fournisseur['nb'] = $obj->nb;
  2742. $this->stats_commande_fournisseur['rows'] = $obj->nb_rows;
  2743. $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
  2744. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2745. $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
  2746. if ($reshook > 0) {
  2747. $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
  2748. }
  2749. return 1;
  2750. } else {
  2751. $this->error = $this->db->error().' sql='.$sql;
  2752. return -1;
  2753. }
  2754. }
  2755. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2756. /**
  2757. * Charge tableau des stats expedition client pour le produit/service
  2758. *
  2759. * @param int $socid Id societe pour filtrer sur une societe
  2760. * @param string $filtrestatut [=''] Ids order status separated by comma
  2761. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2762. * @param string $filterShipmentStatus [=''] Ids shipment status separated by comma
  2763. * @return int Array of stats in $this->stats_expedition, <0 if ko or >0 if ok
  2764. */
  2765. public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '')
  2766. {
  2767. // phpcs:enable
  2768. global $conf, $user, $hookmanager;
  2769. $sql = "SELECT COUNT(DISTINCT e.fk_soc) as nb_customers, COUNT(DISTINCT e.rowid) as nb,";
  2770. $sql .= " COUNT(ed.rowid) as nb_rows, SUM(ed.qty) as qty";
  2771. $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
  2772. $sql .= ", ".$this->db->prefix()."commandedet as cd";
  2773. $sql .= ", ".$this->db->prefix()."commande as c";
  2774. $sql .= ", ".$this->db->prefix()."expedition as e";
  2775. $sql .= ", ".$this->db->prefix()."societe as s";
  2776. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2777. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2778. }
  2779. $sql .= " WHERE e.rowid = ed.fk_expedition";
  2780. $sql .= " AND c.rowid = cd.fk_commande";
  2781. $sql .= " AND e.fk_soc = s.rowid";
  2782. $sql .= " AND e.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'expedition').")";
  2783. $sql .= " AND ed.fk_origin_line = cd.rowid";
  2784. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2785. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2786. $sql .= " AND e.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2787. }
  2788. if ($socid > 0) {
  2789. $sql .= " AND e.fk_soc = ".((int) $socid);
  2790. }
  2791. if ($filtrestatut <> '') {
  2792. $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
  2793. }
  2794. if (!empty($filterShipmentStatus)) {
  2795. $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
  2796. }
  2797. $result = $this->db->query($sql);
  2798. if ($result) {
  2799. $obj = $this->db->fetch_object($result);
  2800. $this->stats_expedition['customers'] = $obj->nb_customers;
  2801. $this->stats_expedition['nb'] = $obj->nb;
  2802. $this->stats_expedition['rows'] = $obj->nb_rows;
  2803. $this->stats_expedition['qty'] = $obj->qty ? $obj->qty : 0;
  2804. // if it's a virtual product, maybe it is in sending by extension
  2805. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2806. $TFather = $this->getFather();
  2807. if (is_array($TFather) && !empty($TFather)) {
  2808. foreach ($TFather as &$fatherData) {
  2809. $pFather = new Product($this->db);
  2810. $pFather->id = $fatherData['id'];
  2811. $qtyCoef = $fatherData['qty'];
  2812. if ($fatherData['incdec']) {
  2813. $pFather->load_stats_sending($socid, $filtrestatut, $forVirtualStock);
  2814. $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
  2815. $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
  2816. $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
  2817. $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
  2818. }
  2819. }
  2820. }
  2821. }
  2822. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
  2823. $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
  2824. if ($reshook > 0) {
  2825. $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
  2826. }
  2827. return 1;
  2828. } else {
  2829. $this->error = $this->db->error();
  2830. return -1;
  2831. }
  2832. }
  2833. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2834. /**
  2835. * Charge tableau des stats réception fournisseur pour le produit/service
  2836. *
  2837. * @param int $socid Id societe pour filtrer sur une societe
  2838. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2839. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2840. * @return int Array of stats in $this->stats_reception, <0 if ko or >0 if ok
  2841. */
  2842. public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2843. {
  2844. // phpcs:enable
  2845. global $conf, $user, $hookmanager, $action;
  2846. $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_suppliers, COUNT(DISTINCT cf.rowid) as nb,";
  2847. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
  2848. $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as fd";
  2849. $sql .= ", ".$this->db->prefix()."commande_fournisseur as cf";
  2850. $sql .= ", ".$this->db->prefix()."societe as s";
  2851. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2852. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2853. }
  2854. $sql .= " WHERE cf.rowid = fd.fk_commande";
  2855. $sql .= " AND cf.fk_soc = s.rowid";
  2856. $sql .= " AND cf.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
  2857. $sql .= " AND fd.fk_product = ".((int) $this->id);
  2858. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2859. $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2860. }
  2861. if ($socid > 0) {
  2862. $sql .= " AND cf.fk_soc = ".((int) $socid);
  2863. }
  2864. if ($filtrestatut <> '') {
  2865. $sql .= " AND cf.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
  2866. }
  2867. $result = $this->db->query($sql);
  2868. if ($result) {
  2869. $obj = $this->db->fetch_object($result);
  2870. $this->stats_reception['suppliers'] = $obj->nb_suppliers;
  2871. $this->stats_reception['nb'] = $obj->nb;
  2872. $this->stats_reception['rows'] = $obj->nb_rows;
  2873. $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
  2874. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2875. $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
  2876. if ($reshook > 0) {
  2877. $this->stats_reception = $hookmanager->resArray['stats_reception'];
  2878. }
  2879. return 1;
  2880. } else {
  2881. $this->error = $this->db->error();
  2882. return -1;
  2883. }
  2884. }
  2885. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2886. /**
  2887. * Charge tableau des stats production pour le produit/service
  2888. *
  2889. * @param int $socid Id societe pour filtrer sur une societe
  2890. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2891. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2892. * @return integer Array of stats in $this->stats_mrptoproduce (nb=nb of order, qty=qty ordered), <0 if ko or >0 if ok
  2893. */
  2894. public function load_stats_inproduction($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2895. {
  2896. // phpcs:enable
  2897. global $conf, $user, $hookmanager;
  2898. $sql = "SELECT COUNT(DISTINCT m.fk_soc) as nb_customers, COUNT(DISTINCT m.rowid) as nb,";
  2899. $sql .= " COUNT(mp.rowid) as nb_rows, SUM(mp.qty) as qty, role";
  2900. $sql .= " FROM ".$this->db->prefix()."mrp_production as mp";
  2901. $sql .= ", ".$this->db->prefix()."mrp_mo as m";
  2902. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON s.rowid = m.fk_soc";
  2903. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2904. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2905. }
  2906. $sql .= " WHERE m.rowid = mp.fk_mo";
  2907. $sql .= " AND m.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'mrp').")";
  2908. $sql .= " AND mp.fk_product = ".((int) $this->id);
  2909. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2910. $sql .= " AND m.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2911. }
  2912. if ($socid > 0) {
  2913. $sql .= " AND m.fk_soc = ".((int) $socid);
  2914. }
  2915. if ($filtrestatut <> '') {
  2916. $sql .= " AND m.status IN (".$this->db->sanitize($filtrestatut).")";
  2917. }
  2918. $sql .= " GROUP BY role";
  2919. $this->stats_mrptoconsume['customers'] = 0;
  2920. $this->stats_mrptoconsume['nb'] = 0;
  2921. $this->stats_mrptoconsume['rows'] = 0;
  2922. $this->stats_mrptoconsume['qty'] = 0;
  2923. $this->stats_mrptoproduce['customers'] = 0;
  2924. $this->stats_mrptoproduce['nb'] = 0;
  2925. $this->stats_mrptoproduce['rows'] = 0;
  2926. $this->stats_mrptoproduce['qty'] = 0;
  2927. $result = $this->db->query($sql);
  2928. if ($result) {
  2929. while ($obj = $this->db->fetch_object($result)) {
  2930. if ($obj->role == 'toconsume') {
  2931. $this->stats_mrptoconsume['customers'] += $obj->nb_customers;
  2932. $this->stats_mrptoconsume['nb'] += $obj->nb;
  2933. $this->stats_mrptoconsume['rows'] += $obj->nb_rows;
  2934. $this->stats_mrptoconsume['qty'] += ($obj->qty ? $obj->qty : 0);
  2935. }
  2936. if ($obj->role == 'consumed') {
  2937. //$this->stats_mrptoconsume['customers'] += $obj->nb_customers;
  2938. //$this->stats_mrptoconsume['nb'] += $obj->nb;
  2939. //$this->stats_mrptoconsume['rows'] += $obj->nb_rows;
  2940. $this->stats_mrptoconsume['qty'] -= ($obj->qty ? $obj->qty : 0);
  2941. }
  2942. if ($obj->role == 'toproduce') {
  2943. $this->stats_mrptoproduce['customers'] += $obj->nb_customers;
  2944. $this->stats_mrptoproduce['nb'] += $obj->nb;
  2945. $this->stats_mrptoproduce['rows'] += $obj->nb_rows;
  2946. $this->stats_mrptoproduce['qty'] += ($obj->qty ? $obj->qty : 0);
  2947. }
  2948. if ($obj->role == 'produced') {
  2949. //$this->stats_mrptoproduce['customers'] += $obj->nb_customers;
  2950. //$this->stats_mrptoproduce['nb'] += $obj->nb;
  2951. //$this->stats_mrptoproduce['rows'] += $obj->nb_rows;
  2952. $this->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
  2953. }
  2954. }
  2955. // Clean data
  2956. if ($this->stats_mrptoconsume['qty'] < 0) {
  2957. $this->stats_mrptoconsume['qty'] = 0;
  2958. }
  2959. if ($this->stats_mrptoproduce['qty'] < 0) {
  2960. $this->stats_mrptoproduce['qty'] = 0;
  2961. }
  2962. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2963. $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
  2964. if ($reshook > 0) {
  2965. $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
  2966. }
  2967. return 1;
  2968. } else {
  2969. $this->error = $this->db->error();
  2970. return -1;
  2971. }
  2972. }
  2973. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2974. /**
  2975. * Charge tableau des stats contrat pour le produit/service
  2976. *
  2977. * @param int $socid Id societe
  2978. * @return int Array of stats in $this->stats_contrat, <0 if ko or >0 if ok
  2979. */
  2980. public function load_stats_contrat($socid = 0)
  2981. {
  2982. // phpcs:enable
  2983. global $conf, $user, $hookmanager;
  2984. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  2985. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  2986. $sql .= " FROM ".$this->db->prefix()."contratdet as cd";
  2987. $sql .= ", ".$this->db->prefix()."contrat as c";
  2988. $sql .= ", ".$this->db->prefix()."societe as s";
  2989. if (empty($user->rights->societe->client->voir) && !$socid) {
  2990. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2991. }
  2992. $sql .= " WHERE c.rowid = cd.fk_contrat";
  2993. $sql .= " AND c.fk_soc = s.rowid";
  2994. $sql .= " AND c.entity IN (".getEntity('contract').")";
  2995. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2996. if (empty($user->rights->societe->client->voir) && !$socid) {
  2997. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2998. }
  2999. //$sql.= " AND c.statut != 0";
  3000. if ($socid > 0) {
  3001. $sql .= " AND c.fk_soc = ".((int) $socid);
  3002. }
  3003. $result = $this->db->query($sql);
  3004. if ($result) {
  3005. $obj = $this->db->fetch_object($result);
  3006. $this->stats_contrat['customers'] = $obj->nb_customers;
  3007. $this->stats_contrat['nb'] = $obj->nb;
  3008. $this->stats_contrat['rows'] = $obj->nb_rows;
  3009. $this->stats_contrat['qty'] = $obj->qty ? $obj->qty : 0;
  3010. // if it's a virtual product, maybe it is in contract by extension
  3011. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  3012. $TFather = $this->getFather();
  3013. if (is_array($TFather) && !empty($TFather)) {
  3014. foreach ($TFather as &$fatherData) {
  3015. $pFather = new Product($this->db);
  3016. $pFather->id = $fatherData['id'];
  3017. $qtyCoef = $fatherData['qty'];
  3018. if ($fatherData['incdec']) {
  3019. $pFather->load_stats_contrat($socid);
  3020. $this->stats_contrat['customers'] += $pFather->stats_contrat['customers'];
  3021. $this->stats_contrat['nb'] += $pFather->stats_contrat['nb'];
  3022. $this->stats_contrat['rows'] += $pFather->stats_contrat['rows'];
  3023. $this->stats_contrat['qty'] += $pFather->stats_contrat['qty'] * $qtyCoef;
  3024. }
  3025. }
  3026. }
  3027. }
  3028. $parameters = array('socid' => $socid);
  3029. $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
  3030. if ($reshook > 0) {
  3031. $this->stats_contrat = $hookmanager->resArray['stats_contrat'];
  3032. }
  3033. return 1;
  3034. } else {
  3035. $this->error = $this->db->error().' sql='.$sql;
  3036. return -1;
  3037. }
  3038. }
  3039. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3040. /**
  3041. * Charge tableau des stats facture pour le produit/service
  3042. *
  3043. * @param int $socid Id societe
  3044. * @return int Array of stats in $this->stats_facture, <0 if ko or >0 if ok
  3045. */
  3046. public function load_stats_facture($socid = 0)
  3047. {
  3048. // phpcs:enable
  3049. global $db, $conf, $user, $hookmanager;
  3050. $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
  3051. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(".$this->db->ifsql('f.type != 2', 'fd.qty', 'fd.qty * -1').") as qty";
  3052. $sql .= " FROM ".$this->db->prefix()."facturedet as fd";
  3053. $sql .= ", ".$this->db->prefix()."facture as f";
  3054. $sql .= ", ".$this->db->prefix()."societe as s";
  3055. if (empty($user->rights->societe->client->voir) && !$socid) {
  3056. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3057. }
  3058. $sql .= " WHERE f.rowid = fd.fk_facture";
  3059. $sql .= " AND f.fk_soc = s.rowid";
  3060. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3061. $sql .= " AND fd.fk_product = ".((int) $this->id);
  3062. if (empty($user->rights->societe->client->voir) && !$socid) {
  3063. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3064. }
  3065. //$sql.= " AND f.fk_statut != 0";
  3066. if ($socid > 0) {
  3067. $sql .= " AND f.fk_soc = ".((int) $socid);
  3068. }
  3069. $result = $this->db->query($sql);
  3070. if ($result) {
  3071. $obj = $this->db->fetch_object($result);
  3072. $this->stats_facture['customers'] = $obj->nb_customers;
  3073. $this->stats_facture['nb'] = $obj->nb;
  3074. $this->stats_facture['rows'] = $obj->nb_rows;
  3075. $this->stats_facture['qty'] = $obj->qty ? $obj->qty : 0;
  3076. // if it's a virtual product, maybe it is in invoice by extension
  3077. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  3078. $TFather = $this->getFather();
  3079. if (is_array($TFather) && !empty($TFather)) {
  3080. foreach ($TFather as &$fatherData) {
  3081. $pFather = new Product($this->db);
  3082. $pFather->id = $fatherData['id'];
  3083. $qtyCoef = $fatherData['qty'];
  3084. if ($fatherData['incdec']) {
  3085. $pFather->load_stats_facture($socid);
  3086. $this->stats_facture['customers'] += $pFather->stats_facture['customers'];
  3087. $this->stats_facture['nb'] += $pFather->stats_facture['nb'];
  3088. $this->stats_facture['rows'] += $pFather->stats_facture['rows'];
  3089. $this->stats_facture['qty'] += $pFather->stats_facture['qty'] * $qtyCoef;
  3090. }
  3091. }
  3092. }
  3093. }
  3094. $parameters = array('socid' => $socid);
  3095. $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
  3096. if ($reshook > 0) {
  3097. $this->stats_facture = $hookmanager->resArray['stats_facture'];
  3098. }
  3099. return 1;
  3100. } else {
  3101. $this->error = $this->db->error();
  3102. return -1;
  3103. }
  3104. }
  3105. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3106. /**
  3107. * Charge tableau des stats facture pour le produit/service
  3108. *
  3109. * @param int $socid Id societe
  3110. * @return int Array of stats in $this->stats_facture_fournisseur, <0 if ko or >0 if ok
  3111. */
  3112. public function load_stats_facture_fournisseur($socid = 0)
  3113. {
  3114. // phpcs:enable
  3115. global $conf, $user, $hookmanager, $action;
  3116. $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
  3117. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
  3118. $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as fd";
  3119. $sql .= ", ".$this->db->prefix()."facture_fourn as f";
  3120. $sql .= ", ".$this->db->prefix()."societe as s";
  3121. if (empty($user->rights->societe->client->voir) && !$socid) {
  3122. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3123. }
  3124. $sql .= " WHERE f.rowid = fd.fk_facture_fourn";
  3125. $sql .= " AND f.fk_soc = s.rowid";
  3126. $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
  3127. $sql .= " AND fd.fk_product = ".((int) $this->id);
  3128. if (empty($user->rights->societe->client->voir) && !$socid) {
  3129. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3130. }
  3131. //$sql.= " AND f.fk_statut != 0";
  3132. if ($socid > 0) {
  3133. $sql .= " AND f.fk_soc = ".((int) $socid);
  3134. }
  3135. $result = $this->db->query($sql);
  3136. if ($result) {
  3137. $obj = $this->db->fetch_object($result);
  3138. $this->stats_facture_fournisseur['suppliers'] = $obj->nb_suppliers;
  3139. $this->stats_facture_fournisseur['nb'] = $obj->nb;
  3140. $this->stats_facture_fournisseur['rows'] = $obj->nb_rows;
  3141. $this->stats_facture_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
  3142. $parameters = array('socid' => $socid);
  3143. $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
  3144. if ($reshook > 0) {
  3145. $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
  3146. }
  3147. return 1;
  3148. } else {
  3149. $this->error = $this->db->error();
  3150. return -1;
  3151. }
  3152. }
  3153. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3154. /**
  3155. * Return an array formated for showing graphs
  3156. *
  3157. * @param string $sql Request to execute
  3158. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3159. * @param int $year Year (0=current year, -1=all years)
  3160. * @return array|int <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3161. */
  3162. private function _get_stats($sql, $mode, $year = 0)
  3163. {
  3164. // phpcs:enable
  3165. $tab = array();
  3166. $resql = $this->db->query($sql);
  3167. if ($resql) {
  3168. $num = $this->db->num_rows($resql);
  3169. $i = 0;
  3170. while ($i < $num) {
  3171. $arr = $this->db->fetch_array($resql);
  3172. $keyfortab = (string) $arr[1];
  3173. if ($year == -1) {
  3174. $keyfortab = substr($keyfortab, -2);
  3175. }
  3176. if ($mode == 'byunit') {
  3177. $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[0]; // 1st field
  3178. } elseif ($mode == 'bynumber') {
  3179. $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
  3180. }
  3181. $i++;
  3182. }
  3183. } else {
  3184. $this->error = $this->db->error().' sql='.$sql;
  3185. return -1;
  3186. }
  3187. if (empty($year)) {
  3188. $year = strftime('%Y', time());
  3189. $month = strftime('%m', time());
  3190. } elseif ($year == -1) {
  3191. $year = '';
  3192. $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
  3193. } else {
  3194. $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
  3195. }
  3196. $result = array();
  3197. for ($j = 0; $j < 12; $j++) {
  3198. // $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
  3199. $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
  3200. //print $idx.'-'.$year.'-'.$month.'<br>';
  3201. $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0);
  3202. // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0);
  3203. $month = "0".($month - 1);
  3204. if (dol_strlen($month) == 3) {
  3205. $month = substr($month, 1);
  3206. }
  3207. if ($month == 0) {
  3208. $month = 12;
  3209. $year = $year - 1;
  3210. }
  3211. }
  3212. return array_reverse($result);
  3213. }
  3214. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3215. /**
  3216. * Return nb of units or customers invoices in which product is included
  3217. *
  3218. * @param int $socid Limit count on a particular third party id
  3219. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3220. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3221. * @param int $year Year (0=last 12 month, -1=all years)
  3222. * @param string $morefilter More sql filters
  3223. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3224. */
  3225. public function get_nb_vente($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3226. {
  3227. // phpcs:enable
  3228. global $conf;
  3229. global $user;
  3230. $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
  3231. if ($mode == 'bynumber') {
  3232. $sql .= ", count(DISTINCT f.rowid)";
  3233. }
  3234. $sql .= " FROM ".$this->db->prefix()."facturedet as d, ".$this->db->prefix()."facture as f, ".$this->db->prefix()."societe as s";
  3235. if ($filteronproducttype >= 0) {
  3236. $sql .= ", ".$this->db->prefix()."product as p";
  3237. }
  3238. if (empty($user->rights->societe->client->voir) && !$socid) {
  3239. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3240. }
  3241. $sql .= " WHERE f.rowid = d.fk_facture";
  3242. if ($this->id > 0) {
  3243. $sql .= " AND d.fk_product = ".((int) $this->id);
  3244. } else {
  3245. $sql .= " AND d.fk_product > 0";
  3246. }
  3247. if ($filteronproducttype >= 0) {
  3248. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3249. }
  3250. $sql .= " AND f.fk_soc = s.rowid";
  3251. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3252. if (empty($user->rights->societe->client->voir) && !$socid) {
  3253. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3254. }
  3255. if ($socid > 0) {
  3256. $sql .= " AND f.fk_soc = $socid";
  3257. }
  3258. $sql .= $morefilter;
  3259. $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
  3260. $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
  3261. return $this->_get_stats($sql, $mode, $year);
  3262. }
  3263. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3264. /**
  3265. * Return nb of units or supplier invoices in which product is included
  3266. *
  3267. * @param int $socid Limit count on a particular third party id
  3268. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3269. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3270. * @param int $year Year (0=last 12 month, -1=all years)
  3271. * @param string $morefilter More sql filters
  3272. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3273. */
  3274. public function get_nb_achat($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3275. {
  3276. // phpcs:enable
  3277. global $conf;
  3278. global $user;
  3279. $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
  3280. if ($mode == 'bynumber') {
  3281. $sql .= ", count(DISTINCT f.rowid)";
  3282. }
  3283. $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as d, ".$this->db->prefix()."facture_fourn as f, ".$this->db->prefix()."societe as s";
  3284. if ($filteronproducttype >= 0) {
  3285. $sql .= ", ".$this->db->prefix()."product as p";
  3286. }
  3287. if (empty($user->rights->societe->client->voir) && !$socid) {
  3288. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3289. }
  3290. $sql .= " WHERE f.rowid = d.fk_facture_fourn";
  3291. if ($this->id > 0) {
  3292. $sql .= " AND d.fk_product = ".((int) $this->id);
  3293. } else {
  3294. $sql .= " AND d.fk_product > 0";
  3295. }
  3296. if ($filteronproducttype >= 0) {
  3297. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3298. }
  3299. $sql .= " AND f.fk_soc = s.rowid";
  3300. $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
  3301. if (empty($user->rights->societe->client->voir) && !$socid) {
  3302. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3303. }
  3304. if ($socid > 0) {
  3305. $sql .= " AND f.fk_soc = $socid";
  3306. }
  3307. $sql .= $morefilter;
  3308. $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
  3309. $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
  3310. return $this->_get_stats($sql, $mode, $year);
  3311. }
  3312. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3313. /**
  3314. * Return nb of units in proposals in which product is included
  3315. *
  3316. * @param int $socid Limit count on a particular third party id
  3317. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3318. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3319. * @param int $year Year (0=last 12 month, -1=all years)
  3320. * @param string $morefilter More sql filters
  3321. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3322. */
  3323. public function get_nb_propal($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3324. {
  3325. // phpcs:enable
  3326. global $conf, $user;
  3327. $sql = "SELECT sum(d.qty), date_format(p.datep, '%Y%m')";
  3328. if ($mode == 'bynumber') {
  3329. $sql .= ", count(DISTINCT p.rowid)";
  3330. }
  3331. $sql .= " FROM ".$this->db->prefix()."propaldet as d, ".$this->db->prefix()."propal as p, ".$this->db->prefix()."societe as s";
  3332. if ($filteronproducttype >= 0) {
  3333. $sql .= ", ".$this->db->prefix()."product as prod";
  3334. }
  3335. if (empty($user->rights->societe->client->voir) && !$socid) {
  3336. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3337. }
  3338. $sql .= " WHERE p.rowid = d.fk_propal";
  3339. if ($this->id > 0) {
  3340. $sql .= " AND d.fk_product = ".((int) $this->id);
  3341. } else {
  3342. $sql .= " AND d.fk_product > 0";
  3343. }
  3344. if ($filteronproducttype >= 0) {
  3345. $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
  3346. }
  3347. $sql .= " AND p.fk_soc = s.rowid";
  3348. $sql .= " AND p.entity IN (".getEntity('propal').")";
  3349. if (empty($user->rights->societe->client->voir) && !$socid) {
  3350. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3351. }
  3352. if ($socid > 0) {
  3353. $sql .= " AND p.fk_soc = ".((int) $socid);
  3354. }
  3355. $sql .= $morefilter;
  3356. $sql .= " GROUP BY date_format(p.datep,'%Y%m')";
  3357. $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC";
  3358. return $this->_get_stats($sql, $mode, $year);
  3359. }
  3360. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3361. /**
  3362. * Return nb of units in proposals in which product is included
  3363. *
  3364. * @param int $socid Limit count on a particular third party id
  3365. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3366. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3367. * @param int $year Year (0=last 12 month, -1=all years)
  3368. * @param string $morefilter More sql filters
  3369. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3370. */
  3371. public function get_nb_propalsupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3372. {
  3373. // phpcs:enable
  3374. global $conf;
  3375. global $user;
  3376. $sql = "SELECT sum(d.qty), date_format(p.date_valid, '%Y%m')";
  3377. if ($mode == 'bynumber') {
  3378. $sql .= ", count(DISTINCT p.rowid)";
  3379. }
  3380. $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as d, ".$this->db->prefix()."supplier_proposal as p, ".$this->db->prefix()."societe as s";
  3381. if ($filteronproducttype >= 0) {
  3382. $sql .= ", ".$this->db->prefix()."product as prod";
  3383. }
  3384. if (empty($user->rights->societe->client->voir) && !$socid) {
  3385. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3386. }
  3387. $sql .= " WHERE p.rowid = d.fk_supplier_proposal";
  3388. if ($this->id > 0) {
  3389. $sql .= " AND d.fk_product = ".((int) $this->id);
  3390. } else {
  3391. $sql .= " AND d.fk_product > 0";
  3392. }
  3393. if ($filteronproducttype >= 0) {
  3394. $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
  3395. }
  3396. $sql .= " AND p.fk_soc = s.rowid";
  3397. $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
  3398. if (empty($user->rights->societe->client->voir) && !$socid) {
  3399. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3400. }
  3401. if ($socid > 0) {
  3402. $sql .= " AND p.fk_soc = ".((int) $socid);
  3403. }
  3404. $sql .= $morefilter;
  3405. $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')";
  3406. $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC";
  3407. return $this->_get_stats($sql, $mode, $year);
  3408. }
  3409. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3410. /**
  3411. * Return nb of units in orders in which product is included
  3412. *
  3413. * @param int $socid Limit count on a particular third party id
  3414. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3415. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3416. * @param int $year Year (0=last 12 month, -1=all years)
  3417. * @param string $morefilter More sql filters
  3418. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3419. */
  3420. public function get_nb_order($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3421. {
  3422. // phpcs:enable
  3423. global $conf, $user;
  3424. $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
  3425. if ($mode == 'bynumber') {
  3426. $sql .= ", count(DISTINCT c.rowid)";
  3427. }
  3428. $sql .= " FROM ".$this->db->prefix()."commandedet as d, ".$this->db->prefix()."commande as c, ".$this->db->prefix()."societe as s";
  3429. if ($filteronproducttype >= 0) {
  3430. $sql .= ", ".$this->db->prefix()."product as p";
  3431. }
  3432. if (empty($user->rights->societe->client->voir) && !$socid) {
  3433. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3434. }
  3435. $sql .= " WHERE c.rowid = d.fk_commande";
  3436. if ($this->id > 0) {
  3437. $sql .= " AND d.fk_product = ".((int) $this->id);
  3438. } else {
  3439. $sql .= " AND d.fk_product > 0";
  3440. }
  3441. if ($filteronproducttype >= 0) {
  3442. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3443. }
  3444. $sql .= " AND c.fk_soc = s.rowid";
  3445. $sql .= " AND c.entity IN (".getEntity('commande').")";
  3446. if (empty($user->rights->societe->client->voir) && !$socid) {
  3447. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3448. }
  3449. if ($socid > 0) {
  3450. $sql .= " AND c.fk_soc = ".((int) $socid);
  3451. }
  3452. $sql .= $morefilter;
  3453. $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
  3454. $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
  3455. return $this->_get_stats($sql, $mode, $year);
  3456. }
  3457. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3458. /**
  3459. * Return nb of units in orders in which product is included
  3460. *
  3461. * @param int $socid Limit count on a particular third party id
  3462. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3463. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3464. * @param int $year Year (0=last 12 month, -1=all years)
  3465. * @param string $morefilter More sql filters
  3466. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3467. */
  3468. public function get_nb_ordersupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3469. {
  3470. // phpcs:enable
  3471. global $conf, $user;
  3472. $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
  3473. if ($mode == 'bynumber') {
  3474. $sql .= ", count(DISTINCT c.rowid)";
  3475. }
  3476. $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as d, ".$this->db->prefix()."commande_fournisseur as c, ".$this->db->prefix()."societe as s";
  3477. if ($filteronproducttype >= 0) {
  3478. $sql .= ", ".$this->db->prefix()."product as p";
  3479. }
  3480. if (empty($user->rights->societe->client->voir) && !$socid) {
  3481. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3482. }
  3483. $sql .= " WHERE c.rowid = d.fk_commande";
  3484. if ($this->id > 0) {
  3485. $sql .= " AND d.fk_product = ".((int) $this->id);
  3486. } else {
  3487. $sql .= " AND d.fk_product > 0";
  3488. }
  3489. if ($filteronproducttype >= 0) {
  3490. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3491. }
  3492. $sql .= " AND c.fk_soc = s.rowid";
  3493. $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
  3494. if (empty($user->rights->societe->client->voir) && !$socid) {
  3495. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3496. }
  3497. if ($socid > 0) {
  3498. $sql .= " AND c.fk_soc = ".((int) $socid);
  3499. }
  3500. $sql .= $morefilter;
  3501. $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
  3502. $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
  3503. return $this->_get_stats($sql, $mode, $year);
  3504. }
  3505. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3506. /**
  3507. * Return nb of units in orders in which product is included
  3508. *
  3509. * @param int $socid Limit count on a particular third party id
  3510. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3511. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3512. * @param int $year Year (0=last 12 month, -1=all years)
  3513. * @param string $morefilter More sql filters
  3514. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3515. */
  3516. public function get_nb_contract($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3517. {
  3518. // phpcs:enable
  3519. global $conf, $user;
  3520. $sql = "SELECT sum(d.qty), date_format(c.date_contrat, '%Y%m')";
  3521. if ($mode == 'bynumber') {
  3522. $sql .= ", count(DISTINCT c.rowid)";
  3523. }
  3524. $sql .= " FROM ".$this->db->prefix()."contratdet as d, ".$this->db->prefix()."contrat as c, ".$this->db->prefix()."societe as s";
  3525. if ($filteronproducttype >= 0) {
  3526. $sql .= ", ".$this->db->prefix()."product as p";
  3527. }
  3528. if (empty($user->rights->societe->client->voir) && !$socid) {
  3529. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3530. }
  3531. $sql .= " WHERE c.entity IN (".getEntity('contract').")";
  3532. $sql .= " AND c.rowid = d.fk_contrat";
  3533. if ($this->id > 0) {
  3534. $sql .= " AND d.fk_product = ".((int) $this->id);
  3535. } else {
  3536. $sql .= " AND d.fk_product > 0";
  3537. }
  3538. if ($filteronproducttype >= 0) {
  3539. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3540. }
  3541. $sql .= " AND c.fk_soc = s.rowid";
  3542. if (empty($user->rights->societe->client->voir) && !$socid) {
  3543. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3544. }
  3545. if ($socid > 0) {
  3546. $sql .= " AND c.fk_soc = ".((int) $socid);
  3547. }
  3548. $sql .= $morefilter;
  3549. $sql .= " GROUP BY date_format(c.date_contrat,'%Y%m')";
  3550. $sql .= " ORDER BY date_format(c.date_contrat,'%Y%m') DESC";
  3551. return $this->_get_stats($sql, $mode, $year);
  3552. }
  3553. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3554. /**
  3555. * Return nb of units in orders in which product is included
  3556. *
  3557. * @param int $socid Limit count on a particular third party id
  3558. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3559. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3560. * @param int $year Year (0=last 12 month, -1=all years)
  3561. * @param string $morefilter More sql filters
  3562. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3563. */
  3564. public function get_nb_mos($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3565. {
  3566. // phpcs:enable
  3567. global $conf, $user;
  3568. $sql = "SELECT sum(d.qty), date_format(d.date_valid, '%Y%m')";
  3569. if ($mode == 'bynumber') {
  3570. $sql .= ", count(DISTINCT d.rowid)";
  3571. }
  3572. $sql .= " FROM ".$this->db->prefix()."mrp_mo as d LEFT JOIN ".$this->db->prefix()."societe as s ON d.fk_soc = s.rowid";
  3573. if ($filteronproducttype >= 0) {
  3574. $sql .= ", ".$this->db->prefix()."product as p";
  3575. }
  3576. if (empty($user->rights->societe->client->voir) && !$socid) {
  3577. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3578. }
  3579. $sql .= " WHERE d.entity IN (".getEntity('mo').")";
  3580. $sql .= " AND d.status > 0";
  3581. if ($this->id > 0) {
  3582. $sql .= " AND d.fk_product = ".((int) $this->id);
  3583. } else {
  3584. $sql .= " AND d.fk_product > 0";
  3585. }
  3586. if ($filteronproducttype >= 0) {
  3587. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3588. }
  3589. if (empty($user->rights->societe->client->voir) && !$socid) {
  3590. $sql .= " AND d.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3591. }
  3592. if ($socid > 0) {
  3593. $sql .= " AND d.fk_soc = ".((int) $socid);
  3594. }
  3595. $sql .= $morefilter;
  3596. $sql .= " GROUP BY date_format(d.date_valid,'%Y%m')";
  3597. $sql .= " ORDER BY date_format(d.date_valid,'%Y%m') DESC";
  3598. return $this->_get_stats($sql, $mode, $year);
  3599. }
  3600. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3601. /**
  3602. * Link a product/service to a parent product/service
  3603. *
  3604. * @param int $id_pere Id of parent product/service
  3605. * @param int $id_fils Id of child product/service
  3606. * @param int $qty Quantity
  3607. * @param int $incdec 1=Increase/decrease stock of child when parent stock increase/decrease
  3608. * @return int < 0 if KO, > 0 if OK
  3609. */
  3610. public function add_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
  3611. {
  3612. // phpcs:enable
  3613. // Clean parameters
  3614. if (!is_numeric($id_pere)) {
  3615. $id_pere = 0;
  3616. }
  3617. if (!is_numeric($id_fils)) {
  3618. $id_fils = 0;
  3619. }
  3620. if (!is_numeric($incdec)) {
  3621. $incdec = 0;
  3622. }
  3623. $result = $this->del_sousproduit($id_pere, $id_fils);
  3624. if ($result < 0) {
  3625. return $result;
  3626. }
  3627. // Check not already father of id_pere (to avoid father -> child -> father links)
  3628. $sql = "SELECT fk_product_pere from ".$this->db->prefix()."product_association";
  3629. $sql .= " WHERE fk_product_pere = ".((int) $id_fils)." AND fk_product_fils = ".((int) $id_pere);
  3630. if (!$this->db->query($sql)) {
  3631. dol_print_error($this->db);
  3632. return -1;
  3633. } else {
  3634. //Selection of the highest row
  3635. $sql = "SELECT MAX(rang) as max_rank FROM ".$this->db->prefix()."product_association";
  3636. $sql .= " WHERE fk_product_pere = ".((int) $id_pere);
  3637. $resql = $this->db->query($sql);
  3638. if ($resql > 0) {
  3639. $obj = $this->db->fetch_object($resql);
  3640. $rank = $obj->max_rank + 1;
  3641. //Addition of a product with the highest rank +1
  3642. $sql = "INSERT INTO ".$this->db->prefix()."product_association(fk_product_pere,fk_product_fils,qty,incdec,rang)";
  3643. $sql .= " VALUES (".((int) $id_pere).", ".((int) $id_fils).", ".price2num($qty, 'MS').", ".price2num($incdec, 'MS').", ".((int) $rank).")";
  3644. if (! $this->db->query($sql)) {
  3645. dol_print_error($this->db);
  3646. return -1;
  3647. } else {
  3648. return 1;
  3649. }
  3650. } else {
  3651. dol_print_error($this->db);
  3652. return -1;
  3653. }
  3654. }
  3655. }
  3656. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3657. /**
  3658. * Modify composed product
  3659. *
  3660. * @param int $id_pere Id of parent product/service
  3661. * @param int $id_fils Id of child product/service
  3662. * @param int $qty Quantity
  3663. * @param int $incdec 1=Increase/decrease stock of child when parent stock increase/decrease
  3664. * @return int < 0 if KO, > 0 if OK
  3665. */
  3666. public function update_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
  3667. {
  3668. // phpcs:enable
  3669. // Clean parameters
  3670. if (!is_numeric($id_pere)) {
  3671. $id_pere = 0;
  3672. }
  3673. if (!is_numeric($id_fils)) {
  3674. $id_fils = 0;
  3675. }
  3676. if (!is_numeric($incdec)) {
  3677. $incdec = 1;
  3678. }
  3679. if (!is_numeric($qty)) {
  3680. $qty = 1;
  3681. }
  3682. $sql = 'UPDATE '.$this->db->prefix().'product_association SET ';
  3683. $sql .= 'qty = '.price2num($qty, 'MS');
  3684. $sql .= ',incdec = '.price2num($incdec, 'MS');
  3685. $sql .= ' WHERE fk_product_pere = '.((int) $id_pere).' AND fk_product_fils = '.((int) $id_fils);
  3686. if (!$this->db->query($sql)) {
  3687. dol_print_error($this->db);
  3688. return -1;
  3689. } else {
  3690. return 1;
  3691. }
  3692. }
  3693. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3694. /**
  3695. * Remove a link between a subproduct and a parent product/service
  3696. *
  3697. * @param int $fk_parent Id of parent product (child will no more be linked to it)
  3698. * @param int $fk_child Id of child product
  3699. * @return int < 0 if KO, > 0 if OK
  3700. */
  3701. public function del_sousproduit($fk_parent, $fk_child)
  3702. {
  3703. // phpcs:enable
  3704. if (!is_numeric($fk_parent)) {
  3705. $fk_parent = 0;
  3706. }
  3707. if (!is_numeric($fk_child)) {
  3708. $fk_child = 0;
  3709. }
  3710. $sql = "DELETE FROM ".$this->db->prefix()."product_association";
  3711. $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
  3712. $sql .= " AND fk_product_fils = ".((int) $fk_child);
  3713. dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG);
  3714. if (!$this->db->query($sql)) {
  3715. dol_print_error($this->db);
  3716. return -1;
  3717. }
  3718. // Updated ranks so that none are missing
  3719. $sqlrank = "SELECT rowid, rang FROM ".$this->db->prefix()."product_association";
  3720. $sqlrank.= " WHERE fk_product_pere = ".((int) $fk_parent);
  3721. $sqlrank.= " ORDER BY rang";
  3722. $resqlrank = $this->db->query($sqlrank);
  3723. if ($resqlrank) {
  3724. $cpt = 0;
  3725. while ($objrank = $this->db->fetch_object($resqlrank)) {
  3726. $cpt++;
  3727. $sql = "UPDATE ".$this->db->prefix()."product_association";
  3728. $sql.= " SET rang = ".((int) $cpt);
  3729. $sql.= " WHERE rowid = ".((int) $objrank->rowid);
  3730. if (! $this->db->query($sql)) {
  3731. dol_print_error($this->db);
  3732. return -1;
  3733. }
  3734. }
  3735. }
  3736. return 1;
  3737. }
  3738. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3739. /**
  3740. * Check if it is a sub-product into a kit
  3741. *
  3742. * @param int $fk_parent Id of parent kit product
  3743. * @param int $fk_child Id of child product
  3744. * @return int <0 if KO, >0 if OK
  3745. */
  3746. public function is_sousproduit($fk_parent, $fk_child)
  3747. {
  3748. // phpcs:enable
  3749. $sql = "SELECT fk_product_pere, qty, incdec";
  3750. $sql .= " FROM ".$this->db->prefix()."product_association";
  3751. $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
  3752. $sql .= " AND fk_product_fils = ".((int) $fk_child);
  3753. $result = $this->db->query($sql);
  3754. if ($result) {
  3755. $num = $this->db->num_rows($result);
  3756. if ($num > 0) {
  3757. $obj = $this->db->fetch_object($result);
  3758. $this->is_sousproduit_qty = $obj->qty;
  3759. $this->is_sousproduit_incdec = $obj->incdec;
  3760. return true;
  3761. } else {
  3762. return false;
  3763. }
  3764. } else {
  3765. dol_print_error($this->db);
  3766. return -1;
  3767. }
  3768. }
  3769. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3770. /**
  3771. * Add a supplier price for the product.
  3772. * Note: Duplicate ref is accepted for different quantity only, or for different companies.
  3773. *
  3774. * @param User $user User that make link
  3775. * @param int $id_fourn Supplier id
  3776. * @param string $ref_fourn Supplier ref
  3777. * @param float $quantity Quantity minimum for price
  3778. * @return int < 0 if KO, 0 if link already exists for this product, > 0 if OK
  3779. */
  3780. public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
  3781. {
  3782. // phpcs:enable
  3783. global $conf;
  3784. $now = dol_now();
  3785. dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG);
  3786. // Clean parameters
  3787. $quantity = price2num($quantity, 'MS');
  3788. if ($ref_fourn) {
  3789. $sql = "SELECT rowid, fk_product";
  3790. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  3791. $sql .= " WHERE fk_soc = ".((int) $id_fourn);
  3792. $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
  3793. $sql .= " AND fk_product <> ".((int) $this->id);
  3794. $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
  3795. $resql = $this->db->query($sql);
  3796. if ($resql) {
  3797. $obj = $this->db->fetch_object($resql);
  3798. if ($obj) {
  3799. // If the supplier ref already exists but for another product (duplicate ref is accepted for different quantity only or different companies)
  3800. $this->product_id_already_linked = $obj->fk_product;
  3801. return -3;
  3802. }
  3803. $this->db->free($resql);
  3804. }
  3805. }
  3806. $sql = "SELECT rowid";
  3807. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  3808. $sql .= " WHERE fk_soc = ".((int) $id_fourn);
  3809. if ($ref_fourn) {
  3810. $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
  3811. } else {
  3812. $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
  3813. }
  3814. $sql .= " AND quantity = ".((float) $quantity);
  3815. $sql .= " AND fk_product = ".((int) $this->id);
  3816. $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
  3817. $resql = $this->db->query($sql);
  3818. if ($resql) {
  3819. $obj = $this->db->fetch_object($resql);
  3820. // The reference supplier does not exist, we create it for this product.
  3821. if (empty($obj)) {
  3822. $sql = "INSERT INTO ".$this->db->prefix()."product_fournisseur_price(";
  3823. $sql .= "datec";
  3824. $sql .= ", entity";
  3825. $sql .= ", fk_product";
  3826. $sql .= ", fk_soc";
  3827. $sql .= ", ref_fourn";
  3828. $sql .= ", quantity";
  3829. $sql .= ", fk_user";
  3830. $sql .= ", tva_tx";
  3831. $sql .= ") VALUES (";
  3832. $sql .= "'".$this->db->idate($now)."'";
  3833. $sql .= ", ".$conf->entity;
  3834. $sql .= ", ".$this->id;
  3835. $sql .= ", ".$id_fourn;
  3836. $sql .= ", '".$this->db->escape($ref_fourn)."'";
  3837. $sql .= ", ".$quantity;
  3838. $sql .= ", ".$user->id;
  3839. $sql .= ", 0";
  3840. $sql .= ")";
  3841. if ($this->db->query($sql)) {
  3842. $this->product_fourn_price_id = $this->db->last_insert_id($this->db->prefix()."product_fournisseur_price");
  3843. return 1;
  3844. } else {
  3845. $this->error = $this->db->lasterror();
  3846. return -1;
  3847. }
  3848. } else {
  3849. // If the supplier price already exists for this product and quantity
  3850. $this->product_fourn_price_id = $obj->rowid;
  3851. return 0;
  3852. }
  3853. } else {
  3854. $this->error = $this->db->lasterror();
  3855. return -2;
  3856. }
  3857. }
  3858. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3859. /**
  3860. * Return list of suppliers providing the product or service
  3861. *
  3862. * @return array Array of vendor ids
  3863. */
  3864. public function list_suppliers()
  3865. {
  3866. // phpcs:enable
  3867. global $conf;
  3868. $list = array();
  3869. $sql = "SELECT DISTINCT p.fk_soc";
  3870. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as p";
  3871. $sql .= " WHERE p.fk_product = ".((int) $this->id);
  3872. $sql .= " AND p.entity = ".((int) $conf->entity);
  3873. $result = $this->db->query($sql);
  3874. if ($result) {
  3875. $num = $this->db->num_rows($result);
  3876. $i = 0;
  3877. while ($i < $num) {
  3878. $obj = $this->db->fetch_object($result);
  3879. $list[$i] = $obj->fk_soc;
  3880. $i++;
  3881. }
  3882. }
  3883. return $list;
  3884. }
  3885. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3886. /**
  3887. * Recopie les prix d'un produit/service sur un autre
  3888. *
  3889. * @param int $fromId Id product source
  3890. * @param int $toId Id product target
  3891. * @return int < 0 if KO, > 0 if OK
  3892. */
  3893. public function clone_price($fromId, $toId)
  3894. {
  3895. global $conf, $user;
  3896. $now = dol_now();
  3897. $this->db->begin();
  3898. // prices
  3899. $sql = "INSERT INTO ".$this->db->prefix()."product_price (";
  3900. $sql .= " entity";
  3901. $sql .= ", fk_product";
  3902. $sql .= ", date_price";
  3903. $sql .= ", price_level";
  3904. $sql .= ", price";
  3905. $sql .= ", price_ttc";
  3906. $sql .= ", price_min";
  3907. $sql .= ", price_min_ttc";
  3908. $sql .= ", price_base_type";
  3909. $sql .= ", default_vat_code";
  3910. $sql .= ", tva_tx";
  3911. $sql .= ", recuperableonly";
  3912. $sql .= ", localtax1_tx";
  3913. $sql .= ", localtax1_type";
  3914. $sql .= ", localtax2_tx";
  3915. $sql .= ", localtax2_type";
  3916. $sql .= ", fk_user_author";
  3917. $sql .= ", tosell";
  3918. $sql .= ", price_by_qty";
  3919. $sql .= ", fk_price_expression";
  3920. $sql .= ", fk_multicurrency";
  3921. $sql .= ", multicurrency_code";
  3922. $sql .= ", multicurrency_tx";
  3923. $sql .= ", multicurrency_price";
  3924. $sql .= ", multicurrency_price_ttc";
  3925. $sql .= ")";
  3926. $sql .= " SELECT";
  3927. $sql .= " entity";
  3928. $sql .= ", ".$toId;
  3929. $sql .= ", '".$this->db->idate($now)."'";
  3930. $sql .= ", price_level";
  3931. $sql .= ", price";
  3932. $sql .= ", price_ttc";
  3933. $sql .= ", price_min";
  3934. $sql .= ", price_min_ttc";
  3935. $sql .= ", price_base_type";
  3936. $sql .= ", default_vat_code";
  3937. $sql .= ", tva_tx";
  3938. $sql .= ", recuperableonly";
  3939. $sql .= ", localtax1_tx";
  3940. $sql .= ", localtax1_type";
  3941. $sql .= ", localtax2_tx";
  3942. $sql .= ", localtax2_type";
  3943. $sql .= ", ".$user->id;
  3944. $sql .= ", tosell";
  3945. $sql .= ", price_by_qty";
  3946. $sql .= ", fk_price_expression";
  3947. $sql .= ", fk_multicurrency";
  3948. $sql .= ", multicurrency_code";
  3949. $sql .= ", multicurrency_tx";
  3950. $sql .= ", multicurrency_price";
  3951. $sql .= ", multicurrency_price_ttc";
  3952. $sql .= " FROM ".$this->db->prefix()."product_price";
  3953. $sql .= " WHERE fk_product = ".((int) $fromId);
  3954. $sql .= " ORDER BY date_price DESC";
  3955. if ($conf->global->PRODUIT_MULTIPRICES_LIMIT > 0) {
  3956. $sql .= " LIMIT ".$conf->global->PRODUIT_MULTIPRICES_LIMIT;
  3957. }
  3958. dol_syslog(__METHOD__, LOG_DEBUG);
  3959. $resql = $this->db->query($sql);
  3960. if (!$resql) {
  3961. $this->db->rollback();
  3962. return -1;
  3963. }
  3964. $this->db->commit();
  3965. return 1;
  3966. }
  3967. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3968. /**
  3969. * Clone links between products
  3970. *
  3971. * @param int $fromId Product id
  3972. * @param int $toId Product id
  3973. * @return int <0 if KO, >0 if OK
  3974. */
  3975. public function clone_associations($fromId, $toId)
  3976. {
  3977. // phpcs:enable
  3978. $this->db->begin();
  3979. $sql = 'INSERT INTO '.$this->db->prefix().'product_association (fk_product_pere, fk_product_fils, qty)';
  3980. $sql .= " SELECT ".$toId.", fk_product_fils, qty FROM ".$this->db->prefix()."product_association";
  3981. $sql .= " WHERE fk_product_pere = ".((int) $fromId);
  3982. dol_syslog(get_class($this).'::clone_association', LOG_DEBUG);
  3983. if (!$this->db->query($sql)) {
  3984. $this->db->rollback();
  3985. return -1;
  3986. }
  3987. $this->db->commit();
  3988. return 1;
  3989. }
  3990. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3991. /**
  3992. * Recopie les fournisseurs et prix fournisseurs d'un produit/service sur un autre
  3993. *
  3994. * @param int $fromId Id produit source
  3995. * @param int $toId Id produit cible
  3996. * @return int < 0 si erreur, > 0 si ok
  3997. */
  3998. public function clone_fournisseurs($fromId, $toId)
  3999. {
  4000. // phpcs:enable
  4001. $this->db->begin();
  4002. $now = dol_now();
  4003. // les fournisseurs
  4004. /*$sql = "INSERT ".$this->db->prefix()."product_fournisseur ("
  4005. . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )"
  4006. . " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, ref_fourn, fk_user_author"
  4007. . " FROM ".$this->db->prefix()."product_fournisseur"
  4008. . " WHERE fk_product = ".((int) $fromId);
  4009. if ( ! $this->db->query($sql ) )
  4010. {
  4011. $this->db->rollback();
  4012. return -1;
  4013. }*/
  4014. // les prix de fournisseurs.
  4015. $sql = "INSERT ".$this->db->prefix()."product_fournisseur_price (";
  4016. $sql .= " datec, fk_product, fk_soc, price, quantity, fk_user)";
  4017. $sql .= " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, price, quantity, fk_user";
  4018. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  4019. $sql .= " WHERE fk_product = ".((int) $fromId);
  4020. dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG);
  4021. $resql = $this->db->query($sql);
  4022. if (!$resql) {
  4023. $this->db->rollback();
  4024. return -1;
  4025. } else {
  4026. $this->db->commit();
  4027. return 1;
  4028. }
  4029. }
  4030. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4031. /**
  4032. * Fonction recursive uniquement utilisee par get_arbo_each_prod, recompose l'arborescence des sousproduits
  4033. * Define value of this->res
  4034. *
  4035. * @param array $prod Products array
  4036. * @param string $compl_path Directory path of parents to add before
  4037. * @param int $multiply Because each sublevel must be multiplicated by parent nb
  4038. * @param int $level Init level
  4039. * @param int $id_parent Id parent
  4040. * @param int $ignore_stock_load Ignore stock load
  4041. * @return void
  4042. */
  4043. public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0)
  4044. {
  4045. // phpcs:enable
  4046. global $conf, $langs;
  4047. $tmpproduct = null;
  4048. //var_dump($prod);
  4049. foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
  4050. if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
  4051. $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
  4052. $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
  4053. $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
  4054. $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
  4055. $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0);
  4056. if ($multiply < 1) {
  4057. $multiply = 1;
  4058. }
  4059. //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
  4060. if (is_null($tmpproduct)) {
  4061. $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
  4062. }
  4063. $tmpproduct->fetch($id); // Load product to get ->ref
  4064. if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  4065. $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
  4066. }
  4067. $this->res[] = array(
  4068. 'id'=>$id, // Id product
  4069. 'id_parent'=>$id_parent,
  4070. 'ref'=>$tmpproduct->ref, // Ref product
  4071. 'nb'=>$nb, // Nb of units that compose parent product
  4072. 'nb_total'=>$nb * $multiply, // Nb of units for all nb of product
  4073. 'stock'=>$tmpproduct->stock_reel, // Stock
  4074. 'stock_alert'=>$tmpproduct->seuil_stock_alerte, // Stock alert
  4075. 'label'=>$label,
  4076. 'fullpath'=>$compl_path.$label, // Label
  4077. 'type'=>$type, // Nb of units that compose parent product
  4078. 'desiredstock'=>$tmpproduct->desiredstock,
  4079. 'level'=>$level,
  4080. 'incdec'=>$incdec,
  4081. 'entity'=>$tmpproduct->entity
  4082. );
  4083. // Recursive call if there is childs to child
  4084. if (is_array($desc_pere['childs'])) {
  4085. //print 'YYY We go down for '.$desc_pere[3]." -> \n";
  4086. $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id, $ignore_stock_load);
  4087. }
  4088. }
  4089. }
  4090. }
  4091. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4092. /**
  4093. * Build the tree of subproducts into an array ->res and return it.
  4094. * this->sousprods must have been loaded by this->get_sousproduits_arbo()
  4095. *
  4096. * @param int $multiply Because each sublevel must be multiplicated by parent nb
  4097. * @param int $ignore_stock_load Ignore stock load
  4098. * @return array $this->res
  4099. */
  4100. public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0)
  4101. {
  4102. // phpcs:enable
  4103. $this->res = array();
  4104. if (isset($this->sousprods) && is_array($this->sousprods)) {
  4105. foreach ($this->sousprods as $prod_name => $desc_product) {
  4106. if (is_array($desc_product)) {
  4107. $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load);
  4108. }
  4109. }
  4110. }
  4111. //var_dump($this->res);
  4112. return $this->res;
  4113. }
  4114. /**
  4115. * Count all parent and children products for current product (first level only)
  4116. *
  4117. * @param int $mode 0=Both parent and child, -1=Parents only, 1=Children only
  4118. * @return int Nb of father + child
  4119. * @see getFather(), get_sousproduits_arbo()
  4120. */
  4121. public function hasFatherOrChild($mode = 0)
  4122. {
  4123. $nb = 0;
  4124. $sql = "SELECT COUNT(pa.rowid) as nb";
  4125. $sql .= " FROM ".$this->db->prefix()."product_association as pa";
  4126. if ($mode == 0) {
  4127. $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id)." OR pa.fk_product_pere = ".((int) $this->id);
  4128. } elseif ($mode == -1) {
  4129. $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)
  4130. } elseif ($mode == 1) {
  4131. $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)
  4132. }
  4133. $resql = $this->db->query($sql);
  4134. if ($resql) {
  4135. $obj = $this->db->fetch_object($resql);
  4136. if ($obj) {
  4137. $nb = $obj->nb;
  4138. }
  4139. } else {
  4140. return -1;
  4141. }
  4142. return $nb;
  4143. }
  4144. /**
  4145. * Return if a product has variants or not
  4146. *
  4147. * @return int Number of variants
  4148. */
  4149. public function hasVariants()
  4150. {
  4151. $nb = 0;
  4152. $sql = "SELECT count(rowid) as nb FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_parent = ".((int) $this->id);
  4153. $sql .= " AND entity IN (".getEntity('product').")";
  4154. $resql = $this->db->query($sql);
  4155. if ($resql) {
  4156. $obj = $this->db->fetch_object($resql);
  4157. if ($obj) {
  4158. $nb = $obj->nb;
  4159. }
  4160. }
  4161. return $nb;
  4162. }
  4163. /**
  4164. * Return if loaded product is a variant
  4165. *
  4166. * @return int
  4167. */
  4168. public function isVariant()
  4169. {
  4170. global $conf;
  4171. if (!empty($conf->variants->enabled)) {
  4172. $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_child = ".((int) $this->id)." AND entity IN (".getEntity('product').")";
  4173. $query = $this->db->query($sql);
  4174. if ($query) {
  4175. if (!$this->db->num_rows($query)) {
  4176. return false;
  4177. }
  4178. return true;
  4179. } else {
  4180. dol_print_error($this->db);
  4181. return -1;
  4182. }
  4183. } else {
  4184. return false;
  4185. }
  4186. }
  4187. /**
  4188. * Return all parent products for current product (first level only)
  4189. *
  4190. * @return array Array of product
  4191. * @see hasFatherOrChild()
  4192. */
  4193. public function getFather()
  4194. {
  4195. $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";
  4196. $sql .= ", p.tosell as status, p.tobuy as status_buy";
  4197. $sql .= " FROM ".$this->db->prefix()."product_association as pa,";
  4198. $sql .= " ".$this->db->prefix()."product as p";
  4199. $sql .= " WHERE p.rowid = pa.fk_product_pere";
  4200. $sql .= " AND pa.fk_product_fils = ".((int) $this->id);
  4201. $res = $this->db->query($sql);
  4202. if ($res) {
  4203. $prods = array();
  4204. while ($record = $this->db->fetch_array($res)) {
  4205. // $record['id'] = $record['rowid'] = id of father
  4206. $prods[$record['id']]['id'] = $record['rowid'];
  4207. $prods[$record['id']]['ref'] = $record['ref'];
  4208. $prods[$record['id']]['label'] = $record['label'];
  4209. $prods[$record['id']]['qty'] = $record['qty'];
  4210. $prods[$record['id']]['incdec'] = $record['incdec'];
  4211. $prods[$record['id']]['fk_product_type'] = $record['fk_product_type'];
  4212. $prods[$record['id']]['entity'] = $record['entity'];
  4213. $prods[$record['id']]['status'] = $record['status'];
  4214. $prods[$record['id']]['status_buy'] = $record['status_buy'];
  4215. }
  4216. return $prods;
  4217. } else {
  4218. dol_print_error($this->db);
  4219. return -1;
  4220. }
  4221. }
  4222. /**
  4223. * Return childs of product $id
  4224. *
  4225. * @param int $id Id of product to search childs of
  4226. * @param int $firstlevelonly Return only direct child
  4227. * @param int $level Level of recursing call (start to 1)
  4228. * @return array Return array(prodid=>array(0=prodid, 1=>qty, 2=>product type, 3=>label, 4=>incdec, 5=>product ref)
  4229. */
  4230. public function getChildsArbo($id, $firstlevelonly = 0, $level = 1)
  4231. {
  4232. global $alreadyfound;
  4233. if (empty($id)) {
  4234. return array();
  4235. }
  4236. $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,";
  4237. $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec,";
  4238. $sql .= " pa.rowid as fk_association, pa.rang";
  4239. $sql .= " FROM ".$this->db->prefix()."product as p,";
  4240. $sql .= " ".$this->db->prefix()."product_association as pa";
  4241. $sql .= " WHERE p.rowid = pa.fk_product_fils";
  4242. $sql .= " AND pa.fk_product_pere = ".((int) $id);
  4243. $sql .= " AND pa.fk_product_fils <> ".((int) $id); // This should not happens, it is to avoid infinite loop if it happens
  4244. $sql.= " ORDER BY pa.rang";
  4245. dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level, LOG_DEBUG);
  4246. if ($level == 1) {
  4247. $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
  4248. }
  4249. // Protection against infinite loop
  4250. if ($level > 30) {
  4251. return array();
  4252. }
  4253. $res = $this->db->query($sql);
  4254. if ($res) {
  4255. $prods = array();
  4256. while ($rec = $this->db->fetch_array($res)) {
  4257. if (!empty($alreadyfound[$rec['rowid']])) {
  4258. 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);
  4259. continue;
  4260. }
  4261. $alreadyfound[$rec['rowid']] = 1;
  4262. $prods[$rec['rowid']] = array(
  4263. 0=>$rec['rowid'],
  4264. 1=>$rec['qty'],
  4265. 2=>$rec['fk_product_type'],
  4266. 3=>$this->db->escape($rec['label']),
  4267. 4=>$rec['incdec'],
  4268. 5=>$rec['ref'],
  4269. 6=>$rec['fk_association'],
  4270. 7=>$rec['rang']
  4271. );
  4272. //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']);
  4273. //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
  4274. if (empty($firstlevelonly)) {
  4275. $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1);
  4276. foreach ($listofchilds as $keyChild => $valueChild) {
  4277. $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
  4278. }
  4279. }
  4280. }
  4281. return $prods;
  4282. } else {
  4283. dol_print_error($this->db);
  4284. return -1;
  4285. }
  4286. }
  4287. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4288. /**
  4289. * 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)
  4290. * Set this->sousprods
  4291. *
  4292. * @return void
  4293. */
  4294. public function get_sousproduits_arbo()
  4295. {
  4296. // phpcs:enable
  4297. $parent = array();
  4298. foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
  4299. $parent[$this->label][$keyChild] = $valueChild;
  4300. }
  4301. foreach ($parent as $key => $value) { // key=label, value is array of childs
  4302. $this->sousprods[$key] = $value;
  4303. }
  4304. }
  4305. /**
  4306. * Return clicable link of object (with eventually picto)
  4307. *
  4308. * @param int $withpicto Add picto into link
  4309. * @param string $option Where point the link ('stock', 'composition', 'category', 'supplier', '')
  4310. * @param int $maxlength Maxlength of ref
  4311. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  4312. * @param int $notooltip No tooltip
  4313. * @return string String with URL
  4314. */
  4315. public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0)
  4316. {
  4317. global $conf, $langs, $hookmanager;
  4318. include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4319. $result = ''; $label = '';
  4320. $newref = $this->ref;
  4321. if ($maxlength) {
  4322. $newref = dol_trunc($newref, $maxlength, 'middle');
  4323. }
  4324. if (!empty($this->entity)) {
  4325. $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
  4326. if ($this->nbphoto > 0) {
  4327. $label .= '<div class="photointooltip floatright">';
  4328. $label .= $tmpphoto;
  4329. $label .= '</div>';
  4330. //$label .= '<div style="clear: both;"></div>';
  4331. }
  4332. }
  4333. if ($this->type == Product::TYPE_PRODUCT) {
  4334. $label .= img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
  4335. } elseif ($this->type == Product::TYPE_SERVICE) {
  4336. $label .= img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
  4337. }
  4338. if (isset($this->status) && isset($this->status_buy)) {
  4339. $label .= ' '.$this->getLibStatut(5, 0);
  4340. $label .= ' '.$this->getLibStatut(5, 1);
  4341. }
  4342. if (!empty($this->ref)) {
  4343. $label .= '<br><b>'.$langs->trans('ProductRef').':</b> '.$this->ref;
  4344. }
  4345. if (!empty($this->label)) {
  4346. $label .= '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label;
  4347. }
  4348. if ($this->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4349. if (!empty($conf->productbatch->enabled)) {
  4350. $langs->load("productbatch");
  4351. $label .= "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
  4352. }
  4353. }
  4354. if (!empty($conf->barcode->enabled)) {
  4355. $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
  4356. }
  4357. if ($this->type == Product::TYPE_PRODUCT) {
  4358. if ($this->weight) {
  4359. $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
  4360. }
  4361. $labelsize = "";
  4362. if ($this->length) {
  4363. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
  4364. }
  4365. if ($this->width) {
  4366. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
  4367. }
  4368. if ($this->height) {
  4369. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
  4370. }
  4371. if ($labelsize) {
  4372. $label .= "<br>".$labelsize;
  4373. }
  4374. $labelsurfacevolume = "";
  4375. if ($this->surface) {
  4376. $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
  4377. }
  4378. if ($this->volume) {
  4379. $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
  4380. }
  4381. if ($labelsurfacevolume) {
  4382. $label .= "<br>".$labelsurfacevolume;
  4383. }
  4384. }
  4385. if (!empty($this->pmp) && $this->pmp) {
  4386. $label .= "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency);
  4387. }
  4388. if (!empty($conf->accounting->enabled)) {
  4389. if ($this->status) {
  4390. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  4391. $label .= '<br>';
  4392. $label .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
  4393. $label .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
  4394. $label .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
  4395. }
  4396. if ($this->status_buy) {
  4397. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  4398. if (empty($this->status)) {
  4399. $label .= '<br>';
  4400. }
  4401. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
  4402. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
  4403. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
  4404. }
  4405. }
  4406. $linkclose = '';
  4407. if (empty($notooltip)) {
  4408. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4409. $label = $langs->trans("ShowProduct");
  4410. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  4411. }
  4412. $linkclose .= ' title="'.dol_escape_htmltag($label, 1, 1).'"';
  4413. $linkclose .= ' class="nowraponall classfortooltip"';
  4414. } else {
  4415. $linkclose = ' class="nowraponall"';
  4416. }
  4417. if ($option == 'supplier' || $option == 'category') {
  4418. $url = DOL_URL_ROOT.'/product/fournisseurs.php?id='.$this->id;
  4419. } elseif ($option == 'stock') {
  4420. $url = DOL_URL_ROOT.'/product/stock/product.php?id='.$this->id;
  4421. } elseif ($option == 'composition') {
  4422. $url = DOL_URL_ROOT.'/product/composition/card.php?id='.$this->id;
  4423. } else {
  4424. $url = DOL_URL_ROOT.'/product/card.php?id='.$this->id;
  4425. }
  4426. if ($option !== 'nolink') {
  4427. // Add param to save lastsearch_values or not
  4428. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  4429. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  4430. $add_save_lastsearch_values = 1;
  4431. }
  4432. if ($add_save_lastsearch_values) {
  4433. $url .= '&save_lastsearch_values=1';
  4434. }
  4435. }
  4436. $linkstart = '<a href="'.$url.'"';
  4437. $linkstart .= $linkclose.'>';
  4438. $linkend = '</a>';
  4439. $result .= $linkstart;
  4440. if ($withpicto) {
  4441. if ($this->type == Product::TYPE_PRODUCT) {
  4442. $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
  4443. }
  4444. if ($this->type == Product::TYPE_SERVICE) {
  4445. $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
  4446. }
  4447. }
  4448. $result .= $newref;
  4449. $result .= $linkend;
  4450. global $action;
  4451. $hookmanager->initHooks(array('productdao'));
  4452. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  4453. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4454. if ($reshook > 0) {
  4455. $result = $hookmanager->resPrint;
  4456. } else {
  4457. $result .= $hookmanager->resPrint;
  4458. }
  4459. return $result;
  4460. }
  4461. /**
  4462. * Create a document onto disk according to template module.
  4463. *
  4464. * @param string $modele Force model to use ('' to not force)
  4465. * @param Translate $outputlangs Object langs to use for output
  4466. * @param int $hidedetails Hide details of lines
  4467. * @param int $hidedesc Hide description
  4468. * @param int $hideref Hide ref
  4469. * @return int 0 if KO, 1 if OK
  4470. */
  4471. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  4472. {
  4473. global $conf, $user, $langs;
  4474. $langs->load("products");
  4475. $outputlangs->load("products");
  4476. // Positionne le modele sur le nom du modele a utiliser
  4477. if (!dol_strlen($modele)) {
  4478. if (!empty($conf->global->PRODUCT_ADDON_PDF)) {
  4479. $modele = $conf->global->PRODUCT_ADDON_PDF;
  4480. } else {
  4481. $modele = 'strato';
  4482. }
  4483. }
  4484. $modelpath = "core/modules/product/doc/";
  4485. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  4486. }
  4487. /**
  4488. * Return label of status of object
  4489. *
  4490. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  4491. * @param int $type 0=Sell, 1=Buy, 2=Batch Number management
  4492. * @return string Label of status
  4493. */
  4494. public function getLibStatut($mode = 0, $type = 0)
  4495. {
  4496. switch ($type) {
  4497. case 0:
  4498. return $this->LibStatut($this->status, $mode, $type);
  4499. case 1:
  4500. return $this->LibStatut($this->status_buy, $mode, $type);
  4501. case 2:
  4502. return $this->LibStatut($this->status_batch, $mode, $type);
  4503. default:
  4504. //Simulate previous behavior but should return an error string
  4505. return $this->LibStatut($this->status_buy, $mode, $type);
  4506. }
  4507. }
  4508. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4509. /**
  4510. * Return label of a given status
  4511. *
  4512. * @param int $status Statut
  4513. * @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
  4514. * @param int $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4515. * @return string Label of status
  4516. */
  4517. public function LibStatut($status, $mode = 0, $type = 0)
  4518. {
  4519. // phpcs:enable
  4520. global $conf, $langs;
  4521. $labelStatus = $labelStatusShort = '';
  4522. $langs->load('products');
  4523. if (!empty($conf->productbatch->enabled)) {
  4524. $langs->load("productbatch");
  4525. }
  4526. if ($type == 2) {
  4527. switch ($mode) {
  4528. case 0:
  4529. $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatch') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial')));
  4530. return dolGetStatus($label);
  4531. case 1:
  4532. $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort')));
  4533. return dolGetStatus($label);
  4534. case 2:
  4535. return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2);
  4536. case 3:
  4537. return dolGetStatus($langs->transnoentitiesnoconv('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot');
  4538. case 4:
  4539. return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2);
  4540. case 5:
  4541. return $this->LibStatut($status, 1, 2).' '.$this->LibStatut($status, 3, 2);
  4542. default:
  4543. return dolGetStatus($langs->transnoentitiesnoconv('Unknown'));
  4544. }
  4545. }
  4546. $statuttrans = empty($status) ? 'status5' : 'status4';
  4547. if ($status == 0) {
  4548. // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4549. if ($type == 0) {
  4550. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnSellShort');
  4551. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnSell');
  4552. } elseif ($type == 1) {
  4553. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBuyShort');
  4554. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBuy');
  4555. } elseif ($type == 2) {
  4556. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBatch');
  4557. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort');
  4558. }
  4559. } elseif ($status == 1) {
  4560. // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4561. if ($type == 0) {
  4562. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSellShort');
  4563. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSell');
  4564. } elseif ($type == 1) {
  4565. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBuyShort');
  4566. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBuy');
  4567. } elseif ($type == 2) {
  4568. $labelStatus = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial'));
  4569. $labelStatusShort = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort'));
  4570. }
  4571. } elseif ( $type == 2 && $status == 2 ) {
  4572. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSerial');
  4573. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSerialShort');
  4574. }
  4575. if ($mode > 6) {
  4576. return dolGetStatus($langs->transnoentitiesnoconv('Unknown'), '', '', 'status0', 0);
  4577. } else {
  4578. return dolGetStatus($labelStatus, $labelStatusShort, '', $statuttrans, $mode);
  4579. }
  4580. }
  4581. /**
  4582. * Retour label of nature of product
  4583. *
  4584. * @return string Label
  4585. */
  4586. public function getLibFinished()
  4587. {
  4588. global $langs;
  4589. $langs->load('products');
  4590. if (isset($this->finished) && $this->finished >= 0) {
  4591. $sql = "SELECT label, code FROM ".$this->db->prefix()."c_product_nature where code = ".((int) $this->finished)." AND active=1";
  4592. $resql = $this->db->query($sql);
  4593. if ($resql && $this->db->num_rows($resql) > 0) {
  4594. $res = $this->db->fetch_array($resql);
  4595. $label = $langs->trans($res['label']);
  4596. $this->db->free($resql);
  4597. return $label;
  4598. } else {
  4599. $this->error = $this->db->error().' sql='.$sql;
  4600. dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR);
  4601. return -1;
  4602. }
  4603. }
  4604. return '';
  4605. }
  4606. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4607. /**
  4608. * Adjust stock in a warehouse for product
  4609. *
  4610. * @param User $user user asking change
  4611. * @param int $id_entrepot id of warehouse
  4612. * @param double $nbpiece nb of units (should be always positive, use $movement to decide if we add or remove)
  4613. * @param int $movement 0 = add, 1 = remove
  4614. * @param string $label Label of stock movement
  4615. * @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.
  4616. * @param string $inventorycode Inventory code
  4617. * @param string $origin_element Origin element type
  4618. * @param int $origin_id Origin id of element
  4619. * @param int $disablestockchangeforsubproduct Disable stock change for sub-products of kit (usefull only if product is a subproduct)
  4620. * @param array $extrafields Array of extrafields
  4621. * @return int <0 if KO, >0 if OK
  4622. */
  4623. public function correct_stock($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
  4624. {
  4625. // phpcs:enable
  4626. if ($id_entrepot) {
  4627. $this->db->begin();
  4628. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  4629. if ($nbpiece < 0) {
  4630. if (!$movement) {
  4631. $movement = 1;
  4632. }
  4633. $nbpiece = abs($nbpiece);
  4634. }
  4635. $op[0] = "+".trim($nbpiece);
  4636. $op[1] = "-".trim($nbpiece);
  4637. $movementstock = new MouvementStock($this->db);
  4638. $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->origin_id
  4639. $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', '', '', '', false, 0, $disablestockchangeforsubproduct);
  4640. if ($result >= 0) {
  4641. if ($extrafields) {
  4642. $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
  4643. $movementstock->array_options = $array_options;
  4644. $movementstock->insertExtraFields();
  4645. }
  4646. $this->db->commit();
  4647. return 1;
  4648. } else {
  4649. $this->error = $movementstock->error;
  4650. $this->errors = $movementstock->errors;
  4651. $this->db->rollback();
  4652. return -1;
  4653. }
  4654. }
  4655. }
  4656. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4657. /**
  4658. * Adjust stock in a warehouse for product with batch number
  4659. *
  4660. * @param User $user user asking change
  4661. * @param int $id_entrepot id of warehouse
  4662. * @param double $nbpiece nb of units (should be always positive, use $movement to decide if we add or remove)
  4663. * @param int $movement 0 = add, 1 = remove
  4664. * @param string $label Label of stock movement
  4665. * @param double $price Price to use for stock eval
  4666. * @param integer $dlc eat-by date
  4667. * @param integer $dluo sell-by date
  4668. * @param string $lot Lot number
  4669. * @param string $inventorycode Inventory code
  4670. * @param string $origin_element Origin element type
  4671. * @param int $origin_id Origin id of element
  4672. * @param int $disablestockchangeforsubproduct Disable stock change for sub-products of kit (usefull only if product is a subproduct)
  4673. * @param array $extrafields Array of extrafields
  4674. * @return int <0 if KO, >0 if OK
  4675. */
  4676. 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)
  4677. {
  4678. // phpcs:enable
  4679. if ($id_entrepot) {
  4680. $this->db->begin();
  4681. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  4682. if ($nbpiece < 0) {
  4683. if (!$movement) {
  4684. $movement = 1;
  4685. }
  4686. $nbpiece = abs($nbpiece);
  4687. }
  4688. $op[0] = "+".trim($nbpiece);
  4689. $op[1] = "-".trim($nbpiece);
  4690. $movementstock = new MouvementStock($this->db);
  4691. $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->fk_origin
  4692. $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot, false, 0, $disablestockchangeforsubproduct);
  4693. if ($result >= 0) {
  4694. if ($extrafields) {
  4695. $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
  4696. $movementstock->array_options = $array_options;
  4697. $movementstock->insertExtraFields();
  4698. }
  4699. $this->db->commit();
  4700. return 1;
  4701. } else {
  4702. $this->error = $movementstock->error;
  4703. $this->errors = $movementstock->errors;
  4704. $this->db->rollback();
  4705. return -1;
  4706. }
  4707. }
  4708. }
  4709. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4710. /**
  4711. * Load information about stock of a product into ->stock_reel, ->stock_warehouse[] (including stock_warehouse[idwarehouse]->detail_batch for batch products)
  4712. * This function need a lot of load. If you use it on list, use a cache to execute it once for each product id.
  4713. * If ENTREPOT_EXTRA_STATUS is set, filtering on warehouse status is possible.
  4714. *
  4715. * @param string $option '' = Load all stock info, also from closed and internal warehouses, 'nobatch', 'novirtual'
  4716. * You can also filter on 'warehouseclosed', 'warehouseopen', 'warehouseinternal'
  4717. * @param int $includedraftpoforvirtual Include draft status of PO for virtual stock calculation
  4718. * @return int < 0 if KO, > 0 if OK
  4719. * @see load_virtual_stock(), loadBatchInfo()
  4720. */
  4721. public function load_stock($option = '', $includedraftpoforvirtual = null)
  4722. {
  4723. // phpcs:enable
  4724. global $conf;
  4725. $this->stock_reel = 0;
  4726. $this->stock_warehouse = array();
  4727. $this->stock_theorique = 0;
  4728. // Set filter on warehouse status
  4729. $warehouseStatus = array();
  4730. if (preg_match('/warehouseclosed/', $option)) {
  4731. $warehouseStatus[Entrepot::STATUS_CLOSED] = Entrepot::STATUS_CLOSED;
  4732. }
  4733. if (preg_match('/warehouseopen/', $option)) {
  4734. $warehouseStatus[Entrepot::STATUS_OPEN_ALL] = Entrepot::STATUS_OPEN_ALL;
  4735. }
  4736. if (preg_match('/warehouseinternal/', $option)) {
  4737. if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
  4738. $warehouseStatus[Entrepot::STATUS_OPEN_INTERNAL] = Entrepot::STATUS_OPEN_INTERNAL;
  4739. } else {
  4740. $warehouseStatus[Entrepot::STATUS_OPEN_ALL] = Entrepot::STATUS_OPEN_ALL;
  4741. }
  4742. }
  4743. $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot";
  4744. $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
  4745. $sql .= ", ".$this->db->prefix()."entrepot as w";
  4746. $sql .= " WHERE w.entity IN (".getEntity('stock').")";
  4747. $sql .= " AND w.rowid = ps.fk_entrepot";
  4748. $sql .= " AND ps.fk_product = ".((int) $this->id);
  4749. if (count($warehouseStatus)) {
  4750. $sql .= " AND w.statut IN (".$this->db->sanitize(implode(',', $warehouseStatus)).")";
  4751. }
  4752. $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;
  4753. dol_syslog(get_class($this)."::load_stock", LOG_DEBUG);
  4754. $result = $this->db->query($sql);
  4755. if ($result) {
  4756. $num = $this->db->num_rows($result);
  4757. $i = 0;
  4758. if ($num > 0) {
  4759. while ($i < $num) {
  4760. $row = $this->db->fetch_object($result);
  4761. $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
  4762. $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
  4763. $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid;
  4764. if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) {
  4765. $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id);
  4766. }
  4767. $this->stock_reel += $row->reel;
  4768. $i++;
  4769. }
  4770. }
  4771. $this->db->free($result);
  4772. if (!preg_match('/novirtual/', $option)) {
  4773. $this->load_virtual_stock($includedraftpoforvirtual); // This also load all arrays stats_xxx...
  4774. }
  4775. return 1;
  4776. } else {
  4777. $this->error = $this->db->lasterror();
  4778. return -1;
  4779. }
  4780. }
  4781. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4782. /**
  4783. * Load value ->stock_theorique of a product. Property this->id must be defined.
  4784. * This function need a lot of load. If you use it on list, use a cache to execute it one for each product id.
  4785. *
  4786. * @param int $includedraftpoforvirtual Include draft status and not yet approved Purchase Orders for virtual stock calculation
  4787. * @return int < 0 if KO, > 0 if OK
  4788. * @see load_stock(), loadBatchInfo()
  4789. */
  4790. public function load_virtual_stock($includedraftpoforvirtual = null)
  4791. {
  4792. // phpcs:enable
  4793. global $conf, $hookmanager, $action;
  4794. $stock_commande_client = 0;
  4795. $stock_commande_fournisseur = 0;
  4796. $stock_sending_client = 0;
  4797. $stock_reception_fournisseur = 0;
  4798. $stock_inproduction = 0;
  4799. //dol_syslog("load_virtual_stock");
  4800. if (!empty($conf->commande->enabled)) {
  4801. $result = $this->load_stats_commande(0, '1,2', 1);
  4802. if ($result < 0) {
  4803. dol_print_error($this->db, $this->error);
  4804. }
  4805. $stock_commande_client = $this->stats_commande['qty'];
  4806. }
  4807. if (!empty($conf->expedition->enabled)) {
  4808. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  4809. $filterShipmentStatus = '';
  4810. if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
  4811. $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
  4812. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
  4813. $filterShipmentStatus = Expedition::STATUS_CLOSED;
  4814. }
  4815. $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
  4816. if ($result < 0) {
  4817. dol_print_error($this->db, $this->error);
  4818. }
  4819. $stock_sending_client = $this->stats_expedition['qty'];
  4820. }
  4821. if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled)) {
  4822. $filterStatus = empty($conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK) ? '3,4' : $conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK;
  4823. if (isset($includedraftpoforvirtual)) {
  4824. $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
  4825. }
  4826. $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1);
  4827. if ($result < 0) {
  4828. dol_print_error($this->db, $this->error);
  4829. }
  4830. $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
  4831. }
  4832. 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)) {
  4833. // Case module reception is not used
  4834. $filterStatus = '4';
  4835. if (isset($includedraftpoforvirtual)) {
  4836. $filterStatus = '0,'.$filterStatus;
  4837. }
  4838. $result = $this->load_stats_reception(0, $filterStatus, 1);
  4839. if ($result < 0) {
  4840. dol_print_error($this->db, $this->error);
  4841. }
  4842. $stock_reception_fournisseur = $this->stats_reception['qty'];
  4843. }
  4844. 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)) {
  4845. // Case module reception is used
  4846. $filterStatus = '4';
  4847. if (isset($includedraftpoforvirtual)) {
  4848. $filterStatus = '0,'.$filterStatus;
  4849. }
  4850. $result = $this->load_stats_reception(0, $filterStatus, 1); // Use same tables than when module reception is not used.
  4851. if ($result < 0) {
  4852. dol_print_error($this->db, $this->error);
  4853. }
  4854. $stock_reception_fournisseur = $this->stats_reception['qty'];
  4855. }
  4856. if (!empty($conf->mrp->enabled)) {
  4857. $result = $this->load_stats_inproduction(0, '1,2', 1);
  4858. if ($result < 0) {
  4859. dol_print_error($this->db, $this->error);
  4860. }
  4861. $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
  4862. }
  4863. $this->stock_theorique = $this->stock_reel + $stock_inproduction;
  4864. // Stock decrease mode
  4865. if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
  4866. $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
  4867. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER)) {
  4868. $this->stock_theorique += 0;
  4869. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  4870. $this->stock_theorique -= $stock_commande_client;
  4871. }
  4872. // Stock Increase mode
  4873. if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  4874. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  4875. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) {
  4876. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  4877. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) {
  4878. $this->stock_theorique -= $stock_reception_fournisseur;
  4879. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  4880. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  4881. }
  4882. if (!is_object($hookmanager)) {
  4883. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  4884. $hookmanager = new HookManager($this->db);
  4885. }
  4886. $hookmanager->initHooks(array('productdao'));
  4887. $parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
  4888. // Note that $action and $object may have been modified by some hooks
  4889. $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
  4890. if ($reshook > 0) {
  4891. $this->stock_theorique = $hookmanager->resArray['stock_theorique'];
  4892. }
  4893. return 1;
  4894. }
  4895. /**
  4896. * Load existing information about a serial
  4897. *
  4898. * @param string $batch Lot/serial number
  4899. * @return array Array with record into product_batch
  4900. * @see load_stock(), load_virtual_stock()
  4901. */
  4902. public function loadBatchInfo($batch)
  4903. {
  4904. $result = array();
  4905. $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";
  4906. $sql .= " WHERE pb.fk_product_stock = ps.rowid AND ps.fk_product = ".((int) $this->id)." AND pb.batch = '".$this->db->escape($batch)."'";
  4907. $sql .= " GROUP BY pb.batch, pb.eatby, pb.sellby";
  4908. dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG);
  4909. $resql = $this->db->query($sql);
  4910. if ($resql) {
  4911. $num = $this->db->num_rows($resql);
  4912. $i = 0;
  4913. while ($i < $num) {
  4914. $obj = $this->db->fetch_object($resql);
  4915. $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty);
  4916. $i++;
  4917. }
  4918. return $result;
  4919. } else {
  4920. dol_print_error($this->db);
  4921. $this->db->rollback();
  4922. return array();
  4923. }
  4924. }
  4925. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4926. /**
  4927. * Move an uploaded file described into $file array into target directory $sdir.
  4928. *
  4929. * @param string $sdir Target directory
  4930. * @param string $file Array of file info of file to upload: array('name'=>..., 'tmp_name'=>...)
  4931. * @return int <0 if KO, >0 if OK
  4932. */
  4933. public function add_photo($sdir, $file)
  4934. {
  4935. // phpcs:enable
  4936. global $conf;
  4937. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4938. $result = 0;
  4939. $dir = $sdir;
  4940. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  4941. $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos";
  4942. } else {
  4943. $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref);
  4944. }
  4945. dol_mkdir($dir);
  4946. $dir_osencoded = $dir;
  4947. if (is_dir($dir_osencoded)) {
  4948. $originImage = $dir.'/'.$file['name'];
  4949. // Cree fichier en taille origine
  4950. $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1);
  4951. if (file_exists(dol_osencode($originImage))) {
  4952. // Create thumbs
  4953. $this->addThumbs($originImage);
  4954. }
  4955. }
  4956. if (is_numeric($result) && $result > 0) {
  4957. return 1;
  4958. } else {
  4959. return -1;
  4960. }
  4961. }
  4962. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4963. /**
  4964. * Return if at least one photo is available
  4965. *
  4966. * @param string $sdir Directory to scan
  4967. * @return boolean True if at least one photo is available, False if not
  4968. */
  4969. public function is_photo_available($sdir)
  4970. {
  4971. // phpcs:enable
  4972. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4973. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  4974. global $conf;
  4975. $dir = $sdir;
  4976. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  4977. $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/";
  4978. } else {
  4979. $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product');
  4980. }
  4981. $nbphoto = 0;
  4982. $dir_osencoded = dol_osencode($dir);
  4983. if (file_exists($dir_osencoded)) {
  4984. $handle = opendir($dir_osencoded);
  4985. if (is_resource($handle)) {
  4986. while (($file = readdir($handle)) !== false) {
  4987. if (!utf8_check($file)) {
  4988. $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory
  4989. }
  4990. if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
  4991. return true;
  4992. }
  4993. }
  4994. }
  4995. }
  4996. return false;
  4997. }
  4998. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4999. /**
  5000. * Return an array with all photos of product found on disk. There is no sorting criteria.
  5001. *
  5002. * @param string $dir Directory to scan
  5003. * @param int $nbmax Number maxium of photos (0=no maximum)
  5004. * @return array Array of photos
  5005. */
  5006. public function liste_photos($dir, $nbmax = 0)
  5007. {
  5008. // phpcs:enable
  5009. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5010. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5011. $nbphoto = 0;
  5012. $tabobj = array();
  5013. $dir_osencoded = dol_osencode($dir);
  5014. $handle = @opendir($dir_osencoded);
  5015. if (is_resource($handle)) {
  5016. while (($file = readdir($handle)) !== false) {
  5017. if (!utf8_check($file)) {
  5018. $file = utf8_encode($file); // readdir returns ISO
  5019. }
  5020. if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
  5021. $nbphoto++;
  5022. // We forge name of thumb.
  5023. $photo = $file;
  5024. $photo_vignette = '';
  5025. $regs = array();
  5026. if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) {
  5027. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
  5028. }
  5029. $dirthumb = $dir.'thumbs/';
  5030. // Objet
  5031. $obj = array();
  5032. $obj['photo'] = $photo;
  5033. if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
  5034. $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
  5035. } else {
  5036. $obj['photo_vignette'] = "";
  5037. }
  5038. $tabobj[$nbphoto - 1] = $obj;
  5039. // Do we have to continue with next photo ?
  5040. if ($nbmax && $nbphoto >= $nbmax) {
  5041. break;
  5042. }
  5043. }
  5044. }
  5045. closedir($handle);
  5046. }
  5047. return $tabobj;
  5048. }
  5049. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5050. /**
  5051. * Delete a photo and its thumbs
  5052. *
  5053. * @param string $file Path to image file
  5054. * @return void
  5055. */
  5056. public function delete_photo($file)
  5057. {
  5058. // phpcs:enable
  5059. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5060. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5061. $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
  5062. $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
  5063. $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
  5064. // On efface l'image d'origine
  5065. dol_delete_file($file, 0, 0, 0, $this); // For triggers
  5066. // Si elle existe, on efface la vignette
  5067. if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) {
  5068. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
  5069. if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
  5070. dol_delete_file($dirthumb.$photo_vignette);
  5071. }
  5072. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0];
  5073. if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
  5074. dol_delete_file($dirthumb.$photo_vignette);
  5075. }
  5076. }
  5077. }
  5078. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5079. /**
  5080. * Load size of image file
  5081. *
  5082. * @param string $file Path to file
  5083. * @return void
  5084. */
  5085. public function get_image_size($file)
  5086. {
  5087. // phpcs:enable
  5088. $file_osencoded = dol_osencode($file);
  5089. $infoImg = getimagesize($file_osencoded); // Get information on image
  5090. $this->imgWidth = $infoImg[0]; // Largeur de l'image
  5091. $this->imgHeight = $infoImg[1]; // Hauteur de l'image
  5092. }
  5093. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5094. /**
  5095. * Load indicators this->nb for the dashboard
  5096. *
  5097. * @return int <0 if KO, >0 if OK
  5098. */
  5099. public function load_state_board()
  5100. {
  5101. // phpcs:enable
  5102. global $hookmanager;
  5103. $this->nb = array();
  5104. $sql = "SELECT count(p.rowid) as nb, fk_product_type";
  5105. $sql .= " FROM ".$this->db->prefix()."product as p";
  5106. $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')';
  5107. // Add where from hooks
  5108. if (is_object($hookmanager)) {
  5109. $parameters = array();
  5110. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $this); // Note that $action and $object may have been modified by hook
  5111. $sql .= $hookmanager->resPrint;
  5112. }
  5113. $sql .= ' GROUP BY fk_product_type';
  5114. $resql = $this->db->query($sql);
  5115. if ($resql) {
  5116. while ($obj = $this->db->fetch_object($resql)) {
  5117. if ($obj->fk_product_type == 1) {
  5118. $this->nb["services"] = $obj->nb;
  5119. } else {
  5120. $this->nb["products"] = $obj->nb;
  5121. }
  5122. }
  5123. $this->db->free($resql);
  5124. return 1;
  5125. } else {
  5126. dol_print_error($this->db);
  5127. $this->error = $this->db->error();
  5128. return -1;
  5129. }
  5130. }
  5131. /**
  5132. * Return if object is a product
  5133. *
  5134. * @return boolean True if it's a product
  5135. */
  5136. public function isProduct()
  5137. {
  5138. return ($this->type == Product::TYPE_PRODUCT ? true : false);
  5139. }
  5140. /**
  5141. * Return if object is a product
  5142. *
  5143. * @return boolean True if it's a service
  5144. */
  5145. public function isService()
  5146. {
  5147. return ($this->type == Product::TYPE_SERVICE ? true : false);
  5148. }
  5149. /**
  5150. * Return if object have a constraint on mandatory_period
  5151. *
  5152. * @return boolean True if mandatory_period setted to 1
  5153. */
  5154. public function isMandatoryPeriod()
  5155. {
  5156. return ($this->mandatory_period == 1 ? true : false);
  5157. }
  5158. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5159. /**
  5160. * Get a barcode from the module to generate barcode values.
  5161. * Return value is stored into this->barcode
  5162. *
  5163. * @param Product $object Object product or service
  5164. * @param string $type Barcode type (ean, isbn, ...)
  5165. * @return string
  5166. */
  5167. public function get_barcode($object, $type = '')
  5168. {
  5169. // phpcs:enable
  5170. global $conf;
  5171. $result = '';
  5172. if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
  5173. $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
  5174. foreach ($dirsociete as $dirroot) {
  5175. $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php');
  5176. if ($res) {
  5177. break;
  5178. }
  5179. }
  5180. $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM;
  5181. $mod = new $var;
  5182. $result = $mod->getNextValue($object, $type);
  5183. dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var);
  5184. }
  5185. return $result;
  5186. }
  5187. /**
  5188. * Initialise an instance with random values.
  5189. * Used to build previews or test instances.
  5190. * id must be 0 if object instance is a specimen.
  5191. *
  5192. * @return void
  5193. */
  5194. public function initAsSpecimen()
  5195. {
  5196. global $user, $langs, $conf, $mysoc;
  5197. $now = dol_now();
  5198. // Initialize parameters
  5199. $this->specimen = 1;
  5200. $this->id = 0;
  5201. $this->ref = 'PRODUCT_SPEC';
  5202. $this->label = 'PRODUCT SPECIMEN';
  5203. $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.';
  5204. $this->specimen = 1;
  5205. $this->country_id = 1;
  5206. $this->tosell = 1;
  5207. $this->tobuy = 1;
  5208. $this->tobatch = 0;
  5209. $this->note = 'This is a comment (private)';
  5210. $this->date_creation = $now;
  5211. $this->date_modification = $now;
  5212. $this->weight = 4;
  5213. $this->weight_units = 3;
  5214. $this->length = 5;
  5215. $this->length_units = 1;
  5216. $this->width = 6;
  5217. $this->width_units = 0;
  5218. $this->height = null;
  5219. $this->height_units = null;
  5220. $this->surface = 30;
  5221. $this->surface_units = 0;
  5222. $this->volume = 300;
  5223. $this->volume_units = 0;
  5224. $this->barcode = -1; // Create barcode automatically
  5225. }
  5226. /**
  5227. * Returns the text label from units dictionary
  5228. *
  5229. * @param string $type Label type (long or short)
  5230. * @return string|int <0 if ko, label if ok
  5231. */
  5232. public function getLabelOfUnit($type = 'long')
  5233. {
  5234. global $langs;
  5235. if (!$this->fk_unit) {
  5236. return '';
  5237. }
  5238. $langs->load('products');
  5239. $label_type = 'label';
  5240. if ($type == 'short') {
  5241. $label_type = 'short_label';
  5242. }
  5243. $sql = "SELECT ".$label_type.", code from ".$this->db->prefix()."c_units where rowid = ".((int) $this->fk_unit);
  5244. $resql = $this->db->query($sql);
  5245. if ($resql && $this->db->num_rows($resql) > 0) {
  5246. $res = $this->db->fetch_array($resql);
  5247. $label = ($label_type == 'short_label' ? $res[$label_type] : 'unit'.$res['code']);
  5248. $this->db->free($resql);
  5249. return $label;
  5250. } else {
  5251. $this->error = $this->db->error();
  5252. dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
  5253. return -1;
  5254. }
  5255. }
  5256. /**
  5257. * Return if object has a sell-by date or eat-by date
  5258. *
  5259. * @return boolean True if it's has
  5260. */
  5261. public function hasbatch()
  5262. {
  5263. return ($this->status_batch > 0 ? true : false);
  5264. }
  5265. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5266. /**
  5267. * Return minimum product recommended price
  5268. *
  5269. * @return int Minimum recommanded price that is higher price among all suppliers * PRODUCT_MINIMUM_RECOMMENDED_PRICE
  5270. */
  5271. public function min_recommended_price()
  5272. {
  5273. // phpcs:enable
  5274. global $conf;
  5275. $maxpricesupplier = 0;
  5276. if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) {
  5277. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5278. $product_fourn = new ProductFournisseur($this->db);
  5279. $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
  5280. if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
  5281. foreach ($product_fourn_list as $productfourn) {
  5282. if ($productfourn->fourn_unitprice > $maxpricesupplier) {
  5283. $maxpricesupplier = $productfourn->fourn_unitprice;
  5284. }
  5285. }
  5286. $maxpricesupplier *= $conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE;
  5287. }
  5288. }
  5289. return $maxpricesupplier;
  5290. }
  5291. /**
  5292. * Sets object to supplied categories.
  5293. *
  5294. * Deletes object from existing categories not supplied.
  5295. * Adds it to non existing supplied categories.
  5296. * Existing categories are left untouch.
  5297. *
  5298. * @param int[]|int $categories Category or categories IDs
  5299. * @return void
  5300. */
  5301. public function setCategories($categories)
  5302. {
  5303. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  5304. return parent::setCategoriesCommon($categories, Categorie::TYPE_PRODUCT);
  5305. }
  5306. /**
  5307. * Function used to replace a thirdparty id with another one.
  5308. *
  5309. * @param DoliDB $db Database handler
  5310. * @param int $origin_id Old thirdparty id
  5311. * @param int $dest_id New thirdparty id
  5312. * @return bool
  5313. */
  5314. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  5315. {
  5316. $tables = array(
  5317. 'product_customer_price',
  5318. 'product_customer_price_log'
  5319. );
  5320. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  5321. }
  5322. /**
  5323. * Generates prices for a product based on product multiprice generation rules
  5324. *
  5325. * @param User $user User that updates the prices
  5326. * @param float $baseprice Base price
  5327. * @param string $price_type Base price type
  5328. * @param float $price_vat VAT % tax
  5329. * @param int $npr NPR
  5330. * @param string $psq ¿?
  5331. * @return int -1 KO, 1 OK
  5332. */
  5333. public function generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
  5334. {
  5335. global $conf, $db;
  5336. $sql = "SELECT rowid, level, fk_level, var_percent, var_min_percent FROM ".$this->db->prefix()."product_pricerules";
  5337. $query = $this->db->query($sql);
  5338. $rules = array();
  5339. while ($result = $this->db->fetch_object($query)) {
  5340. $rules[$result->level] = $result;
  5341. }
  5342. //Because prices can be based on other level's prices, we temporarily store them
  5343. $prices = array(
  5344. 1 => $baseprice
  5345. );
  5346. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  5347. $price = $baseprice;
  5348. $price_min = $baseprice;
  5349. //We have to make sure it does exist and it is > 0
  5350. //First price level only allows changing min_price
  5351. if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) {
  5352. $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100));
  5353. }
  5354. $prices[$i] = $price;
  5355. //We have to make sure it does exist and it is > 0
  5356. if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) {
  5357. $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100));
  5358. }
  5359. //Little check to make sure the price is modified before triggering generation
  5360. $check_amount = (($price == $this->multiprices[$i]) && ($price_min == $this->multiprices_min[$i]));
  5361. $check_type = ($baseprice == $this->multiprices_base_type[$i]);
  5362. if ($check_amount && $check_type) {
  5363. continue;
  5364. }
  5365. if ($this->updatePrice($price, $price_type, $user, $price_vat, $price_min, $i, $npr, $psq, true) < 0) {
  5366. return -1;
  5367. }
  5368. }
  5369. return 1;
  5370. }
  5371. /**
  5372. * Returns the rights used for this class
  5373. *
  5374. * @return Object
  5375. */
  5376. public function getRights()
  5377. {
  5378. global $user;
  5379. if ($this->isProduct()) {
  5380. return $user->rights->produit;
  5381. } else {
  5382. return $user->rights->service;
  5383. }
  5384. }
  5385. /**
  5386. * Load information for tab info
  5387. *
  5388. * @param int $id Id of thirdparty to load
  5389. * @return void
  5390. */
  5391. public function info($id)
  5392. {
  5393. $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, p.tms as date_modification,";
  5394. $sql .= " p.fk_user_author, p.fk_user_modif";
  5395. $sql .= " FROM ".$this->db->prefix().$this->table_element." as p";
  5396. $sql .= " WHERE p.rowid = ".((int) $id);
  5397. $result = $this->db->query($sql);
  5398. if ($result) {
  5399. if ($this->db->num_rows($result)) {
  5400. $obj = $this->db->fetch_object($result);
  5401. $this->id = $obj->rowid;
  5402. if ($obj->fk_user_author) {
  5403. $cuser = new User($this->db);
  5404. $cuser->fetch($obj->fk_user_author);
  5405. $this->user_creation = $cuser;
  5406. }
  5407. if ($obj->fk_user_modif) {
  5408. $muser = new User($this->db);
  5409. $muser->fetch($obj->fk_user_modif);
  5410. $this->user_modification = $muser;
  5411. }
  5412. $this->ref = $obj->ref;
  5413. $this->date_creation = $this->db->jdate($obj->date_creation);
  5414. $this->date_modification = $this->db->jdate($obj->date_modification);
  5415. }
  5416. $this->db->free($result);
  5417. } else {
  5418. dol_print_error($this->db);
  5419. }
  5420. }
  5421. }
  5422. /**
  5423. * Class to manage products or services.
  5424. * Do not use 'Service' as class name since it is already used by APIs.
  5425. */
  5426. class ProductService extends Product
  5427. {
  5428. public $picto = 'service';
  5429. }