societe.class.php 180 KB

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