societe.class.php 175 KB

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