societe.class.php 186 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401
  1. <?php
  2. /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2021 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
  5. * Copyright (C) 2003 Brian Fraval <brian@fraval.org>
  6. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  7. * Copyright (C) 2005-2017 Regis Houssin <regis.houssin@inodbox.com>
  8. * Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
  9. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  10. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  11. * Copyright (C) 2013-2023 Alexandre Spangaro <aspangaro@open-dsi.fr>
  12. * Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
  13. * Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
  14. * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
  15. * Copyright (C) 2017 Rui Strecht <rui.strecht@aliartalentos.com>
  16. * Copyright (C) 2018 Philippe Grand <philippe.grand@atoo-net.com>
  17. * Copyright (C) 2019-2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
  18. * Copyright (C) 2019-2023 Frédéric France <frederic.france@netlogic.fr>
  19. * Copyright (C) 2020 Open-Dsi <support@open-dsi.fr>
  20. * Copyright (C) 2022 ButterflyOfFire <butterflyoffire+dolibarr@protonmail.com>
  21. *
  22. * This program is free software; you can redistribute it and/or modify
  23. * it under the terms of the GNU General Public License as published by
  24. * the Free Software Foundation; either version 3 of the License, or
  25. * (at your option) any later version.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU General Public License
  33. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  34. */
  35. /**
  36. * \file htdocs/societe/class/societe.class.php
  37. * \ingroup societe
  38. * \brief File for third party class
  39. */
  40. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/core/class/commonincoterm.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/core/class/commonsocialnetworks.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/class/commonpeople.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  45. /**
  46. * Class to manage third parties objects (customers, suppliers, prospects...)
  47. */
  48. class Societe extends CommonObject
  49. {
  50. use CommonIncoterm;
  51. use CommonSocialNetworks;
  52. use CommonPeople;
  53. /**
  54. * @var string ID of module.
  55. */
  56. public $module = 'societe';
  57. /**
  58. * @var string ID to identify managed object
  59. */
  60. public $element = 'societe';
  61. /**
  62. * @var string Name of table without prefix where object is stored
  63. */
  64. public $table_element = 'societe';
  65. /**
  66. * @var string Field with ID of parent key if this field has a parent or for child tables
  67. */
  68. public $fk_element = 'fk_soc';
  69. /**
  70. * @var string Fields for combobox
  71. */
  72. public $fieldsforcombobox = 'nom,name_alias';
  73. /**
  74. * @var array List of child tables. To test if we can delete object.
  75. */
  76. protected $childtables = array(
  77. 'supplier_proposal' => array('name' => 'SupplierProposal'),
  78. 'propal' => array('name' => 'Proposal'),
  79. 'commande' => array('name' => 'Order'),
  80. 'facture' => array('name' => 'Invoice'),
  81. 'facture_rec' => array('name' => 'RecurringInvoiceTemplate'),
  82. 'contrat' => array('name' => 'Contract'),
  83. 'fichinter' => array('name' => 'Fichinter'),
  84. 'facture_fourn' => array('name' => 'SupplierInvoice'),
  85. 'commande_fournisseur' => array('name' => 'SupplierOrder'),
  86. 'projet' => array('name' => 'Project'),
  87. 'expedition' => array('name' => 'Shipment'),
  88. 'prelevement_lignes' => array('name' => 'DirectDebitRecord'),
  89. );
  90. /**
  91. * @var array List of child tables. To know object to delete on cascade.
  92. * if name like with @ClassName:FilePathClass:ParentFkFieldName' it will call method deleteByParentField (with parentId as parameters) and FieldName to fetch and delete child object
  93. */
  94. protected $childtablesoncascade = array(
  95. 'societe_prices',
  96. 'societe_address',
  97. 'product_fournisseur_price',
  98. 'product_customer_price_log',
  99. 'product_customer_price',
  100. '@Contact:/contact/class/contact.class.php:fk_soc',
  101. 'adherent',
  102. 'societe_account',
  103. 'societe_rib',
  104. 'societe_remise',
  105. 'societe_remise_except',
  106. 'societe_commerciaux',
  107. 'categorie',
  108. 'notify',
  109. 'notify_def',
  110. 'actioncomm',
  111. );
  112. /**
  113. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  114. */
  115. public $picto = 'company';
  116. /**
  117. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  118. * @var int
  119. */
  120. public $ismultientitymanaged = 1;
  121. /**
  122. * @var int Does object support extrafields ? 0=No, 1=Yes
  123. */
  124. public $isextrafieldmanaged = 1;
  125. /**
  126. * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
  127. * @var integer
  128. */
  129. public $restrictiononfksoc = 1;
  130. /**
  131. * @var Societe To store a cloned copy of object before to edit it and keep track of old properties
  132. */
  133. public $oldcopy;
  134. /**
  135. * array of supplier categories
  136. * @var array
  137. */
  138. public $SupplierCategories = array();
  139. /**
  140. * prefixCustomerIsRequired
  141. * @var int
  142. */
  143. public $prefixCustomerIsRequired;
  144. /**
  145. * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  146. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  147. * 'label' the translation key.
  148. * 'picto' is code of a picto to show before value in forms
  149. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  150. * 'position' is the sort order of field.
  151. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  152. * '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)
  153. * 'noteditable' says if field is not editable (1 or 0)
  154. * '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.
  155. * 'index' if we want an index in database.
  156. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  157. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  158. * '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).
  159. * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'maxwidth200', 'wordbreak', 'tdoverflowmax200'
  160. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  161. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  162. * '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.
  163. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  164. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  165. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  166. *
  167. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  168. */
  169. /**
  170. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  171. */
  172. public $fields = array(
  173. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  174. 'parent' =>array('type'=>'integer', 'label'=>'Parent', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
  175. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
  176. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
  177. 'nom' =>array('type'=>'varchar(128)', 'label'=>'Nom', 'enabled'=>1, 'visible'=>-1, 'position'=>35, 'showoncombobox'=>1),
  178. 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name alias', 'enabled'=>1, 'visible'=>-1, 'position'=>36, 'showoncombobox'=>2),
  179. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>40, 'index'=>1),
  180. 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'RefExt', 'enabled'=>1, 'visible'=>0, 'position'=>45),
  181. 'code_client' =>array('type'=>'varchar(24)', 'label'=>'CustomerCode', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
  182. 'code_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierCode', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
  183. 'code_compta' =>array('type'=>'varchar(24)', 'label'=>'CustomerAccountancyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
  184. 'code_compta_fournisseur' =>array('type'=>'varchar(24)', 'label'=>'SupplierAccountancyCode', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
  185. 'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
  186. 'zip' =>array('type'=>'varchar(25)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  187. 'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
  188. 'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  189. 'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
  190. 'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
  191. 'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
  192. 'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110),
  193. 'email' =>array('type'=>'varchar(128)', 'label'=>'Email', 'enabled'=>1, 'visible'=>-1, 'position'=>115),
  194. 'socialnetworks' =>array('type'=>'text', 'label'=>'Socialnetworks', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
  195. 'fk_effectif' =>array('type'=>'integer', 'label'=>'Workforce', 'enabled'=>1, 'visible'=>-1, 'position'=>170),
  196. 'fk_typent' =>array('type'=>'integer', 'label'=>'TypeOfCompany', 'enabled'=>1, 'visible'=>-1, 'position'=>175, 'csslist'=>'minwidth200'),
  197. 'fk_forme_juridique' =>array('type'=>'integer', 'label'=>'JuridicalStatus', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
  198. 'fk_currency' =>array('type'=>'varchar(3)', 'label'=>'Currency', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  199. 'siren' =>array('type'=>'varchar(128)', 'label'=>'Idprof1', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
  200. 'siret' =>array('type'=>'varchar(128)', 'label'=>'Idprof2', 'enabled'=>1, 'visible'=>-1, 'position'=>195),
  201. 'ape' =>array('type'=>'varchar(128)', 'label'=>'Idprof3', 'enabled'=>1, 'visible'=>-1, 'position'=>200),
  202. 'idprof4' =>array('type'=>'varchar(128)', 'label'=>'Idprof4', 'enabled'=>1, 'visible'=>-1, 'position'=>205),
  203. 'idprof5' =>array('type'=>'varchar(128)', 'label'=>'Idprof5', 'enabled'=>1, 'visible'=>-1, 'position'=>206),
  204. 'idprof6' =>array('type'=>'varchar(128)', 'label'=>'Idprof6', 'enabled'=>1, 'visible'=>-1, 'position'=>207),
  205. 'tva_intra' =>array('type'=>'varchar(20)', 'label'=>'Tva intra', 'enabled'=>1, 'visible'=>-1, 'position'=>210),
  206. 'capital' =>array('type'=>'double(24,8)', 'label'=>'Capital', 'enabled'=>1, 'visible'=>-1, 'position'=>215),
  207. 'fk_stcomm' =>array('type'=>'integer', 'label'=>'CommercialStatus', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>220),
  208. 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>225),
  209. 'note_private' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>230),
  210. 'prefix_comm' =>array('type'=>'varchar(5)', 'label'=>'Prefix comm', 'enabled'=>"getDolGlobalInt('SOCIETE_USEPREFIX')", 'visible'=>-1, 'position'=>235),
  211. 'client' =>array('type'=>'tinyint(4)', 'label'=>'Client', 'enabled'=>1, 'visible'=>-1, 'position'=>240),
  212. 'fournisseur' =>array('type'=>'tinyint(4)', 'label'=>'Fournisseur', 'enabled'=>1, 'visible'=>-1, 'position'=>245),
  213. 'supplier_account' =>array('type'=>'varchar(32)', 'label'=>'Supplier account', 'enabled'=>1, 'visible'=>-1, 'position'=>250),
  214. 'fk_prospectlevel' =>array('type'=>'varchar(12)', 'label'=>'ProspectLevel', 'enabled'=>1, 'visible'=>-1, 'position'=>255),
  215. 'customer_bad' =>array('type'=>'tinyint(4)', 'label'=>'Customer bad', 'enabled'=>1, 'visible'=>-1, 'position'=>260),
  216. 'customer_rate' =>array('type'=>'double', 'label'=>'Customer rate', 'enabled'=>1, 'visible'=>-1, 'position'=>265),
  217. 'supplier_rate' =>array('type'=>'double', 'label'=>'Supplier rate', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
  218. 'fk_user_creat' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>275),
  219. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>280),
  220. //'remise_client' =>array('type'=>'double', 'label'=>'CustomerDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>285, 'isameasure'=>1),
  221. //'remise_supplier' =>array('type'=>'double', 'label'=>'SupplierDiscount', 'enabled'=>1, 'visible'=>-1, 'position'=>290, 'isameasure'=>1),
  222. 'mode_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Mode reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>295),
  223. 'cond_reglement' =>array('type'=>'tinyint(4)', 'label'=>'Cond reglement', 'enabled'=>1, 'visible'=>-1, 'position'=>300),
  224. 'deposit_percent' =>array('type'=>'varchar(63)', 'label'=>'DepositPercent', 'enabled'=>1, 'visible'=>-1, 'position'=>301),
  225. 'mode_reglement_supplier' =>array('type'=>'integer', 'label'=>'Mode reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>305),
  226. 'cond_reglement_supplier' =>array('type'=>'integer', 'label'=>'Cond reglement supplier', 'enabled'=>1, 'visible'=>-1, 'position'=>308),
  227. 'outstanding_limit' =>array('type'=>'double(24,8)', 'label'=>'OutstandingBill', 'enabled'=>1, 'visible'=>-1, 'position'=>310, 'isameasure'=>1),
  228. 'order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Order min amount', 'enabled'=>'isModEnabled("commande") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>315, 'isameasure'=>1),
  229. 'supplier_order_min_amount' =>array('type'=>'double(24,8)', 'label'=>'Supplier order min amount', 'enabled'=>'isModEnabled("commande") && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)', 'visible'=>-1, 'position'=>320, 'isameasure'=>1),
  230. 'fk_shipping_method' =>array('type'=>'integer', 'label'=>'Fk shipping method', 'enabled'=>1, 'visible'=>-1, 'position'=>330),
  231. 'tva_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Tva assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
  232. 'localtax1_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax1 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>340),
  233. 'localtax1_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax1 value', 'enabled'=>1, 'visible'=>-1, 'position'=>345),
  234. 'localtax2_assuj' =>array('type'=>'tinyint(4)', 'label'=>'Localtax2 assuj', 'enabled'=>1, 'visible'=>-1, 'position'=>350),
  235. 'localtax2_value' =>array('type'=>'double(6,3)', 'label'=>'Localtax2 value', 'enabled'=>1, 'visible'=>-1, 'position'=>355),
  236. 'vat_reverse_charge' =>array('type'=>'tinyint(4)', 'label'=>'Vat reverse charge', 'enabled'=>1, 'visible'=>-1, 'position'=>335),
  237. 'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>1, 'visible'=>-1, 'position'=>360),
  238. 'price_level' =>array('type'=>'integer', 'label'=>'Price level', 'enabled'=>'$conf->global->PRODUIT_MULTIPRICES || $conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES', 'visible'=>-1, 'position'=>365),
  239. 'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=>370),
  240. 'canvas' =>array('type'=>'varchar(32)', 'label'=>'Canvas', 'enabled'=>1, 'visible'=>-1, 'position'=>375),
  241. 'fk_barcode_type' =>array('type'=>'integer', 'label'=>'Fk barcode type', 'enabled'=>1, 'visible'=>-1, 'position'=>405),
  242. 'webservices_url' =>array('type'=>'varchar(255)', 'label'=>'Webservices url', 'enabled'=>1, 'visible'=>-1, 'position'=>410),
  243. 'webservices_key' =>array('type'=>'varchar(128)', 'label'=>'Webservices key', 'enabled'=>1, 'visible'=>-1, 'position'=>415),
  244. 'fk_incoterms' =>array('type'=>'integer', 'label'=>'Fk incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>425),
  245. 'location_incoterms' =>array('type'=>'varchar(255)', 'label'=>'Location incoterms', 'enabled'=>1, 'visible'=>-1, 'position'=>430),
  246. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>435),
  247. 'last_main_doc' =>array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>1, 'visible'=>-1, 'position'=>270),
  248. 'fk_multicurrency' =>array('type'=>'integer', 'label'=>'Fk multicurrency', 'enabled'=>1, 'visible'=>-1, 'position'=>440),
  249. 'multicurrency_code' =>array('type'=>'varchar(255)', 'label'=>'Multicurrency code', 'enabled'=>1, 'visible'=>-1, 'position'=>445),
  250. 'fk_account' =>array('type'=>'integer', 'label'=>'PaymentBankAccount', 'enabled'=>1, 'visible'=>-1, 'position'=>450),
  251. 'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>455),
  252. 'logo' =>array('type'=>'varchar(255)', 'label'=>'Logo', 'enabled'=>1, 'visible'=>-1, 'position'=>400),
  253. 'logo_squarred' =>array('type'=>'varchar(255)', 'label'=>'Logo squarred', 'enabled'=>1, 'visible'=>-1, 'position'=>401),
  254. 'status' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>-1, 'position'=>500),
  255. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
  256. );
  257. /**
  258. * @var int Entity
  259. */
  260. public $entity;
  261. /**
  262. * Thirdparty name
  263. * @var string
  264. * @deprecated Use $name instead
  265. * @see $name
  266. */
  267. public $nom;
  268. /**
  269. * @var string Thirdparty name
  270. */
  271. public $name;
  272. /**
  273. * Alias names (commercial, trademark or alias names)
  274. * @var string
  275. */
  276. public $name_alias;
  277. /**
  278. * @var int Physical thirdparty not a company
  279. */
  280. public $particulier;
  281. /**
  282. * Thirdparty status : 0=activity ceased, 1= in activity
  283. * @var int
  284. */
  285. public $status = 1;
  286. /**
  287. * Id of region
  288. * @var int
  289. */
  290. public $region_code;
  291. /**
  292. * @var string Region name
  293. */
  294. public $region;
  295. /**
  296. * @var string State code
  297. * @deprecated Use state_code instead
  298. * @see $state_code
  299. */
  300. public $departement_code;
  301. /**
  302. * @var string
  303. * @deprecated Use state instead
  304. * @see $state
  305. */
  306. public $departement;
  307. /**
  308. * @var string
  309. * @deprecated Use country instead
  310. * @see $country
  311. */
  312. public $pays;
  313. /**
  314. * Phone number
  315. * @var string
  316. */
  317. public $phone;
  318. /**
  319. * Fax number
  320. * @var string
  321. */
  322. public $fax;
  323. /**
  324. * Email
  325. * @var string
  326. */
  327. public $email;
  328. /**
  329. * No Email
  330. * @var int Set if company email found into unsubscribe of emailing list table
  331. */
  332. public $no_email;
  333. /**
  334. * Skype username
  335. * @var string
  336. * @deprecated
  337. */
  338. public $skype;
  339. /**
  340. * Twitter username
  341. * @var string
  342. * @deprecated
  343. */
  344. public $twitter;
  345. /**
  346. * Facebook username
  347. * @var string
  348. * @deprecated
  349. */
  350. public $facebook;
  351. /**
  352. * LinkedIn username
  353. * @var string
  354. * @deprecated
  355. */
  356. public $linkedin;
  357. /**
  358. * Webpage
  359. * @var string
  360. */
  361. public $url;
  362. /**
  363. * Barcode value
  364. * @var string
  365. */
  366. public $barcode;
  367. // 6 professional id (usage depends on country)
  368. /**
  369. * Professional ID 1 (Ex: Siren in France)
  370. * @var string
  371. */
  372. public $idprof1;
  373. /**
  374. * @var string Professional ID 1
  375. * @deprecated
  376. * @see $idprof1
  377. */
  378. public $siren;
  379. /**
  380. * Professional ID 2 (Ex: Siret in France)
  381. * @var string
  382. */
  383. public $idprof2;
  384. /**
  385. * @var string Professional ID 2
  386. * @deprecated
  387. * @see $idprof2
  388. */
  389. public $siret;
  390. /**
  391. * Professional ID 3 (Ex: Ape in France)
  392. * @var string
  393. */
  394. public $idprof3;
  395. /**
  396. * @var string Professional ID 3
  397. * @deprecated
  398. * @see $idprof3
  399. */
  400. public $ape;
  401. /**
  402. * Professional ID 4 (Ex: RCS in France)
  403. * @var string
  404. */
  405. public $idprof4;
  406. /**
  407. * Professional ID 5
  408. * @var string
  409. */
  410. public $idprof5;
  411. /**
  412. * Professional ID 6
  413. * @var string
  414. */
  415. public $idprof6;
  416. /**
  417. * Social object of the company
  418. * @var string
  419. */
  420. public $socialobject;
  421. /**
  422. * @var string Prefix comm
  423. */
  424. public $prefix_comm;
  425. /**
  426. * @var int Vat concerned
  427. */
  428. public $tva_assuj = 1;
  429. /**
  430. * Intracommunitary VAT ID
  431. * @var string
  432. */
  433. public $tva_intra;
  434. /**
  435. * @var int Vat reverse-charge concerned
  436. */
  437. public $vat_reverse_charge = 0;
  438. // Local taxes
  439. public $localtax1_assuj;
  440. public $localtax1_value;
  441. public $localtax2_assuj;
  442. public $localtax2_value;
  443. /**
  444. * @var string Manager
  445. */
  446. public $managers;
  447. /**
  448. * @var float Capital
  449. */
  450. public $capital;
  451. /**
  452. * @var int Type thirdparty
  453. */
  454. public $typent_id = 0;
  455. public $typent_code;
  456. public $effectif;
  457. public $effectif_id = 0;
  458. public $forme_juridique_code;
  459. public $forme_juridique = 0;
  460. public $remise_percent;
  461. public $remise_supplier_percent;
  462. public $mode_reglement_id;
  463. public $cond_reglement_id;
  464. public $deposit_percent;
  465. public $mode_reglement_supplier_id;
  466. public $cond_reglement_supplier_id;
  467. public $transport_mode_supplier_id;
  468. /**
  469. * @var int ID
  470. */
  471. public $fk_prospectlevel;
  472. /**
  473. * @var string second name
  474. */
  475. public $name_bis;
  476. //Log data
  477. /**
  478. * Date of last update
  479. * @var integer|string
  480. */
  481. public $date_modification;
  482. /**
  483. * User that made last update
  484. * @var User
  485. */
  486. public $user_modification;
  487. /**
  488. * Date of creation
  489. * @var integer|string
  490. */
  491. public $date_creation;
  492. /**
  493. * User that created the thirdparty
  494. * @var User
  495. */
  496. public $user_creation;
  497. /**
  498. * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
  499. * @var int
  500. */
  501. public $client = 0;
  502. /**
  503. * 0=no prospect, 1=prospect
  504. * @var int
  505. */
  506. public $prospect = 0;
  507. /**
  508. * 0=no supplier, 1=supplier
  509. * @var int
  510. */
  511. public $fournisseur;
  512. /**
  513. * Client code. E.g: CU2014-003
  514. * @var string
  515. */
  516. public $code_client;
  517. /**
  518. * Supplier code. E.g: SU2014-003
  519. * @var string
  520. */
  521. public $code_fournisseur;
  522. /**
  523. * Accounting code for client
  524. * @var string
  525. */
  526. public $code_compta_client;
  527. /**
  528. * Duplicate of code_compta_client (for backward compatibility)
  529. * @var string
  530. * @deprecated
  531. * @see $code_compta_client
  532. */
  533. public $code_compta;
  534. /**
  535. * Accounting code for customer
  536. * @var string
  537. */
  538. public $accountancy_code_customer;
  539. /**
  540. * Accounting code for supplier
  541. * @var string
  542. */
  543. public $code_compta_fournisseur;
  544. /**
  545. * Accounting code for supplier
  546. * @var string
  547. */
  548. public $accountancy_code_supplier;
  549. /**
  550. * Accounting code for product (for level 3 of suggestion of prouct accounting account)
  551. * @var string
  552. */
  553. public $code_compta_product;
  554. /**
  555. * @var string
  556. * @deprecated Note is split in public and private notes
  557. * @see $note_public, $note_private
  558. */
  559. public $note;
  560. /**
  561. * Private note
  562. * @var string
  563. */
  564. public $note_private;
  565. /**
  566. * Public note
  567. * @var string
  568. */
  569. public $note_public;
  570. /**
  571. * Status prospect id
  572. * @var int
  573. */
  574. public $stcomm_id;
  575. /**
  576. * Status prospect picto
  577. * @var string
  578. */
  579. public $stcomm_picto;
  580. /**
  581. * Status prospect label
  582. * @var int
  583. */
  584. public $status_prospect_label;
  585. /**
  586. * Assigned price level
  587. * @var int
  588. */
  589. public $price_level;
  590. /**
  591. * @var string outstanding limit
  592. */
  593. public $outstanding_limit;
  594. /**
  595. * @var string Min order amount
  596. */
  597. public $order_min_amount;
  598. /**
  599. * @var string Supplier min order amount
  600. */
  601. public $supplier_order_min_amount;
  602. /**
  603. * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
  604. * @var int
  605. */
  606. public $commercial_id;
  607. /**
  608. * Id of parent thirdparty (if one)
  609. * @var int
  610. */
  611. public $parent;
  612. /**
  613. * Default language code of thirdparty (en_US, ...)
  614. * @var string
  615. */
  616. public $default_lang;
  617. /**
  618. * @var string Ref
  619. */
  620. public $ref;
  621. /**
  622. * External user reference.
  623. * This is to allow external systems to store their id and make self-developed synchronizing functions easier to build.
  624. * @var string
  625. */
  626. public $ref_ext;
  627. /**
  628. * Import key.
  629. * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
  630. * to an import process
  631. * @var string
  632. */
  633. public $import_key;
  634. /**
  635. * Supplier WebServices URL
  636. * @var string
  637. */
  638. public $webservices_url;
  639. /**
  640. * Supplier WebServices Key
  641. * @var string
  642. */
  643. public $webservices_key;
  644. /**
  645. * @var string Logo
  646. */
  647. public $logo;
  648. /**
  649. * @var string logo small
  650. */
  651. public $logo_small;
  652. /**
  653. * @var string Logo mini
  654. */
  655. public $logo_mini;
  656. /**
  657. * @var string Logo squarred
  658. */
  659. public $logo_squarred;
  660. /**
  661. * @var string Logo squarred small
  662. */
  663. public $logo_squarred_small;
  664. /**
  665. * @var string Logo squarred mini
  666. */
  667. public $logo_squarred_mini;
  668. /**
  669. * @var string Accountancy account for sales
  670. */
  671. public $accountancy_code_sell;
  672. /**
  673. * @var string Accountancy account for bought
  674. */
  675. public $accountancy_code_buy;
  676. // Multicurrency
  677. /**
  678. * @var int ID
  679. */
  680. public $fk_multicurrency;
  681. // Warehouse
  682. /**
  683. * @var int ID
  684. */
  685. public $fk_warehouse;
  686. /**
  687. * @var string Multicurrency code
  688. */
  689. public $multicurrency_code;
  690. // Fields loaded by fetchPartnerships()
  691. public $partnerships = array();
  692. /**
  693. * @var Account|string Default BAN account
  694. */
  695. public $bank_account;
  696. const STATUS_CEASED = 0;
  697. const STATUS_INACTIVITY = 1;
  698. /**
  699. * Third party type is no customer
  700. */
  701. const NO_CUSTOMER = 0;
  702. /**
  703. * Third party type is a customer
  704. */
  705. const CUSTOMER = 1;
  706. /**
  707. * Third party type is a prospect
  708. */
  709. const PROSPECT = 2;
  710. /**
  711. * Third party type is a customer and a prospect
  712. */
  713. const CUSTOMER_AND_PROSPECT = 3;
  714. /**
  715. * Third party supplier flag is not supplier
  716. */
  717. const NO_SUPPLIER = 0;
  718. /**
  719. * Third party supplier flag is a supplier
  720. */
  721. const SUPPLIER = 1;
  722. /**
  723. * Constructor
  724. *
  725. * @param DoliDB $db Database handler
  726. */
  727. public function __construct($db)
  728. {
  729. global $conf;
  730. $this->db = $db;
  731. $this->client = 0;
  732. $this->prospect = 0;
  733. $this->fournisseur = 0;
  734. $this->typent_id = 0;
  735. $this->effectif_id = 0;
  736. $this->forme_juridique_code = 0;
  737. $this->tva_assuj = 1;
  738. $this->vat_reverse_charge = 0;
  739. $this->status = 1;
  740. if (!empty($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST)) {
  741. $this->fields['address']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
  742. $this->fields['zip']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
  743. $this->fields['town']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
  744. //$this->fields['fk_pays']['showoncombobox'] = $conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST;
  745. }
  746. }
  747. /**
  748. * Create third party in database.
  749. * $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement.
  750. *
  751. * @param User $user Object of user that ask creation
  752. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  753. * @return int >=0 if OK, <0 if KO
  754. */
  755. public function create(User $user, $notrigger = 0)
  756. {
  757. global $langs, $conf, $mysoc;
  758. $error = 0;
  759. // Clean parameters
  760. if (empty($this->status)) {
  761. $this->status = 0;
  762. }
  763. $this->name = $this->name ?trim($this->name) : trim($this->nom);
  764. $this->setUpperOrLowerCase();
  765. $this->nom = $this->name; // For backward compatibility
  766. if (empty($this->client)) {
  767. $this->client = 0;
  768. }
  769. if (empty($this->fournisseur)) {
  770. $this->fournisseur = 0;
  771. }
  772. $this->import_key = trim($this->import_key);
  773. $this->accountancy_code_customer = trim($this->code_compta);
  774. $this->accountancy_code_supplier = trim($this->code_compta_fournisseur);
  775. $this->accountancy_code_buy = trim($this->accountancy_code_buy);
  776. $this->accountancy_code_sell = trim($this->accountancy_code_sell);
  777. if (!empty($this->multicurrency_code)) {
  778. $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  779. }
  780. if (empty($this->fk_multicurrency)) {
  781. $this->multicurrency_code = '';
  782. $this->fk_multicurrency = 0;
  783. }
  784. dol_syslog(get_class($this)."::create ".$this->name);
  785. $now = dol_now();
  786. $this->db->begin();
  787. // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
  788. if ($this->code_client == -1 || $this->code_client === 'auto') {
  789. $this->get_codeclient($this, 0);
  790. }
  791. if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
  792. $this->get_codefournisseur($this, 1);
  793. }
  794. // Check more parameters (including mandatory setup
  795. // If error, this->errors[] is filled
  796. $result = $this->verify();
  797. if ($result >= 0) {
  798. $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
  799. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (";
  800. $sql .= "nom";
  801. $sql .= ", name_alias";
  802. $sql .= ", entity";
  803. $sql .= ", datec";
  804. $sql .= ", fk_user_creat";
  805. $sql .= ", fk_typent";
  806. $sql .= ", canvas";
  807. $sql .= ", status";
  808. $sql .= ", ref_ext";
  809. $sql .= ", fk_stcomm";
  810. $sql .= ", fk_incoterms";
  811. $sql .= ", location_incoterms";
  812. $sql .= ", import_key";
  813. $sql .= ", fk_multicurrency";
  814. $sql .= ", multicurrency_code";
  815. if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  816. $sql .= ", vat_reverse_charge";
  817. $sql .= ", accountancy_code_buy";
  818. $sql .= ", accountancy_code_sell";
  819. }
  820. $sql .= ") VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".((int) $this->entity).", '".$this->db->idate($now)."'";
  821. $sql .= ", ".(!empty($user->id) ? ((int) $user->id) : "null");
  822. $sql .= ", ".(!empty($this->typent_id) ? ((int) $this->typent_id) : "null");
  823. $sql .= ", ".(!empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'" : "null");
  824. $sql .= ", ".((int) $this->status);
  825. $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  826. $sql .= ", 0";
  827. $sql .= ", ".(int) $this->fk_incoterms;
  828. $sql .= ", '".$this->db->escape($this->location_incoterms)."'";
  829. $sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
  830. $sql .= ", ".(int) $this->fk_multicurrency;
  831. $sql .= ", '".$this->db->escape($this->multicurrency_code)."'";
  832. if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  833. $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
  834. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
  835. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
  836. }
  837. $sql .= ")";
  838. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  839. $result = $this->db->query($sql);
  840. if ($result) {
  841. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
  842. $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
  843. // update accountancy for this entity
  844. if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  845. $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
  846. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
  847. $sql .= " fk_soc";
  848. $sql .= ", entity";
  849. $sql .= ", vat_reverse_charge";
  850. $sql .= ", accountancy_code_customer";
  851. $sql .= ", accountancy_code_supplier";
  852. $sql .= ", accountancy_code_buy";
  853. $sql .= ", accountancy_code_sell";
  854. $sql .= ") VALUES (";
  855. $sql .= $this->id;
  856. $sql .= ", ".((int) $conf->entity);
  857. $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
  858. $sql .= ", '".$this->db->escape($this->accountancy_code_customer)."'";
  859. $sql .= ", '".$this->db->escape($this->accountancy_code_supplier)."'";
  860. $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
  861. $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
  862. $sql .= ")";
  863. $result = $this->db->query($sql);
  864. if (!$result) {
  865. $error++;
  866. $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
  867. }
  868. }
  869. // Ajout du commercial affecte
  870. if ($this->commercial_id != '' && $this->commercial_id != -1) {
  871. $this->add_commercial($user, $this->commercial_id);
  872. } elseif (empty($user->rights->societe->client->voir)) {
  873. // si un commercial cree un client il lui est affecte automatiquement
  874. $this->add_commercial($user, $user->id);
  875. }
  876. if ($ret >= 0 && !$notrigger) {
  877. // Call trigger
  878. $result = $this->call_trigger('COMPANY_CREATE', $user);
  879. if ($result < 0) {
  880. $error++;
  881. }
  882. // End call triggers
  883. } else {
  884. $error++;
  885. }
  886. if (!$error) {
  887. dol_syslog(get_class($this)."::Create success id=".$this->id);
  888. $this->db->commit();
  889. return $this->id;
  890. } else {
  891. dol_syslog(get_class($this)."::Create echec update ".$this->error.(empty($this->errors) ? '' : ' '.join(',', $this->errors)), LOG_ERR);
  892. $this->db->rollback();
  893. return -4;
  894. }
  895. } else {
  896. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  897. $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name); // duplicate on a field (code or profid or ...)
  898. $result = -1;
  899. } else {
  900. $this->error = $this->db->lasterror();
  901. $result = -2;
  902. }
  903. $this->db->rollback();
  904. return $result;
  905. }
  906. } else {
  907. $this->db->rollback();
  908. dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
  909. return -3;
  910. }
  911. }
  912. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  913. /**
  914. * Create a contact/address from thirdparty
  915. *
  916. * @param User $user Object user
  917. * @param int $no_email 1=Do not send mailing, 0=Ok to recieve mailling
  918. * @param array $tags Array of tag to affect to contact
  919. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  920. * @return int <0 if KO, >0 if OK
  921. */
  922. public function create_individual(User $user, $no_email = 0, $tags = array(), $notrigger = 0)
  923. {
  924. global $conf;
  925. $error = 0;
  926. $this->db->begin();
  927. // phpcs:enable
  928. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  929. $contact = new Contact($this->db);
  930. $contact->name = $this->name_bis;
  931. $contact->firstname = $this->firstname;
  932. $contact->civility_id = $this->civility_id;
  933. $contact->socid = $this->id; // fk_soc
  934. $contact->statut = 1; // deprecated
  935. $contact->status = 1;
  936. $contact->priv = 0;
  937. $contact->country_id = $this->country_id;
  938. $contact->state_id = $this->state_id;
  939. $contact->address = $this->address;
  940. $contact->email = $this->email;
  941. $contact->zip = $this->zip;
  942. $contact->town = $this->town;
  943. $this->setUpperOrLowerCase();
  944. $contact->phone_pro = $this->phone;
  945. $contactId = $contact->create($user, $notrigger);
  946. if ($contactId < 0) {
  947. $error++;
  948. $this->error = $contact->error;
  949. $this->errors = $contact->errors;
  950. dol_syslog(get_class($this)."::create_individual ERROR:".$this->error, LOG_ERR);
  951. }
  952. if (empty($error) && is_array($tags) && !empty($tags)) {
  953. $result = $contact->setCategories($tags);
  954. if ($result < 0) {
  955. $error++;
  956. $this->error = $contact->error;
  957. $this->errors = array_merge($this->errors, $contact->errors);
  958. dol_syslog(get_class($this)."::create_individual Affect Tag ERROR:".$this->error, LOG_ERR);
  959. $contactId = $result;
  960. }
  961. }
  962. if (empty($error) && isModEnabled('mailing') && !empty($contact->email) && isset($no_email)) {
  963. $result = $contact->setNoEmail($no_email);
  964. if ($result < 0) {
  965. $this->error = $contact->error;
  966. $this->errors = array_merge($this->errors, $contact->errors);
  967. dol_syslog(get_class($this)."::create_individual set mailing status ERROR:".$this->error, LOG_ERR);
  968. $contactId = $result;
  969. }
  970. }
  971. if (empty($error)) {
  972. dol_syslog(get_class($this)."::create_individual success");
  973. $this->db->commit();
  974. } else {
  975. $this->db->rollback();
  976. }
  977. return $contactId;
  978. }
  979. /**
  980. * Check properties of third party are ok (like name, third party codes, ...)
  981. * Used before an add or update.
  982. *
  983. * @return int 0 if OK, <0 if KO
  984. */
  985. public function verify()
  986. {
  987. global $conf, $langs, $mysoc;
  988. $error = 0;
  989. $this->errors = array();
  990. $result = 0;
  991. $this->name = trim($this->name);
  992. $this->nom = $this->name; // For backward compatibility
  993. if (!$this->name) {
  994. $this->errors[] = 'ErrorBadThirdPartyName';
  995. $result = -2;
  996. }
  997. if ($this->client) {
  998. $rescode = $this->check_codeclient();
  999. if ($rescode != 0 && $rescode != -5) {
  1000. if ($rescode == -1) {
  1001. $this->errors[] = 'ErrorBadCustomerCodeSyntax';
  1002. } elseif ($rescode == -2) {
  1003. $this->errors[] = 'ErrorCustomerCodeRequired';
  1004. } elseif ($rescode == -3) {
  1005. $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
  1006. } elseif ($rescode == -4) {
  1007. $this->errors[] = 'ErrorPrefixRequired';
  1008. } else {
  1009. $this->errors[] = 'ErrorUnknownOnCustomerCodeCheck';
  1010. }
  1011. $result = -3;
  1012. }
  1013. }
  1014. if ($this->fournisseur) {
  1015. $rescode = $this->check_codefournisseur();
  1016. if ($rescode != 0 && $rescode != -5) {
  1017. if ($rescode == -1) {
  1018. $this->errors[] = 'ErrorBadSupplierCodeSyntax';
  1019. } elseif ($rescode == -2) {
  1020. $this->errors[] = 'ErrorSupplierCodeRequired';
  1021. } elseif ($rescode == -3) {
  1022. $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
  1023. } elseif ($rescode == -4) {
  1024. $this->errors[] = 'ErrorPrefixRequired';
  1025. } else {
  1026. $this->errors[] = 'ErrorUnknownOnSupplierCodeCheck';
  1027. }
  1028. $result = -3;
  1029. }
  1030. }
  1031. // Check for duplicate or mandatory fields defined into setup
  1032. $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL', 'TVA_INTRA', 'ACCOUNTANCY_CODE_CUSTOMER', 'ACCOUNTANCY_CODE_SUPPLIER');
  1033. foreach ($array_to_check as $key) {
  1034. $keymin = strtolower($key);
  1035. if ($key == 'ACCOUNTANCY_CODE_CUSTOMER') $keymin = 'code_compta';
  1036. elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER') $keymin = 'code_compta_fournisseur';
  1037. $i = (int) preg_replace('/[^0-9]/', '', $key);
  1038. $vallabel = $this->$keymin;
  1039. if ($i > 0) {
  1040. if ($this->isACompany()) {
  1041. // Check for mandatory prof id (but only if country is same than ours)
  1042. if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
  1043. $idprof_mandatory = 'SOCIETE_'.$key.'_MANDATORY';
  1044. if (!$vallabel && getDolGlobalString($idprof_mandatory)) {
  1045. $langs->load("errors");
  1046. $error++;
  1047. $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
  1048. }
  1049. }
  1050. }
  1051. // Check for unicity on profid
  1052. if (!$error && $vallabel && $this->id_prof_verifiable($i)) {
  1053. if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
  1054. $langs->load("errors");
  1055. $error++;
  1056. $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
  1057. }
  1058. }
  1059. } else {
  1060. //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
  1061. //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
  1062. if ($key == 'EMAIL') {
  1063. // Check for mandatory
  1064. if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
  1065. $langs->load("errors");
  1066. $error++;
  1067. $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
  1068. }
  1069. // Check for unicity
  1070. if (!$error && $vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
  1071. if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
  1072. $langs->load("errors");
  1073. $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
  1074. }
  1075. }
  1076. } elseif ($key == 'TVA_INTRA') {
  1077. // Check for unicity
  1078. if ($vallabel && !empty($conf->global->SOCIETE_VAT_INTRA_UNIQUE)) {
  1079. if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
  1080. $langs->load("errors");
  1081. $error++; $this->errors[] = $langs->trans('VATIntra')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
  1082. }
  1083. }
  1084. } elseif ($key == 'ACCOUNTANCY_CODE_CUSTOMER' && !empty($this->client)) {
  1085. // Check for unicity
  1086. if ($vallabel && !empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_UNIQUE)) {
  1087. if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
  1088. $langs->loadLangs(array("errors", 'compta'));
  1089. $error++;
  1090. $this->errors[] = $langs->trans('CustomerAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
  1091. }
  1092. }
  1093. // Check for mandatory
  1094. if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_CUSTOMER_MANDATORY) && (!isset($vallabel) || trim($vallabel) === '')) {
  1095. $langs->loadLangs(array("errors", 'compta'));
  1096. $error++;
  1097. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('CustomerAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
  1098. }
  1099. } elseif ($key == 'ACCOUNTANCY_CODE_SUPPLIER' && !empty($this->fournisseur)) {
  1100. // Check for unicity
  1101. if ($vallabel && !empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_UNIQUE)) {
  1102. if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
  1103. $langs->loadLangs(array("errors", 'compta'));
  1104. $error++;
  1105. $this->errors[] = $langs->trans('SupplierAccountancyCodeShort') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
  1106. }
  1107. }
  1108. // Check for mandatory
  1109. if (!empty($conf->global->SOCIETE_ACCOUNTANCY_CODE_SUPPLIER_MANDATORY) && (!isset($vallabel) || trim($vallabel) === '')) {
  1110. $langs->loadLangs(array("errors", 'compta'));
  1111. $error++;
  1112. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv('SupplierAccountancyCodeShort')) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
  1113. }
  1114. }
  1115. }
  1116. }
  1117. if ($error) {
  1118. $result = -4;
  1119. }
  1120. return $result;
  1121. }
  1122. /**
  1123. * Update parameters of third party
  1124. *
  1125. * @param int $id Id of company (deprecated, use 0 here and call update on an object loaded by a fetch)
  1126. * @param User $user User who requests the update
  1127. * @param int $call_trigger 0=no, 1=yes
  1128. * @param int $allowmodcodeclient Inclut modif code client et code compta
  1129. * @param int $allowmodcodefournisseur Inclut modif code fournisseur et code compta fournisseur
  1130. * @param string $action 'add' or 'update' or 'merge'
  1131. * @param int $nosyncmember Do not synchronize info of linked member
  1132. * @return int <0 if KO, >=0 if OK
  1133. */
  1134. public function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
  1135. {
  1136. global $langs, $conf, $hookmanager;
  1137. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  1138. if (empty($id)) {
  1139. $id = $this->id;
  1140. }
  1141. $error = 0;
  1142. dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
  1143. $now = dol_now();
  1144. // Clean parameters
  1145. $this->id = $id;
  1146. $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
  1147. $this->name = $this->name ? trim($this->name) : trim($this->nom);
  1148. $this->nom = $this->name; // For backward compatibility
  1149. $this->name_alias = trim($this->name_alias);
  1150. $this->ref_ext = trim($this->ref_ext);
  1151. $this->address = $this->address ?trim($this->address) : trim($this->address);
  1152. $this->zip = $this->zip ?trim($this->zip) : trim($this->zip);
  1153. $this->town = $this->town ?trim($this->town) : trim($this->town);
  1154. $this->state_id = trim($this->state_id);
  1155. $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
  1156. $this->phone = trim($this->phone);
  1157. $this->phone = preg_replace("/\s/", "", $this->phone);
  1158. $this->phone = preg_replace("/\./", "", $this->phone);
  1159. $this->fax = trim($this->fax);
  1160. $this->fax = preg_replace("/\s/", "", $this->fax);
  1161. $this->fax = preg_replace("/\./", "", $this->fax);
  1162. $this->email = trim($this->email);
  1163. $this->url = $this->url ?clean_url($this->url, 0) : '';
  1164. $this->note_private = trim($this->note_private);
  1165. $this->note_public = trim($this->note_public);
  1166. $this->idprof1 = trim($this->idprof1);
  1167. $this->idprof2 = trim($this->idprof2);
  1168. $this->idprof3 = trim($this->idprof3);
  1169. $this->idprof4 = trim($this->idprof4);
  1170. $this->idprof5 = (!empty($this->idprof5) ?trim($this->idprof5) : '');
  1171. $this->idprof6 = (!empty($this->idprof6) ?trim($this->idprof6) : '');
  1172. $this->prefix_comm = trim($this->prefix_comm);
  1173. $this->outstanding_limit = price2num($this->outstanding_limit);
  1174. $this->order_min_amount = price2num($this->order_min_amount);
  1175. $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
  1176. $this->tva_assuj = trim($this->tva_assuj);
  1177. $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
  1178. $this->vat_reverse_charge = empty($this->vat_reverse_charge) ? '0' : '1';
  1179. if (empty($this->status)) {
  1180. $this->status = 0;
  1181. }
  1182. if (!empty($this->multicurrency_code)) {
  1183. $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  1184. }
  1185. if (empty($this->fk_multicurrency)) {
  1186. $this->multicurrency_code = '';
  1187. $this->fk_multicurrency = 0;
  1188. }
  1189. // Local taxes
  1190. $this->localtax1_assuj = trim($this->localtax1_assuj);
  1191. $this->localtax2_assuj = trim($this->localtax2_assuj);
  1192. $this->localtax1_value = trim($this->localtax1_value);
  1193. $this->localtax2_value = trim($this->localtax2_value);
  1194. if ($this->capital != '') {
  1195. $this->capital = price2num(trim($this->capital));
  1196. }
  1197. if (!is_numeric($this->capital)) {
  1198. $this->capital = ''; // '' = undef
  1199. }
  1200. $this->effectif_id = trim($this->effectif_id);
  1201. $this->forme_juridique_code = trim($this->forme_juridique_code);
  1202. //Gencod
  1203. $this->barcode = trim($this->barcode);
  1204. // For automatic creation
  1205. if ($this->code_client == -1 || $this->code_client === 'auto') {
  1206. $this->get_codeclient($this, 0);
  1207. }
  1208. if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
  1209. $this->get_codefournisseur($this, 1);
  1210. }
  1211. $this->code_compta_client = trim(empty($this->code_compta) ? $this->code_compta_client : $this->code_compta);
  1212. $this->code_compta = $this->code_compta_client; // for backward compatibility
  1213. $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
  1214. // Check parameters. More tests are done later in the ->verify()
  1215. if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
  1216. $langs->load("errors");
  1217. $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
  1218. return -1;
  1219. }
  1220. $customer = false;
  1221. if (!empty($allowmodcodeclient) && !empty($this->client)) {
  1222. // If $allowmodcodeclient is set and value is not set, we generate it
  1223. if (empty($this->code_compta_client)) {
  1224. $ret = $this->get_codecompta('customer');
  1225. if ($ret < 0) {
  1226. return -1;
  1227. }
  1228. }
  1229. $customer = true;
  1230. }
  1231. $supplier = false;
  1232. if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
  1233. // If $allowmodcodefournisseur is set and value is not set, we generate it
  1234. if (empty($this->code_compta_fournisseur)) {
  1235. $ret = $this->get_codecompta('supplier');
  1236. if ($ret < 0) {
  1237. return -1;
  1238. }
  1239. }
  1240. $supplier = true;
  1241. }
  1242. //Web services
  1243. $this->webservices_url = $this->webservices_url ?clean_url($this->webservices_url, 0) : '';
  1244. $this->webservices_key = trim($this->webservices_key);
  1245. $this->accountancy_code_buy = trim($this->accountancy_code_buy);
  1246. $this->accountancy_code_sell = trim($this->accountancy_code_sell);
  1247. //Incoterms
  1248. $this->fk_incoterms = (int) $this->fk_incoterms;
  1249. $this->location_incoterms = trim($this->location_incoterms);
  1250. $this->db->begin();
  1251. // Check name is required and codes are ok or unique.
  1252. // If error, this->errors[] is filled
  1253. $result = 0;
  1254. if ($action != 'add' && $action != 'merge') {
  1255. // We don't check when update called during a create because verify was already done.
  1256. // For a merge, we suppose source data is clean and a customer code of a deleted thirdparty must be accepted into a target thirdparty with empty code without duplicate error
  1257. $result = $this->verify();
  1258. // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
  1259. // So we can update record that were using and old numbering rule.
  1260. if (is_array($this->errors)) {
  1261. if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
  1262. if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) {
  1263. unset($this->errors[$key]); // Remove error message
  1264. }
  1265. }
  1266. if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
  1267. if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) {
  1268. unset($this->errors[$key]); // Remove error message
  1269. }
  1270. }
  1271. if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
  1272. $result = 0;
  1273. }
  1274. }
  1275. }
  1276. $this->setUpperOrLowerCase();
  1277. if ($result >= 0) {
  1278. dol_syslog(get_class($this)."::update verify ok or not done");
  1279. $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
  1280. $sql .= "entity = ".$this->db->escape($this->entity);
  1281. $sql .= ",nom = '".$this->db->escape($this->name)."'"; // Required
  1282. $sql .= ",name_alias = '".$this->db->escape($this->name_alias)."'";
  1283. $sql .= ",ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  1284. $sql .= ",address = '".$this->db->escape($this->address)."'";
  1285. $sql .= ",zip = ".(!empty($this->zip) ? "'".$this->db->escape($this->zip)."'" : "null");
  1286. $sql .= ",town = ".(!empty($this->town) ? "'".$this->db->escape($this->town)."'" : "null");
  1287. $sql .= ",fk_departement = ".((!empty($this->state_id) && $this->state_id > 0) ? ((int) $this->state_id) : 'null');
  1288. $sql .= ",fk_pays = ".((!empty($this->country_id) && $this->country_id > 0) ? ((int) $this->country_id) : 'null');
  1289. $sql .= ",phone = ".(!empty($this->phone) ? "'".$this->db->escape($this->phone)."'" : "null");
  1290. $sql .= ",fax = ".(!empty($this->fax) ? "'".$this->db->escape($this->fax)."'" : "null");
  1291. $sql .= ",email = ".(!empty($this->email) ? "'".$this->db->escape($this->email)."'" : "null");
  1292. $sql .= ",socialnetworks = '".$this->db->escape(json_encode($this->socialnetworks))."'";
  1293. $sql .= ",url = ".(!empty($this->url) ? "'".$this->db->escape($this->url)."'" : "null");
  1294. $sql .= ",parent = ".($this->parent > 0 ? $this->parent : "null");
  1295. $sql .= ",note_private = ".(!empty($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null");
  1296. $sql .= ",note_public = ".(!empty($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null");
  1297. $sql .= ",siren = '".$this->db->escape($this->idprof1)."'";
  1298. $sql .= ",siret = '".$this->db->escape($this->idprof2)."'";
  1299. $sql .= ",ape = '".$this->db->escape($this->idprof3)."'";
  1300. $sql .= ",idprof4 = '".$this->db->escape($this->idprof4)."'";
  1301. $sql .= ",idprof5 = '".$this->db->escape($this->idprof5)."'";
  1302. $sql .= ",idprof6 = '".$this->db->escape($this->idprof6)."'";
  1303. $sql .= ",tva_assuj = ".($this->tva_assuj != '' ? "'".$this->db->escape($this->tva_assuj)."'" : "null");
  1304. $sql .= ",tva_intra = '".$this->db->escape($this->tva_intra)."'";
  1305. if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  1306. $sql .= ",vat_reverse_charge = " . ($this->vat_reverse_charge != '' ? "'" . $this->db->escape($this->vat_reverse_charge) . "'" : 0);
  1307. }
  1308. $sql .= ",status = ".((int) $this->status);
  1309. // Local taxes
  1310. $sql .= ",localtax1_assuj = ".($this->localtax1_assuj != '' ? "'".$this->db->escape($this->localtax1_assuj)."'" : "null");
  1311. $sql .= ",localtax2_assuj = ".($this->localtax2_assuj != '' ? "'".$this->db->escape($this->localtax2_assuj)."'" : "null");
  1312. if ($this->localtax1_assuj == 1) {
  1313. if ($this->localtax1_value != '') {
  1314. $sql .= ",localtax1_value =".$this->localtax1_value;
  1315. } else {
  1316. $sql .= ",localtax1_value =0.000";
  1317. }
  1318. } else {
  1319. $sql .= ",localtax1_value =0.000";
  1320. }
  1321. if ($this->localtax2_assuj == 1) {
  1322. if ($this->localtax2_value != '') {
  1323. $sql .= ",localtax2_value =".$this->localtax2_value;
  1324. } else {
  1325. $sql .= ",localtax2_value =0.000";
  1326. }
  1327. } else {
  1328. $sql .= ",localtax2_value =0.000";
  1329. }
  1330. $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
  1331. $sql .= ",prefix_comm = ".(!empty($this->prefix_comm) ? "'".$this->db->escape($this->prefix_comm)."'" : "null");
  1332. $sql .= ",fk_effectif = ".($this->effectif_id > 0 ? ((int) $this->effectif_id) : "null");
  1333. if (isset($this->stcomm_id)) {
  1334. $sql .= ",fk_stcomm=".(int) $this->stcomm_id;
  1335. }
  1336. if (isset($this->typent_id)) {
  1337. $sql .= ",fk_typent = ".($this->typent_id > 0 ? ((int) $this->typent_id) : "0");
  1338. }
  1339. $sql .= ",fk_forme_juridique = ".(!empty($this->forme_juridique_code) ? "'".$this->db->escape($this->forme_juridique_code)."'" : "null");
  1340. $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null");
  1341. $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null");
  1342. $sql .= ",deposit_percent = ".(!empty($this->deposit_percent) ? "'".$this->db->escape($this->deposit_percent)."'" : "null");
  1343. $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null");
  1344. $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null");
  1345. $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null");
  1346. $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null");
  1347. $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null");
  1348. $sql .= ",client = ".(!empty($this->client) ? $this->client : 0);
  1349. $sql .= ",fournisseur = ".(!empty($this->fournisseur) ? $this->fournisseur : 0);
  1350. $sql .= ",barcode = ".(!empty($this->barcode) ? "'".$this->db->escape($this->barcode)."'" : "null");
  1351. $sql .= ",default_lang = ".(!empty($this->default_lang) ? "'".$this->db->escape($this->default_lang)."'" : "null");
  1352. $sql .= ",logo = ".(!empty($this->logo) ? "'".$this->db->escape($this->logo)."'" : "null");
  1353. $sql .= ",logo_squarred = ".(!empty($this->logo_squarred) ? "'".$this->db->escape($this->logo_squarred)."'" : "null");
  1354. $sql .= ",outstanding_limit= ".($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
  1355. $sql .= ",order_min_amount= ".($this->order_min_amount != '' ? $this->order_min_amount : 'null');
  1356. $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
  1357. $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
  1358. if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  1359. $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
  1360. $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
  1361. if ($customer) {
  1362. $sql .= ", code_compta = ".(!empty($this->code_compta_client) ? "'".$this->db->escape($this->code_compta_client)."'" : "null");
  1363. }
  1364. if ($supplier) {
  1365. $sql .= ", code_compta_fournisseur = ".(($this->code_compta_fournisseur != "") ? "'".$this->db->escape($this->code_compta_fournisseur)."'" : "null");
  1366. }
  1367. }
  1368. $sql .= ",webservices_url = ".(!empty($this->webservices_url) ? "'".$this->db->escape($this->webservices_url)."'" : "null");
  1369. $sql .= ",webservices_key = ".(!empty($this->webservices_key) ? "'".$this->db->escape($this->webservices_key)."'" : "null");
  1370. //Incoterms
  1371. $sql .= ", fk_incoterms = ".((int) $this->fk_incoterms);
  1372. $sql .= ", location_incoterms = ".(!empty($this->location_incoterms) ? "'".$this->db->escape($this->location_incoterms)."'" : "null");
  1373. if ($customer) {
  1374. $sql .= ", code_client = ".(!empty($this->code_client) ? "'".$this->db->escape($this->code_client)."'" : "null");
  1375. }
  1376. if ($supplier) {
  1377. $sql .= ", code_fournisseur = ".(!empty($this->code_fournisseur) ? "'".$this->db->escape($this->code_fournisseur)."'" : "null");
  1378. }
  1379. $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : "null");
  1380. $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
  1381. $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
  1382. $sql .= ", model_pdf = '".$this->db->escape($this->model_pdf)."'";
  1383. $sql .= " WHERE rowid = ".(int) $id;
  1384. $resql = $this->db->query($sql);
  1385. if ($resql) {
  1386. if (is_object($this->oldcopy)) { // If we have information on old values
  1387. if ($this->oldcopy->country_id != $this->country_id) {
  1388. unset($this->country_code);
  1389. unset($this->country);
  1390. }
  1391. if ($this->oldcopy->state_id != $this->state_id) {
  1392. unset($this->state_code);
  1393. unset($this->state);
  1394. }
  1395. } else {
  1396. unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
  1397. unset($this->country);
  1398. unset($this->state_code);
  1399. unset($this->state);
  1400. }
  1401. $nbrowsaffected = $this->db->affected_rows($resql);
  1402. if (!$error && $nbrowsaffected) {
  1403. // Update information on linked member if it is an update
  1404. if (!$nosyncmember && isModEnabled('adherent')) {
  1405. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  1406. dol_syslog(get_class($this)."::update update linked member");
  1407. $lmember = new Adherent($this->db);
  1408. $result = $lmember->fetch(0, 0, $this->id);
  1409. if ($result > 0) {
  1410. $lmember->company = $this->name;
  1411. //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
  1412. //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
  1413. $lmember->address = $this->address;
  1414. $lmember->zip = $this->zip;
  1415. $lmember->town = $this->town;
  1416. $lmember->email = $this->email;
  1417. $lmember->socialnetworks = $this->socialnetworks;
  1418. $lmember->phone = $this->phone;
  1419. $lmember->state_id = $this->state_id;
  1420. $lmember->country_id = $this->country_id;
  1421. $lmember->default_lang = $this->default_lang;
  1422. $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
  1423. if ($result < 0) {
  1424. $this->error = $lmember->error;
  1425. $this->errors = array_merge($this->errors, $lmember->errors);
  1426. dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
  1427. $error++;
  1428. }
  1429. } elseif ($result < 0) {
  1430. $this->error = $lmember->error;
  1431. $error++;
  1432. }
  1433. }
  1434. }
  1435. $action = 'update';
  1436. // update accountancy for this entity
  1437. if (!$error && !empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  1438. $this->db->query("DELETE FROM ".MAIN_DB_PREFIX."societe_perentity WHERE fk_soc = ".((int) $this->id)." AND entity = ".((int) $conf->entity));
  1439. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_perentity (";
  1440. $sql .= " fk_soc";
  1441. $sql .= ", entity";
  1442. $sql .= ", vat_reverse_charge";
  1443. $sql .= ", accountancy_code_customer";
  1444. $sql .= ", accountancy_code_supplier";
  1445. $sql .= ", accountancy_code_buy";
  1446. $sql .= ", accountancy_code_sell";
  1447. $sql .= ") VALUES (";
  1448. $sql .= $this->id;
  1449. $sql .= ", ".$conf->entity;
  1450. $sql .= ", ".(empty($this->vat_reverse_charge) ? '0' : '1');
  1451. $sql .= ", '".$this->db->escape($this->code_compta_client)."'";
  1452. $sql .= ", '".$this->db->escape($this->code_compta_fournisseur)."'";
  1453. $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
  1454. $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
  1455. $sql .= ")";
  1456. $result = $this->db->query($sql);
  1457. if (!$result) {
  1458. $error++;
  1459. $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
  1460. }
  1461. }
  1462. // Actions on extra fields
  1463. if (!$error) {
  1464. $result = $this->insertExtraFields();
  1465. if ($result < 0) {
  1466. $error++;
  1467. }
  1468. }
  1469. // Actions on extra languages
  1470. if (!$error && empty($conf->global->MAIN_EXTRALANGUAGES_DISABLED)) { // For avoid conflicts if trigger used
  1471. $result = $this->insertExtraLanguages();
  1472. if ($result < 0) {
  1473. $error++;
  1474. }
  1475. }
  1476. if (!$error && $call_trigger) {
  1477. // Call trigger
  1478. $result = $this->call_trigger('COMPANY_MODIFY', $user);
  1479. if ($result < 0) {
  1480. $error++;
  1481. }
  1482. // End call triggers
  1483. }
  1484. if (!$error) {
  1485. dol_syslog(get_class($this)."::Update success");
  1486. $this->db->commit();
  1487. return 1;
  1488. } else {
  1489. $this->db->rollback();
  1490. return -1;
  1491. }
  1492. } else {
  1493. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1494. // Doublon
  1495. $this->error = $langs->trans("ErrorDuplicateField");
  1496. $result = -1;
  1497. } else {
  1498. $this->error = $this->db->lasterror();
  1499. $result = -2;
  1500. }
  1501. $this->db->rollback();
  1502. return $result;
  1503. }
  1504. } else {
  1505. $this->db->rollback();
  1506. dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
  1507. return -3;
  1508. }
  1509. }
  1510. /**
  1511. * Load a third party from database into memory
  1512. *
  1513. * @param int $rowid Id of third party to load
  1514. * @param string $ref Reference of third party, name (Warning, this can return several records)
  1515. * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr)
  1516. * @param string $barcode Barcode of third party to load
  1517. * @param string $idprof1 Prof id 1 of third party (Warning, this can return several records)
  1518. * @param string $idprof2 Prof id 2 of third party (Warning, this can return several records)
  1519. * @param string $idprof3 Prof id 3 of third party (Warning, this can return several records)
  1520. * @param string $idprof4 Prof id 4 of third party (Warning, this can return several records)
  1521. * @param string $idprof5 Prof id 5 of third party (Warning, this can return several records)
  1522. * @param string $idprof6 Prof id 6 of third party (Warning, this can return several records)
  1523. * @param string $email Email of third party (Warning, this can return several records)
  1524. * @param string $ref_alias Name_alias of third party (Warning, this can return several records)
  1525. * @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
  1526. */
  1527. public function fetch($rowid, $ref = '', $ref_ext = '', $barcode = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
  1528. {
  1529. global $langs;
  1530. global $conf;
  1531. if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($barcode) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) {
  1532. return -1;
  1533. }
  1534. $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.address, s.datec as date_creation, s.prefix_comm';
  1535. $sql .= ', s.status, s.fk_warehouse';
  1536. $sql .= ', s.price_level';
  1537. $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
  1538. $sql .= ', s.phone, s.fax, s.email';
  1539. $sql .= ', s.socialnetworks';
  1540. $sql .= ', s.url, s.zip, s.town, s.note_private, s.note_public, s.client, s.fournisseur';
  1541. $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
  1542. $sql .= ', s.capital, s.tva_intra';
  1543. $sql .= ', s.fk_typent as typent_id';
  1544. $sql .= ', s.fk_effectif as effectif_id';
  1545. $sql .= ', s.fk_forme_juridique as forme_juridique_code';
  1546. $sql .= ', s.webservices_url, s.webservices_key, s.model_pdf, s.last_main_doc';
  1547. if (empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  1548. $sql .= ', s.code_compta, s.code_compta_fournisseur, s.accountancy_code_buy, s.accountancy_code_sell';
  1549. $sql .= ', s.vat_reverse_charge as soc_vat_reverse_charge';
  1550. } else {
  1551. $sql .= ', spe.accountancy_code_customer as code_compta, spe.accountancy_code_supplier as code_compta_fournisseur, spe.accountancy_code_buy, spe.accountancy_code_sell';
  1552. $sql .= ', spe.vat_reverse_charge as spe_vat_reverse_charge';
  1553. }
  1554. $sql .= ', s.code_client, s.code_fournisseur, s.parent, s.barcode';
  1555. $sql .= ', s.fk_departement as state_id, s.fk_pays as country_id, s.fk_stcomm, s.mode_reglement, s.cond_reglement, s.deposit_percent, s.transport_mode';
  1556. $sql .= ', s.fk_account, s.tva_assuj';
  1557. $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.transport_mode_supplier';
  1558. $sql .= ', s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo, s.logo_squarred';
  1559. $sql .= ', s.fk_shipping_method';
  1560. $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
  1561. $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
  1562. $sql .= ', s.fk_multicurrency, s.multicurrency_code';
  1563. $sql .= ', fj.libelle as forme_juridique';
  1564. $sql .= ', e.libelle as effectif';
  1565. $sql .= ', c.code as country_code, c.label as country';
  1566. $sql .= ', d.code_departement as state_code, d.nom as state';
  1567. $sql .= ', r.rowid as region_id, r.code_region as region_code';
  1568. $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto';
  1569. $sql .= ', te.code as typent_code';
  1570. $sql .= ', i.libelle as label_incoterms';
  1571. if (!isModEnabled('multicompany')) {
  1572. $sql .= ', s.remise_client, s.remise_supplier';
  1573. } else {
  1574. $sql .= ', sr.remise_client, sr2.remise_supplier';
  1575. }
  1576. $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
  1577. if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  1578. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = ".((int) $conf->entity);
  1579. }
  1580. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
  1581. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
  1582. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
  1583. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
  1584. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
  1585. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.code_region ';
  1586. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
  1587. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
  1588. // With default setup, llx_societe_remise is a history table in default setup and current value is in llx_societe.
  1589. // We use it for real value when multicompany is on. A better place would be into llx_societe_perentity.
  1590. if (isModEnabled('multicompany')) {
  1591. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_remise as sr ON sr.rowid = (SELECT MAX(rowid) FROM '.MAIN_DB_PREFIX.'societe_remise WHERE fk_soc = s.rowid AND entity IN ('.getEntity('discount').'))';
  1592. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_remise_supplier as sr2 ON sr2.rowid = (SELECT MAX(rowid) FROM '.MAIN_DB_PREFIX.'societe_remise_supplier WHERE fk_soc = s.rowid AND entity IN ('.getEntity('discount').'))';
  1593. }
  1594. $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
  1595. if ($rowid) {
  1596. $sql .= ' AND s.rowid = '.((int) $rowid);
  1597. }
  1598. if ($ref) {
  1599. $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
  1600. }
  1601. if ($ref_alias) {
  1602. $sql .= " AND s.name_alias = '".$this->db->escape($ref_alias)."'";
  1603. }
  1604. if ($ref_ext) {
  1605. $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
  1606. }
  1607. if ($barcode) {
  1608. $sql .= " AND s.barcode = '".$this->db->escape($barcode)."'";
  1609. }
  1610. if ($idprof1) {
  1611. $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
  1612. }
  1613. if ($idprof2) {
  1614. $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
  1615. }
  1616. if ($idprof3) {
  1617. $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
  1618. }
  1619. if ($idprof4) {
  1620. $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
  1621. }
  1622. if ($idprof5) {
  1623. $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
  1624. }
  1625. if ($idprof6) {
  1626. $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
  1627. }
  1628. if ($email) {
  1629. $sql .= " AND s.email = '".$this->db->escape($email)."'";
  1630. }
  1631. $resql = $this->db->query($sql);
  1632. if ($resql) {
  1633. $num = $this->db->num_rows($resql);
  1634. if ($num > 1) {
  1635. $this->error = 'Fetch found several records. Rename one of thirdparties to avoid duplicate.';
  1636. dol_syslog($this->error, LOG_ERR);
  1637. $result = -2;
  1638. } elseif ($num) { // $num = 1
  1639. $obj = $this->db->fetch_object($resql);
  1640. $this->id = $obj->rowid;
  1641. $this->entity = $obj->entity;
  1642. $this->canvas = $obj->canvas;
  1643. $this->ref = $obj->rowid;
  1644. $this->name = $obj->name;
  1645. $this->nom = $obj->name; // deprecated
  1646. $this->name_alias = $obj->name_alias;
  1647. $this->ref_ext = $obj->ref_ext;
  1648. $this->date_creation = $this->db->jdate($obj->date_creation);
  1649. $this->date_modification = $this->db->jdate($obj->date_modification);
  1650. $this->user_creation = $obj->fk_user_creat;
  1651. $this->user_modification = $obj->fk_user_modif;
  1652. $this->address = $obj->address;
  1653. $this->zip = $obj->zip;
  1654. $this->town = $obj->town;
  1655. $this->country_id = $obj->country_id;
  1656. $this->country_code = $obj->country_id ? $obj->country_code : '';
  1657. $this->country = $obj->country_id ? (($langs->transnoentities('Country'.$obj->country_code) != 'Country'.$obj->country_code) ? $langs->transnoentities('Country'.$obj->country_code) : $obj->country) : '';
  1658. $this->state_id = $obj->state_id;
  1659. $this->state_code = $obj->state_code;
  1660. $this->region_id = $obj->region_id;
  1661. $this->region_code = $obj->region_code;
  1662. $this->state = ($obj->state != '-' ? $obj->state : '');
  1663. $transcode = $langs->trans('StatusProspect'.$obj->fk_stcomm);
  1664. $label = ($transcode != 'StatusProspect'.$obj->fk_stcomm ? $transcode : $obj->stcomm);
  1665. $this->stcomm_id = $obj->fk_stcomm; // id status prospect
  1666. $this->status_prospect_label = $label; // label status prospect
  1667. $this->stcomm_picto = $obj->stcomm_picto; // picto statut commercial
  1668. $this->email = $obj->email;
  1669. $this->socialnetworks = ($obj->socialnetworks ? (array) json_decode($obj->socialnetworks, true) : array());
  1670. $this->url = $obj->url;
  1671. $this->phone = $obj->phone;
  1672. $this->fax = $obj->fax;
  1673. $this->parent = $obj->parent;
  1674. $this->idprof1 = $obj->idprof1;
  1675. $this->idprof2 = $obj->idprof2;
  1676. $this->idprof3 = $obj->idprof3;
  1677. $this->idprof4 = $obj->idprof4;
  1678. $this->idprof5 = $obj->idprof5;
  1679. $this->idprof6 = $obj->idprof6;
  1680. $this->capital = $obj->capital;
  1681. $this->code_client = $obj->code_client;
  1682. $this->code_fournisseur = $obj->code_fournisseur;
  1683. $this->code_compta = $obj->code_compta; // For backward compatibility
  1684. $this->code_compta_client = $obj->code_compta;
  1685. $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
  1686. $this->barcode = $obj->barcode;
  1687. $this->tva_assuj = $obj->tva_assuj;
  1688. $this->tva_intra = $obj->tva_intra;
  1689. if (!empty($obj->spe_vat_reverse_charge)) {
  1690. $this->vat_reverse_charge = $obj->spe_vat_reverse_charge;
  1691. } elseif (!empty($obj->soc_vat_reverse_charge)) {
  1692. $this->vat_reverse_charge = $obj->soc_vat_reverse_charge;
  1693. } else {
  1694. $this->vat_reverse_charge = 0;
  1695. }
  1696. $this->status = $obj->status;
  1697. // Local Taxes
  1698. $this->localtax1_assuj = $obj->localtax1_assuj;
  1699. $this->localtax2_assuj = $obj->localtax2_assuj;
  1700. $this->localtax1_value = $obj->localtax1_value;
  1701. $this->localtax2_value = $obj->localtax2_value;
  1702. $this->typent_id = $obj->typent_id;
  1703. $this->typent_code = $obj->typent_code;
  1704. $this->effectif_id = $obj->effectif_id;
  1705. $this->effectif = $obj->effectif_id ? $obj->effectif : '';
  1706. $this->forme_juridique_code = $obj->forme_juridique_code;
  1707. $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
  1708. $this->fk_prospectlevel = $obj->fk_prospectlevel;
  1709. $this->prefix_comm = $obj->prefix_comm;
  1710. $this->remise_percent = $obj->remise_client ? price2num($obj->remise_client) : 0; // 0.000000 must be 0
  1711. $this->remise_supplier_percent = $obj->remise_supplier;
  1712. $this->mode_reglement_id = $obj->mode_reglement;
  1713. $this->cond_reglement_id = $obj->cond_reglement;
  1714. $this->deposit_percent = $obj->deposit_percent;
  1715. $this->transport_mode_id = $obj->transport_mode;
  1716. $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
  1717. $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
  1718. $this->transport_mode_supplier_id = $obj->transport_mode_supplier;
  1719. $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
  1720. $this->fk_account = $obj->fk_account;
  1721. $this->client = $obj->client;
  1722. $this->fournisseur = $obj->fournisseur;
  1723. $this->note = $obj->note_private; // TODO Deprecated for backward comtability
  1724. $this->note_private = $obj->note_private;
  1725. $this->note_public = $obj->note_public;
  1726. $this->model_pdf = $obj->model_pdf;
  1727. $this->default_lang = $obj->default_lang;
  1728. $this->logo = $obj->logo;
  1729. $this->logo_squarred = $obj->logo_squarred;
  1730. $this->webservices_url = $obj->webservices_url;
  1731. $this->webservices_key = $obj->webservices_key;
  1732. $this->accountancy_code_buy = $obj->accountancy_code_buy;
  1733. $this->accountancy_code_sell = $obj->accountancy_code_sell;
  1734. $this->outstanding_limit = $obj->outstanding_limit;
  1735. $this->order_min_amount = $obj->order_min_amount;
  1736. $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
  1737. // multiprix
  1738. $this->price_level = $obj->price_level;
  1739. // warehouse
  1740. $this->fk_warehouse = $obj->fk_warehouse;
  1741. $this->import_key = $obj->import_key;
  1742. //Incoterms
  1743. $this->fk_incoterms = $obj->fk_incoterms;
  1744. $this->location_incoterms = $obj->location_incoterms;
  1745. $this->label_incoterms = $obj->label_incoterms;
  1746. // multicurrency
  1747. $this->fk_multicurrency = $obj->fk_multicurrency;
  1748. $this->multicurrency_code = $obj->multicurrency_code;
  1749. // pdf
  1750. $this->model_pdf = $obj->model_pdf;
  1751. $this->last_main_doc = $obj->last_main_doc;
  1752. $result = 1;
  1753. // fetch optionals attributes and labels
  1754. $this->fetch_optionals();
  1755. } else {
  1756. $result = 0;
  1757. }
  1758. $this->db->free($resql);
  1759. } else {
  1760. $this->error = $this->db->lasterror();
  1761. $this->errors[] = $this->db->lasterror();
  1762. $result = -3;
  1763. }
  1764. // Use first price level if level not defined for third party
  1765. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) {
  1766. $this->price_level = 1;
  1767. }
  1768. return $result;
  1769. }
  1770. /**
  1771. * Delete a third party from database and all its dependencies (contacts, rib...)
  1772. *
  1773. * @param int $id Id of third party to delete
  1774. * @param User|null $fuser User who ask to delete thirdparty
  1775. * @param int $call_trigger 0=No, 1=yes
  1776. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1777. */
  1778. public function delete($id, User $fuser = null, $call_trigger = 1)
  1779. {
  1780. global $langs, $conf, $user;
  1781. if (empty($fuser)) {
  1782. $fuser = $user;
  1783. }
  1784. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1785. $entity = isset($this->entity) ? $this->entity : $conf->entity;
  1786. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1787. $error = 0;
  1788. // Test if child exists
  1789. $objectisused = $this->isObjectUsed($id);
  1790. if (empty($objectisused)) {
  1791. $this->db->begin();
  1792. // User is mandatory for trigger call
  1793. if (!$error && $call_trigger) {
  1794. // Call trigger
  1795. $result = $this->call_trigger('COMPANY_DELETE', $fuser);
  1796. if ($result < 0) {
  1797. $error++;
  1798. }
  1799. // End call triggers
  1800. }
  1801. if (!$error) {
  1802. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1803. $static_cat = new Categorie($this->db);
  1804. $toute_categs = array();
  1805. // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
  1806. if ($this->client || $this->prospect) {
  1807. $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
  1808. }
  1809. if ($this->fournisseur) {
  1810. $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
  1811. }
  1812. // Remove each "Categorie"
  1813. foreach ($toute_categs as $type => $categs_type) {
  1814. foreach ($categs_type as $cat) {
  1815. $cat->del_type($this, $type);
  1816. }
  1817. }
  1818. }
  1819. if (!$error) {
  1820. foreach ($this->childtablesoncascade as $tabletodelete) {
  1821. $deleteFromObject = explode(':', $tabletodelete);
  1822. if (count($deleteFromObject) >= 2) {
  1823. $className = str_replace('@', '', $deleteFromObject[0]);
  1824. $filepath = $deleteFromObject[1];
  1825. $columnName = $deleteFromObject[2];
  1826. if (dol_include_once($filepath)) {
  1827. $child_object = new $className($this->db);
  1828. $result = $child_object->deleteByParentField($id, $columnName);
  1829. if ($result < 0) {
  1830. $error++;
  1831. $this->errors[] = $child_object->error;
  1832. break;
  1833. }
  1834. } else {
  1835. $error++;
  1836. $this->errors[] = 'Cannot include child class file '.$filepath;
  1837. break;
  1838. }
  1839. } else {
  1840. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
  1841. $sql .= " WHERE fk_soc = ".((int) $id);
  1842. if (!$this->db->query($sql)) {
  1843. $error++;
  1844. $this->errors[] = $this->db->lasterror();
  1845. break;
  1846. }
  1847. }
  1848. }
  1849. }
  1850. // Removed extrafields
  1851. if (!$error) {
  1852. $result = $this->deleteExtraFields();
  1853. if ($result < 0) {
  1854. $error++;
  1855. dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
  1856. }
  1857. }
  1858. // Remove links to subsidiaries companies
  1859. if (!$error) {
  1860. $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
  1861. $sql .= " SET parent = NULL";
  1862. $sql .= " WHERE parent = ".((int) $id);
  1863. if (!$this->db->query($sql)) {
  1864. $error++;
  1865. $this->errors[] = $this->db->lasterror();
  1866. }
  1867. }
  1868. // Remove third party
  1869. if (!$error) {
  1870. if (!empty($conf->global->MAIN_COMPANY_PERENTITY_SHARED)) {
  1871. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_perentity";
  1872. $sql .= " WHERE fk_soc = ".((int) $id);
  1873. if (!$this->db->query($sql)) {
  1874. $error++;
  1875. $this->errors[] = $this->db->lasterror();
  1876. }
  1877. }
  1878. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
  1879. $sql .= " WHERE rowid = ".((int) $id);
  1880. if (!$this->db->query($sql)) {
  1881. $error++;
  1882. $this->errors[] = $this->db->lasterror();
  1883. }
  1884. }
  1885. if (!$error) {
  1886. $this->db->commit();
  1887. // Delete directory
  1888. if (!empty($conf->societe->multidir_output[$entity])) {
  1889. $docdir = $conf->societe->multidir_output[$entity]."/".$id;
  1890. if (dol_is_dir($docdir)) {
  1891. dol_delete_dir_recursive($docdir);
  1892. }
  1893. }
  1894. return 1;
  1895. } else {
  1896. dol_syslog($this->error, LOG_ERR);
  1897. $this->db->rollback();
  1898. return -1;
  1899. }
  1900. } else {
  1901. dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
  1902. }
  1903. return 0;
  1904. }
  1905. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1906. /**
  1907. * Define third party as a customer
  1908. *
  1909. * @return int <0 if KO, >0 if OK
  1910. * @deprecated
  1911. * @see setAsCustomer()
  1912. */
  1913. public function set_as_client()
  1914. {
  1915. global $conf;
  1916. // phpcs:enable
  1917. dol_syslog(get_class($this)."::set_as_client is deprecated use setAsCustomer instead", LOG_NOTICE);
  1918. return $this->setAsCustomer();
  1919. }
  1920. /**
  1921. * Define third party as a customer
  1922. *
  1923. * @return int <0 if KO, >0 if OK
  1924. * @since dolibarr v19
  1925. */
  1926. public function setAsCustomer()
  1927. {
  1928. if ($this->id) {
  1929. $newclient = 1;
  1930. if (($this->client == 2 || $this->client == 3) && !getDolGlobalInt('SOCIETE_DISABLE_PROSPECTSCUSTOMERS')) {
  1931. $newclient = 3; //If prospect, we keep prospect tag
  1932. }
  1933. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  1934. $sql .= " SET client = ".((int) $newclient);
  1935. $sql .= " WHERE rowid = ".((int) $this->id);
  1936. $resql = $this->db->query($sql);
  1937. if ($resql) {
  1938. $this->client = $newclient;
  1939. return 1;
  1940. } else {
  1941. return -1;
  1942. }
  1943. }
  1944. return 0;
  1945. }
  1946. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1947. /**
  1948. * Defines the company as a customer
  1949. *
  1950. * @param float $remise Value in % of the discount
  1951. * @param string $note Note/Reason for changing the discount
  1952. * @param User $user User who sets the discount
  1953. * @return int <0 if KO, >0 if OK
  1954. */
  1955. public function set_remise_client($remise, $note, User $user)
  1956. {
  1957. // phpcs:enable
  1958. global $conf, $langs;
  1959. // Parameter cleaning
  1960. $note = trim($note);
  1961. if (!$note) {
  1962. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
  1963. return -2;
  1964. }
  1965. dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
  1966. if ($this->id) {
  1967. $this->db->begin();
  1968. $now = dol_now();
  1969. // Position current discount
  1970. $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
  1971. $sql .= " SET remise_client = '".$this->db->escape($remise)."'";
  1972. $sql .= " WHERE rowid = ".((int) $this->id);
  1973. $resql = $this->db->query($sql);
  1974. if (!$resql) {
  1975. $this->db->rollback();
  1976. $this->error = $this->db->error();
  1977. return -1;
  1978. }
  1979. // Writes trace in discount history
  1980. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
  1981. $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
  1982. $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
  1983. $sql .= " '".$this->db->escape($note)."',";
  1984. $sql .= " ".((int) $user->id);
  1985. $sql .= ")";
  1986. $resql = $this->db->query($sql);
  1987. if (!$resql) {
  1988. $this->db->rollback();
  1989. $this->error = $this->db->lasterror();
  1990. return -1;
  1991. }
  1992. $this->db->commit();
  1993. return 1;
  1994. }
  1995. return -1;
  1996. }
  1997. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1998. /**
  1999. * Defines the company as a customer
  2000. *
  2001. * @param float $remise Value in % of the discount
  2002. * @param string $note Note/Reason for changing the discount
  2003. * @param User $user User who sets the discount
  2004. * @return int <0 if KO, >0 if OK
  2005. */
  2006. public function set_remise_supplier($remise, $note, User $user)
  2007. {
  2008. // phpcs:enable
  2009. global $conf, $langs;
  2010. // Parameter cleaning
  2011. $note = trim($note);
  2012. if (!$note) {
  2013. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("NoteReason"));
  2014. return -2;
  2015. }
  2016. dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
  2017. if ($this->id) {
  2018. $this->db->begin();
  2019. $now = dol_now();
  2020. // Position current discount
  2021. $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
  2022. $sql .= " SET remise_supplier = '".$this->db->escape($remise)."'";
  2023. $sql .= " WHERE rowid = ".((int) $this->id);
  2024. $resql = $this->db->query($sql);
  2025. if (!$resql) {
  2026. $this->db->rollback();
  2027. $this->error = $this->db->error();
  2028. return -1;
  2029. }
  2030. // Writes trace in discount history
  2031. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
  2032. $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
  2033. $sql .= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".((int) $this->id).", '".$this->db->escape($remise)."',";
  2034. $sql .= " '".$this->db->escape($note)."',";
  2035. $sql .= " ".((int) $user->id);
  2036. $sql .= ")";
  2037. $resql = $this->db->query($sql);
  2038. if (!$resql) {
  2039. $this->db->rollback();
  2040. $this->error = $this->db->lasterror();
  2041. return -1;
  2042. }
  2043. $this->db->commit();
  2044. return 1;
  2045. }
  2046. return -1;
  2047. }
  2048. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2049. /**
  2050. * Add a discount for third party
  2051. *
  2052. * @param float $remise Amount of discount
  2053. * @param User $user User adding discount
  2054. * @param string $desc Reason of discount
  2055. * @param string $vatrate VAT rate (may contain the vat code too). Exemple: '1.23', '1.23 (ABC)', ...
  2056. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  2057. * @param string $price_base_type Price base type 'HT' or 'TTC'
  2058. * @return int <0 if KO, id of discount record if OK
  2059. */
  2060. public function set_remise_except($remise, User $user, $desc, $vatrate = '', $discount_type = 0, $price_base_type = 'HT')
  2061. {
  2062. // phpcs:enable
  2063. global $langs;
  2064. // Clean parameters
  2065. $remise = price2num($remise);
  2066. $desc = trim($desc);
  2067. // Check parameters
  2068. if (!($remise > 0)) {
  2069. $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
  2070. return -1;
  2071. }
  2072. if (!$desc) {
  2073. $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
  2074. return -2;
  2075. }
  2076. if ($this->id > 0) {
  2077. // Clean vat code
  2078. $reg = array();
  2079. $vat_src_code = '';
  2080. if (preg_match('/\((.*)\)/', $vatrate, $reg)) {
  2081. $vat_src_code = $reg[1];
  2082. $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate.
  2083. }
  2084. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  2085. $discount = new DiscountAbsolute($this->db);
  2086. $discount->fk_soc = $this->id;
  2087. $discount->discount_type = $discount_type;
  2088. if ($price_base_type == 'TTC') {
  2089. $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($remise, 'MT');
  2090. $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise / (1 + $vatrate / 100), 'MT');
  2091. $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($discount->amount_ttc - $discount->amount_ht, 'MT');
  2092. } else {
  2093. $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
  2094. $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $vatrate / 100, 'MT');
  2095. $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
  2096. }
  2097. $discount->tva_tx = price2num($vatrate);
  2098. $discount->vat_src_code = $vat_src_code;
  2099. $discount->description = $desc;
  2100. $result = $discount->create($user);
  2101. if ($result > 0) {
  2102. return $result;
  2103. } else {
  2104. $this->error = $discount->error;
  2105. return -3;
  2106. }
  2107. } else {
  2108. return 0;
  2109. }
  2110. }
  2111. /**
  2112. * Returns amount of included taxes of the current discounts/credits available from the company
  2113. *
  2114. * @param User $user Filter on a user author of discounts
  2115. * @param string $filter Other filter
  2116. * @param integer $maxvalue Filter on max value for discount
  2117. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  2118. * @return int <0 if KO, Credit note amount otherwise
  2119. */
  2120. public function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
  2121. {
  2122. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  2123. $discountstatic = new DiscountAbsolute($this->db);
  2124. $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
  2125. if ($result >= 0) {
  2126. return $result;
  2127. } else {
  2128. $this->error = $discountstatic->error;
  2129. return -1;
  2130. }
  2131. }
  2132. /**
  2133. * Return array of sales representatives
  2134. *
  2135. * @param User $user Object user (not used)
  2136. * @param int $mode 0=Array with properties, 1=Array of id.
  2137. * @param string $sortfield List of sort fields, separated by comma. Example: 't1.fielda,t2.fieldb'
  2138. * @param string $sortorder Sort order, separated by comma. Example: 'ASC,DESC';
  2139. * @return array|int Array of sales representatives of third party or <0 if KO
  2140. */
  2141. public function getSalesRepresentatives(User $user, $mode = 0, $sortfield = null, $sortorder = null)
  2142. {
  2143. global $conf;
  2144. $reparray = array();
  2145. $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.office_phone, u.job, u.email, u.statut as status, u.entity, u.photo, u.gender";
  2146. $sql .= ", u.office_fax, u.user_mobile, u.personal_mobile";
  2147. $sql .= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
  2148. if (isModEnabled('multicompany') && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
  2149. $sql .= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
  2150. $sql .= " WHERE ((ug.fk_user = sc.fk_user";
  2151. $sql .= " AND ug.entity = ".$conf->entity.")";
  2152. $sql .= " OR u.admin = 1)";
  2153. } else {
  2154. $sql .= " WHERE entity in (0, ".$conf->entity.")";
  2155. }
  2156. $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".((int) $this->id);
  2157. if (empty($sortfield) && empty($sortorder)) {
  2158. $sortfield = 'u.lastname,u.firstname';
  2159. $sortorder = 'ASC,ASC';
  2160. }
  2161. $sql .= $this->db->order($sortfield, $sortorder);
  2162. $resql = $this->db->query($sql);
  2163. if ($resql) {
  2164. $num = $this->db->num_rows($resql);
  2165. $i = 0;
  2166. while ($i < $num) {
  2167. $obj = $this->db->fetch_object($resql);
  2168. if (empty($mode)) {
  2169. $reparray[$i]['id'] = $obj->rowid;
  2170. $reparray[$i]['lastname'] = $obj->lastname;
  2171. $reparray[$i]['firstname'] = $obj->firstname;
  2172. $reparray[$i]['email'] = $obj->email;
  2173. $reparray[$i]['phone'] = $obj->office_phone;
  2174. $reparray[$i]['office_phone'] = $obj->office_phone; // Pro phone
  2175. $reparray[$i]['office_fax'] = $obj->office_fax;
  2176. $reparray[$i]['user_mobile'] = $obj->user_mobile; // Pro mobile
  2177. $reparray[$i]['personal_mobile'] = $obj->personal_mobile; // Personal mobile
  2178. $reparray[$i]['job'] = $obj->job;
  2179. $reparray[$i]['statut'] = $obj->status; // deprecated
  2180. $reparray[$i]['status'] = $obj->status;
  2181. $reparray[$i]['entity'] = $obj->entity;
  2182. $reparray[$i]['login'] = $obj->login;
  2183. $reparray[$i]['photo'] = $obj->photo;
  2184. $reparray[$i]['gender'] = $obj->gender;
  2185. } else {
  2186. $reparray[] = $obj->rowid;
  2187. }
  2188. $i++;
  2189. }
  2190. return $reparray;
  2191. } else {
  2192. dol_print_error($this->db);
  2193. return -1;
  2194. }
  2195. }
  2196. /**
  2197. * Set the price level
  2198. *
  2199. * @param int $price_level Level of price
  2200. * @param User $user Use making change
  2201. * @return int <0 if KO, >0 if OK
  2202. */
  2203. public function setPriceLevel($price_level, User $user)
  2204. {
  2205. if ($this->id) {
  2206. $now = dol_now();
  2207. $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
  2208. $sql .= " SET price_level = ".((int) $price_level);
  2209. $sql .= " WHERE rowid = ".((int) $this->id);
  2210. if (!$this->db->query($sql)) {
  2211. dol_print_error($this->db);
  2212. return -1;
  2213. }
  2214. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
  2215. $sql .= " (datec, fk_soc, price_level, fk_user_author)";
  2216. $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $price_level).", ".((int) $user->id).")";
  2217. if (!$this->db->query($sql)) {
  2218. dol_print_error($this->db);
  2219. return -1;
  2220. }
  2221. return 1;
  2222. }
  2223. return -1;
  2224. }
  2225. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2226. /**
  2227. * Add link to sales representative
  2228. *
  2229. * @param User $user Object user
  2230. * @param int $commid Id of user
  2231. * @return int <=0 if KO, >0 if OK
  2232. */
  2233. public function add_commercial(User $user, $commid)
  2234. {
  2235. // phpcs:enable
  2236. $error = 0;
  2237. if ($this->id > 0 && $commid > 0) {
  2238. $this->db->begin();
  2239. if (!$error) {
  2240. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
  2241. $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
  2242. $resql = $this->db->query($sql);
  2243. if (!$resql) {
  2244. dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
  2245. $error++;
  2246. }
  2247. }
  2248. if (!$error) {
  2249. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
  2250. $sql .= " (fk_soc, fk_user)";
  2251. $sql .= " VALUES (".((int) $this->id).", ".((int) $commid).")";
  2252. $resql = $this->db->query($sql);
  2253. if (!$resql) {
  2254. dol_syslog(get_class($this)."::add_commercial Error ".$this->db->lasterror());
  2255. $error++;
  2256. }
  2257. }
  2258. if (!$error) {
  2259. $this->context = array('commercial_modified' => $commid);
  2260. $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
  2261. if ($result < 0) {
  2262. $error++;
  2263. }
  2264. }
  2265. if (!$error) {
  2266. $this->db->commit();
  2267. return 1;
  2268. } else {
  2269. $this->db->rollback();
  2270. return -1;
  2271. }
  2272. }
  2273. return 0;
  2274. }
  2275. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2276. /**
  2277. * Add link to sales representative
  2278. *
  2279. * @param User $user Object user
  2280. * @param int $commid Id of user
  2281. * @return void
  2282. */
  2283. public function del_commercial(User $user, $commid)
  2284. {
  2285. // phpcs:enable
  2286. $error = 0;
  2287. $this->context = array('commercial_modified'=>$commid);
  2288. $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
  2289. if ($result < 0) {
  2290. $error++;
  2291. }
  2292. if ($this->id > 0 && $commid > 0) {
  2293. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
  2294. $sql .= " WHERE fk_soc = ".((int) $this->id)." AND fk_user = ".((int) $commid);
  2295. if (!$this->db->query($sql)) {
  2296. dol_syslog(get_class($this)."::del_commercial Erreur");
  2297. }
  2298. }
  2299. }
  2300. /**
  2301. * getTooltipContentArray
  2302. *
  2303. * @param array $params params to construct tooltip data
  2304. * @since v18
  2305. * @return array
  2306. */
  2307. public function getTooltipContentArray($params)
  2308. {
  2309. global $conf, $langs, $user;
  2310. $langs->loadLangs(['companies', 'commercial']);
  2311. $datas = array();
  2312. $option = $params['option'] ?? '';
  2313. $nofetch = !empty($params['nofetch']);
  2314. $noaliasinname = (empty($params['noaliasinname']) ? 0 : $params['noaliasinname']);
  2315. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2316. return ['optimize' => $langs->trans("ShowCompany")];
  2317. }
  2318. if (!empty($this->logo) && class_exists('Form')) {
  2319. $photo = '<div class="photointooltip floatright">';
  2320. $photo .= Form::showphoto('societe', $this, 0, 40, 0, 'photoref', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
  2321. $photo .= '</div>';
  2322. $datas['photo'] = $photo;
  2323. } elseif (!empty($this->logo_squarred) && class_exists('Form')) {
  2324. /*$label.= '<div class="photointooltip">';
  2325. $label.= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
  2326. $label.= '</div><div style="clear: both;"></div>';*/
  2327. }
  2328. $datas['divopen'] = '<div class="centpercent">';
  2329. if ($option == 'customer' || $option == 'compta' || $option == 'category') {
  2330. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Customer").'</u>';
  2331. } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
  2332. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Prospect").'</u>';
  2333. } elseif ($option == 'supplier' || $option == 'category_supplier') {
  2334. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Supplier").'</u>';
  2335. } elseif ($option == 'agenda') {
  2336. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
  2337. } elseif ($option == 'project') {
  2338. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
  2339. } elseif ($option == 'margin') {
  2340. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
  2341. } elseif ($option == 'contact') {
  2342. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
  2343. } elseif ($option == 'ban') {
  2344. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
  2345. }
  2346. // By default
  2347. if (empty($datas['picto'])) {
  2348. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ThirdParty").'</u>';
  2349. }
  2350. if (isset($this->status)) {
  2351. $datas['status'] = ' '.$this->getLibStatut(5);
  2352. }
  2353. if (isset($this->client) && isset($this->fournisseur)) {
  2354. $datas['type'] = ' &nbsp; ' . $this->getTypeUrl(1);
  2355. }
  2356. $datas['name'] = '<br><b>'.$langs->trans('Name').':</b> '.dol_escape_htmltag(dol_string_nohtmltag($this->name));
  2357. if (!empty($this->name_alias) && empty($noaliasinname)) {
  2358. $datas['namealias'] = ' ('.dol_escape_htmltag(dol_string_nohtmltag($this->name_alias)).')';
  2359. }
  2360. if (!empty($this->email)) {
  2361. $datas['email'] = '<br>'.img_picto('', 'email', 'class="pictofixedwidth"').$this->email;
  2362. }
  2363. if (!empty($this->url)) {
  2364. $datas['url'] = '<br>'.img_picto('', 'globe', 'class="pictofixedwidth"').$this->url;
  2365. }
  2366. if (!empty($this->phone) || !empty($this->fax)) {
  2367. $phonelist = array();
  2368. if ($this->phone) {
  2369. $phonelist[] = dol_print_phone($this->phone, $this->country_code, $this->id, 0, '', '&nbsp', 'phone');
  2370. }
  2371. if ($this->fax) {
  2372. $phonelist[] = dol_print_phone($this->fax, $this->country_code, $this->id, 0, '', '&nbsp', 'fax');
  2373. }
  2374. $datas['phonelist'] = '<br>'.implode('&nbsp;', $phonelist);
  2375. }
  2376. if (!empty($this->address)) {
  2377. $datas['address'] = '<br><b>'.$langs->trans("Address").':</b> '.dol_format_address($this, 1, ' ', $langs); // Address + country
  2378. } elseif (!empty($this->country_code)) {
  2379. $datas['address'] = '<br><b>'.$langs->trans('Country').':</b> '.$this->country_code;
  2380. }
  2381. if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false)) {
  2382. $datas['vatintra'] = '<br><b>'.$langs->trans('VATIntra').':</b> '.dol_escape_htmltag($this->tva_intra);
  2383. }
  2384. if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
  2385. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false && $langs->trans('ProfId1'.$this->country_code) != '-') {
  2386. $datas['profid1'] = '<br><b>'.$langs->trans('ProfId1'.$this->country_code).':</b> '.$this->idprof1;
  2387. }
  2388. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false && $langs->trans('ProfId2'.$this->country_code) != '-') {
  2389. $datas['profid2'] = '<br><b>'.$langs->trans('ProfId2'.$this->country_code).':</b> '.$this->idprof2;
  2390. }
  2391. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false && $langs->trans('ProfId3'.$this->country_code) != '-') {
  2392. $datas['profid3'] = '<br><b>'.$langs->trans('ProfId3'.$this->country_code).':</b> '.$this->idprof3;
  2393. }
  2394. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false && $langs->trans('ProfId4'.$this->country_code) != '-') {
  2395. $datas['profid4'] = '<br><b>'.$langs->trans('ProfId4'.$this->country_code).':</b> '.$this->idprof4;
  2396. }
  2397. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false && $langs->trans('ProfId5'.$this->country_code) != '-') {
  2398. $datas['profid5'] = '<br><b>'.$langs->trans('ProfId5'.$this->country_code).':</b> '.$this->idprof5;
  2399. }
  2400. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false && $langs->trans('ProfId6'.$this->country_code) != '-') {
  2401. $datas['profid6'] = '<br><b>'.$langs->trans('ProfId6'.$this->country_code).':</b> '.$this->idprof6;
  2402. }
  2403. }
  2404. $datas['separator'] = '<br>';
  2405. if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3)) {
  2406. $datas['customercode'] = '<br><b>'.$langs->trans('CustomerCode').':</b> '.$this->code_client;
  2407. }
  2408. if (isModEnabled('accounting') && ($this->client == 1 || $this->client == 3)) {
  2409. $langs->load('compta');
  2410. $datas['accountancycustomercode'] = '<br><b>'.$langs->trans('CustomerAccountancyCode').':</b> '.($this->code_compta ? $this->code_compta : $this->code_compta_client);
  2411. }
  2412. // show categories for this record only in ajax to not overload lists
  2413. if (!$nofetch && isModEnabled('categorie') && $this->client) {
  2414. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  2415. $form = new Form($this->db);
  2416. $datas['categories_customer'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_CUSTOMER, 1, 1);
  2417. }
  2418. if (!empty($this->code_fournisseur) && $this->fournisseur) {
  2419. $datas['suppliercode'] = '<br><b>'.$langs->trans('SupplierCode').':</b> '.$this->code_fournisseur;
  2420. }
  2421. if (isModEnabled('accounting') && $this->fournisseur) {
  2422. $langs->load('compta');
  2423. $datas['accountancysuppliercode'] = '<br><b>'.$langs->trans('SupplierAccountancyCode').':</b> '.$this->code_compta_fournisseur;
  2424. }
  2425. // show categories for this record only in ajax to not overload lists
  2426. if (!$nofetch && isModEnabled('categorie') && $this->fournisseur) {
  2427. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  2428. $form = new Form($this->db);
  2429. $datas['categories_supplier'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_SUPPLIER, 1, 1);
  2430. }
  2431. $datas['divclose'] = '</div>';
  2432. return $datas;
  2433. }
  2434. /**
  2435. * Return a link on thirdparty (with picto)
  2436. *
  2437. * @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
  2438. * @param string $option Target of link ('', 'customer', 'prospect', 'supplier', 'project')
  2439. * @param int $maxlen Max length of name
  2440. * @param int $notooltip 1=Disable tooltip
  2441. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  2442. * @param int $noaliasinname 1=Do not add alias into the link ref
  2443. * @param string $target add attribute target
  2444. * @return string String with URL
  2445. */
  2446. public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1, $noaliasinname = 0, $target = '')
  2447. {
  2448. global $conf, $langs, $hookmanager;
  2449. if (!empty($conf->dol_no_mouse_hover)) {
  2450. $notooltip = 1; // Force disable tooltips
  2451. }
  2452. $name = $this->name ? $this->name : $this->nom;
  2453. if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
  2454. if (empty($option) && $this->client > 0) {
  2455. $option = 'customer';
  2456. }
  2457. if (empty($option) && $this->fournisseur > 0) {
  2458. $option = 'supplier';
  2459. }
  2460. }
  2461. if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
  2462. $code = '';
  2463. if (($this->client) && (!empty($this->code_client)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 2)) {
  2464. $code = $this->code_client.' - ';
  2465. }
  2466. if (($this->fournisseur) && (!empty($this->code_fournisseur)) && (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1 || getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 3)) {
  2467. $code .= $this->code_fournisseur.' - ';
  2468. }
  2469. if ($code) {
  2470. if (getDolGlobalInt('SOCIETE_ADD_REF_IN_LIST') == 1) {
  2471. $name = $code.' '.$name;
  2472. } else {
  2473. $name = $code;
  2474. }
  2475. }
  2476. }
  2477. if (!empty($this->name_alias) && empty($noaliasinname)) {
  2478. $name .= ' ('.$this->name_alias.')';
  2479. }
  2480. $result = '';
  2481. $params = [
  2482. 'id' => $this->id,
  2483. 'objecttype' => $this->element,
  2484. 'option' => $option,
  2485. 'nofetch' => 1,
  2486. ];
  2487. $classfortooltip = 'classfortooltip';
  2488. $dataparams = '';
  2489. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  2490. $classfortooltip = 'classforajaxtooltip';
  2491. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  2492. $label = '';
  2493. } else {
  2494. $label = implode($this->getTooltipContentArray($params));
  2495. }
  2496. $linkstart = '';
  2497. $linkend = '';
  2498. if ($option == 'customer' || $option == 'compta' || $option == 'category') {
  2499. $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
  2500. } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
  2501. $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
  2502. } elseif ($option == 'supplier' || $option == 'category_supplier') {
  2503. $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
  2504. } elseif ($option == 'agenda') {
  2505. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
  2506. } elseif ($option == 'project') {
  2507. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
  2508. } elseif ($option == 'margin') {
  2509. $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
  2510. } elseif ($option == 'contact') {
  2511. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
  2512. } elseif ($option == 'ban') {
  2513. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
  2514. }
  2515. // By default
  2516. if (empty($linkstart)) {
  2517. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
  2518. }
  2519. // Add type of canvas
  2520. $linkstart .= (!empty($this->canvas) ? '&canvas='.$this->canvas : '');
  2521. // Add param to save lastsearch_values or not
  2522. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  2523. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  2524. $add_save_lastsearch_values = 1;
  2525. }
  2526. if ($add_save_lastsearch_values) {
  2527. $linkstart .= '&save_lastsearch_values=1';
  2528. }
  2529. $linkstart .= '"';
  2530. $linkclose = '';
  2531. if (empty($notooltip)) {
  2532. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  2533. $label = $langs->trans("ShowCompany");
  2534. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  2535. }
  2536. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  2537. $linkclose .= $dataparams.' class="'.$classfortooltip.' refurl valignmiddle"';
  2538. $target_value = array('_self', '_blank', '_parent', '_top');
  2539. if (in_array($target, $target_value)) {
  2540. $linkclose .= ' target="'.dol_escape_htmltag($target).'"';
  2541. }
  2542. } else {
  2543. $linkclose .= ' class="valignmiddle"';
  2544. }
  2545. $linkstart .= $linkclose.'>';
  2546. $linkend = '</a>';
  2547. global $user;
  2548. if (empty($user->rights->societe->client->voir) && $user->socid > 0 && $this->id != $user->socid) {
  2549. $linkstart = '';
  2550. $linkend = '';
  2551. }
  2552. $result .= $linkstart;
  2553. if ($withpicto) {
  2554. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (' class="'.(($withpicto != 2) ? 'paddingright' : '').'"'), 0, 0, $notooltip ? 0 : 1);
  2555. }
  2556. if ($withpicto != 2) {
  2557. $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
  2558. }
  2559. $result .= $linkend;
  2560. global $action;
  2561. $hookmanager->initHooks(array('thirdpartydao'));
  2562. $parameters = array(
  2563. 'id'=>$this->id,
  2564. 'getnomurl' => &$result,
  2565. 'withpicto '=> $withpicto,
  2566. 'option'=> $option,
  2567. 'maxlen'=> $maxlen,
  2568. 'notooltip'=> $notooltip,
  2569. 'save_lastsearch_value'=> $save_lastsearch_value
  2570. );
  2571. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  2572. if ($reshook > 0) {
  2573. $result = $hookmanager->resPrint;
  2574. } else {
  2575. $result .= $hookmanager->resPrint;
  2576. }
  2577. return $result;
  2578. }
  2579. /**
  2580. * Return link(s) on type of thirdparty (with picto)
  2581. *
  2582. * @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
  2583. * @param string $option ''=All
  2584. * @param int $notooltip 1=Disable tooltip
  2585. * @param string $tag Tag 'a' or 'span'
  2586. * @return string String with URL
  2587. */
  2588. public function getTypeUrl($withpicto = 0, $option = '', $notooltip = 0, $tag = 'a')
  2589. {
  2590. global $conf, $langs;
  2591. $s = '';
  2592. if (empty($option) || preg_match('/prospect/', $option)) {
  2593. if (($this->client == 2 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
  2594. $s .= '<'.$tag.' class="customer-back opacitymedium" title="'.$langs->trans("Prospect").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Prospect"), 0, 1).'</'.$tag.'>';
  2595. }
  2596. }
  2597. if (empty($option) || preg_match('/customer/', $option)) {
  2598. if (($this->client == 1 || $this->client == 3) && empty($conf->global->SOCIETE_DISABLE_CUSTOMERS)) {
  2599. $s .= '<'.$tag.' class="customer-back" title="'.$langs->trans("Customer").'" href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Customer"), 0, 1).'</'.$tag.'>';
  2600. }
  2601. }
  2602. if (empty($option) || preg_match('/supplier/', $option)) {
  2603. if ((isModEnabled("supplier_order") || isModEnabled("supplier_invoice")) && $this->fournisseur) {
  2604. $s .= '<'.$tag.' class="vendor-back" title="'.$langs->trans("Supplier").'" href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id.'">'.dol_substr($langs->trans("Supplier"), 0, 1).'</'.$tag.'>';
  2605. }
  2606. }
  2607. return $s;
  2608. }
  2609. /**
  2610. * Return label of status (activity, closed)
  2611. *
  2612. * @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
  2613. * @return string Label of status
  2614. */
  2615. public function getLibStatut($mode = 0)
  2616. {
  2617. return $this->LibStatut($this->status, $mode);
  2618. }
  2619. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2620. /**
  2621. * Return the label of a given status
  2622. *
  2623. * @param int $status Status id
  2624. * @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
  2625. * @return string Status label
  2626. */
  2627. public function LibStatut($status, $mode = 0)
  2628. {
  2629. // phpcs:enable
  2630. global $langs;
  2631. $langs->load('companies');
  2632. $statusType = 'status4';
  2633. if ($status == 0) {
  2634. $statusType = 'status6';
  2635. }
  2636. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  2637. $this->labelStatus[0] = $langs->transnoentitiesnoconv("ActivityCeased");
  2638. $this->labelStatus[1] = $langs->transnoentitiesnoconv("InActivity");
  2639. $this->labelStatusShort[0] = $langs->transnoentitiesnoconv("ActivityCeased");
  2640. $this->labelStatusShort[1] = $langs->transnoentitiesnoconv("InActivity");
  2641. }
  2642. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  2643. }
  2644. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2645. /**
  2646. * Return list of contacts emails existing for third party
  2647. *
  2648. * @param int $addthirdparty 1=Add also a record for thirdparty email, 2=Same than 1 but add text ThirdParty in grey
  2649. * @return array Array of contacts emails
  2650. */
  2651. public function thirdparty_and_contact_email_array($addthirdparty = 0)
  2652. {
  2653. // phpcs:enable
  2654. global $langs;
  2655. $contact_emails = $this->contact_property_array('email', 1);
  2656. if ($this->email && $addthirdparty) {
  2657. if (empty($this->name)) {
  2658. $this->name = $this->nom;
  2659. }
  2660. $contact_emails['thirdparty'] = ($addthirdparty == 2 ? '<span class="opacitymedium">' : '').$langs->transnoentitiesnoconv("ThirdParty").($addthirdparty == 2 ? '</span>' : '').': '.dol_trunc($this->name, 16)." <".$this->email.">";
  2661. }
  2662. //var_dump($contact_emails)
  2663. return $contact_emails;
  2664. }
  2665. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2666. /**
  2667. * Return list of contacts mobile phone existing for third party
  2668. *
  2669. * @return array Array of contacts emails
  2670. */
  2671. public function thirdparty_and_contact_phone_array()
  2672. {
  2673. // phpcs:enable
  2674. global $langs;
  2675. $contact_phone = $this->contact_property_array('mobile');
  2676. if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
  2677. if (empty($this->name)) {
  2678. $this->name = $this->nom;
  2679. }
  2680. // TODO: Tester si tel non deja present dans tableau contact
  2681. $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name, 16)." <".$this->phone.">";
  2682. }
  2683. return $contact_phone;
  2684. }
  2685. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2686. /**
  2687. * Return list of contacts emails or mobile existing for third party
  2688. *
  2689. * @param string $mode 'email' or 'mobile'
  2690. * @param int $hidedisabled 1=Hide contact if disabled
  2691. * @return array Array of contacts emails or mobile. Example: array(id=>'Name <email>')
  2692. */
  2693. public function contact_property_array($mode = 'email', $hidedisabled = 0)
  2694. {
  2695. // phpcs:enable
  2696. global $langs;
  2697. $contact_property = array();
  2698. $sql = "SELECT rowid, email, statut as status, phone_mobile, lastname, poste, firstname";
  2699. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
  2700. $sql .= " WHERE fk_soc = ".((int) $this->id);
  2701. $sql .= " ORDER BY lastname, firstname";
  2702. $resql = $this->db->query($sql);
  2703. if ($resql) {
  2704. $nump = $this->db->num_rows($resql);
  2705. if ($nump) {
  2706. $sepa = "("; $sepb = ")";
  2707. if ($mode == 'email') {
  2708. //$sepa="&lt;"; $sepb="&gt;";
  2709. $sepa = "<"; $sepb = ">";
  2710. }
  2711. $i = 0;
  2712. while ($i < $nump) {
  2713. $obj = $this->db->fetch_object($resql);
  2714. if ($mode == 'email') {
  2715. $property = $obj->email;
  2716. } elseif ($mode == 'mobile') {
  2717. $property = $obj->phone_mobile;
  2718. } else {
  2719. $property = $obj->$mode;
  2720. }
  2721. // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
  2722. if ($obj->status == 1 || empty($hidedisabled)) {
  2723. if (empty($property)) {
  2724. if ($mode == 'email') {
  2725. $property = $langs->transnoentitiesnoconv("NoEMail");
  2726. } elseif ($mode == 'mobile') {
  2727. $property = $langs->transnoentitiesnoconv("NoMobilePhone");
  2728. }
  2729. }
  2730. if (!empty($obj->poste)) {
  2731. $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).($obj->poste ? " - ".$obj->poste : "").(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
  2732. } else {
  2733. $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)).(($mode != 'poste' && $property) ? " ".$sepa.$property.$sepb : '');
  2734. }
  2735. }
  2736. $i++;
  2737. }
  2738. }
  2739. } else {
  2740. dol_print_error($this->db);
  2741. }
  2742. return $contact_property;
  2743. }
  2744. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2745. /**
  2746. * Returns the contact list of this company
  2747. *
  2748. * @return array array of contacts
  2749. */
  2750. public function contact_array()
  2751. {
  2752. // phpcs:enable
  2753. $contacts = array();
  2754. $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
  2755. $resql = $this->db->query($sql);
  2756. if ($resql) {
  2757. $nump = $this->db->num_rows($resql);
  2758. if ($nump) {
  2759. $i = 0;
  2760. while ($i < $nump) {
  2761. $obj = $this->db->fetch_object($resql);
  2762. $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
  2763. $i++;
  2764. }
  2765. }
  2766. } else {
  2767. dol_print_error($this->db);
  2768. }
  2769. return $contacts;
  2770. }
  2771. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2772. /**
  2773. * Returns the contact list of this company
  2774. *
  2775. * @return array $contacts array of contacts
  2776. */
  2777. public function contact_array_objects()
  2778. {
  2779. // phpcs:enable
  2780. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  2781. $contacts = array();
  2782. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".((int) $this->id);
  2783. $resql = $this->db->query($sql);
  2784. if ($resql) {
  2785. $nump = $this->db->num_rows($resql);
  2786. if ($nump) {
  2787. $i = 0;
  2788. while ($i < $nump) {
  2789. $obj = $this->db->fetch_object($resql);
  2790. $contact = new Contact($this->db);
  2791. $contact->fetch($obj->rowid);
  2792. $contacts[] = $contact;
  2793. $i++;
  2794. }
  2795. }
  2796. } else {
  2797. dol_print_error($this->db);
  2798. }
  2799. return $contacts;
  2800. }
  2801. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2802. /**
  2803. * Return property of contact from its id
  2804. *
  2805. * @param int $rowid id of contact
  2806. * @param string $mode 'email' or 'mobile'
  2807. * @return string Email of contact with format: "Full name <email>"
  2808. */
  2809. public function contact_get_property($rowid, $mode)
  2810. {
  2811. // phpcs:enable
  2812. $contact_property = '';
  2813. if (empty($rowid)) {
  2814. return '';
  2815. }
  2816. $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
  2817. $sql .= " FROM ".MAIN_DB_PREFIX."socpeople";
  2818. $sql .= " WHERE rowid = ".((int) $rowid);
  2819. $resql = $this->db->query($sql);
  2820. if ($resql) {
  2821. $nump = $this->db->num_rows($resql);
  2822. if ($nump) {
  2823. $obj = $this->db->fetch_object($resql);
  2824. if ($mode == 'email') {
  2825. $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
  2826. } elseif ($mode == 'mobile') {
  2827. $contact_property = $obj->phone_mobile;
  2828. }
  2829. }
  2830. return $contact_property;
  2831. } else {
  2832. dol_print_error($this->db);
  2833. }
  2834. return '';
  2835. }
  2836. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2837. /**
  2838. * Return bank number property of thirdparty (label or rum)
  2839. *
  2840. * @param string $mode 'label' or 'rum' or 'format'
  2841. * @return string Bank label or RUM or '' if no bank account found
  2842. */
  2843. public function display_rib($mode = 'label')
  2844. {
  2845. // phpcs:enable
  2846. require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  2847. $bac = new CompanyBankAccount($this->db);
  2848. $bac->fetch(0, $this->id);
  2849. if ($bac->id > 0) { // If a bank account has been found for company $this->id
  2850. if ($mode == 'label') {
  2851. return $bac->getRibLabel(true);
  2852. } elseif ($mode == 'rum') {
  2853. if (empty($bac->rum)) {
  2854. require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
  2855. $prelevement = new BonPrelevement($this->db);
  2856. $bac->fetch_thirdparty();
  2857. $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
  2858. }
  2859. return $bac->rum;
  2860. } elseif ($mode == 'format') {
  2861. return $bac->frstrecur;
  2862. } else {
  2863. return 'BadParameterToFunctionDisplayRib';
  2864. }
  2865. } else {
  2866. return '';
  2867. }
  2868. }
  2869. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2870. /**
  2871. * Return Array of RIB
  2872. *
  2873. * @return array|int 0 if KO, Array of CompanyBanckAccount if OK
  2874. */
  2875. public function get_all_rib()
  2876. {
  2877. // phpcs:enable
  2878. require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  2879. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".((int) $this->id);
  2880. $result = $this->db->query($sql);
  2881. if (!$result) {
  2882. $this->error++;
  2883. $this->errors[] = $this->db->lasterror;
  2884. return 0;
  2885. } else {
  2886. $num_rows = $this->db->num_rows($result);
  2887. $rib_array = array();
  2888. if ($num_rows) {
  2889. while ($obj = $this->db->fetch_object($result)) {
  2890. $rib = new CompanyBankAccount($this->db);
  2891. $rib->fetch($obj->rowid);
  2892. $rib_array[] = $rib;
  2893. }
  2894. }
  2895. return $rib_array;
  2896. }
  2897. }
  2898. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2899. /**
  2900. * Assigns a customer code from the code control module.
  2901. * Return value is stored into this->code_client
  2902. *
  2903. * @param Societe $objsoc Object thirdparty
  2904. * @param int $type Should be 0 to say customer
  2905. * @return void
  2906. */
  2907. public function get_codeclient($objsoc = 0, $type = 0)
  2908. {
  2909. // phpcs:enable
  2910. global $conf;
  2911. if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
  2912. $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
  2913. $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
  2914. foreach ($dirsociete as $dirroot) {
  2915. $res = dol_include_once($dirroot.$module.'.php');
  2916. if ($res) {
  2917. break;
  2918. }
  2919. }
  2920. $mod = new $module();
  2921. $this->code_client = $mod->getNextValue($objsoc, $type);
  2922. $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
  2923. dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
  2924. }
  2925. }
  2926. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2927. /**
  2928. * Assigns a vendor code from the code control module.
  2929. * Return value is stored into this->code_fournisseur
  2930. *
  2931. * @param Societe $objsoc Object thirdparty
  2932. * @param int $type Should be 1 to say supplier
  2933. * @return void
  2934. */
  2935. public function get_codefournisseur($objsoc = 0, $type = 1)
  2936. {
  2937. // phpcs:enable
  2938. global $conf;
  2939. if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
  2940. $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
  2941. $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
  2942. foreach ($dirsociete as $dirroot) {
  2943. $res = dol_include_once($dirroot.$module.'.php');
  2944. if ($res) {
  2945. break;
  2946. }
  2947. }
  2948. $mod = new $module();
  2949. $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
  2950. dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
  2951. }
  2952. }
  2953. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2954. /**
  2955. * Check if a client code is editable based on the parameters of the
  2956. * code control module.
  2957. *
  2958. * @return int 0=No, 1=Yes
  2959. */
  2960. public function codeclient_modifiable()
  2961. {
  2962. // phpcs:enable
  2963. global $conf;
  2964. if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
  2965. $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
  2966. $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
  2967. foreach ($dirsociete as $dirroot) {
  2968. $res = dol_include_once($dirroot.$module.'.php');
  2969. if ($res) {
  2970. break;
  2971. }
  2972. }
  2973. $mod = new $module();
  2974. dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
  2975. if ($mod->code_modifiable_null && !$this->code_client) {
  2976. return 1;
  2977. }
  2978. if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) {
  2979. return 1;
  2980. }
  2981. if ($mod->code_modifiable) {
  2982. return 1; // A mettre en dernier
  2983. }
  2984. return 0;
  2985. } else {
  2986. return 0;
  2987. }
  2988. }
  2989. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2990. /**
  2991. * Check if a vendor code is editable in the code control module configuration
  2992. *
  2993. * @return int 0=No, 1=Yes
  2994. */
  2995. public function codefournisseur_modifiable()
  2996. {
  2997. // phpcs:enable
  2998. global $conf;
  2999. if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
  3000. $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
  3001. $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
  3002. foreach ($dirsociete as $dirroot) {
  3003. $res = dol_include_once($dirroot.$module.'.php');
  3004. if ($res) {
  3005. break;
  3006. }
  3007. }
  3008. $mod = new $module();
  3009. dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
  3010. if ($mod->code_modifiable_null && !$this->code_fournisseur) {
  3011. return 1;
  3012. }
  3013. if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) {
  3014. return 1;
  3015. }
  3016. if ($mod->code_modifiable) {
  3017. return 1; // A mettre en dernier
  3018. }
  3019. return 0;
  3020. } else {
  3021. return 0;
  3022. }
  3023. }
  3024. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3025. /**
  3026. * Check customer code
  3027. *
  3028. * @return int 0 if OK
  3029. * -1 ErrorBadCustomerCodeSyntax
  3030. * -2 ErrorCustomerCodeRequired
  3031. * -3 ErrorCustomerCodeAlreadyUsed
  3032. * -4 ErrorPrefixRequired
  3033. * -5 NotConfigured - Setup empty so any value may be ok or not
  3034. * -6 Other (see this->error)
  3035. */
  3036. public function check_codeclient()
  3037. {
  3038. // phpcs:enable
  3039. global $conf;
  3040. if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
  3041. $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
  3042. $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
  3043. foreach ($dirsociete as $dirroot) {
  3044. $res = dol_include_once($dirroot.$module.'.php');
  3045. if ($res) {
  3046. break;
  3047. }
  3048. }
  3049. $mod = new $module();
  3050. dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
  3051. $result = $mod->verif($this->db, $this->code_client, $this, 0);
  3052. if ($result) { // If error
  3053. $this->error = $mod->error;
  3054. $this->errors = $mod->errors;
  3055. }
  3056. return $result;
  3057. } else {
  3058. return 0;
  3059. }
  3060. }
  3061. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3062. /**
  3063. * Check supplier code
  3064. *
  3065. * @return int 0 if OK
  3066. * -1 ErrorBadCustomerCodeSyntax
  3067. * -2 ErrorCustomerCodeRequired
  3068. * -3 ErrorCustomerCodeAlreadyUsed
  3069. * -4 ErrorPrefixRequired
  3070. * -5 NotConfigured - Setup empty so any value may be ok or not
  3071. * -6 Other (see this->error)
  3072. */
  3073. public function check_codefournisseur()
  3074. {
  3075. // phpcs:enable
  3076. global $conf;
  3077. if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
  3078. $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
  3079. $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
  3080. foreach ($dirsociete as $dirroot) {
  3081. $res = dol_include_once($dirroot.$module.'.php');
  3082. if ($res) {
  3083. break;
  3084. }
  3085. }
  3086. $mod = new $module();
  3087. dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
  3088. $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
  3089. if ($result) { // If error
  3090. $this->error = $mod->error;
  3091. $this->errors = $mod->errors;
  3092. }
  3093. return $result;
  3094. } else {
  3095. return 0;
  3096. }
  3097. }
  3098. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3099. /**
  3100. * Assigns a accounting code from the accounting code module.
  3101. * Computed value is stored into this->code_compta or this->code_compta_fournisseur according to $type.
  3102. * May be identical to the one entered or generated automatically. Currently, only the automatic generation is implemented.
  3103. *
  3104. * @param string $type Type of thirdparty ('customer' or 'supplier')
  3105. * @return int 0 if OK, <0 if $type is not valid
  3106. */
  3107. public function get_codecompta($type)
  3108. {
  3109. // phpcs:enable
  3110. global $conf;
  3111. if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
  3112. $module=$conf->global->SOCIETE_CODECOMPTA_ADDON;
  3113. $res = false;
  3114. $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
  3115. foreach ($dirsociete as $dirroot) {
  3116. $res = dol_include_once($dirroot.$module.'.php');
  3117. if ($res) {
  3118. break;
  3119. }
  3120. }
  3121. if ($res) {
  3122. $mod = new $module();
  3123. // Set code count in $mod->code
  3124. $result = $mod->get_code($this->db, $this, $type);
  3125. if ($type == 'customer') {
  3126. $this->code_compta_client = $mod->code;
  3127. $this->code_compta = $this->code_compta_client; // For backward compatibility
  3128. } elseif ($type == 'supplier') {
  3129. $this->code_compta_fournisseur = $mod->code;
  3130. }
  3131. return $result;
  3132. } else {
  3133. $this->error = 'ErrorAccountancyCodeNotDefined';
  3134. return -1;
  3135. }
  3136. } else {
  3137. if ($type == 'customer') {
  3138. $this->code_compta_client = '';
  3139. $this->code_compta = '';
  3140. } elseif ($type == 'supplier') {
  3141. $this->code_compta_fournisseur = '';
  3142. }
  3143. return 0;
  3144. }
  3145. }
  3146. /**
  3147. * Define parent company of current company
  3148. *
  3149. * @param int $id Id of thirdparty to set or '' to remove
  3150. * @return int <0 if KO, >0 if OK
  3151. */
  3152. public function setParent($id)
  3153. {
  3154. dol_syslog(get_class($this).'::setParent', LOG_DEBUG);
  3155. if ($this->id) {
  3156. // Check if the id we want to add as parent has not already one parent that is the current id we try to update
  3157. if ($id > 0) {
  3158. $sameparent = $this->validateFamilyTree($id, $this->id, 0);
  3159. if ($sameparent < 0) {
  3160. return -1;
  3161. }
  3162. if ($sameparent == 1) {
  3163. setEventMessages('ParentCompanyToAddIsAlreadyAChildOfModifiedCompany', null, 'warnings');
  3164. return -1;
  3165. }
  3166. }
  3167. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe SET parent = '.($id > 0 ? $id : 'null').' WHERE rowid = '.((int) $this->id);
  3168. $resql = $this->db->query($sql);
  3169. if ($resql) {
  3170. $this->parent = $id;
  3171. return 1;
  3172. } else {
  3173. return -1;
  3174. }
  3175. }
  3176. return -1;
  3177. }
  3178. /**
  3179. * Check if a thirdparty $idchild is or not inside the parents (or grand parents) of another thirdparty id $idparent.
  3180. *
  3181. * @param int $idparent Id of thirdparty to check
  3182. * @param int $idchild Id of thirdparty to compare to
  3183. * @param int $counter Counter to protect against infinite loops
  3184. * @return int <0 if KO, 0 if OK or 1 if at some level a parent company was the child to compare to
  3185. */
  3186. public function validateFamilyTree($idparent, $idchild, $counter = 0)
  3187. {
  3188. if ($counter > 100) {
  3189. dol_syslog("Too high level of parent - child for company. May be an infinite loop ?", LOG_WARNING);
  3190. }
  3191. $sql = 'SELECT s.parent';
  3192. $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
  3193. $sql .= ' WHERE rowid = '.((int) $idparent);
  3194. $resql = $this->db->query($sql);
  3195. if ($resql) {
  3196. $obj = $this->db->fetch_object($resql);
  3197. if ($obj->parent == '') {
  3198. return 0;
  3199. } elseif ($obj->parent == $idchild) {
  3200. return 1;
  3201. } else {
  3202. $sameparent = $this->validateFamilyTree($obj->parent, $idchild, ($counter + 1));
  3203. }
  3204. return $sameparent;
  3205. } else {
  3206. return -1;
  3207. }
  3208. }
  3209. /**
  3210. * Get parents for company
  3211. *
  3212. * @param int $company_id ID of company to search parent
  3213. * @param array $parents List of companies ID found
  3214. * @return array
  3215. */
  3216. public function getParentsForCompany($company_id, $parents = array())
  3217. {
  3218. global $langs;
  3219. if ($company_id > 0) {
  3220. $sql = "SELECT parent FROM " . MAIN_DB_PREFIX . "societe WHERE rowid = ".((int) $company_id);
  3221. $resql = $this->db->query($sql);
  3222. if ($resql) {
  3223. if ($obj = $this->db->fetch_object($resql)) {
  3224. $parent = $obj->parent;
  3225. if ($parent > 0 && !in_array($parent, $parents)) {
  3226. $parents[] = $parent;
  3227. return $this->getParentsForCompany($parent, $parents);
  3228. } else {
  3229. return $parents;
  3230. }
  3231. }
  3232. $this->db->free($resql);
  3233. } else {
  3234. setEventMessage($langs->trans('GetCompanyParentsError', $this->db->lasterror()), 'errors');
  3235. }
  3236. }
  3237. // Return a default value when $company_id is not greater than 0
  3238. return array();
  3239. }
  3240. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3241. /**
  3242. * Returns if a profid sould be verified to be unique
  3243. *
  3244. * @param int $idprof 1,2,3,4,5,6 (Example: 1=siren, 2=siret, 3=naf, 4=rcs/rm, 5=eori, 6=idprof6)
  3245. * @return boolean true if the ID must be unique
  3246. */
  3247. public function id_prof_verifiable($idprof)
  3248. {
  3249. // phpcs:enable
  3250. global $conf;
  3251. switch ($idprof) {
  3252. case 1:
  3253. $ret = (empty($conf->global->SOCIETE_IDPROF1_UNIQUE) ? false : true);
  3254. break;
  3255. case 2:
  3256. $ret = (empty($conf->global->SOCIETE_IDPROF2_UNIQUE) ? false : true);
  3257. break;
  3258. case 3:
  3259. $ret = (empty($conf->global->SOCIETE_IDPROF3_UNIQUE) ? false : true);
  3260. break;
  3261. case 4:
  3262. $ret = (empty($conf->global->SOCIETE_IDPROF4_UNIQUE) ? false : true);
  3263. break;
  3264. case 5:
  3265. $ret = (empty($conf->global->SOCIETE_IDPROF5_UNIQUE) ? false : true);
  3266. break;
  3267. case 6:
  3268. $ret = (empty($conf->global->SOCIETE_IDPROF6_UNIQUE) ? false : true);
  3269. break;
  3270. default:
  3271. $ret = false;
  3272. }
  3273. return $ret;
  3274. }
  3275. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3276. /**
  3277. * Verify if a profid exists into database for others thirds
  3278. *
  3279. * @param string $idprof 'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm)
  3280. * @param string $value Value of profid
  3281. * @param int $socid Id of thirdparty to exclude (if update)
  3282. * @return boolean True if exists, False if not
  3283. */
  3284. public function id_prof_exists($idprof, $value, $socid = 0)
  3285. {
  3286. // phpcs:enable
  3287. $field = $idprof;
  3288. switch ($idprof) { // For backward compatibility
  3289. case '1':
  3290. case 'idprof1':
  3291. $field = "siren";
  3292. break;
  3293. case '2':
  3294. case 'idprof2':
  3295. $field = "siret";
  3296. break;
  3297. case '3':
  3298. case 'idprof3':
  3299. $field = "ape";
  3300. break;
  3301. case '4':
  3302. case 'idprof4':
  3303. $field = "idprof4";
  3304. break;
  3305. case '5':
  3306. $field = "idprof5";
  3307. break;
  3308. case '6':
  3309. $field = "idprof6";
  3310. break;
  3311. }
  3312. //Verify duplicate entries
  3313. $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$this->db->escape($value)."' AND entity IN (".getEntity('societe').")";
  3314. if ($socid) {
  3315. $sql .= " AND rowid <> ".$socid;
  3316. }
  3317. $resql = $this->db->query($sql);
  3318. if ($resql) {
  3319. $obj = $this->db->fetch_object($resql);
  3320. $count = $obj->nb;
  3321. } else {
  3322. $count = 0;
  3323. print $this->db->error();
  3324. }
  3325. $this->db->free($resql);
  3326. if ($count > 0) {
  3327. return true;
  3328. } else {
  3329. return false;
  3330. }
  3331. }
  3332. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3333. /**
  3334. * Check the validity of a professional identifier according to the country of the company (siren, siret, ...)
  3335. *
  3336. * @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
  3337. * @param Societe $soc Objet societe
  3338. * @return int <=0 if KO, >0 if OK
  3339. * TODO better to have this in a lib than into a business class
  3340. */
  3341. public function id_prof_check($idprof, $soc)
  3342. {
  3343. // phpcs:enable
  3344. global $conf;
  3345. $ok = 1;
  3346. if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
  3347. return 1;
  3348. }
  3349. // Check SIREN if country FR
  3350. if ($idprof == 1 && $soc->country_code == 'FR') {
  3351. $chaine = trim($this->idprof1);
  3352. $chaine = preg_replace('/(\s)/', '', $chaine);
  3353. if (!is_numeric($chaine)) {
  3354. return -1;
  3355. }
  3356. if (dol_strlen($chaine) != 9) {
  3357. return -1;
  3358. }
  3359. // on prend chaque chiffre un par un
  3360. // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
  3361. // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
  3362. // on ajoute cette valeur à la somme totale
  3363. $sum = 0;
  3364. for ($index = 0; $index < 9; $index++) {
  3365. $number = (int) $chaine[$index];
  3366. if (($index % 2) != 0) {
  3367. if (($number *= 2) > 9) {
  3368. $number -= 9;
  3369. }
  3370. }
  3371. $sum += $number;
  3372. }
  3373. // le numéro est valide si la somme des chiffres est multiple de 10
  3374. if (($sum % 10) != 0) {
  3375. return -1;
  3376. }
  3377. }
  3378. // Verifie SIRET si pays FR
  3379. if ($idprof == 2 && $soc->country_code == 'FR') {
  3380. $chaine = trim($this->idprof2);
  3381. $chaine = preg_replace('/(\s)/', '', $chaine);
  3382. if (!is_numeric($chaine)) {
  3383. return -1;
  3384. }
  3385. if (dol_strlen($chaine) != 14) {
  3386. return -1;
  3387. }
  3388. // on prend chaque chiffre un par un
  3389. // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
  3390. // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
  3391. // on ajoute cette valeur à la somme totale
  3392. $sum = 0;
  3393. for ($index = 0; $index < 14; $index++) {
  3394. $number = (int) $chaine[$index];
  3395. if (($index % 2) == 0) {
  3396. if (($number *= 2) > 9) {
  3397. $number -= 9;
  3398. }
  3399. }
  3400. $sum += $number;
  3401. }
  3402. // le numéro est valide si la somme des chiffres est multiple de 10
  3403. if (($sum % 10) != 0) {
  3404. return -1;
  3405. }
  3406. }
  3407. //Verify CIF/NIF/NIE if pays ES
  3408. //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
  3409. if ($idprof == 1 && $soc->country_code == 'ES') {
  3410. $string = trim($this->idprof1);
  3411. $string = preg_replace('/(\s)/', '', $string);
  3412. $string = strtoupper($string);
  3413. //Check format
  3414. if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string)) {
  3415. return 0;
  3416. }
  3417. $num = array();
  3418. for ($i = 0; $i < 9; $i++) {
  3419. $num[$i] = substr($string, $i, 1);
  3420. }
  3421. //Check NIF
  3422. if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string)) {
  3423. if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1)) {
  3424. return 1;
  3425. } else {
  3426. return -1;
  3427. }
  3428. }
  3429. //algorithm checking type code CIF
  3430. $sum = $num[2] + $num[4] + $num[6];
  3431. for ($i = 1; $i < 8; $i += 2) {
  3432. $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
  3433. }
  3434. $n = 10 - substr($sum, strlen($sum) - 1, 1);
  3435. //Chek special NIF
  3436. if (preg_match('/^[KLM]{1}/', $string)) {
  3437. if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1)) {
  3438. return 1;
  3439. } else {
  3440. return -1;
  3441. }
  3442. }
  3443. //Check CIF
  3444. if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string)) {
  3445. if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1)) {
  3446. return 2;
  3447. } else {
  3448. return -2;
  3449. }
  3450. }
  3451. //Check NIE T
  3452. if (preg_match('/^[T]{1}/', $string)) {
  3453. if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string)) {
  3454. return 3;
  3455. } else {
  3456. return -3;
  3457. }
  3458. }
  3459. //Check NIE XYZ
  3460. if (preg_match('/^[XYZ]{1}/', $string)) {
  3461. if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1)) {
  3462. return 3;
  3463. } else {
  3464. return -3;
  3465. }
  3466. }
  3467. //Can not be verified
  3468. return -4;
  3469. }
  3470. //Verify NIF if country is PT
  3471. //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
  3472. if ($idprof == 1 && $soc->country_code == 'PT') {
  3473. $string = trim($this->idprof1);
  3474. $string = preg_replace('/(\s)/', '', $string);
  3475. //Check NIF
  3476. if (preg_match('/(^[0-9]{9}$)/', $string)) {
  3477. return 1;
  3478. } else {
  3479. return -1;
  3480. }
  3481. }
  3482. //Verify NIF if country is DZ
  3483. //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
  3484. if ($idprof == 1 && $soc->country_code == 'DZ') {
  3485. $string = trim($this->idprof1);
  3486. $string = preg_replace('/(\s)/', '', $string);
  3487. //Check NIF
  3488. if (preg_match('/(^[0-9]{15}$)/', $string)) {
  3489. return 1;
  3490. } else {
  3491. return -1;
  3492. }
  3493. }
  3494. //Verify ID Prof 1 if country is BE (xxxx.xxx.xxx) (https://economie.fgov.be/fr/themes/entreprises/banque-carrefour-des/actualites/structure-du-numero)
  3495. //Returns: 1 if ok, -1 if bad, 0 if unexpected bad
  3496. if ($idprof == 1 && $soc->country_code == 'BE') {
  3497. $string = trim($this->idprof1);
  3498. $string = preg_replace('/(\s)/', '', $string);
  3499. //Check
  3500. if (preg_match('/(^[0-9]{4}\.[0-9]{3}\.[0-9]{3}$)/', $string)) {
  3501. return 1;
  3502. } else {
  3503. return -1;
  3504. }
  3505. }
  3506. return $ok;
  3507. }
  3508. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3509. /**
  3510. * Return an url to check online a professional id or empty string
  3511. *
  3512. * @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
  3513. * @param Societe $thirdparty Object thirdparty
  3514. * @return string Url or empty string if no URL known
  3515. * TODO better in a lib than into business class
  3516. */
  3517. public function id_prof_url($idprof, $thirdparty)
  3518. {
  3519. // phpcs:enable
  3520. global $conf, $langs, $hookmanager;
  3521. $url = '';
  3522. $action = '';
  3523. $hookmanager->initHooks(array('idprofurl'));
  3524. $parameters = array('idprof'=>$idprof, 'company'=>$thirdparty);
  3525. $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  3526. if (empty($reshook)) {
  3527. if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
  3528. return '';
  3529. }
  3530. // TODO Move links to validate professional ID into a dictionary table "country" + "link"
  3531. $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
  3532. if ($idprof == 1 && $thirdparty->country_code == 'FR') {
  3533. $url = 'https://annuaire-entreprises.data.gouv.fr/entreprise/'.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
  3534. }
  3535. if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
  3536. $url = 'https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
  3537. }
  3538. if ($idprof == 1 && $thirdparty->country_code == 'ES') {
  3539. $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
  3540. }
  3541. if ($idprof == 1 && $thirdparty->country_code == 'IN') {
  3542. $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
  3543. }
  3544. if ($idprof == 1 && $thirdparty->country_code == 'DZ') {
  3545. $url = 'http://nif.mfdgi.gov.dz/nif.asp?Nif='.$strippedIdProf1;
  3546. }
  3547. if ($idprof == 1 && $thirdparty->country_code == 'PT') {
  3548. $url = 'http://www.nif.pt/'.$strippedIdProf1;
  3549. }
  3550. if ($url) {
  3551. return '<a target="_blank" rel="noopener noreferrer" href="'.$url.'">'.$langs->trans("Check").'</a>';
  3552. }
  3553. } else {
  3554. return $hookmanager->resPrint;
  3555. }
  3556. return '';
  3557. }
  3558. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3559. /**
  3560. * Indicates if the company has projects
  3561. *
  3562. * @return bool true if the company has projects, false otherwise
  3563. */
  3564. public function has_projects()
  3565. {
  3566. // phpcs:enable
  3567. $sql = "SELECT COUNT(*) as numproj FROM ".MAIN_DB_PREFIX."projet WHERE fk_soc = ".((int) $this->id);
  3568. $resql = $this->db->query($sql);
  3569. if ($resql) {
  3570. $obj = $this->db->fetch_object($resql);
  3571. $count = $obj->numproj;
  3572. } else {
  3573. $count = 0;
  3574. print $this->db->error();
  3575. }
  3576. $this->db->free($resql);
  3577. return ($count > 0);
  3578. }
  3579. /**
  3580. * Load information for tab info
  3581. *
  3582. * @param int $id Id of thirdparty to load
  3583. * @return void
  3584. */
  3585. public function info($id)
  3586. {
  3587. $sql = "SELECT s.rowid, s.nom as name, s.datec, tms as datem,";
  3588. $sql .= " fk_user_creat, fk_user_modif";
  3589. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
  3590. $sql .= " WHERE s.rowid = ".((int) $id);
  3591. $result = $this->db->query($sql);
  3592. if ($result) {
  3593. if ($this->db->num_rows($result)) {
  3594. $obj = $this->db->fetch_object($result);
  3595. $this->id = $obj->rowid;
  3596. $this->user_creation_id = $obj->fk_user_creat;
  3597. $this->user_modification_id = $obj->fk_user_modif;
  3598. $this->date_creation = $this->db->jdate($obj->datec);
  3599. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  3600. $this->ref = $obj->name;
  3601. }
  3602. $this->db->free($result);
  3603. } else {
  3604. dol_print_error($this->db);
  3605. }
  3606. }
  3607. /**
  3608. * Return if third party is a company (Business) or an end user (Consumer)
  3609. *
  3610. * @return boolean true=is a company, false=a and user
  3611. */
  3612. public function isACompany()
  3613. {
  3614. global $conf;
  3615. // Define if third party is treated as company (or not) when nature is unknown
  3616. $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
  3617. if (!empty($this->tva_intra)) {
  3618. $isacompany = 1;
  3619. } elseif (!empty($this->idprof1) || !empty($this->idprof2) || !empty($this->idprof3) || !empty($this->idprof4) || !empty($this->idprof5) || !empty($this->idprof6)) {
  3620. $isacompany = 1;
  3621. } elseif (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
  3622. // TODO Add a field is_a_company into dictionary
  3623. if (preg_match('/^TE_PRIVATE/', $this->typent_code)) {
  3624. $isacompany = 0;
  3625. } else {
  3626. $isacompany = 1;
  3627. }
  3628. }
  3629. return $isacompany;
  3630. }
  3631. /**
  3632. * Return if a company is inside the EEC (European Economic Community)
  3633. *
  3634. * @return boolean true = country inside EEC, false = country outside EEC
  3635. */
  3636. public function isInEEC()
  3637. {
  3638. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  3639. return isInEEC($this);
  3640. }
  3641. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3642. /**
  3643. * Load the list of provider categories
  3644. *
  3645. * @return int 0 if success, <> 0 if error
  3646. */
  3647. public function LoadSupplierCateg()
  3648. {
  3649. // phpcs:enable
  3650. $this->SupplierCategories = array();
  3651. $sql = "SELECT rowid, label";
  3652. $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
  3653. $sql .= " WHERE type = ".Categorie::TYPE_SUPPLIER;
  3654. $resql = $this->db->query($sql);
  3655. if ($resql) {
  3656. while ($obj = $this->db->fetch_object($resql)) {
  3657. $this->SupplierCategories[$obj->rowid] = $obj->label;
  3658. }
  3659. return 0;
  3660. } else {
  3661. return -1;
  3662. }
  3663. }
  3664. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3665. /**
  3666. * Insert link supplier - category
  3667. *
  3668. * @param int $categorie_id Id of category
  3669. * @return int 0 if success, <> 0 if error
  3670. */
  3671. public function AddFournisseurInCategory($categorie_id)
  3672. {
  3673. // phpcs:enable
  3674. if ($categorie_id > 0 && $this->id > 0) {
  3675. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
  3676. $sql .= " VALUES (".((int) $categorie_id).", ".((int) $this->id).")";
  3677. if ($resql = $this->db->query($sql)) {
  3678. return 0;
  3679. }
  3680. } else {
  3681. return 0;
  3682. }
  3683. return -1;
  3684. }
  3685. /**
  3686. * Return number of mass Emailing received by this contacts with its email
  3687. *
  3688. * @return int Number of EMailings
  3689. */
  3690. public function getNbOfEMailings()
  3691. {
  3692. $sql = "SELECT count(mc.email) as nb";
  3693. $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc, ".MAIN_DB_PREFIX."mailing as m";
  3694. $sql .= " WHERE mc.fk_mailing=m.rowid AND mc.email = '".$this->db->escape($this->email)."' ";
  3695. $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success
  3696. $resql = $this->db->query($sql);
  3697. if ($resql) {
  3698. $obj = $this->db->fetch_object($resql);
  3699. $nb = $obj->nb;
  3700. $this->db->free($resql);
  3701. return $nb;
  3702. } else {
  3703. $this->error = $this->db->error();
  3704. return -1;
  3705. }
  3706. }
  3707. /**
  3708. * Set "blacklist" mailing status
  3709. *
  3710. * @param int $no_email 1=Do not send mailing, 0=Ok to recieve mailling
  3711. * @return int <0 if KO, >0 if OK
  3712. */
  3713. public function setNoEmail($no_email)
  3714. {
  3715. $error = 0;
  3716. // Update mass emailing flag into table mailing_unsubscribe
  3717. if ($this->email) {
  3718. $this->db->begin();
  3719. if ($no_email) {
  3720. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$this->db->escape($this->email)."'";
  3721. $resql = $this->db->query($sql);
  3722. if ($resql) {
  3723. $obj = $this->db->fetch_object($resql);
  3724. $noemail = $obj->nb;
  3725. if (empty($noemail)) {
  3726. $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$this->db->escape($this->email)."', ".getEntity('mailing', 0).", '".$this->db->idate(dol_now())."')";
  3727. $resql = $this->db->query($sql);
  3728. if (!$resql) {
  3729. $error++;
  3730. $this->error = $this->db->lasterror();
  3731. $this->errors[] = $this->error;
  3732. }
  3733. }
  3734. } else {
  3735. $error++;
  3736. $this->error = $this->db->lasterror();
  3737. $this->errors[] = $this->error;
  3738. }
  3739. } else {
  3740. $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity IN (".getEntity('mailing', 0).")";
  3741. $resql = $this->db->query($sql);
  3742. if (!$resql) {
  3743. $error++;
  3744. $this->error = $this->db->lasterror();
  3745. $this->errors[] = $this->error;
  3746. }
  3747. }
  3748. if (empty($error)) {
  3749. $this->no_email = $no_email;
  3750. $this->db->commit();
  3751. return 1;
  3752. } else {
  3753. $this->db->rollback();
  3754. return $error * -1;
  3755. }
  3756. }
  3757. return 0;
  3758. }
  3759. /**
  3760. * get "blacklist" mailing status
  3761. * set no_email attribut to 1 or 0
  3762. *
  3763. * @return int <0 if KO, >0 if OK
  3764. */
  3765. public function getNoEmail()
  3766. {
  3767. if ($this->email) {
  3768. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'";
  3769. $resql = $this->db->query($sql);
  3770. if ($resql) {
  3771. $obj = $this->db->fetch_object($resql);
  3772. $this->no_email = $obj->nb;
  3773. return 1;
  3774. } else {
  3775. $this->error = $this->db->lasterror();
  3776. $this->errors[] = $this->error;
  3777. return -1;
  3778. }
  3779. }
  3780. return 0;
  3781. }
  3782. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3783. /**
  3784. * Create a third party into database from a member object
  3785. *
  3786. * @param Adherent $member Object member
  3787. * @param string $socname Name of third party to force
  3788. * @param string $socalias Alias name of third party to force
  3789. * @param string $customercode Customer code
  3790. * @return int <0 if KO, id of created account if OK
  3791. */
  3792. public function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
  3793. {
  3794. // phpcs:enable
  3795. global $conf, $user, $langs;
  3796. dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
  3797. $fullname = $member->getFullName($langs);
  3798. if ($member->morphy == 'mor') {
  3799. if (empty($socname)) {
  3800. $socname = $member->company? $member->company : $member->societe;
  3801. }
  3802. if (!empty($fullname) && empty($socalias)) {
  3803. $socalias = $fullname;
  3804. }
  3805. } elseif (empty($socname) && $member->morphy == 'phy') {
  3806. if (empty($socname)) {
  3807. $socname = $fullname;
  3808. }
  3809. if (!empty($member->company) && empty($socalias)) {
  3810. $socalias = $member->company;
  3811. }
  3812. }
  3813. $name = $socname;
  3814. $alias = $socalias ? $socalias : '';
  3815. // Positionne parametres
  3816. $this->nom = $name; // TODO deprecated
  3817. $this->name = $name;
  3818. $this->name_alias = $alias;
  3819. $this->address = $member->address;
  3820. $this->zip = $member->zip;
  3821. $this->town = $member->town;
  3822. $this->country_code = $member->country_code;
  3823. $this->country_id = $member->country_id;
  3824. $this->phone = $member->phone; // Prof phone
  3825. $this->email = $member->email;
  3826. $this->socialnetworks = $member->socialnetworks;
  3827. $this->entity = $member->entity;
  3828. $this->client = 1; // A member is a customer by default
  3829. $this->code_client = ($customercode ? $customercode : -1);
  3830. $this->code_fournisseur = -1;
  3831. $this->typent_code = ($member->morphy == 'phy' ? 'TE_PRIVATE' : 0);
  3832. $this->typent_id = $this->typent_code ? dol_getIdFromCode($this->db, $this->typent_code, 'c_typent', 'id', 'code') : 0;
  3833. $this->db->begin();
  3834. // Cree et positionne $this->id
  3835. $result = $this->create($user);
  3836. if ($result >= 0) {
  3837. // Auto-create contact on thirdparty creation
  3838. if (!empty($conf->global->THIRDPARTY_DEFAULT_CREATE_CONTACT)) {
  3839. // Fill fields needed by contact
  3840. $this->name_bis = $member->lastname;
  3841. $this->firstname = $member->firstname;
  3842. $this->civility_id = $member->civility_id;
  3843. dol_syslog("We ask to create a contact/address too", LOG_DEBUG);
  3844. $result = $this->create_individual($user);
  3845. if ($result < 0) {
  3846. setEventMessages($this->error, $this->errors, 'errors');
  3847. $this->db->rollback();
  3848. return -1;
  3849. }
  3850. }
  3851. $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
  3852. $sql .= " SET fk_soc = ".((int) $this->id);
  3853. $sql .= " WHERE rowid = ".((int) $member->id);
  3854. $resql = $this->db->query($sql);
  3855. if ($resql) {
  3856. $this->db->commit();
  3857. return $this->id;
  3858. } else {
  3859. $this->error = $this->db->error();
  3860. $this->db->rollback();
  3861. return -1;
  3862. }
  3863. } else {
  3864. // $this->error deja positionne
  3865. dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',', $this->errors), LOG_ERR);
  3866. $this->db->rollback();
  3867. return $result;
  3868. }
  3869. }
  3870. /**
  3871. * Set properties with value into $conf
  3872. *
  3873. * @param Conf $conf Conf object (possibility to use another entity)
  3874. * @return void
  3875. */
  3876. public function setMysoc(Conf $conf)
  3877. {
  3878. global $langs;
  3879. $this->id = 0;
  3880. $this->entity = $conf->entity;
  3881. $this->name = getDolGlobalString('MAIN_INFO_SOCIETE_NOM');
  3882. $this->nom = $this->name; // deprecated
  3883. $this->address = getDolGlobalString('MAIN_INFO_SOCIETE_ADDRESS');
  3884. $this->zip = getDolGlobalString('MAIN_INFO_SOCIETE_ZIP');
  3885. $this->town = getDolGlobalString('MAIN_INFO_SOCIETE_TOWN');
  3886. $this->region_code = getDolGlobalString('MAIN_INFO_SOCIETE_REGION');
  3887. $this->socialobject = getDolGlobalString('MAIN_INFO_SOCIETE_OBJECT');
  3888. $this->note_private = getDolGlobalString('MAIN_INFO_SOCIETE_NOTE');
  3889. // We define country_id, country_code and country
  3890. $country_id = $country_code = $country_label = '';
  3891. if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
  3892. $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
  3893. $country_id = $tmp[0];
  3894. if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
  3895. $country_code = $tmp[1];
  3896. $country_label = $tmp[2];
  3897. } else {
  3898. // For backward compatibility
  3899. dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_WARNING);
  3900. include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  3901. $country_code = getCountry($country_id, 2, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
  3902. $country_label = getCountry($country_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
  3903. }
  3904. }
  3905. $this->country_id = $country_id;
  3906. $this->country_code = $country_code;
  3907. $this->country = $country_label;
  3908. if (is_object($langs)) {
  3909. $this->country = ($langs->trans('Country'.$country_code) != 'Country'.$country_code) ? $langs->trans('Country'.$country_code) : $country_label;
  3910. }
  3911. //TODO This could be replicated for region but function `getRegion` didn't exist, so I didn't added it.
  3912. // We define state_id, state_code and state
  3913. $state_id = 0; $state_code = $state_label = '';
  3914. if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
  3915. $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE);
  3916. $state_id = $tmp[0];
  3917. if (!empty($tmp[1])) { // If $conf->global->MAIN_INFO_SOCIETE_STATE is "id:code:label"
  3918. $state_code = $tmp[1];
  3919. $state_label = $tmp[2];
  3920. } else { // For backward compatibility
  3921. dol_syslog("Your setup of State has an old syntax (entity=".$conf->entity."). Go in Home - Setup - Organization then Save should remove this error.", LOG_ERR);
  3922. include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  3923. $state_code = getState($state_id, 2, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
  3924. $state_label = getState($state_id, 0, $this->db); // This need a SQL request, but it's the old feature that should not be used anymore
  3925. }
  3926. }
  3927. $this->state_id = $state_id;
  3928. $this->state_code = $state_code;
  3929. $this->state = $state_label;
  3930. if (is_object($langs)) {
  3931. $this->state = ($langs->trans('State'.$state_code) != 'State'.$state_code) ? $langs->trans('State'.$state_code) : $state_label;
  3932. }
  3933. $this->phone = getDolGlobalString('MAIN_INFO_SOCIETE_TEL');
  3934. $this->fax = getDolGlobalString('MAIN_INFO_SOCIETE_FAX');
  3935. $this->url = getDolGlobalString('MAIN_INFO_SOCIETE_WEB');
  3936. // Social networks
  3937. $facebook_url = getDolGlobalString('MAIN_INFO_SOCIETE_FACEBOOK_URL');
  3938. $twitter_url = getDolGlobalString('MAIN_INFO_SOCIETE_TWITTER_URL');
  3939. $linkedin_url = getDolGlobalString('MAIN_INFO_SOCIETE_LINKEDIN_URL');
  3940. $instagram_url = getDolGlobalString('MAIN_INFO_SOCIETE_INSTAGRAM_URL');
  3941. $youtube_url = getDolGlobalString('MAIN_INFO_SOCIETE_YOUTUBE_URL');
  3942. $github_url = getDolGlobalString('MAIN_INFO_SOCIETE_GITHUB_URL');
  3943. $this->socialnetworks = array();
  3944. if (!empty($facebook_url)) {
  3945. $this->socialnetworks['facebook'] = $facebook_url;
  3946. }
  3947. if (!empty($twitter_url)) {
  3948. $this->socialnetworks['twitter'] = $twitter_url;
  3949. }
  3950. if (!empty($linkedin_url)) {
  3951. $this->socialnetworks['linkedin'] = $linkedin_url;
  3952. }
  3953. if (!empty($instagram_url)) {
  3954. $this->socialnetworks['instagram'] = $instagram_url;
  3955. }
  3956. if (!empty($youtube_url)) {
  3957. $this->socialnetworks['youtube'] = $youtube_url;
  3958. }
  3959. if (!empty($github_url)) {
  3960. $this->socialnetworks['github'] = $github_url;
  3961. }
  3962. // Id prof generiques
  3963. $this->idprof1 = getDolGlobalString('MAIN_INFO_SIREN');
  3964. $this->idprof2 = getDolGlobalString('MAIN_INFO_SIRET');
  3965. $this->idprof3 = getDolGlobalString('MAIN_INFO_APE');
  3966. $this->idprof4 = getDolGlobalString('MAIN_INFO_RCS');
  3967. $this->idprof5 = getDolGlobalString('MAIN_INFO_PROFID5');
  3968. $this->idprof6 = getDolGlobalString('MAIN_INFO_PROFID6');
  3969. $this->tva_intra = getDolGlobalString('MAIN_INFO_TVAINTRA'); // VAT number, not necessarly INTRA.
  3970. $this->managers = getDolGlobalString('MAIN_INFO_SOCIETE_MANAGERS');
  3971. $this->capital = getDolGlobalString('MAIN_INFO_CAPITAL');
  3972. $this->forme_juridique_code = getDolGlobalString('MAIN_INFO_SOCIETE_FORME_JURIDIQUE');
  3973. $this->email = getDolGlobalString('MAIN_INFO_SOCIETE_MAIL');
  3974. $this->default_lang = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
  3975. $this->logo =getDolGlobalString('MAIN_INFO_SOCIETE_LOGO');
  3976. $this->logo_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SMALL');
  3977. $this->logo_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_MINI');
  3978. $this->logo_squarred = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED');
  3979. $this->logo_squarred_small = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_SMALL');
  3980. $this->logo_squarred_mini = getDolGlobalString('MAIN_INFO_SOCIETE_LOGO_SQUARRED_MINI');
  3981. // Define if company use vat or not
  3982. $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
  3983. // Define if company use local taxes
  3984. $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX1_OPTION') == 'localtax1on')) ? 1 : 0);
  3985. $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && (getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == '1' || getDolGlobalString('FACTURE_LOCAL_TAX2_OPTION') == 'localtax2on')) ? 1 : 0);
  3986. }
  3987. /**
  3988. * Initialise an instance with random values.
  3989. * Used to build previews or test instances.
  3990. * id must be 0 if object instance is a specimen.
  3991. *
  3992. * @return int >0 if ok
  3993. */
  3994. public function initAsSpecimen()
  3995. {
  3996. $now = dol_now();
  3997. // Initialize parameters
  3998. $this->id = 0;
  3999. $this->entity = 1;
  4000. $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now, 'dayhourlog');
  4001. $this->nom = $this->name; // For backward compatibility
  4002. $this->ref_ext = 'Ref ext';
  4003. $this->specimen = 1;
  4004. $this->address = '21 jump street';
  4005. $this->zip = '99999';
  4006. $this->town = 'MyTown';
  4007. $this->state_id = 1;
  4008. $this->state_code = 'AA';
  4009. $this->state = 'MyState';
  4010. $this->country_id = 1;
  4011. $this->country_code = 'FR';
  4012. $this->email = 'specimen@specimen.com';
  4013. $this->socialnetworks = array(
  4014. 'skype' => 'skypepseudo',
  4015. 'twitter' => 'twitterpseudo',
  4016. 'facebook' => 'facebookpseudo',
  4017. 'linkedin' => 'linkedinpseudo',
  4018. );
  4019. $this->url = 'http://www.specimen.com';
  4020. $this->phone = '0909090901';
  4021. $this->fax = '0909090909';
  4022. $this->code_client = 'CC-'.dol_print_date($now, 'dayhourlog');
  4023. $this->code_fournisseur = 'SC-'.dol_print_date($now, 'dayhourlog');
  4024. $this->capital = 10000;
  4025. $this->client = 1;
  4026. $this->prospect = 1;
  4027. $this->fournisseur = 1;
  4028. $this->tva_assuj = 1;
  4029. $this->tva_intra = 'EU1234567';
  4030. $this->note_public = 'This is a comment (public)';
  4031. $this->note_private = 'This is a comment (private)';
  4032. $this->idprof1 = 'idprof1';
  4033. $this->idprof2 = 'idprof2';
  4034. $this->idprof3 = 'idprof3';
  4035. $this->idprof4 = 'idprof4';
  4036. $this->idprof5 = 'idprof5';
  4037. $this->idprof6 = 'idprof6';
  4038. return 1;
  4039. }
  4040. /**
  4041. * Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
  4042. *
  4043. * @param int $localTaxNum To get info for only localtax1 or localtax2
  4044. * @return boolean true or false
  4045. */
  4046. public function useLocalTax($localTaxNum = 0)
  4047. {
  4048. $sql = "SELECT t.localtax1, t.localtax2";
  4049. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4050. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
  4051. $sql .= " AND t.active = 1";
  4052. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  4053. if (empty($localTaxNum)) {
  4054. $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
  4055. } elseif ($localTaxNum == 1) {
  4056. $sql .= " AND t.localtax1_type <> '0'";
  4057. } elseif ($localTaxNum == 2) {
  4058. $sql .= " AND t.localtax2_type <> '0'";
  4059. }
  4060. $resql = $this->db->query($sql);
  4061. if ($resql) {
  4062. return ($this->db->num_rows($resql) > 0);
  4063. } else {
  4064. return false;
  4065. }
  4066. }
  4067. /**
  4068. * Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
  4069. *
  4070. * @return boolean true or false
  4071. */
  4072. public function useNPR()
  4073. {
  4074. $sql = "SELECT t.rowid";
  4075. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  4076. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
  4077. $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
  4078. $sql .= " AND t.entity IN (".getEntity('c_tva').")";
  4079. dol_syslog("useNPR", LOG_DEBUG);
  4080. $resql = $this->db->query($sql);
  4081. if ($resql) {
  4082. return ($this->db->num_rows($resql) > 0);
  4083. } else {
  4084. return false;
  4085. }
  4086. }
  4087. /**
  4088. * Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
  4089. * Table c_revenuestamp contains the country and value of stamp per invoice.
  4090. *
  4091. * @return boolean true or false
  4092. */
  4093. public function useRevenueStamp()
  4094. {
  4095. $sql = "SELECT COUNT(*) as nb";
  4096. $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
  4097. $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
  4098. $sql .= " AND r.active = 1";
  4099. dol_syslog("useRevenueStamp", LOG_DEBUG);
  4100. $resql = $this->db->query($sql);
  4101. if ($resql) {
  4102. $obj = $this->db->fetch_object($resql);
  4103. return (($obj->nb > 0) ?true:false);
  4104. } else {
  4105. $this->error = $this->db->lasterror();
  4106. return false;
  4107. }
  4108. }
  4109. /**
  4110. * Return prostect level
  4111. *
  4112. * @return string Label of prospect status
  4113. */
  4114. public function getLibProspLevel()
  4115. {
  4116. return $this->LibProspLevel($this->fk_prospectlevel);
  4117. }
  4118. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4119. /**
  4120. * Return label of prospect level
  4121. *
  4122. * @param int $fk_prospectlevel Prospect level
  4123. * @return string label of level
  4124. */
  4125. public function LibProspLevel($fk_prospectlevel)
  4126. {
  4127. // phpcs:enable
  4128. global $langs;
  4129. $lib = $langs->trans("ProspectLevel".$fk_prospectlevel);
  4130. // If lib not found in language file, we get label from cache/databse
  4131. if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) {
  4132. $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
  4133. }
  4134. return $lib;
  4135. }
  4136. /**
  4137. * Return status of prospect
  4138. *
  4139. * @param int $mode 0=label long, 1=label short, 2=Picto + Label short, 3=Picto, 4=Picto + Label long
  4140. * @param string $label Label to use for status for added status
  4141. * @return string Label
  4142. */
  4143. public function getLibProspCommStatut($mode = 0, $label = '')
  4144. {
  4145. return $this->LibProspCommStatut($this->stcomm_id, $mode, $label, $this->stcomm_picto);
  4146. }
  4147. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4148. /**
  4149. * Return label of a given status
  4150. *
  4151. * @param int|string $status Id or code for prospection status
  4152. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  4153. * @param string $label Label to use for status for added status
  4154. * @param string $picto Name of image file to show ('filenew', ...)
  4155. * If no extension provided, we use '.png'. Image must be stored into theme/xxx/img directory.
  4156. * Example: picto.png if picto.png is stored into htdocs/theme/mytheme/img
  4157. * Example: picto.png@mymodule if picto.png is stored into htdocs/mymodule/img
  4158. * Example: /mydir/mysubdir/picto.png if picto.png is stored into htdocs/mydir/mysubdir (pictoisfullpath must be set to 1)
  4159. * @return string Label of prospection status
  4160. */
  4161. public function LibProspCommStatut($status, $mode = 0, $label = '', $picto = '')
  4162. {
  4163. // phpcs:enable
  4164. global $langs;
  4165. $langs->load('customers');
  4166. if ($mode == 2) {
  4167. if ($status == '-1' || $status == 'ST_NO') {
  4168. return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
  4169. } elseif ($status == '0' || $status == 'ST_NEVER') {
  4170. return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
  4171. } elseif ($status == '1' || $status == 'ST_TODO') {
  4172. return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
  4173. } elseif ($status == '2' || $status == 'ST_PEND') {
  4174. return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
  4175. } elseif ($status == '3' || $status == 'ST_DONE') {
  4176. return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
  4177. } else {
  4178. return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"').' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
  4179. }
  4180. } elseif ($mode == 3) {
  4181. if ($status == '-1' || $status == 'ST_NO') {
  4182. return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"');
  4183. } elseif ($status == '0' || $status == 'ST_NEVER') {
  4184. return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"');
  4185. } elseif ($status == '1' || $status == 'ST_TODO') {
  4186. return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"');
  4187. } elseif ($status == '2' || $status == 'ST_PEND') {
  4188. return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"');
  4189. } elseif ($status == '3' || $status == 'ST_DONE') {
  4190. return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"');
  4191. } else {
  4192. return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"');
  4193. }
  4194. } elseif ($mode == 4) {
  4195. if ($status == '-1' || $status == 'ST_NO') {
  4196. return img_action($langs->trans("StatusProspect-1"), -1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect-1");
  4197. } elseif ($status == '0' || $status == 'ST_NEVER') {
  4198. return img_action($langs->trans("StatusProspect0"), 0, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect0");
  4199. } elseif ($status == '1' || $status == 'ST_TODO') {
  4200. return img_action($langs->trans("StatusProspect1"), 1, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect1");
  4201. } elseif ($status == '2' || $status == 'ST_PEND') {
  4202. return img_action($langs->trans("StatusProspect2"), 2, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect2");
  4203. } elseif ($status == '3' || $status == 'ST_DONE') {
  4204. return img_action($langs->trans("StatusProspect3"), 3, $picto, 'class="inline-block valignmiddle"').' '.$langs->trans("StatusProspect3");
  4205. } else {
  4206. return img_action(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label, 0, $picto, 'class="inline-block valignmiddle"').' '.(($langs->trans("StatusProspect".$status) != "StatusProspect".$status) ? $langs->trans("StatusProspect".$status) : $label);
  4207. }
  4208. }
  4209. return "Error, mode/status not found";
  4210. }
  4211. /**
  4212. * Return amount of proposal not yet paid and total an dlist of all proposals
  4213. *
  4214. * @param string $mode 'customer' or 'supplier'
  4215. * @return array array('opened'=>Amount including tax that remains to pay, 'total_ht'=>Total amount without tax of all objects paid or not, 'total_ttc'=>Total amunt including tax of all object paid or not)
  4216. */
  4217. public function getOutstandingProposals($mode = 'customer')
  4218. {
  4219. $table = 'propal';
  4220. if ($mode == 'supplier') {
  4221. $table = 'supplier_proposal';
  4222. }
  4223. $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
  4224. $sql .= " WHERE fk_soc = ".((int) $this->id);
  4225. if ($mode == 'supplier') {
  4226. $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
  4227. } else {
  4228. $sql .= " AND entity IN (".getEntity('propal').")";
  4229. }
  4230. dol_syslog("getOutstandingProposals for fk_soc = ".((int) $this->id), LOG_DEBUG);
  4231. $resql = $this->db->query($sql);
  4232. if ($resql) {
  4233. $outstandingOpened = 0;
  4234. $outstandingTotal = 0;
  4235. $outstandingTotalIncTax = 0;
  4236. $arrayofref = array();
  4237. while ($obj = $this->db->fetch_object($resql)) {
  4238. $arrayofref[$obj->rowid] = $obj->ref;
  4239. $outstandingTotal += $obj->total_ht;
  4240. $outstandingTotalIncTax += $obj->total_ttc;
  4241. if ($obj->status != 0) {
  4242. // Not a draft
  4243. $outstandingOpened += $obj->total_ttc;
  4244. }
  4245. }
  4246. return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
  4247. } else {
  4248. return array();
  4249. }
  4250. }
  4251. /**
  4252. * Return amount of order not yet paid and total and list of all orders
  4253. *
  4254. * @param string $mode 'customer' or 'supplier'
  4255. * @return array array('opened'=>Amount including tax that remains to pay, 'total_ht'=>Total amount without tax of all objects paid or not, 'total_ttc'=>Total amunt including tax of all object paid or not)
  4256. */
  4257. public function getOutstandingOrders($mode = 'customer')
  4258. {
  4259. $table = 'commande';
  4260. if ($mode == 'supplier') {
  4261. $table = 'commande_fournisseur';
  4262. }
  4263. $sql = "SELECT rowid, ref, total_ht, total_ttc, fk_statut as status FROM ".MAIN_DB_PREFIX.$table." as f";
  4264. $sql .= " WHERE fk_soc = ".((int) $this->id);
  4265. if ($mode == 'supplier') {
  4266. $sql .= " AND entity IN (".getEntity('supplier_order').")";
  4267. } else {
  4268. $sql .= " AND entity IN (".getEntity('commande').")";
  4269. }
  4270. dol_syslog("getOutstandingOrders", LOG_DEBUG);
  4271. $resql = $this->db->query($sql);
  4272. if ($resql) {
  4273. $outstandingOpened = 0;
  4274. $outstandingTotal = 0;
  4275. $outstandingTotalIncTax = 0;
  4276. $arrayofref = array();
  4277. while ($obj = $this->db->fetch_object($resql)) {
  4278. $arrayofref[$obj->rowid] = $obj->ref;
  4279. $outstandingTotal += $obj->total_ht;
  4280. $outstandingTotalIncTax += $obj->total_ttc;
  4281. if ($obj->status != 0) {
  4282. // Not a draft
  4283. $outstandingOpened += $obj->total_ttc;
  4284. }
  4285. }
  4286. return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref); // 'opened' is 'incl taxes'
  4287. } else {
  4288. return array();
  4289. }
  4290. }
  4291. /**
  4292. * Return amount of bill not yet paid and total of all invoices
  4293. *
  4294. * @param string $mode 'customer' or 'supplier'
  4295. * @param int $late 0 => all invoice, 1=> only late
  4296. * @return array array('opened'=>Amount including tax that remains to pay, 'total_ht'=>Total amount without tax of all objects paid or not, 'total_ttc'=>Total amunt including tax of all object paid or not)
  4297. */
  4298. public function getOutstandingBills($mode = 'customer', $late = 0)
  4299. {
  4300. $table = 'facture';
  4301. if ($mode == 'supplier') {
  4302. $table = 'facture_fourn';
  4303. }
  4304. /* Accurate value of remain to pay is to sum remaintopay for each invoice
  4305. $paiement = $invoice->getSommePaiement();
  4306. $creditnotes=$invoice->getSumCreditNotesUsed();
  4307. $deposits=$invoice->getSumDepositsUsed();
  4308. $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
  4309. $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
  4310. */
  4311. $sql = "SELECT rowid, ref, total_ht, total_ttc, paye, type, fk_statut as status, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
  4312. $sql .= " WHERE fk_soc = ".((int) $this->id);
  4313. if (!empty($late)) {
  4314. $sql .= " AND date_lim_reglement < '".$this->db->idate(dol_now())."'";
  4315. }
  4316. if ($mode == 'supplier') {
  4317. $sql .= " AND entity IN (".getEntity('facture_fourn').")";
  4318. } else {
  4319. $sql .= " AND entity IN (".getEntity('invoice').")";
  4320. }
  4321. dol_syslog("getOutstandingBills", LOG_DEBUG);
  4322. $resql = $this->db->query($sql);
  4323. if ($resql) {
  4324. $outstandingOpened = 0;
  4325. $outstandingTotal = 0;
  4326. $outstandingTotalIncTax = 0;
  4327. $arrayofref = array();
  4328. $arrayofrefopened = array();
  4329. if ($mode == 'supplier') {
  4330. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  4331. $tmpobject = new FactureFournisseur($this->db);
  4332. } else {
  4333. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  4334. $tmpobject = new Facture($this->db);
  4335. }
  4336. while ($obj = $this->db->fetch_object($resql)) {
  4337. $arrayofref[$obj->rowid] = $obj->ref;
  4338. $tmpobject->id = $obj->rowid;
  4339. if ($obj->status != $tmpobject::STATUS_DRAFT // Not a draft
  4340. && !($obj->status == $tmpobject::STATUS_ABANDONED && $obj->close_code == 'replaced') // Not a replaced invoice
  4341. ) {
  4342. $outstandingTotal += $obj->total_ht;
  4343. $outstandingTotalIncTax += $obj->total_ttc;
  4344. }
  4345. $remaintopay = 0;
  4346. if ($obj->paye == 0
  4347. && $obj->status != $tmpobject::STATUS_DRAFT // Not a draft
  4348. && $obj->status != $tmpobject::STATUS_ABANDONED // Not abandonned
  4349. && $obj->status != $tmpobject::STATUS_CLOSED) { // Not classified as paid
  4350. //$sql .= " AND (status <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
  4351. $paiement = $tmpobject->getSommePaiement();
  4352. $creditnotes = $tmpobject->getSumCreditNotesUsed();
  4353. $deposits = $tmpobject->getSumDepositsUsed();
  4354. $remaintopay = ($obj->total_ttc - $paiement - $creditnotes - $deposits);
  4355. $outstandingOpened += $remaintopay;
  4356. }
  4357. //if credit note is converted but not used
  4358. // TODO Do this also for customer ?
  4359. if ($mode == 'supplier' && $obj->type == FactureFournisseur::TYPE_CREDIT_NOTE && $tmpobject->isCreditNoteUsed()) {
  4360. $remainingcreditnote = $tmpobject->getSumFromThisCreditNotesNotUsed();
  4361. $remaintopay -= $remainingcreditnote;
  4362. $outstandingOpened -= $remainingcreditnote;
  4363. }
  4364. if ($remaintopay) {
  4365. $arrayofrefopened[$obj->rowid] = $obj->ref;
  4366. }
  4367. }
  4368. return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax, 'refs'=>$arrayofref, 'refsopened'=>$arrayofrefopened); // 'opened' is 'incl taxes'
  4369. } else {
  4370. dol_syslog("Sql error ".$this->db->lasterror, LOG_ERR);
  4371. return array();
  4372. }
  4373. }
  4374. /**
  4375. * Return label of status customer is prospect/customer
  4376. *
  4377. * @return string Label
  4378. * @see getTypeUrl()
  4379. */
  4380. public function getLibCustProspStatut()
  4381. {
  4382. return $this->LibCustProspStatut($this->client);
  4383. }
  4384. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4385. /**
  4386. * Return the label of the customer/prospect status
  4387. *
  4388. * @param int $status Id of prospection status
  4389. * @return string Label of prospection status
  4390. */
  4391. public function LibCustProspStatut($status)
  4392. {
  4393. // phpcs:enable
  4394. global $langs;
  4395. $langs->load('companies');
  4396. if ($status == 0) {
  4397. return $langs->trans("NorProspectNorCustomer");
  4398. } elseif ($status == 1) {
  4399. return $langs->trans("Customer");
  4400. } elseif ($status == 2) {
  4401. return $langs->trans("Prospect");
  4402. } elseif ($status == 3) {
  4403. return $langs->trans("ProspectCustomer");
  4404. }
  4405. return '';
  4406. }
  4407. /**
  4408. * Create a document onto disk according to template module.
  4409. *
  4410. * @param string $modele Generator to use. Caller must set it to obj->model_pdf or GETPOST('model','alpha') for example.
  4411. * @param Translate $outputlangs objet lang a utiliser pour traduction
  4412. * @param int $hidedetails Hide details of lines
  4413. * @param int $hidedesc Hide description
  4414. * @param int $hideref Hide ref
  4415. * @param null|array $moreparams Array to provide more information
  4416. * @return int <0 if KO, >0 if OK
  4417. */
  4418. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  4419. {
  4420. global $conf, $user, $langs;
  4421. if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
  4422. $modelpath = "core/modules/bank/doc/";
  4423. include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  4424. $companybankaccount = new CompanyBankAccount($this->db);
  4425. $result = $companybankaccount->fetch($moreparams['use_companybankid']);
  4426. if (!$result) {
  4427. dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
  4428. }
  4429. $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  4430. $this->last_main_doc=$companybankaccount->last_main_doc;
  4431. } else {
  4432. // Positionne le modele sur le nom du modele a utiliser
  4433. if (!dol_strlen($modele)) {
  4434. if (!empty($conf->global->COMPANY_ADDON_PDF)) {
  4435. $modele = $conf->global->COMPANY_ADDON_PDF;
  4436. } else {
  4437. print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
  4438. return 0;
  4439. }
  4440. }
  4441. if (!isset($this->bank_account)) {
  4442. require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  4443. $bac = new CompanyBankAccount($this->db);
  4444. $result = $bac->fetch(0, $this->id);
  4445. if ($result > 0) {
  4446. $this->bank_account = $bac;
  4447. } else {
  4448. $this->bank_account = '';
  4449. }
  4450. }
  4451. $modelpath = "core/modules/societe/doc/";
  4452. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  4453. }
  4454. return $result;
  4455. }
  4456. /**
  4457. * Sets object to supplied categories.
  4458. *
  4459. * Deletes object from existing categories not supplied.
  4460. * Adds it to non existing supplied categories.
  4461. * Existing categories are left untouch.
  4462. *
  4463. * @param int[]|int $categories Category ID or array of Categories IDs
  4464. * @param string $type_categ Category type ('customer' or 'supplier')
  4465. * @return int <0 if KO, >0 if OK
  4466. */
  4467. public function setCategories($categories, $type_categ)
  4468. {
  4469. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  4470. // Decode type
  4471. if (!in_array($type_categ, array(Categorie::TYPE_CUSTOMER, Categorie::TYPE_SUPPLIER))) {
  4472. dol_syslog(__METHOD__.': Type '.$type_categ.'is an unknown company category type. Done nothing.', LOG_ERR);
  4473. return -1;
  4474. }
  4475. return parent::setCategoriesCommon($categories, $type_categ);
  4476. }
  4477. /**
  4478. * Sets sales representatives of the thirdparty
  4479. *
  4480. * @param int[]|int $salesrep User ID or array of user IDs
  4481. * @param bool $onlyAdd Only add (no delete before)
  4482. * @return int <0 if KO, >0 if OK
  4483. */
  4484. public function setSalesRep($salesrep, $onlyAdd = false)
  4485. {
  4486. global $user;
  4487. // Handle single user
  4488. if (!is_array($salesrep)) {
  4489. $salesrep = array($salesrep);
  4490. }
  4491. $to_del = array(); // Nothing to delete
  4492. $to_add = $salesrep;
  4493. if ($onlyAdd === false) {
  4494. // Get current users
  4495. $existing = $this->getSalesRepresentatives($user, 1);
  4496. // Diff
  4497. if (is_array($existing)) {
  4498. $to_del = array_diff($existing, $salesrep);
  4499. $to_add = array_diff($salesrep, $existing);
  4500. }
  4501. }
  4502. $error = 0;
  4503. // Process
  4504. foreach ($to_del as $del) {
  4505. $this->del_commercial($user, $del);
  4506. }
  4507. foreach ($to_add as $add) {
  4508. $result = $this->add_commercial($user, $add);
  4509. if ($result < 0) {
  4510. $error++;
  4511. break;
  4512. }
  4513. }
  4514. return $error ? -1 : 1;
  4515. }
  4516. /**
  4517. * Define third-party type of current company
  4518. *
  4519. * @param int $typent_id third party type rowid in llx_c_typent
  4520. * @return int <0 if KO, >0 if OK
  4521. */
  4522. public function setThirdpartyType($typent_id)
  4523. {
  4524. global $user;
  4525. dol_syslog(__METHOD__, LOG_DEBUG);
  4526. if ($this->id) {
  4527. $result = $this->setValueFrom('fk_typent', $typent_id, '', null, '', '', $user, 'COMPANY_MODIFY');
  4528. if ($result > 0) {
  4529. $this->typent_id = $typent_id;
  4530. $this->typent_code = dol_getIdFromCode($this->db, $this->typent_id, 'c_typent', 'id', 'code');
  4531. return 1;
  4532. } else {
  4533. return -1;
  4534. }
  4535. } else {
  4536. return -1;
  4537. }
  4538. }
  4539. /**
  4540. * Function used to replace a thirdparty id with another one.
  4541. * It must be used within a transaction to avoid trouble
  4542. *
  4543. * @param DoliDB $dbs Database handler, because function is static we name it $dbs not $db to avoid breaking coding test
  4544. * @param int $origin_id Old thirdparty id (will be removed)
  4545. * @param int $dest_id New thirdparty id
  4546. * @return bool True if success, False if error
  4547. */
  4548. public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
  4549. {
  4550. if ($origin_id == $dest_id) {
  4551. dol_syslog('Error: Try to merge a thirdparty into itself');
  4552. return false;
  4553. }
  4554. /**
  4555. * Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some to avoid duplicate.
  4556. * Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
  4557. */
  4558. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
  4559. $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
  4560. $sql .= ' SELECT fk_user ';
  4561. $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
  4562. $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
  4563. $resql = $dbs->query($sql);
  4564. while ($obj = $dbs->fetch_object($resql)) {
  4565. $dbs->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.((int) $obj->rowid));
  4566. }
  4567. /**
  4568. * llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
  4569. * Do not include llx_societe because it will be replaced later
  4570. */
  4571. $tables = array(
  4572. 'societe_address',
  4573. 'societe_commerciaux',
  4574. 'societe_prices',
  4575. 'societe_remise',
  4576. 'societe_remise_except',
  4577. 'societe_rib'
  4578. );
  4579. return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
  4580. }
  4581. /**
  4582. * Sets an accountancy code for a thirdparty.
  4583. * Also calls COMPANY_MODIFY trigger when modified
  4584. *
  4585. * @param string $type It can be only 'buy' or 'sell'
  4586. * @param string $value Accountancy code
  4587. * @return int <0 KO >0 OK
  4588. */
  4589. public function setAccountancyCode($type, $value)
  4590. {
  4591. global $user, $langs, $conf;
  4592. $this->db->begin();
  4593. $field = 'accountancy_code_sell';
  4594. if ($type == 'buy') {
  4595. $field = 'accountancy_code_buy';
  4596. } elseif ($type == 'sell') {
  4597. $field = 'accountancy_code_sell';
  4598. } else {
  4599. return -1;
  4600. }
  4601. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ";
  4602. $sql .= $field." = '".$this->db->escape($value)."'";
  4603. $sql .= " WHERE rowid = ".((int) $this->id);
  4604. dol_syslog(get_class($this)."::".__FUNCTION__, LOG_DEBUG);
  4605. $resql = $this->db->query($sql);
  4606. if ($resql) {
  4607. // Call triggers
  4608. include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
  4609. $interface = new Interfaces($this->db);
  4610. $result = $interface->run_triggers('COMPANY_MODIFY', $this, $user, $langs, $conf);
  4611. if ($result < 0) {
  4612. $this->errors = $interface->errors;
  4613. $this->db->rollback();
  4614. return -1;
  4615. }
  4616. // End call triggers
  4617. $this->$field = $value;
  4618. $this->db->commit();
  4619. return 1;
  4620. } else {
  4621. $this->error = $this->db->lasterror();
  4622. $this->db->rollback();
  4623. return -1;
  4624. }
  4625. }
  4626. /**
  4627. * Function to get partnerships array
  4628. *
  4629. * @param string $mode 'member' or 'thirdparty'
  4630. * @return int <0 if KO, >0 if OK
  4631. */
  4632. public function fetchPartnerships($mode)
  4633. {
  4634. global $langs;
  4635. require_once DOL_DOCUMENT_ROOT.'/partnership/class/partnership.class.php';
  4636. $this->partnerships[] = array();
  4637. return 1;
  4638. }
  4639. /**
  4640. * Return clicable link of object (with eventually picto)
  4641. *
  4642. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  4643. * @param array $arraydata Array of data
  4644. * @return string HTML Code for Kanban thumb.
  4645. */
  4646. public function getKanbanView($option = '', $arraydata = null)
  4647. {
  4648. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  4649. $return = '<div class="box-flex-item box-flex-grow-zero">';
  4650. $return .= '<div class="info-box info-box-sm">';
  4651. $return .= '<span class="info-box-icon bg-infobox-action">';
  4652. $return .= img_picto('', $this->picto);
  4653. $return .= '</span>';
  4654. $return .= '<div class="info-box-content">';
  4655. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  4656. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  4657. if (property_exists($this, 'code_client')) {
  4658. $return .= '<br><span class="info-box-label opacitymedium">'.$this->code_client.'</span>';
  4659. }
  4660. if (method_exists($this, 'getLibStatut')) {
  4661. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
  4662. }
  4663. $return .= '</div>';
  4664. $return .= '</div>';
  4665. $return .= '</div>';
  4666. return $return;
  4667. }
  4668. /**
  4669. * Get array of all contacts for a society (stored in societe_contacts instead of element_contacts for all other objects)
  4670. *
  4671. * @param int $list 0:Return array contains all properties, 1:Return array contains just id
  4672. * @param string $code Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
  4673. * @param string $element Filter on this element of default contact type ('facture', 'propal', 'commande' ...)
  4674. * @return array|int Array of contacts, -1 if error
  4675. *
  4676. */
  4677. public function getContacts($list = 0, $code = '', $element = '')
  4678. {
  4679. // phpcs:enable
  4680. global $langs;
  4681. $tab = array();
  4682. $sql = "SELECT sc.rowid, sc.fk_socpeople as id, sc.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
  4683. $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
  4684. $sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
  4685. $sql .= ", tc.source, tc.element, tc.code, tc.libelle as type_label";
  4686. $sql .= " FROM ".$this->db->prefix()."c_type_contact tc";
  4687. $sql .= ", ".$this->db->prefix()."societe_contacts sc";
  4688. $sql .= " LEFT JOIN ".$this->db->prefix()."socpeople t on sc.fk_socpeople = t.rowid";
  4689. $sql .= " WHERE sc.fk_soc = ".((int) $this->id);
  4690. $sql .= " AND sc.fk_c_type_contact = tc.rowid";
  4691. if (!empty($element)) {
  4692. $sql .= " AND tc.element = '".$this->db->escape($element)."'";
  4693. }
  4694. if ($code) {
  4695. $sql .= " AND tc.code = '".$this->db->escape($code)."'";
  4696. }
  4697. $sql .= " AND sc.entity IN (".getEntity($this->element).")";
  4698. $sql .= " AND tc.source = 'external'";
  4699. $sql .= " AND tc.active=1";
  4700. $sql .= " ORDER BY t.lastname ASC";
  4701. dol_syslog(get_class($this)."::getContacts", LOG_DEBUG);
  4702. $resql = $this->db->query($sql);
  4703. if ($resql) {
  4704. $num = $this->db->num_rows($resql);
  4705. $i = 0;
  4706. while ($i < $num) {
  4707. $obj = $this->db->fetch_object($resql);
  4708. if (!$list) {
  4709. $transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
  4710. $libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->type_label);
  4711. $tab[$i] = array(
  4712. 'source' => $obj->source,
  4713. 'socid' => $obj->socid,
  4714. 'id' => $obj->id,
  4715. 'nom' => $obj->lastname, // For backward compatibility
  4716. 'civility' => $obj->civility,
  4717. 'lastname' => $obj->lastname,
  4718. 'firstname' => $obj->firstname,
  4719. 'email'=>$obj->email,
  4720. 'login'=> (empty($obj->login) ? '' : $obj->login),
  4721. 'photo' => (empty($obj->photo) ? '' : $obj->photo),
  4722. 'statuscontact' => $obj->statuscontact,
  4723. 'rowid' => $obj->rowid,
  4724. 'code' => $obj->code,
  4725. 'element' => $obj->element,
  4726. 'libelle' => $libelle_type,
  4727. 'status' => $obj->statuslink,
  4728. 'fk_c_type_contact' => $obj->fk_c_type_contact
  4729. );
  4730. } else {
  4731. $tab[$i] = $obj->id;
  4732. }
  4733. $i++;
  4734. }
  4735. return $tab;
  4736. } else {
  4737. $this->error = $this->db->lasterror();
  4738. dol_print_error($this->db);
  4739. return -1;
  4740. }
  4741. }
  4742. }