product.class.php 240 KB

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