product.class.php 234 KB

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