product.class.php 218 KB

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