societe.class.php 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152
  1. <?php
  2. /* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2015 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 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>
  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. *
  18. * This program is free software; you can redistribute it and/or modify
  19. * it under the terms of the GNU General Public License as published by
  20. * the Free Software Foundation; either version 3 of the License, or
  21. * (at your option) any later version.
  22. *
  23. * This program is distributed in the hope that it will be useful,
  24. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  25. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  26. * GNU General Public License for more details.
  27. *
  28. * You should have received a copy of the GNU General Public License
  29. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  30. */
  31. /**
  32. * \file htdocs/societe/class/societe.class.php
  33. * \ingroup societe
  34. * \brief File for third party class
  35. */
  36. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
  38. /**
  39. * Class to manage third parties objects (customers, suppliers, prospects...)
  40. */
  41. class Societe extends CommonObject
  42. {
  43. /**
  44. * @var string ID to identify managed object
  45. */
  46. public $element='societe';
  47. /**
  48. * @var string Name of table without prefix where object is stored
  49. */
  50. public $table_element = 'societe';
  51. /**
  52. * @var int Field with ID of parent key if this field has a parent
  53. */
  54. public $fk_element='fk_soc';
  55. public $fieldsforcombobox='nom,name_alias';
  56. protected $childtables=array("supplier_proposal"=>'SupplierProposal',"propal"=>'Proposal',"commande"=>'Order',"facture"=>'Invoice',"facture_rec"=>'RecurringInvoiceTemplate',"contrat"=>'Contract',"fichinter"=>'Fichinter',"facture_fourn"=>'SupplierInvoice',"commande_fournisseur"=>'SupplierOrder',"projet"=>'Project',"expedition"=>'Shipment',"prelevement_lignes"=>'DirectDebitRecord'); // To test if we can delete object
  57. protected $childtablesoncascade=array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
  58. public $picto = 'company';
  59. /**
  60. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  61. * @var int
  62. */
  63. public $ismultientitymanaged = 1;
  64. /**
  65. * 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
  66. * @var integer
  67. */
  68. public $restrictiononfksoc = 1;
  69. // BEGIN MODULEBUILDER PROPERTIES
  70. /**
  71. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  72. */
  73. public $fields=array(
  74. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
  75. 'nom' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
  76. 'name_alias' =>array('type'=>'varchar(128)', 'label'=>'Name', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
  77. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>20),
  78. 'note_public' =>array('type'=>'text', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>60),
  79. 'note_private' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>61),
  80. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
  81. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
  82. //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
  83. 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510),
  84. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
  85. //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
  86. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>1, 'position'=>1000),
  87. );
  88. /**
  89. * @var int Entity
  90. */
  91. public $entity;
  92. /**
  93. * Thirdparty name
  94. * @var string
  95. * @deprecated Use $name instead
  96. * @see $name
  97. */
  98. public $nom;
  99. /**
  100. * @var string name
  101. */
  102. public $name;
  103. /**
  104. * Alias names (commercial, trademark or alias names)
  105. * @var string
  106. */
  107. public $name_alias;
  108. public $particulier;
  109. /**
  110. * @var string Address
  111. */
  112. public $address;
  113. public $zip;
  114. public $town;
  115. /**
  116. * Thirdparty status : 0=activity ceased, 1= in activity
  117. * @var int
  118. */
  119. public $status=1;
  120. /**
  121. * Id of department
  122. * @var int
  123. */
  124. public $state_id;
  125. public $state_code;
  126. public $state;
  127. /**
  128. * Id of region
  129. * @var int
  130. */
  131. public $region_code;
  132. public $region;
  133. /**
  134. * State code
  135. * @var string
  136. * @deprecated Use state_code instead
  137. * @see $state_code
  138. */
  139. public $departement_code;
  140. /**
  141. * @var string
  142. * @deprecated Use state instead
  143. * @see $state
  144. */
  145. public $departement;
  146. /**
  147. * @var string
  148. * @deprecated Use country instead
  149. * @see $country
  150. */
  151. public $pays;
  152. /**
  153. * Phone number
  154. * @var string
  155. */
  156. public $phone;
  157. /**
  158. * Fax number
  159. * @var string
  160. */
  161. public $fax;
  162. /**
  163. * Email
  164. * @var string
  165. */
  166. public $email;
  167. /**
  168. * Skype username
  169. * @var string
  170. */
  171. public $skype;
  172. /**
  173. * Twitter username
  174. * @var string
  175. */
  176. public $twitter;
  177. /**
  178. * Facebook username
  179. * @var string
  180. */
  181. public $facebook;
  182. /**
  183. * Webpage
  184. * @var string
  185. */
  186. public $url;
  187. //! barcode
  188. /**
  189. * Barcode value
  190. * @var string
  191. */
  192. public $barcode;
  193. // 6 professional id (usage depends on country)
  194. /**
  195. * Professional ID 1 (Ex: Siren in France)
  196. * @var string
  197. */
  198. public $idprof1;
  199. /**
  200. * Professional ID 2 (Ex: Siret in France)
  201. * @var string
  202. */
  203. public $idprof2;
  204. /**
  205. * Professional ID 3 (Ex: Ape in France)
  206. * @var string
  207. */
  208. public $idprof3;
  209. /**
  210. * Professional ID 4 (Ex: RCS in France)
  211. * @var string
  212. */
  213. public $idprof4;
  214. /**
  215. * Professional ID 5
  216. * @var string
  217. */
  218. public $idprof5;
  219. /**
  220. * Professional ID 6
  221. * @var string
  222. */
  223. public $idprof6;
  224. public $prefix_comm;
  225. public $tva_assuj=1;
  226. /**
  227. * Intracommunitary VAT ID
  228. * @var string
  229. */
  230. public $tva_intra;
  231. // Local taxes
  232. public $localtax1_assuj;
  233. public $localtax1_value;
  234. public $localtax2_assuj;
  235. public $localtax2_value;
  236. public $managers;
  237. public $capital;
  238. public $typent_id=0;
  239. public $typent_code;
  240. public $effectif;
  241. public $effectif_id=0;
  242. public $forme_juridique_code;
  243. public $forme_juridique=0;
  244. public $remise_percent;
  245. public $remise_supplier_percent;
  246. public $mode_reglement_supplier_id;
  247. public $cond_reglement_supplier_id;
  248. /**
  249. * @var int ID
  250. */
  251. public $fk_prospectlevel;
  252. public $name_bis;
  253. //Log data
  254. /**
  255. * Date of last update
  256. * @var string
  257. */
  258. public $date_modification;
  259. /**
  260. * User that made last update
  261. * @var string
  262. */
  263. public $user_modification;
  264. /**
  265. * Date of creation
  266. * @var string
  267. */
  268. public $date_creation;
  269. /**
  270. * User that created the thirdparty
  271. * @var User
  272. */
  273. public $user_creation;
  274. public $specimen;
  275. /**
  276. * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
  277. * @var int
  278. */
  279. public $client=0;
  280. /**
  281. * 0=no prospect, 1=prospect
  282. * @var int
  283. */
  284. public $prospect=0;
  285. /**
  286. * 0=no supplier, 1=supplier
  287. * @var int
  288. */
  289. public $fournisseur;
  290. /**
  291. * Client code. E.g: CU2014-003
  292. * @var string
  293. */
  294. public $code_client;
  295. /**
  296. * Supplier code. E.g: SU2014-003
  297. * @var string
  298. */
  299. public $code_fournisseur;
  300. /**
  301. * Accounting code for client
  302. * @var string
  303. */
  304. public $code_compta;
  305. /**
  306. * Accounting code for client
  307. * @var string
  308. */
  309. public $code_compta_client;
  310. /**
  311. * Accounting code for suppliers
  312. * @var string
  313. */
  314. public $code_compta_fournisseur;
  315. /**
  316. * @var string
  317. * @deprecated Note is split in public and private notes
  318. * @see $note_public, $note_private
  319. */
  320. public $note;
  321. /**
  322. * Private note
  323. * @var string
  324. */
  325. public $note_private;
  326. /**
  327. * Public note
  328. * @var string
  329. */
  330. public $note_public;
  331. //! code statut prospect
  332. public $stcomm_id;
  333. public $statut_commercial;
  334. /**
  335. * Assigned price level
  336. * @var int
  337. */
  338. public $price_level;
  339. public $outstanding_limit;
  340. /**
  341. * Min order amounts
  342. */
  343. public $order_min_amount;
  344. public $supplier_order_min_amount;
  345. /**
  346. * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
  347. * @var int
  348. */
  349. public $commercial_id;
  350. /**
  351. * Id of parent thirdparty (if one)
  352. * @var int
  353. */
  354. public $parent;
  355. /**
  356. * Default language code of thirdparty (en_US, ...)
  357. * @var string
  358. */
  359. public $default_lang;
  360. /**
  361. * @var string Ref
  362. */
  363. public $ref;
  364. public $ref_int;
  365. /**
  366. * External user reference.
  367. * This is to allow external systems to store their id and make self-developed synchronizing functions easier to
  368. * build.
  369. * @var string
  370. */
  371. public $ref_ext;
  372. /**
  373. * Import key.
  374. * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
  375. * to an import process
  376. * @var string
  377. */
  378. public $import_key;
  379. /**
  380. * Supplier WebServices URL
  381. * @var string
  382. */
  383. public $webservices_url;
  384. /**
  385. * Supplier WebServices Key
  386. * @var string
  387. */
  388. public $webservices_key;
  389. public $logo;
  390. public $logo_small;
  391. public $logo_mini;
  392. public $array_options;
  393. // Incoterms
  394. /**
  395. * @var int ID
  396. */
  397. public $fk_incoterms;
  398. public $location_incoterms;
  399. public $libelle_incoterms; //Used into tooltip
  400. // Multicurrency
  401. /**
  402. * @var int ID
  403. */
  404. public $fk_multicurrency;
  405. public $multicurrency_code;
  406. // END MODULEBUILDER PROPERTIES
  407. /**
  408. * Constructor
  409. *
  410. * @param DoliDB $db Database handler
  411. */
  412. public function __construct($db)
  413. {
  414. $this->db = $db;
  415. $this->client = 0;
  416. $this->prospect = 0;
  417. $this->fournisseur = 0;
  418. $this->typent_id = 0;
  419. $this->effectif_id = 0;
  420. $this->forme_juridique_code = 0;
  421. $this->tva_assuj = 1;
  422. $this->status = 1;
  423. }
  424. /**
  425. * Create third party in database.
  426. * $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement.
  427. *
  428. * @param User $user Object of user that ask creation
  429. * @return int >= 0 if OK, < 0 if KO
  430. */
  431. function create(User $user)
  432. {
  433. global $langs,$conf,$mysoc;
  434. $error=0;
  435. // Clean parameters
  436. if (empty($this->status)) $this->status=0;
  437. $this->name=$this->name?trim($this->name):trim($this->nom);
  438. if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
  439. $this->nom=$this->name; // For backward compatibility
  440. if (empty($this->client)) $this->client=0;
  441. if (empty($this->fournisseur)) $this->fournisseur=0;
  442. $this->import_key = trim($this->import_key);
  443. if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  444. if (empty($this->fk_multicurrency))
  445. {
  446. $this->multicurrency_code = '';
  447. $this->fk_multicurrency = 0;
  448. }
  449. dol_syslog(get_class($this)."::create ".$this->name);
  450. $now=dol_now();
  451. $this->db->begin();
  452. // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
  453. if ($this->code_client == -1 || $this->code_client === 'auto') $this->get_codeclient($this,0);
  454. if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this,1);
  455. // Check more parameters (including mandatory setup
  456. // If error, this->errors[] is filled
  457. $result = $this->verify();
  458. if ($result >= 0)
  459. {
  460. $this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
  461. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
  462. $sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$this->db->escape($this->entity).", '".$this->db->idate($now)."'";
  463. $sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
  464. $sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
  465. $sql.= ", ".$this->status;
  466. $sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
  467. $sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
  468. $sql.= ", 0";
  469. $sql.= ", ".(int) $this->fk_incoterms;
  470. $sql.= ", '".$this->db->escape($this->location_incoterms)."'";
  471. $sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
  472. $sql.= ", ".(int) $this->fk_multicurrency;
  473. $sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
  474. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  475. $result=$this->db->query($sql);
  476. if ($result)
  477. {
  478. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
  479. $ret = $this->update($this->id,$user,0,1,1,'add');
  480. // Ajout du commercial affecte
  481. if ($this->commercial_id != '' && $this->commercial_id != -1)
  482. {
  483. $this->add_commercial($user, $this->commercial_id);
  484. }
  485. // si un commercial cree un client il lui est affecte automatiquement
  486. elseif (empty($user->rights->societe->client->voir))
  487. {
  488. $this->add_commercial($user, $user->id);
  489. }
  490. if ($ret >= 0)
  491. {
  492. // Call trigger
  493. $result=$this->call_trigger('COMPANY_CREATE',$user);
  494. if ($result < 0) $error++;
  495. // End call triggers
  496. }
  497. else $error++;
  498. if (! $error)
  499. {
  500. dol_syslog(get_class($this)."::Create success id=".$this->id);
  501. $this->db->commit();
  502. return $this->id;
  503. }
  504. else
  505. {
  506. dol_syslog(get_class($this)."::Create echec update ".$this->error." ".join(',',$this->errors), LOG_ERR);
  507. $this->db->rollback();
  508. return -4;
  509. }
  510. }
  511. else
  512. {
  513. if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  514. {
  515. $this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name); // duplicate on a field (code or profid or ...)
  516. $result=-1;
  517. }
  518. else
  519. {
  520. $this->error=$this->db->lasterror();
  521. $result=-2;
  522. }
  523. $this->db->rollback();
  524. return $result;
  525. }
  526. }
  527. else
  528. {
  529. $this->db->rollback();
  530. dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
  531. return -3;
  532. }
  533. }
  534. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  535. /**
  536. * Create a contact/address from thirdparty
  537. *
  538. * @param User $user Object user
  539. * @return int <0 if KO, >0 if OK
  540. */
  541. function create_individual(User $user)
  542. {
  543. // phpcs:enable
  544. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  545. $contact=new Contact($this->db);
  546. $contact->name = $this->name_bis;
  547. $contact->firstname = $this->firstname;
  548. $contact->civility_id = $this->civility_id;
  549. $contact->socid = $this->id; // fk_soc
  550. $contact->statut = 1;
  551. $contact->priv = 0;
  552. $contact->country_id = $this->country_id;
  553. $contact->state_id = $this->state_id;
  554. $contact->address = $this->address;
  555. $contact->email = $this->email;
  556. $contact->zip = $this->zip;
  557. $contact->town = $this->town;
  558. $contact->phone_pro = $this->phone;
  559. $result = $contact->create($user);
  560. if ($result < 0)
  561. {
  562. $this->error = $contact->error;
  563. $this->errors = $contact->errors;
  564. dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
  565. }
  566. return $result;
  567. }
  568. /**
  569. * Check properties of third party are ok (like name, third party codes, ...)
  570. * Used before an add or update.
  571. *
  572. * @return int 0 if OK, <0 if KO
  573. */
  574. function verify()
  575. {
  576. global $conf, $langs, $mysoc;
  577. $error = 0;
  578. $this->errors=array();
  579. $result = 0;
  580. $this->name = trim($this->name);
  581. $this->nom=$this->name; // For backward compatibility
  582. if (! $this->name)
  583. {
  584. $this->errors[] = 'ErrorBadThirdPartyName';
  585. $result = -2;
  586. }
  587. if ($this->client)
  588. {
  589. $rescode = $this->check_codeclient();
  590. if ($rescode <> 0)
  591. {
  592. if ($rescode == -1)
  593. {
  594. $this->errors[] = 'ErrorBadCustomerCodeSyntax';
  595. }
  596. elseif ($rescode == -2)
  597. {
  598. $this->errors[] = 'ErrorCustomerCodeRequired';
  599. }
  600. elseif ($rescode == -3)
  601. {
  602. $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
  603. }
  604. elseif ($rescode == -4)
  605. {
  606. $this->errors[] = 'ErrorPrefixRequired';
  607. }
  608. $result = -3;
  609. }
  610. }
  611. if ($this->fournisseur)
  612. {
  613. $rescode = $this->check_codefournisseur();
  614. if ($rescode <> 0)
  615. {
  616. if ($rescode == -1)
  617. {
  618. $this->errors[] = 'ErrorBadSupplierCodeSyntax';
  619. }
  620. elseif ($rescode == -2)
  621. {
  622. $this->errors[] = 'ErrorSupplierCodeRequired';
  623. }
  624. elseif ($rescode == -3)
  625. {
  626. $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
  627. }
  628. elseif ($rescode == -5)
  629. {
  630. $this->errors[] = 'ErrorprefixRequired';
  631. }
  632. $result = -3;
  633. }
  634. }
  635. // Check for duplicate or mandatory fields defined into setup
  636. $array_to_check=array('IDPROF1','IDPROF2','IDPROF3','IDPROF4','IDPROF5','IDPROF6','EMAIL');
  637. foreach($array_to_check as $key)
  638. {
  639. $keymin=strtolower($key);
  640. $i=(int) preg_replace('/[^0-9]/','',$key);
  641. $vallabel=$this->$keymin;
  642. if ($i > 0)
  643. {
  644. if ($this->isACompany())
  645. {
  646. // Check for unicity
  647. if ($vallabel && $this->id_prof_verifiable($i))
  648. {
  649. if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
  650. {
  651. $langs->load("errors");
  652. $error++; $this->errors[] = $langs->transcountry('ProfId'.$i, $this->country_code)." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
  653. }
  654. }
  655. // Check for mandatory prof id (but only if country is other than ours)
  656. if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id)
  657. {
  658. $idprof_mandatory ='SOCIETE_'.$key.'_MANDATORY';
  659. if (! $vallabel && ! empty($conf->global->$idprof_mandatory))
  660. {
  661. $langs->load("errors");
  662. $error++;
  663. $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId'.$i, $this->country_code)).' ('.$langs->trans("ForbiddenBySetupRules").')';
  664. }
  665. }
  666. }
  667. }
  668. else
  669. {
  670. //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
  671. //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
  672. if ($key == 'EMAIL')
  673. {
  674. // Check for unicity
  675. if ($vallabel && ! empty($conf->global->SOCIETE_EMAIL_UNIQUE))
  676. {
  677. if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0)))
  678. {
  679. $langs->load("errors");
  680. $error++; $this->errors[] = $langs->trans('Email')." ".$langs->trans("ErrorProdIdAlreadyExist", $vallabel).' ('.$langs->trans("ForbiddenBySetupRules").')';
  681. }
  682. }
  683. // Check for mandatory
  684. if (! empty($conf->global->SOCIETE_EMAIL_MANDATORY) && ! isValidEMail($this->email))
  685. {
  686. $langs->load("errors");
  687. $error++;
  688. $this->errors[] = $langs->trans("ErrorBadEMail", $this->email).' ('.$langs->trans("ForbiddenBySetupRules").')';
  689. }
  690. }
  691. }
  692. }
  693. if ($error) $result = -4;
  694. return $result;
  695. }
  696. /**
  697. * Update parameters of third party
  698. *
  699. * @param int $id Id of company (deprecated, use 0 here and call update on an object loaded by a fetch)
  700. * @param User $user Utilisateur qui demande la mise a jour
  701. * @param int $call_trigger 0=no, 1=yes
  702. * @param int $allowmodcodeclient Inclut modif code client et code compta
  703. * @param int $allowmodcodefournisseur Inclut modif code fournisseur et code compta fournisseur
  704. * @param string $action 'add' or 'update' or 'merge'
  705. * @param int $nosyncmember Do not synchronize info of linked member
  706. * @return int <0 if KO, >=0 if OK
  707. */
  708. function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
  709. {
  710. global $langs,$conf,$hookmanager;
  711. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  712. if (empty($id)) $id = $this->id;
  713. $error=0;
  714. dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
  715. $now=dol_now();
  716. // Clean parameters
  717. $this->id = $id;
  718. $this->entity = ((isset($this->entity) && is_numeric($this->entity))?$this->entity:$conf->entity);
  719. $this->name = $this->name?trim($this->name):trim($this->nom);
  720. $this->nom = $this->name; // For backward compatibility
  721. $this->name_alias = trim($this->name_alias);
  722. $this->ref_ext = trim($this->ref_ext);
  723. $this->address = $this->address?trim($this->address):trim($this->address);
  724. $this->zip = $this->zip?trim($this->zip):trim($this->zip);
  725. $this->town = $this->town?trim($this->town):trim($this->town);
  726. $this->state_id = trim($this->state_id);
  727. $this->country_id = ($this->country_id > 0)?$this->country_id:0;
  728. $this->phone = trim($this->phone);
  729. $this->phone = preg_replace("/\s/","",$this->phone);
  730. $this->phone = preg_replace("/\./","",$this->phone);
  731. $this->fax = trim($this->fax);
  732. $this->fax = preg_replace("/\s/","",$this->fax);
  733. $this->fax = preg_replace("/\./","",$this->fax);
  734. $this->email = trim($this->email);
  735. $this->skype = trim($this->skype);
  736. $this->twitter = trim($this->twitter);
  737. $this->facebook = trim($this->facebook);
  738. $this->url = $this->url?clean_url($this->url,0):'';
  739. $this->note_private = trim($this->note_private);
  740. $this->note_public = trim($this->note_public);
  741. $this->idprof1 = trim($this->idprof1);
  742. $this->idprof2 = trim($this->idprof2);
  743. $this->idprof3 = trim($this->idprof3);
  744. $this->idprof4 = trim($this->idprof4);
  745. $this->idprof5 = (! empty($this->idprof5)?trim($this->idprof5):'');
  746. $this->idprof6 = (! empty($this->idprof6)?trim($this->idprof6):'');
  747. $this->prefix_comm = trim($this->prefix_comm);
  748. $this->outstanding_limit = price2num($this->outstanding_limit);
  749. $this->order_min_amount = price2num($this->order_min_amount);
  750. $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
  751. $this->tva_assuj = trim($this->tva_assuj);
  752. $this->tva_intra = dol_sanitizeFileName($this->tva_intra,'');
  753. if (empty($this->status)) $this->status = 0;
  754. if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
  755. if (empty($this->fk_multicurrency))
  756. {
  757. $this->multicurrency_code = '';
  758. $this->fk_multicurrency = 0;
  759. }
  760. // Local taxes
  761. $this->localtax1_assuj=trim($this->localtax1_assuj);
  762. $this->localtax2_assuj=trim($this->localtax2_assuj);
  763. $this->localtax1_value=trim($this->localtax1_value);
  764. $this->localtax2_value=trim($this->localtax2_value);
  765. if ($this->capital != '') $this->capital=price2num(trim($this->capital));
  766. if (! is_numeric($this->capital)) $this->capital = ''; // '' = undef
  767. $this->effectif_id=trim($this->effectif_id);
  768. $this->forme_juridique_code=trim($this->forme_juridique_code);
  769. //Gencod
  770. $this->barcode=trim($this->barcode);
  771. // For automatic creation
  772. if ($this->code_client == -1 || $this->code_client === 'auto') $this->get_codeclient($this,0);
  773. if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') $this->get_codefournisseur($this,1);
  774. $this->code_compta=trim($this->code_compta);
  775. $this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
  776. // Check parameters. More tests are done later in the ->verify()
  777. if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
  778. {
  779. $langs->load("errors");
  780. $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
  781. return -1;
  782. }
  783. $customer=false;
  784. if (! empty($allowmodcodeclient) && ! empty($this->client))
  785. {
  786. // Attention get_codecompta peut modifier le code suivant le module utilise
  787. if (empty($this->code_compta))
  788. {
  789. $ret=$this->get_codecompta('customer');
  790. if ($ret < 0) return -1;
  791. }
  792. $customer=true;
  793. }
  794. $supplier=false;
  795. if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
  796. {
  797. // Attention get_codecompta peut modifier le code suivant le module utilise
  798. if (empty($this->code_compta_fournisseur))
  799. {
  800. $ret=$this->get_codecompta('supplier');
  801. if ($ret < 0) return -1;
  802. }
  803. $supplier=true;
  804. }
  805. //Web services
  806. $this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
  807. $this->webservices_key = trim($this->webservices_key);
  808. //Incoterms
  809. $this->fk_incoterms = (int) $this->fk_incoterms;
  810. $this->location_incoterms = trim($this->location_incoterms);
  811. $this->db->begin();
  812. // Check name is required and codes are ok or unique.
  813. // If error, this->errors[] is filled
  814. $result = 0;
  815. if ($action != 'add' && $action != 'merge')
  816. {
  817. // We don't check when update called during a create because verify was already done.
  818. // 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
  819. $result = $this->verify();
  820. // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
  821. // So we can update record that were using and old numbering rule.
  822. if (is_array($this->errors))
  823. {
  824. if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client)
  825. {
  826. if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]); // Remove error message
  827. }
  828. if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur)
  829. {
  830. if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false) unset($this->errors[$key]); // Remove error message
  831. }
  832. if (empty($this->errors)) // If there is no more error, we can make like if there is no error at all
  833. {
  834. $result = 0;
  835. }
  836. }
  837. }
  838. if ($result >= 0)
  839. {
  840. dol_syslog(get_class($this)."::update verify ok or not done");
  841. $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
  842. $sql .= "entity = " . $this->db->escape($this->entity);
  843. $sql .= ",nom = '" . $this->db->escape($this->name) ."'"; // Required
  844. $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
  845. $sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
  846. $sql .= ",address = '" . $this->db->escape($this->address) ."'";
  847. $sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
  848. $sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
  849. $sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
  850. $sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
  851. $sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
  852. $sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
  853. $sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
  854. $sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
  855. $sql .= ",twitter = ".(! empty($this->twitter)?"'".$this->db->escape($this->twitter)."'":"null");
  856. $sql .= ",facebook = ".(! empty($this->facebook)?"'".$this->db->escape($this->facebook)."'":"null");
  857. $sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
  858. $sql .= ",parent = " . ($this->parent > 0 ? $this->parent : "null");
  859. $sql .= ",note_private = ".(! empty($this->note_private)?"'".$this->db->escape($this->note_private)."'":"null");
  860. $sql .= ",note_public = ".(! empty($this->note_public)?"'".$this->db->escape($this->note_public)."'":"null");
  861. $sql .= ",siren = '". $this->db->escape($this->idprof1) ."'";
  862. $sql .= ",siret = '". $this->db->escape($this->idprof2) ."'";
  863. $sql .= ",ape = '". $this->db->escape($this->idprof3) ."'";
  864. $sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
  865. $sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
  866. $sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
  867. $sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->db->escape($this->tva_assuj)."'":"null");
  868. $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
  869. $sql .= ",status = " .$this->status;
  870. // Local taxes
  871. $sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->db->escape($this->localtax1_assuj)."'":"null");
  872. $sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->db->escape($this->localtax2_assuj)."'":"null");
  873. if($this->localtax1_assuj==1)
  874. {
  875. if($this->localtax1_value!='')
  876. {
  877. $sql .=",localtax1_value =".$this->localtax1_value;
  878. }
  879. else $sql .=",localtax1_value =0.000";
  880. }
  881. else $sql .=",localtax1_value =0.000";
  882. if($this->localtax2_assuj==1)
  883. {
  884. if($this->localtax2_value!='')
  885. {
  886. $sql .=",localtax2_value =".$this->localtax2_value;
  887. }
  888. else $sql .=",localtax2_value =0.000";
  889. }
  890. else $sql .=",localtax2_value =0.000";
  891. $sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
  892. $sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
  893. $sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
  894. if (isset($this->stcomm_id))
  895. {
  896. $sql .= ",fk_stcomm=".(!empty($this->stcomm_id) ? $this->stcomm_id : "0");
  897. }
  898. $sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
  899. $sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
  900. $sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
  901. $sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
  902. $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
  903. $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
  904. $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
  905. $sql .= ",client = " . (! empty($this->client)?$this->client:0);
  906. $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
  907. $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
  908. $sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
  909. $sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
  910. $sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
  911. $sql .= ",order_min_amount= ".($this->order_min_amount!=''?$this->order_min_amount:'null');
  912. $sql .= ",supplier_order_min_amount= ".($this->supplier_order_min_amount!=''?$this->supplier_order_min_amount:'null');
  913. $sql .= ",fk_prospectlevel='".$this->db->escape($this->fk_prospectlevel)."'";
  914. $sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
  915. $sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
  916. //Incoterms
  917. $sql.= ", fk_incoterms = ".$this->fk_incoterms;
  918. $sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
  919. if ($customer)
  920. {
  921. $sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
  922. $sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
  923. }
  924. if ($supplier)
  925. {
  926. $sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
  927. $sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
  928. }
  929. $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id:"null");
  930. $sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
  931. $sql .= ", multicurrency_code = '".$this->db->escape($this->multicurrency_code)."'";
  932. $sql .= " WHERE rowid = " . (int) $id;
  933. $resql=$this->db->query($sql);
  934. if ($resql)
  935. {
  936. if (is_object($this->oldcopy)) // If we have information on old values
  937. {
  938. if ($this->oldcopy->country_id != $this->country_id)
  939. {
  940. unset($this->country_code);
  941. unset($this->country);
  942. }
  943. if ($this->oldcopy->state_id != $this->state_id)
  944. {
  945. unset($this->state_code);
  946. unset($this->state);
  947. }
  948. }
  949. else
  950. {
  951. unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
  952. unset($this->country);
  953. unset($this->state_code);
  954. unset($this->state);
  955. }
  956. $nbrowsaffected = $this->db->affected_rows($resql);
  957. if (! $error && $nbrowsaffected)
  958. {
  959. // Update information on linked member if it is an update
  960. if (! $nosyncmember && ! empty($conf->adherent->enabled))
  961. {
  962. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  963. dol_syslog(get_class($this)."::update update linked member");
  964. $lmember=new Adherent($this->db);
  965. $result=$lmember->fetch(0, 0, $this->id);
  966. if ($result > 0)
  967. {
  968. $lmember->societe=$this->name;
  969. //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
  970. //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
  971. $lmember->address=$this->address;
  972. $lmember->email=$this->email;
  973. $lmember->skype=$this->skype;
  974. $lmember->twitter=$this->twitter;
  975. $lmember->facebook=$this->facebook;
  976. $lmember->phone=$this->phone;
  977. $result=$lmember->update($user,0,1,1,1); // Use nosync to 1 to avoid cyclic updates
  978. if ($result < 0)
  979. {
  980. $this->error=$lmember->error;
  981. dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
  982. $error++;
  983. }
  984. }
  985. elseif ($result < 0)
  986. {
  987. $this->error=$lmember->error;
  988. $error++;
  989. }
  990. }
  991. }
  992. $action='update';
  993. // Actions on extra fields
  994. if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
  995. {
  996. $result=$this->insertExtraFields();
  997. if ($result < 0)
  998. {
  999. $error++;
  1000. }
  1001. }
  1002. if (! $error && $call_trigger)
  1003. {
  1004. // Call trigger
  1005. $result=$this->call_trigger('COMPANY_MODIFY',$user);
  1006. if ($result < 0) $error++;
  1007. // End call triggers
  1008. }
  1009. if (! $error)
  1010. {
  1011. dol_syslog(get_class($this)."::Update success");
  1012. $this->db->commit();
  1013. return 1;
  1014. }
  1015. else
  1016. {
  1017. $this->db->rollback();
  1018. return -1;
  1019. }
  1020. }
  1021. else
  1022. {
  1023. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
  1024. {
  1025. // Doublon
  1026. $this->error = $langs->trans("ErrorDuplicateField");
  1027. $result = -1;
  1028. }
  1029. else
  1030. {
  1031. $this->error = $this->db->lasterror();
  1032. $result = -2;
  1033. }
  1034. $this->db->rollback();
  1035. return $result;
  1036. }
  1037. }
  1038. else
  1039. {
  1040. $this->db->rollback();
  1041. dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
  1042. return -3;
  1043. }
  1044. }
  1045. /**
  1046. * Load a third party from database into memory
  1047. *
  1048. * @param int $rowid Id of third party to load
  1049. * @param string $ref Reference of third party, name (Warning, this can return several records)
  1050. * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr)
  1051. * @param string $ref_int Internal reference of third party (not used by dolibarr)
  1052. * @param string $idprof1 Prof id 1 of third party (Warning, this can return several records)
  1053. * @param string $idprof2 Prof id 2 of third party (Warning, this can return several records)
  1054. * @param string $idprof3 Prof id 3 of third party (Warning, this can return several records)
  1055. * @param string $idprof4 Prof id 4 of third party (Warning, this can return several records)
  1056. * @param string $idprof5 Prof id 5 of third party (Warning, this can return several records)
  1057. * @param string $idprof6 Prof id 6 of third party (Warning, this can return several records)
  1058. * @param string $email Email of third party (Warning, this can return several records)
  1059. * @param string $ref_alias Name_alias of third party (Warning, this can return several records)
  1060. * @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
  1061. */
  1062. function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='', $email='', $ref_alias='')
  1063. {
  1064. global $langs;
  1065. global $conf;
  1066. if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email)) return -1;
  1067. $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
  1068. $sql .= ', s.status';
  1069. $sql .= ', s.price_level';
  1070. $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
  1071. $sql .= ', s.phone, s.fax, s.email, s.skype, s.twitter, s.facebook, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
  1072. $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
  1073. $sql .= ', s.capital, s.tva_intra';
  1074. $sql .= ', s.fk_typent as typent_id';
  1075. $sql .= ', s.fk_effectif as effectif_id';
  1076. $sql .= ', s.fk_forme_juridique as forme_juridique_code';
  1077. $sql .= ', s.webservices_url, s.webservices_key';
  1078. $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
  1079. $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_supplier, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
  1080. $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
  1081. $sql .= ', s.fk_shipping_method';
  1082. $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
  1083. $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
  1084. $sql .= ', s.fk_multicurrency, s.multicurrency_code';
  1085. $sql .= ', fj.libelle as forme_juridique';
  1086. $sql .= ', e.libelle as effectif';
  1087. $sql .= ', c.code as country_code, c.label as country';
  1088. $sql .= ', d.code_departement as state_code, d.nom as state';
  1089. $sql .= ', st.libelle as stcomm';
  1090. $sql .= ', te.code as typent_code';
  1091. $sql .= ', i.libelle as libelle_incoterms';
  1092. $sql .= ', sr.remise_client';
  1093. $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
  1094. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
  1095. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
  1096. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
  1097. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
  1098. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
  1099. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
  1100. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
  1101. $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 = '.$conf->entity.')';
  1102. $sql .= ' WHERE s.entity IN ('.getEntity($this->element).')';
  1103. if ($rowid) $sql .= ' AND s.rowid = '.$rowid;
  1104. if ($ref) $sql .= " AND s.nom = '".$this->db->escape($ref)."'";
  1105. if ($ref_alias) $sql .= " AND s.nom_alias = '".$this->db->escape($ref_alias)."'";
  1106. if ($ref_ext) $sql .= " AND s.ref_ext = '".$this->db->escape($ref_ext)."'";
  1107. if ($ref_int) $sql .= " AND s.ref_int = '".$this->db->escape($ref_int)."'";
  1108. if ($idprof1) $sql .= " AND s.siren = '".$this->db->escape($idprof1)."'";
  1109. if ($idprof2) $sql .= " AND s.siret = '".$this->db->escape($idprof2)."'";
  1110. if ($idprof3) $sql .= " AND s.ape = '".$this->db->escape($idprof3)."'";
  1111. if ($idprof4) $sql .= " AND s.idprof4 = '".$this->db->escape($idprof4)."'";
  1112. if ($idprof5) $sql .= " AND s.idprof5 = '".$this->db->escape($idprof5)."'";
  1113. if ($idprof6) $sql .= " AND s.idprof6 = '".$this->db->escape($idprof6)."'";
  1114. if ($email) $sql .= " AND s.email = '".$this->db->escape($email)."'";
  1115. $resql=$this->db->query($sql);
  1116. if ($resql)
  1117. {
  1118. $num=$this->db->num_rows($resql);
  1119. if ($num > 1)
  1120. {
  1121. $this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
  1122. dol_syslog($this->error, LOG_ERR);
  1123. $result = -2;
  1124. }
  1125. elseif ($num) // $num = 1
  1126. {
  1127. $obj = $this->db->fetch_object($resql);
  1128. $this->id = $obj->rowid;
  1129. $this->entity = $obj->entity;
  1130. $this->canvas = $obj->canvas;
  1131. $this->ref = $obj->rowid;
  1132. $this->name = $obj->name;
  1133. $this->nom = $obj->name; // deprecated
  1134. $this->name_alias = $obj->name_alias;
  1135. $this->ref_ext = $obj->ref_ext;
  1136. $this->ref_int = $obj->ref_int;
  1137. $this->date_creation = $this->db->jdate($obj->date_creation);
  1138. $this->date_modification = $this->db->jdate($obj->date_modification);
  1139. $this->user_creation = $obj->fk_user_creat;
  1140. $this->user_modification = $obj->fk_user_modif;
  1141. $this->address = $obj->address;
  1142. $this->zip = $obj->zip;
  1143. $this->town = $obj->town;
  1144. $this->country_id = $obj->country_id;
  1145. $this->country_code = $obj->country_id?$obj->country_code:'';
  1146. $this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
  1147. $this->state_id = $obj->fk_departement;
  1148. $this->state_code = $obj->state_code;
  1149. $this->state = ($obj->state!='-'?$obj->state:'');
  1150. $transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
  1151. $libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
  1152. $this->stcomm_id = $obj->fk_stcomm; // id statut commercial
  1153. $this->statut_commercial = $libelle; // libelle statut commercial
  1154. $this->email = $obj->email;
  1155. $this->skype = $obj->skype;
  1156. $this->twitter = $obj->twitter;
  1157. $this->facebook = $obj->facebook;
  1158. $this->url = $obj->url;
  1159. $this->phone = $obj->phone;
  1160. $this->fax = $obj->fax;
  1161. $this->parent = $obj->parent;
  1162. $this->idprof1 = $obj->idprof1;
  1163. $this->idprof2 = $obj->idprof2;
  1164. $this->idprof3 = $obj->idprof3;
  1165. $this->idprof4 = $obj->idprof4;
  1166. $this->idprof5 = $obj->idprof5;
  1167. $this->idprof6 = $obj->idprof6;
  1168. $this->capital = $obj->capital;
  1169. $this->code_client = $obj->code_client;
  1170. $this->code_fournisseur = $obj->code_fournisseur;
  1171. $this->code_compta = $obj->code_compta;
  1172. $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
  1173. $this->barcode = $obj->barcode;
  1174. $this->tva_assuj = $obj->tva_assuj;
  1175. $this->tva_intra = $obj->tva_intra;
  1176. $this->status = $obj->status;
  1177. // Local Taxes
  1178. $this->localtax1_assuj = $obj->localtax1_assuj;
  1179. $this->localtax2_assuj = $obj->localtax2_assuj;
  1180. $this->localtax1_value = $obj->localtax1_value;
  1181. $this->localtax2_value = $obj->localtax2_value;
  1182. $this->typent_id = $obj->typent_id;
  1183. $this->typent_code = $obj->typent_code;
  1184. $this->effectif_id = $obj->effectif_id;
  1185. $this->effectif = $obj->effectif_id?$obj->effectif:'';
  1186. $this->forme_juridique_code= $obj->forme_juridique_code;
  1187. $this->forme_juridique = $obj->forme_juridique_code?$obj->forme_juridique:'';
  1188. $this->fk_prospectlevel = $obj->fk_prospectlevel;
  1189. $this->prefix_comm = $obj->prefix_comm;
  1190. $this->remise_percent = price2num($obj->remise_client); // 0.000000 must be 0
  1191. $this->remise_supplier_percent = $obj->remise_supplier;
  1192. $this->mode_reglement_id = $obj->mode_reglement;
  1193. $this->cond_reglement_id = $obj->cond_reglement;
  1194. $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
  1195. $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
  1196. $this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
  1197. $this->fk_account = $obj->fk_account;
  1198. $this->client = $obj->client;
  1199. $this->fournisseur = $obj->fournisseur;
  1200. $this->note = $obj->note_private; // TODO Deprecated for backward comtability
  1201. $this->note_private = $obj->note_private;
  1202. $this->note_public = $obj->note_public;
  1203. $this->modelpdf = $obj->model_pdf;
  1204. $this->default_lang = $obj->default_lang;
  1205. $this->logo = $obj->logo;
  1206. $this->webservices_url = $obj->webservices_url;
  1207. $this->webservices_key = $obj->webservices_key;
  1208. $this->outstanding_limit = $obj->outstanding_limit;
  1209. $this->order_min_amount = $obj->order_min_amount;
  1210. $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
  1211. // multiprix
  1212. $this->price_level = $obj->price_level;
  1213. $this->import_key = $obj->import_key;
  1214. //Incoterms
  1215. $this->fk_incoterms = $obj->fk_incoterms;
  1216. $this->location_incoterms = $obj->location_incoterms;
  1217. $this->libelle_incoterms = $obj->libelle_incoterms;
  1218. // multicurrency
  1219. $this->fk_multicurrency = $obj->fk_multicurrency;
  1220. $this->multicurrency_code = $obj->multicurrency_code;
  1221. $result = 1;
  1222. // fetch optionals attributes and labels
  1223. $this->fetch_optionals();
  1224. }
  1225. else
  1226. {
  1227. $result = 0;
  1228. }
  1229. $this->db->free($resql);
  1230. }
  1231. else
  1232. {
  1233. $this->error=$this->db->lasterror();
  1234. $result = -3;
  1235. }
  1236. // Use first price level if level not defined for third party
  1237. if ((! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && empty($this->price_level)) $this->price_level=1;
  1238. return $result;
  1239. }
  1240. /**
  1241. * Delete a third party from database and all its dependencies (contacts, rib...)
  1242. *
  1243. * @param int $id Id of third party to delete
  1244. * @param User $fuser User who ask to delete thirparty
  1245. * @param int $call_trigger 0=No, 1=yes
  1246. * @return int <0 if KO, 0 if nothing done, >0 if OK
  1247. */
  1248. function delete($id, User $fuser=null, $call_trigger=1)
  1249. {
  1250. global $langs, $conf, $user;
  1251. if (empty($fuser)) $fuser=$user;
  1252. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1253. $entity=isset($this->entity)?$this->entity:$conf->entity;
  1254. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1255. $error = 0;
  1256. // Test if child exists
  1257. $objectisused = $this->isObjectUsed($id);
  1258. if (empty($objectisused))
  1259. {
  1260. $this->db->begin();
  1261. // User is mandatory for trigger call
  1262. if (! $error && $call_trigger)
  1263. {
  1264. // Call trigger
  1265. $result=$this->call_trigger('COMPANY_DELETE',$fuser);
  1266. if ($result < 0) $error++;
  1267. // End call triggers
  1268. }
  1269. if (! $error)
  1270. {
  1271. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  1272. $static_cat = new Categorie($this->db);
  1273. $toute_categs = array();
  1274. // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
  1275. if ($this->client || $this->prospect)
  1276. {
  1277. $toute_categs['customer'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
  1278. }
  1279. if ($this->fournisseur)
  1280. {
  1281. $toute_categs['supplier'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
  1282. }
  1283. // Remove each "Categorie"
  1284. foreach ($toute_categs as $type => $categs_type)
  1285. {
  1286. foreach ($categs_type as $cat)
  1287. {
  1288. $cat->del_type($this, $type);
  1289. }
  1290. }
  1291. }
  1292. foreach ($this->childtablesoncascade as $tabletodelete)
  1293. {
  1294. if (! $error)
  1295. {
  1296. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$tabletodelete;
  1297. $sql.= " WHERE fk_soc = " . $id;
  1298. if (! $this->db->query($sql))
  1299. {
  1300. $error++;
  1301. $this->errors[] = $this->db->lasterror();
  1302. }
  1303. }
  1304. }
  1305. // Removed extrafields
  1306. if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
  1307. {
  1308. $result=$this->deleteExtraFields();
  1309. if ($result < 0)
  1310. {
  1311. $error++;
  1312. dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
  1313. }
  1314. }
  1315. // Remove links to subsidiaries companies
  1316. if (! $error)
  1317. {
  1318. $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
  1319. $sql.= " SET parent = NULL";
  1320. $sql.= " WHERE parent = " . $id;
  1321. if (! $this->db->query($sql))
  1322. {
  1323. $error++;
  1324. $this->errors[] = $this->db->lasterror();
  1325. }
  1326. }
  1327. // Remove third party
  1328. if (! $error)
  1329. {
  1330. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
  1331. $sql.= " WHERE rowid = " . $id;
  1332. if (! $this->db->query($sql))
  1333. {
  1334. $error++;
  1335. $this->errors[] = $this->db->lasterror();
  1336. }
  1337. }
  1338. if (! $error)
  1339. {
  1340. $this->db->commit();
  1341. // Delete directory
  1342. if (! empty($conf->societe->multidir_output[$entity]))
  1343. {
  1344. $docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
  1345. if (dol_is_dir($docdir))
  1346. {
  1347. dol_delete_dir_recursive($docdir);
  1348. }
  1349. }
  1350. return 1;
  1351. }
  1352. else
  1353. {
  1354. dol_syslog($this->error, LOG_ERR);
  1355. $this->db->rollback();
  1356. return -1;
  1357. }
  1358. }
  1359. else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
  1360. return 0;
  1361. }
  1362. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1363. /**
  1364. * Define third party as a customer
  1365. *
  1366. * @return int <0 if KO, >0 if OK
  1367. */
  1368. function set_as_client()
  1369. {
  1370. // phpcs:enable
  1371. if ($this->id)
  1372. {
  1373. $newclient=1;
  1374. if ($this->client == 2 || $this->client == 3) $newclient=3; //If prospect, we keep prospect tag
  1375. $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
  1376. $sql.= " SET client = ".$newclient;
  1377. $sql.= " WHERE rowid = " . $this->id;
  1378. $resql=$this->db->query($sql);
  1379. if ($resql)
  1380. {
  1381. $this->client = $newclient;
  1382. return 1;
  1383. }
  1384. else return -1;
  1385. }
  1386. return 0;
  1387. }
  1388. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1389. /**
  1390. * Definit la societe comme un client
  1391. *
  1392. * @param float $remise Valeur en % de la remise
  1393. * @param string $note Note/Motif de modification de la remise
  1394. * @param User $user Utilisateur qui definie la remise
  1395. * @return int <0 if KO, >0 if OK
  1396. */
  1397. function set_remise_client($remise, $note, User $user)
  1398. {
  1399. // phpcs:enable
  1400. global $conf, $langs;
  1401. // Nettoyage parametres
  1402. $note=trim($note);
  1403. if (! $note)
  1404. {
  1405. $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
  1406. return -2;
  1407. }
  1408. dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
  1409. if ($this->id)
  1410. {
  1411. $this->db->begin();
  1412. $now=dol_now();
  1413. // Positionne remise courante
  1414. $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
  1415. $sql.= " SET remise_client = '".$this->db->escape($remise)."'";
  1416. $sql.= " WHERE rowid = " . $this->id;
  1417. $resql=$this->db->query($sql);
  1418. if (! $resql)
  1419. {
  1420. $this->db->rollback();
  1421. $this->error=$this->db->error();
  1422. return -1;
  1423. }
  1424. // Ecrit trace dans historique des remises
  1425. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
  1426. $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
  1427. $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
  1428. $sql.= " '".$this->db->escape($note)."',";
  1429. $sql.= " ".$user->id;
  1430. $sql.= ")";
  1431. $resql=$this->db->query($sql);
  1432. if (! $resql)
  1433. {
  1434. $this->db->rollback();
  1435. $this->error=$this->db->lasterror();
  1436. return -1;
  1437. }
  1438. $this->db->commit();
  1439. return 1;
  1440. }
  1441. }
  1442. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1443. /**
  1444. * Definit la societe comme un client
  1445. *
  1446. * @param float $remise Valeur en % de la remise
  1447. * @param string $note Note/Motif de modification de la remise
  1448. * @param User $user Utilisateur qui definie la remise
  1449. * @return int <0 if KO, >0 if OK
  1450. */
  1451. function set_remise_supplier($remise, $note, User $user)
  1452. {
  1453. // phpcs:enable
  1454. global $conf, $langs;
  1455. // Nettoyage parametres
  1456. $note=trim($note);
  1457. if (! $note)
  1458. {
  1459. $this->error=$langs->trans("ErrorFieldRequired",$langs->trans("NoteReason"));
  1460. return -2;
  1461. }
  1462. dol_syslog(get_class($this)."::set_remise_supplier ".$remise.", ".$note.", ".$user->id);
  1463. if ($this->id)
  1464. {
  1465. $this->db->begin();
  1466. $now=dol_now();
  1467. // Positionne remise courante
  1468. $sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
  1469. $sql.= " SET remise_supplier = '".$this->db->escape($remise)."'";
  1470. $sql.= " WHERE rowid = " . $this->id;
  1471. $resql=$this->db->query($sql);
  1472. if (! $resql)
  1473. {
  1474. $this->db->rollback();
  1475. $this->error=$this->db->error();
  1476. return -1;
  1477. }
  1478. // Ecrit trace dans historique des remises
  1479. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_supplier";
  1480. $sql.= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
  1481. $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
  1482. $sql.= " '".$this->db->escape($note)."',";
  1483. $sql.= " ".$user->id;
  1484. $sql.= ")";
  1485. $resql=$this->db->query($sql);
  1486. if (! $resql)
  1487. {
  1488. $this->db->rollback();
  1489. $this->error=$this->db->lasterror();
  1490. return -1;
  1491. }
  1492. $this->db->commit();
  1493. return 1;
  1494. }
  1495. }
  1496. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1497. /**
  1498. * Add a discount for third party
  1499. *
  1500. * @param float $remise Amount of discount
  1501. * @param User $user User adding discount
  1502. * @param string $desc Reason of discount
  1503. * @param float $tva_tx VAT rate
  1504. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  1505. * @return int <0 if KO, id of discount record if OK
  1506. */
  1507. function set_remise_except($remise, User $user, $desc, $tva_tx=0, $discount_type=0)
  1508. {
  1509. // phpcs:enable
  1510. global $langs;
  1511. // Clean parameters
  1512. $remise = price2num($remise);
  1513. $desc = trim($desc);
  1514. // Check parameters
  1515. if (! $remise > 0)
  1516. {
  1517. $this->error=$langs->trans("ErrorWrongValueForParameter","1");
  1518. return -1;
  1519. }
  1520. if (! $desc)
  1521. {
  1522. $this->error=$langs->trans("ErrorWrongValueForParameter","3");
  1523. return -2;
  1524. }
  1525. if ($this->id)
  1526. {
  1527. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  1528. $discount = new DiscountAbsolute($this->db);
  1529. $discount->fk_soc=$this->id;
  1530. $discount->discount_type=$discount_type;
  1531. $discount->amount_ht=$discount->multicurrency_amount_ht=price2num($remise,'MT');
  1532. $discount->amount_tva=$discount->multicurrency_amount_tva=price2num($remise*$tva_tx/100,'MT');
  1533. $discount->amount_ttc=$discount->multicurrency_amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
  1534. $discount->tva_tx=price2num($tva_tx,'MT');
  1535. $discount->description=$desc;
  1536. $result=$discount->create($user);
  1537. if ($result > 0)
  1538. {
  1539. return $result;
  1540. }
  1541. else
  1542. {
  1543. $this->error=$discount->error;
  1544. return -3;
  1545. }
  1546. }
  1547. else return 0;
  1548. }
  1549. /**
  1550. * Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
  1551. *
  1552. * @param User $user Filtre sur un user auteur des remises
  1553. * @param string $filter Filtre autre
  1554. * @param integer $maxvalue Filter on max value for discount
  1555. * @param int $discount_type 0 => customer discount, 1 => supplier discount
  1556. * @return int <0 if KO, Credit note amount otherwise
  1557. */
  1558. function getAvailableDiscounts($user='',$filter='',$maxvalue=0,$discount_type=0)
  1559. {
  1560. require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
  1561. $discountstatic=new DiscountAbsolute($this->db);
  1562. $result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue,$discount_type);
  1563. if ($result >= 0)
  1564. {
  1565. return $result;
  1566. }
  1567. else
  1568. {
  1569. $this->error=$discountstatic->error;
  1570. return -1;
  1571. }
  1572. }
  1573. /**
  1574. * Return array of sales representatives
  1575. *
  1576. * @param User $user Object user
  1577. * @param int $mode 0=Array with properties, 1=Array of id.
  1578. * @return array Array of sales representatives of third party
  1579. */
  1580. function getSalesRepresentatives(User $user, $mode=0)
  1581. {
  1582. global $conf;
  1583. $reparray=array();
  1584. $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
  1585. $sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
  1586. if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
  1587. {
  1588. $sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
  1589. $sql.= " WHERE ((ug.fk_user = sc.fk_user";
  1590. $sql.= " AND ug.entity = ".$conf->entity.")";
  1591. $sql.= " OR u.admin = 1)";
  1592. }
  1593. else
  1594. $sql.= " WHERE entity in (0, ".$conf->entity.")";
  1595. $sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc = ".$this->id;
  1596. $resql = $this->db->query($sql);
  1597. if ($resql)
  1598. {
  1599. $num = $this->db->num_rows($resql);
  1600. $i=0;
  1601. while ($i < $num)
  1602. {
  1603. $obj = $this->db->fetch_object($resql);
  1604. if (empty($mode))
  1605. {
  1606. $reparray[$i]['id']=$obj->rowid;
  1607. $reparray[$i]['lastname']=$obj->lastname;
  1608. $reparray[$i]['firstname']=$obj->firstname;
  1609. $reparray[$i]['email']=$obj->email;
  1610. $reparray[$i]['statut']=$obj->statut;
  1611. $reparray[$i]['entity']=$obj->entity;
  1612. $reparray[$i]['login']=$obj->login;
  1613. $reparray[$i]['photo']=$obj->photo;
  1614. }
  1615. else
  1616. {
  1617. $reparray[]=$obj->rowid;
  1618. }
  1619. $i++;
  1620. }
  1621. return $reparray;
  1622. }
  1623. else {
  1624. dol_print_error($this->db);
  1625. return -1;
  1626. }
  1627. }
  1628. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1629. /**
  1630. * Set the price level
  1631. *
  1632. * @param int $price_level Level of price
  1633. * @param User $user Use making change
  1634. * @return int <0 if KO, >0 if OK
  1635. */
  1636. function set_price_level($price_level, User $user)
  1637. {
  1638. // phpcs:enable
  1639. if ($this->id)
  1640. {
  1641. $now=dol_now();
  1642. $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
  1643. $sql .= " SET price_level = '".$this->db->escape($price_level)."'";
  1644. $sql .= " WHERE rowid = " . $this->id;
  1645. if (! $this->db->query($sql))
  1646. {
  1647. dol_print_error($this->db);
  1648. return -1;
  1649. }
  1650. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
  1651. $sql .= " (datec, fk_soc, price_level, fk_user_author)";
  1652. $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($price_level)."', ".$user->id.")";
  1653. if (! $this->db->query($sql))
  1654. {
  1655. dol_print_error($this->db);
  1656. return -1;
  1657. }
  1658. return 1;
  1659. }
  1660. return -1;
  1661. }
  1662. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1663. /**
  1664. * Add link to sales representative
  1665. *
  1666. * @param User $user Object user
  1667. * @param int $commid Id of user
  1668. * @return void
  1669. */
  1670. function add_commercial(User $user, $commid)
  1671. {
  1672. // phpcs:enable
  1673. $error=0;
  1674. if ($this->id > 0 && $commid > 0)
  1675. {
  1676. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
  1677. $sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
  1678. $this->db->query($sql);
  1679. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
  1680. $sql.= " ( fk_soc, fk_user )";
  1681. $sql.= " VALUES (".$this->id.",".$commid.")";
  1682. if (! $this->db->query($sql) )
  1683. {
  1684. dol_syslog(get_class($this)."::add_commercial Erreur");
  1685. }
  1686. else {
  1687. $this->context=array('commercial_modified'=>$commid);
  1688. $result=$this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE',$user);
  1689. if ($result < 0) $error++;
  1690. }
  1691. }
  1692. }
  1693. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1694. /**
  1695. * Add link to sales representative
  1696. *
  1697. * @param User $user Object user
  1698. * @param int $commid Id of user
  1699. * @return void
  1700. */
  1701. function del_commercial(User $user, $commid)
  1702. {
  1703. // phpcs:enable
  1704. $error=0;
  1705. $this->context=array('commercial_modified'=>$commid);
  1706. $result=$this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE',$user);
  1707. if ($result < 0) $error++;
  1708. if ($this->id > 0 && $commid > 0)
  1709. {
  1710. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
  1711. $sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
  1712. if (! $this->db->query($sql) )
  1713. {
  1714. dol_syslog(get_class($this)."::del_commercial Erreur");
  1715. }
  1716. }
  1717. }
  1718. /**
  1719. * Return a link on thirdparty (with picto)
  1720. *
  1721. * @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
  1722. * @param string $option Target of link ('', 'customer', 'prospect', 'supplier', 'project')
  1723. * @param int $maxlen Max length of name
  1724. * @param int $notooltip 1=Disable tooltip
  1725. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1726. * @return string String with URL
  1727. */
  1728. function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $save_lastsearch_value=-1)
  1729. {
  1730. global $conf, $langs, $hookmanager;
  1731. if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
  1732. $name=$this->name?$this->name:$this->nom;
  1733. if(!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)){
  1734. if(empty($option) && $this->client > 0) $option = 'customer';
  1735. if(empty($option) && $this->fournisseur > 0) $option = 'supplier';
  1736. }
  1737. if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
  1738. {
  1739. $code = '';
  1740. if (($this->client) && (! empty ( $this->code_client ))
  1741. && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
  1742. || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
  1743. )
  1744. )
  1745. {
  1746. $code = $this->code_client . ' - ';
  1747. }
  1748. if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))
  1749. && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1
  1750. || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
  1751. )
  1752. )
  1753. {
  1754. $code .= $this->code_fournisseur . ' - ';
  1755. }
  1756. if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1)
  1757. {
  1758. $name =$code.' '.$name;
  1759. }
  1760. else
  1761. {
  1762. $name =$code;
  1763. }
  1764. }
  1765. if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
  1766. $result=''; $label='';
  1767. $linkstart=''; $linkend='';
  1768. if (! empty($this->logo) && class_exists('Form'))
  1769. {
  1770. $label.= '<div class="photointooltip">';
  1771. $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.
  1772. $label.= '</div><div style="clear: both;"></div>';
  1773. }
  1774. $label.= '<div class="centpercent">';
  1775. if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
  1776. {
  1777. $label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
  1778. $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
  1779. }
  1780. elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
  1781. {
  1782. $label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
  1783. $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
  1784. }
  1785. elseif ($option == 'supplier')
  1786. {
  1787. $label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
  1788. $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
  1789. }
  1790. elseif ($option == 'agenda')
  1791. {
  1792. $label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
  1793. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
  1794. }
  1795. elseif ($option == 'project')
  1796. {
  1797. $label.= '<u>' . $langs->trans("ShowProject") . '</u>';
  1798. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
  1799. }
  1800. elseif ($option == 'margin')
  1801. {
  1802. $label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
  1803. $linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
  1804. }
  1805. elseif ($option == 'contact')
  1806. {
  1807. $label.= '<u>' . $langs->trans("ShowContacts") . '</u>';
  1808. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
  1809. }
  1810. elseif ($option == 'ban')
  1811. {
  1812. $label.= '<u>' . $langs->trans("ShowBan") . '</u>';
  1813. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
  1814. }
  1815. // By default
  1816. if (empty($linkstart))
  1817. {
  1818. $label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
  1819. $linkstart = '<a href="'.DOL_URL_ROOT.'/societe/card.php?socid='.$this->id;
  1820. }
  1821. if (! empty($this->name))
  1822. {
  1823. $label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
  1824. if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
  1825. $label.= '<br><b>' . $langs->trans('Email') . ':</b> '. $this->email;
  1826. }
  1827. if (! empty($this->country_code))
  1828. $label.= '<br><b>' . $langs->trans('Country') . ':</b> '. $this->country_code;
  1829. if (! empty($this->tva_intra) || (! empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false))
  1830. $label.= '<br><b>' . $langs->trans('VATIntra') . ':</b> '. $this->tva_intra;
  1831. if (! empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP))
  1832. {
  1833. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false) $label.= '<br><b>' . $langs->trans('ProfId1'.$this->country_code) . ':</b> '. $this->idprof1;
  1834. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false) $label.= '<br><b>' . $langs->trans('ProfId2'.$this->country_code) . ':</b> '. $this->idprof2;
  1835. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false) $label.= '<br><b>' . $langs->trans('ProfId3'.$this->country_code) . ':</b> '. $this->idprof3;
  1836. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false) $label.= '<br><b>' . $langs->trans('ProfId4'.$this->country_code) . ':</b> '. $this->idprof4;
  1837. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false) $label.= '<br><b>' . $langs->trans('ProfId5'.$this->country_code) . ':</b> '. $this->idprof5;
  1838. if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false) $label.= '<br><b>' . $langs->trans('ProfId6'.$this->country_code) . ':</b> '. $this->idprof6;
  1839. }
  1840. if (! empty($this->code_client) && ($this->client == 1 || $this->client == 3))
  1841. $label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
  1842. if (! empty($this->code_fournisseur) && $this->fournisseur)
  1843. $label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
  1844. if (! empty($conf->accounting->enabled) && ($this->client == 1 || $this->client == 3))
  1845. $label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. ($this->code_compta ? $this->code_compta : $this->code_compta_client);
  1846. if (! empty($conf->accounting->enabled) && $this->fournisseur)
  1847. $label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
  1848. $label.= '</div>';
  1849. // Add type of canvas
  1850. $linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'');
  1851. // Add param to save lastsearch_values or not
  1852. $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
  1853. if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
  1854. if ($add_save_lastsearch_values) $linkstart.='&save_lastsearch_values=1';
  1855. $linkstart.='"';
  1856. $linkclose='';
  1857. if (empty($notooltip))
  1858. {
  1859. if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
  1860. {
  1861. $label=$langs->trans("ShowCompany");
  1862. $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
  1863. }
  1864. $linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
  1865. $linkclose.=' class="classfortooltip refurl"';
  1866. /*
  1867. $hookmanager->initHooks(array('thirdpartydao'));
  1868. $parameters=array('id'=>$this->id);
  1869. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  1870. if ($reshook > 0) $linkclose = $hookmanager->resPrint;
  1871. */
  1872. }
  1873. $linkstart.=$linkclose.'>';
  1874. $linkend='</a>';
  1875. global $user;
  1876. if (! $user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id)
  1877. {
  1878. $linkstart='';
  1879. $linkend='';
  1880. }
  1881. $result.=$linkstart;
  1882. if ($withpicto) $result.=img_object(($notooltip?'':$label), ($this->picto?$this->picto:'generic'), ($notooltip?(($withpicto != 2) ? 'class="paddingright"' : ''):'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip valigntextbottom"'), 0, 0, $notooltip?0:1);
  1883. if ($withpicto != 2) $result.=($maxlen?dol_trunc($name,$maxlen):$name);
  1884. $result.=$linkend;
  1885. global $action;
  1886. $hookmanager->initHooks(array('thirdpartydao'));
  1887. $parameters=array('id'=>$this->id, 'getnomurl'=>$result);
  1888. $reshook=$hookmanager->executeHooks('getNomUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  1889. if ($reshook > 0) $result = $hookmanager->resPrint;
  1890. else $result .= $hookmanager->resPrint;
  1891. return $result;
  1892. }
  1893. /**
  1894. * Return label of status (activity, closed)
  1895. *
  1896. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1897. * @return string Libelle
  1898. */
  1899. function getLibStatut($mode=0)
  1900. {
  1901. return $this->LibStatut($this->status,$mode);
  1902. }
  1903. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1904. /**
  1905. * Renvoi le libelle d'un statut donne
  1906. *
  1907. * @param int $statut Id statut
  1908. * @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
  1909. * @return string Libelle du statut
  1910. */
  1911. function LibStatut($statut,$mode=0)
  1912. {
  1913. // phpcs:enable
  1914. global $langs;
  1915. $langs->load('companies');
  1916. if ($mode == 0)
  1917. {
  1918. if ($statut==0) return $langs->trans("ActivityCeased");
  1919. elseif ($statut==1) return $langs->trans("InActivity");
  1920. }
  1921. elseif ($mode == 1)
  1922. {
  1923. if ($statut==0) return $langs->trans("ActivityCeased");
  1924. elseif ($statut==1) return $langs->trans("InActivity");
  1925. }
  1926. elseif ($mode == 2)
  1927. {
  1928. if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
  1929. elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
  1930. }
  1931. elseif ($mode == 3)
  1932. {
  1933. if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
  1934. elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
  1935. }
  1936. elseif ($mode == 4)
  1937. {
  1938. if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
  1939. elseif ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
  1940. }
  1941. elseif ($mode == 5)
  1942. {
  1943. if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
  1944. elseif ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
  1945. }
  1946. elseif ($mode == 6)
  1947. {
  1948. if ($statut==0) return '<span class="hideonsmartphone">'.$langs->trans("ActivityCeased").'</span> '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
  1949. elseif ($statut==1) return '<span class="hideonsmartphone">'.$langs->trans("InActivity").'</span> '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
  1950. }
  1951. }
  1952. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1953. /**
  1954. * Return list of contacts emails existing for third party
  1955. *
  1956. * @param int $addthirdparty 1=Add also a record for thirdparty email
  1957. * @return array Array of contacts emails
  1958. */
  1959. function thirdparty_and_contact_email_array($addthirdparty=0)
  1960. {
  1961. // phpcs:enable
  1962. global $langs;
  1963. $contact_emails = $this->contact_property_array('email',1);
  1964. if ($this->email && $addthirdparty)
  1965. {
  1966. if (empty($this->name)) $this->name=$this->nom;
  1967. $contact_emails['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->email.">";
  1968. }
  1969. //var_dump($contact_emails)
  1970. return $contact_emails;
  1971. }
  1972. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1973. /**
  1974. * Return list of contacts mobile phone existing for third party
  1975. *
  1976. * @return array Array of contacts emails
  1977. */
  1978. function thirdparty_and_contact_phone_array()
  1979. {
  1980. // phpcs:enable
  1981. global $langs;
  1982. $contact_phone = $this->contact_property_array('mobile');
  1983. if (! empty($this->phone)) // If a phone of thirdparty is defined, we add it ot mobile of contacts
  1984. {
  1985. if (empty($this->name)) $this->name=$this->nom;
  1986. // TODO: Tester si tel non deja present dans tableau contact
  1987. $contact_phone['thirdparty']=$langs->transnoentitiesnoconv("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->phone.">";
  1988. }
  1989. return $contact_phone;
  1990. }
  1991. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  1992. /**
  1993. * Return list of contacts emails or mobile existing for third party
  1994. *
  1995. * @param string $mode 'email' or 'mobile'
  1996. * @param int $hidedisabled 1=Hide contact if disabled
  1997. * @return array Array of contacts emails or mobile. Example: array(id=>'Name <email>')
  1998. */
  1999. function contact_property_array($mode='email', $hidedisabled=0)
  2000. {
  2001. // phpcs:enable
  2002. global $langs;
  2003. $contact_property = array();
  2004. $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
  2005. $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
  2006. $sql.= " WHERE fk_soc = ".$this->id;
  2007. $resql=$this->db->query($sql);
  2008. if ($resql)
  2009. {
  2010. $nump = $this->db->num_rows($resql);
  2011. if ($nump)
  2012. {
  2013. $sepa="("; $sepb=")";
  2014. if ($mode == 'email')
  2015. {
  2016. //$sepa="&lt;"; $sepb="&gt;";
  2017. $sepa="<"; $sepb=">";
  2018. }
  2019. $i = 0;
  2020. while ($i < $nump)
  2021. {
  2022. $obj = $this->db->fetch_object($resql);
  2023. if ($mode == 'email') $property=$obj->email;
  2024. else if ($mode == 'mobile') $property=$obj->phone_mobile;
  2025. else $property=$obj->$mode;
  2026. // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
  2027. if ($obj->statut == 1 || empty($hidedisabled))
  2028. {
  2029. if (empty($property))
  2030. {
  2031. if ($mode == 'email') $property=$langs->transnoentitiesnoconv("NoEMail");
  2032. else if ($mode == 'mobile') $property=$langs->transnoentitiesnoconv("NoMobilePhone");
  2033. }
  2034. if (!empty($obj->poste))
  2035. {
  2036. $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
  2037. }
  2038. else
  2039. {
  2040. $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
  2041. }
  2042. }
  2043. $i++;
  2044. }
  2045. }
  2046. }
  2047. else
  2048. {
  2049. dol_print_error($this->db);
  2050. }
  2051. return $contact_property;
  2052. }
  2053. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2054. /**
  2055. * Renvoie la liste des contacts de cette societe
  2056. *
  2057. * @return array tableau des contacts
  2058. */
  2059. function contact_array()
  2060. {
  2061. // phpcs:enable
  2062. $contacts = array();
  2063. $sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
  2064. $resql=$this->db->query($sql);
  2065. if ($resql)
  2066. {
  2067. $nump = $this->db->num_rows($resql);
  2068. if ($nump)
  2069. {
  2070. $i = 0;
  2071. while ($i < $nump)
  2072. {
  2073. $obj = $this->db->fetch_object($resql);
  2074. $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
  2075. $i++;
  2076. }
  2077. }
  2078. }
  2079. else
  2080. {
  2081. dol_print_error($this->db);
  2082. }
  2083. return $contacts;
  2084. }
  2085. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2086. /**
  2087. * Renvoie la liste des contacts de cette societe
  2088. *
  2089. * @return array $contacts tableau des contacts
  2090. */
  2091. function contact_array_objects()
  2092. {
  2093. // phpcs:enable
  2094. require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
  2095. $contacts = array();
  2096. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = ".$this->id;
  2097. $resql=$this->db->query($sql);
  2098. if ($resql)
  2099. {
  2100. $nump = $this->db->num_rows($resql);
  2101. if ($nump)
  2102. {
  2103. $i = 0;
  2104. while ($i < $nump)
  2105. {
  2106. $obj = $this->db->fetch_object($resql);
  2107. $contact = new Contact($this->db);
  2108. $contact->fetch($obj->rowid);
  2109. $contacts[] = $contact;
  2110. $i++;
  2111. }
  2112. }
  2113. }
  2114. else
  2115. {
  2116. dol_print_error($this->db);
  2117. }
  2118. return $contacts;
  2119. }
  2120. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2121. /**
  2122. * Return property of contact from its id
  2123. *
  2124. * @param int $rowid id of contact
  2125. * @param string $mode 'email' or 'mobile'
  2126. * @return string Email of contact with format: "Full name <email>"
  2127. */
  2128. function contact_get_property($rowid,$mode)
  2129. {
  2130. // phpcs:enable
  2131. $contact_property='';
  2132. if (empty($rowid)) return '';
  2133. $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
  2134. $sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
  2135. $sql.= " WHERE rowid = '".$rowid."'";
  2136. $resql=$this->db->query($sql);
  2137. if ($resql)
  2138. {
  2139. $nump = $this->db->num_rows($resql);
  2140. if ($nump)
  2141. {
  2142. $obj = $this->db->fetch_object($resql);
  2143. if ($mode == 'email') $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(","))." <".$obj->email.">";
  2144. else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
  2145. }
  2146. return $contact_property;
  2147. }
  2148. else
  2149. {
  2150. dol_print_error($this->db);
  2151. }
  2152. }
  2153. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2154. /**
  2155. * Return bank number property of thirdparty (label or rum)
  2156. *
  2157. * @param string $mode 'label' or 'rum' or 'format'
  2158. * @return string Bank number
  2159. */
  2160. function display_rib($mode='label')
  2161. {
  2162. // phpcs:enable
  2163. require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
  2164. $bac = new CompanyBankAccount($this->db);
  2165. $bac->fetch(0,$this->id);
  2166. if ($mode == 'label')
  2167. {
  2168. return $bac->getRibLabel(true);
  2169. }
  2170. elseif ($mode == 'rum')
  2171. {
  2172. if (empty($bac->rum))
  2173. {
  2174. require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
  2175. $prelevement = new BonPrelevement($this->db);
  2176. $bac->fetch_thirdparty();
  2177. $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
  2178. }
  2179. return $bac->rum;
  2180. }
  2181. elseif ($mode == 'format')
  2182. {
  2183. return $bac->frstrecur;
  2184. }
  2185. return 'BadParameterToFunctionDisplayRib';
  2186. }
  2187. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2188. /**
  2189. * Return Array of RIB
  2190. *
  2191. * @return array|int 0 if KO, Array of CompanyBanckAccount if OK
  2192. */
  2193. function get_all_rib()
  2194. {
  2195. // phpcs:enable
  2196. require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
  2197. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE type='ban' AND fk_soc = ".$this->id;
  2198. $result = $this->db->query($sql);
  2199. if (!$result) {
  2200. $this->error++;
  2201. $this->errors[] = $this->db->lasterror;
  2202. return 0;
  2203. } else {
  2204. $num_rows = $this->db->num_rows($result);
  2205. $rib_array = array();
  2206. if ($num_rows) {
  2207. while ($obj = $this->db->fetch_object($result)) {
  2208. $rib = new CompanyBankAccount($this->db);
  2209. $rib->fetch($obj->rowid);
  2210. $rib_array[] = $rib;
  2211. }
  2212. }
  2213. return $rib_array;
  2214. }
  2215. }
  2216. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2217. /**
  2218. * Attribut un code client a partir du module de controle des codes.
  2219. * Return value is stored into this->code_client
  2220. *
  2221. * @param Societe $objsoc Object thirdparty
  2222. * @param int $type Should be 0 to say customer
  2223. * @return void
  2224. */
  2225. function get_codeclient($objsoc=0,$type=0)
  2226. {
  2227. // phpcs:enable
  2228. global $conf;
  2229. if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
  2230. {
  2231. $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
  2232. $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
  2233. foreach ($dirsociete as $dirroot)
  2234. {
  2235. $res=dol_include_once($dirroot.$module.'.php');
  2236. if ($res) break;
  2237. }
  2238. $mod = new $module();
  2239. $this->code_client = $mod->getNextValue($objsoc,$type);
  2240. $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
  2241. dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
  2242. }
  2243. }
  2244. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2245. /**
  2246. * Attribut un code fournisseur a partir du module de controle des codes.
  2247. * Return value is stored into this->code_fournisseur
  2248. *
  2249. * @param Societe $objsoc Object thirdparty
  2250. * @param int $type Should be 1 to say supplier
  2251. * @return void
  2252. */
  2253. function get_codefournisseur($objsoc=0,$type=1)
  2254. {
  2255. // phpcs:enable
  2256. global $conf;
  2257. if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
  2258. {
  2259. $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
  2260. $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
  2261. foreach ($dirsociete as $dirroot)
  2262. {
  2263. $res=dol_include_once($dirroot.$module.'.php');
  2264. if ($res) break;
  2265. }
  2266. $mod = new $module();
  2267. $this->code_fournisseur = $mod->getNextValue($objsoc,$type);
  2268. dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
  2269. }
  2270. }
  2271. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2272. /**
  2273. * Verifie si un code client est modifiable en fonction des parametres
  2274. * du module de controle des codes.
  2275. *
  2276. * @return int 0=No, 1=Yes
  2277. */
  2278. function codeclient_modifiable()
  2279. {
  2280. // phpcs:enable
  2281. global $conf;
  2282. if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
  2283. {
  2284. $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
  2285. $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
  2286. foreach ($dirsociete as $dirroot)
  2287. {
  2288. $res=dol_include_once($dirroot.$module.'.php');
  2289. if ($res) break;
  2290. }
  2291. $mod = new $module();
  2292. dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
  2293. if ($mod->code_modifiable_null && ! $this->code_client) return 1;
  2294. if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
  2295. if ($mod->code_modifiable) return 1; // A mettre en dernier
  2296. return 0;
  2297. }
  2298. else
  2299. {
  2300. return 0;
  2301. }
  2302. }
  2303. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2304. /**
  2305. * Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
  2306. *
  2307. * @return int 0=No, 1=Yes
  2308. */
  2309. function codefournisseur_modifiable()
  2310. {
  2311. // phpcs:enable
  2312. global $conf;
  2313. if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
  2314. {
  2315. $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
  2316. $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
  2317. foreach ($dirsociete as $dirroot)
  2318. {
  2319. $res=dol_include_once($dirroot.$module.'.php');
  2320. if ($res) break;
  2321. }
  2322. $mod = new $module();
  2323. dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
  2324. if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
  2325. if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
  2326. if ($mod->code_modifiable) return 1; // A mettre en dernier
  2327. return 0;
  2328. }
  2329. else
  2330. {
  2331. return 0;
  2332. }
  2333. }
  2334. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2335. /**
  2336. * Check customer code
  2337. *
  2338. * @return int 0 if OK
  2339. * -1 ErrorBadCustomerCodeSyntax
  2340. * -2 ErrorCustomerCodeRequired
  2341. * -3 ErrorCustomerCodeAlreadyUsed
  2342. * -4 ErrorPrefixRequired
  2343. */
  2344. function check_codeclient()
  2345. {
  2346. // phpcs:enable
  2347. global $conf;
  2348. if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
  2349. {
  2350. $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
  2351. $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
  2352. foreach ($dirsociete as $dirroot)
  2353. {
  2354. $res=dol_include_once($dirroot.$module.'.php');
  2355. if ($res) break;
  2356. }
  2357. $mod = new $module();
  2358. dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
  2359. $result = $mod->verif($this->db, $this->code_client, $this, 0);
  2360. return $result;
  2361. }
  2362. else
  2363. {
  2364. return 0;
  2365. }
  2366. }
  2367. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2368. /**
  2369. * Check supplier code
  2370. *
  2371. * @return int 0 if OK
  2372. * -1 ErrorBadCustomerCodeSyntax
  2373. * -2 ErrorCustomerCodeRequired
  2374. * -3 ErrorCustomerCodeAlreadyUsed
  2375. * -4 ErrorPrefixRequired
  2376. */
  2377. function check_codefournisseur()
  2378. {
  2379. // phpcs:enable
  2380. global $conf;
  2381. if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
  2382. {
  2383. $module=$conf->global->SOCIETE_CODECLIENT_ADDON;
  2384. $dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
  2385. foreach ($dirsociete as $dirroot)
  2386. {
  2387. $res=dol_include_once($dirroot.$module.'.php');
  2388. if ($res) break;
  2389. }
  2390. $mod = new $module();
  2391. dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
  2392. $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
  2393. return $result;
  2394. }
  2395. else
  2396. {
  2397. return 0;
  2398. }
  2399. }
  2400. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2401. /**
  2402. * Renvoie un code compta, suivant le module de code compta.
  2403. * Peut etre identique a celui saisit ou genere automatiquement.
  2404. * A ce jour seule la generation automatique est implementee
  2405. *
  2406. * @param string $type Type of thirdparty ('customer' or 'supplier')
  2407. * @return string Code compta si ok, 0 si aucun, <0 si ko
  2408. */
  2409. function get_codecompta($type)
  2410. {
  2411. // phpcs:enable
  2412. global $conf;
  2413. if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
  2414. {
  2415. $res=false;
  2416. $dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
  2417. foreach ($dirsociete as $dirroot)
  2418. {
  2419. $res=dol_include_once($dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.'.php');
  2420. if ($res) break;
  2421. }
  2422. if ($res)
  2423. {
  2424. $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
  2425. $mod = new $classname;
  2426. // Defini code compta dans $mod->code
  2427. $result = $mod->get_code($this->db, $this, $type);
  2428. if ($type == 'customer') $this->code_compta = $mod->code;
  2429. else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
  2430. return $result;
  2431. }
  2432. else
  2433. {
  2434. $this->error = 'ErrorAccountancyCodeNotDefined';
  2435. return -1;
  2436. }
  2437. }
  2438. else
  2439. {
  2440. if ($type == 'customer') $this->code_compta = '';
  2441. else if ($type == 'supplier') $this->code_compta_fournisseur = '';
  2442. return 0;
  2443. }
  2444. }
  2445. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2446. /**
  2447. * Define parent commany of current company
  2448. *
  2449. * @param int $id Id of thirdparty to set or '' to remove
  2450. * @return int <0 if KO, >0 if OK
  2451. */
  2452. function set_parent($id)
  2453. {
  2454. // phpcs:enable
  2455. if ($this->id)
  2456. {
  2457. $sql = "UPDATE ".MAIN_DB_PREFIX."societe";
  2458. $sql.= " SET parent = ".($id > 0 ? $id : "null");
  2459. $sql.= " WHERE rowid = " . $this->id;
  2460. dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
  2461. $resql=$this->db->query($sql);
  2462. if ($resql)
  2463. {
  2464. $this->parent = $id;
  2465. return 1;
  2466. }
  2467. else
  2468. {
  2469. return -1;
  2470. }
  2471. }
  2472. else return -1;
  2473. }
  2474. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2475. /**
  2476. * Returns if a profid sould be verified
  2477. *
  2478. * @param int $idprof 1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6)
  2479. * @return boolean true , false
  2480. */
  2481. function id_prof_verifiable($idprof)
  2482. {
  2483. // phpcs:enable
  2484. global $conf;
  2485. switch($idprof)
  2486. {
  2487. case 1:
  2488. $ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
  2489. break;
  2490. case 2:
  2491. $ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
  2492. break;
  2493. case 3:
  2494. $ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
  2495. break;
  2496. case 4:
  2497. $ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
  2498. break;
  2499. case 5:
  2500. $ret=(!$conf->global->SOCIETE_IDPROF5_UNIQUE?false:true);
  2501. break;
  2502. case 6:
  2503. $ret=(!$conf->global->SOCIETE_IDPROF6_UNIQUE?false:true);
  2504. break;
  2505. default:
  2506. $ret=false;
  2507. }
  2508. return $ret;
  2509. }
  2510. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2511. /**
  2512. * Verify if a profid exists into database for others thirds
  2513. *
  2514. * @param string $idprof 'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm)
  2515. * @param string $value Value of profid
  2516. * @param int $socid Id of thirdparty to exclude (if update)
  2517. * @return boolean True if exists, False if not
  2518. */
  2519. function id_prof_exists($idprof, $value, $socid=0)
  2520. {
  2521. // phpcs:enable
  2522. $field = $idprof;
  2523. switch($idprof) // For backward compatibility
  2524. {
  2525. case '1':
  2526. case 'idprof1':
  2527. $field="siren";
  2528. break;
  2529. case '2':
  2530. case 'idprof2':
  2531. $field="siret";
  2532. break;
  2533. case '3':
  2534. case 'idprof3':
  2535. $field="ape";
  2536. break;
  2537. case '4':
  2538. case 'idprof4':
  2539. $field="idprof4";
  2540. break;
  2541. case '5':
  2542. $field="idprof5";
  2543. break;
  2544. case '6':
  2545. $field="idprof6";
  2546. break;
  2547. }
  2548. //Verify duplicate entries
  2549. $sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe').")";
  2550. if($socid) $sql .= " AND rowid <> ".$socid;
  2551. $resql = $this->db->query($sql);
  2552. if ($resql)
  2553. {
  2554. $obj = $this->db->fetch_object($resql);
  2555. $count = $obj->idprof;
  2556. }
  2557. else
  2558. {
  2559. $count = 0;
  2560. print $this->db->error();
  2561. }
  2562. $this->db->free($resql);
  2563. if ($count > 0) return true;
  2564. else return false;
  2565. }
  2566. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2567. /**
  2568. * Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
  2569. *
  2570. * @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
  2571. * @param Societe $soc Objet societe
  2572. * @return int <=0 if KO, >0 if OK
  2573. * TODO better to have this in a lib than into a business class
  2574. */
  2575. function id_prof_check($idprof,$soc)
  2576. {
  2577. // phpcs:enable
  2578. global $conf;
  2579. $ok=1;
  2580. if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
  2581. // Verifie SIREN si pays FR
  2582. if ($idprof == 1 && $soc->country_code == 'FR')
  2583. {
  2584. $chaine=trim($this->idprof1);
  2585. $chaine=preg_replace('/(\s)/','',$chaine);
  2586. if (!is_numeric($chaine)) return -1;
  2587. if (dol_strlen($chaine) != 9) return -1;
  2588. // on prend chaque chiffre un par un
  2589. // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
  2590. // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
  2591. // on ajoute cette valeur à la somme totale
  2592. for ($index = 0; $index < 9; $index ++)
  2593. {
  2594. $number = (int) $siren[$index];
  2595. if (($index % 2) != 0) { if (($number *= 2) > 9) $number -= 9; }
  2596. $sum += $number;
  2597. }
  2598. // le numéro est valide si la somme des chiffres est multiple de 10
  2599. if (($sum % 10) != 0) return -1;
  2600. }
  2601. // Verifie SIRET si pays FR
  2602. if ($idprof == 2 && $soc->country_code == 'FR')
  2603. {
  2604. $chaine=trim($this->idprof2);
  2605. $chaine=preg_replace('/(\s)/','',$chaine);
  2606. if (!is_numeric($chaine)) return -1;
  2607. if (dol_strlen($chaine) != 14) return -1;
  2608. // on prend chaque chiffre un par un
  2609. // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
  2610. // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
  2611. // on ajoute cette valeur à la somme totale
  2612. for ($index = 0; $index < 14; $index ++)
  2613. {
  2614. $number = (int) $chaine[$index];
  2615. if (($index % 2) == 0) { if (($number *= 2) > 9) $number -= 9; }
  2616. $sum += $number;
  2617. }
  2618. // le numéro est valide si la somme des chiffres est multiple de 10
  2619. if (($sum % 10) != 0) return -1;
  2620. }
  2621. //Verify CIF/NIF/NIE if pays ES
  2622. //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
  2623. if ($idprof == 1 && $soc->country_code == 'ES')
  2624. {
  2625. $string=trim($this->idprof1);
  2626. $string=preg_replace('/(\s)/','',$string);
  2627. $string = strtoupper($string);
  2628. for ($i = 0; $i < 9; $i ++)
  2629. $num[$i] = substr($string, $i, 1);
  2630. //Check format
  2631. 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))
  2632. return 0;
  2633. //Check NIF
  2634. if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
  2635. if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
  2636. return 1;
  2637. else
  2638. return -1;
  2639. //algorithm checking type code CIF
  2640. $sum = $num[2] + $num[4] + $num[6];
  2641. for ($i = 1; $i < 8; $i += 2)
  2642. $sum += intval(substr((2 * $num[$i]),0,1)) + intval(substr((2 * $num[$i]),1,1));
  2643. $n = 10 - substr($sum, strlen($sum) - 1, 1);
  2644. //Chek special NIF
  2645. if (preg_match('/^[KLM]{1}/', $string))
  2646. if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
  2647. return 1;
  2648. else
  2649. return -1;
  2650. //Check CIF
  2651. if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
  2652. if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
  2653. return 2;
  2654. else
  2655. return -2;
  2656. //Check NIE T
  2657. if (preg_match('/^[T]{1}/', $string))
  2658. if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
  2659. return 3;
  2660. else
  2661. return -3;
  2662. //Check NIE XYZ
  2663. if (preg_match('/^[XYZ]{1}/', $string))
  2664. if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
  2665. return 3;
  2666. else
  2667. return -3;
  2668. //Can not be verified
  2669. return -4;
  2670. }
  2671. //Verify NIF if country is PT
  2672. //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
  2673. if ($idprof == 1 && $soc->country_code == 'PT')
  2674. {
  2675. $string=trim($this->idprof1);
  2676. $string=preg_replace('/(\s)/','',$string);
  2677. for ($i = 0; $i < 9; $i ++) {
  2678. $num[$i] = substr($string, $i, 1);
  2679. }
  2680. //Check NIF
  2681. if (preg_match('/(^[0-9]{9}$)/', $string)) {
  2682. return 1;
  2683. }
  2684. else {
  2685. return -1;
  2686. }
  2687. }
  2688. return $ok;
  2689. }
  2690. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2691. /**
  2692. * Return an url to check online a professional id or empty string
  2693. *
  2694. * @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
  2695. * @param Societe $thirdparty Object thirdparty
  2696. * @return string Url or empty string if no URL known
  2697. * TODO better in a lib than into business class
  2698. */
  2699. function id_prof_url($idprof,$thirdparty)
  2700. {
  2701. // phpcs:enable
  2702. global $conf,$langs,$hookmanager;
  2703. $url='';
  2704. $action = '';
  2705. $hookmanager->initHooks(array('idprofurl'));
  2706. $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
  2707. $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  2708. if (empty($reshook)) {
  2709. if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
  2710. return '';
  2711. }
  2712. // TODO Move links to validate professional ID into a dictionary table "country" + "link"
  2713. $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
  2714. if ($idprof == 1 && $thirdparty->country_code == 'FR') {
  2715. $url='http://www.societe.com/cgi-bin/search?champs='.$strippedIdProf1; // See also http://avis-situation-sirene.insee.fr/
  2716. }
  2717. if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
  2718. $url='https://beta.companieshouse.gov.uk/company/'.$strippedIdProf1;
  2719. }
  2720. if ($idprof == 1 && $thirdparty->country_code == 'ES') {
  2721. $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$strippedIdProf1;
  2722. }
  2723. if ($idprof == 1 && $thirdparty->country_code == 'IN') {
  2724. $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$strippedIdProf1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
  2725. }
  2726. if ($idprof == 1 && $thirdparty->country_code == 'PT') {
  2727. $url='http://www.nif.pt/'.$strippedIdProf1;
  2728. }
  2729. if ($url) {
  2730. return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
  2731. }
  2732. }
  2733. else {
  2734. return $hookmanager->resPrint;
  2735. }
  2736. return '';
  2737. }
  2738. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2739. /**
  2740. * Indique si la societe a des projets
  2741. *
  2742. * @return bool true si la societe a des projets, false sinon
  2743. */
  2744. function has_projects()
  2745. {
  2746. // phpcs:enable
  2747. $sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
  2748. $resql = $this->db->query($sql);
  2749. if ($resql)
  2750. {
  2751. $obj = $this->db->fetch_object($resql);
  2752. $count = $obj->numproj;
  2753. }
  2754. else
  2755. {
  2756. $count = 0;
  2757. print $this->db->error();
  2758. }
  2759. $this->db->free($resql);
  2760. return ($count > 0);
  2761. }
  2762. /**
  2763. * Load information for tab info
  2764. *
  2765. * @param int $id Id of thirdparty to load
  2766. * @return void
  2767. */
  2768. function info($id)
  2769. {
  2770. $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
  2771. $sql.= " fk_user_creat, fk_user_modif";
  2772. $sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
  2773. $sql.= " WHERE s.rowid = ".$id;
  2774. $result=$this->db->query($sql);
  2775. if ($result)
  2776. {
  2777. if ($this->db->num_rows($result))
  2778. {
  2779. $obj = $this->db->fetch_object($result);
  2780. $this->id = $obj->rowid;
  2781. if ($obj->fk_user_creat) {
  2782. $cuser = new User($this->db);
  2783. $cuser->fetch($obj->fk_user_creat);
  2784. $this->user_creation = $cuser;
  2785. }
  2786. if ($obj->fk_user_modif) {
  2787. $muser = new User($this->db);
  2788. $muser->fetch($obj->fk_user_modif);
  2789. $this->user_modification = $muser;
  2790. }
  2791. $this->ref = $obj->name;
  2792. $this->date_creation = $this->db->jdate($obj->date_creation);
  2793. $this->date_modification = $this->db->jdate($obj->date_modification);
  2794. }
  2795. $this->db->free($result);
  2796. }
  2797. else
  2798. {
  2799. dol_print_error($this->db);
  2800. }
  2801. }
  2802. /**
  2803. * Return if third party is a company (Business) or an end user (Consumer)
  2804. *
  2805. * @return boolean true=is a company, false=a and user
  2806. */
  2807. function isACompany()
  2808. {
  2809. global $conf;
  2810. // Define if third party is treated as company (or not) when nature is unknown
  2811. $isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
  2812. if (! empty($this->tva_intra)) $isacompany=1;
  2813. else if (! empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN')
  2814. {
  2815. // TODO Add a field is_a_company into dictionary
  2816. if (preg_match('/^TE_PRIVATE/', $this->typent_code)) $isacompany=0;
  2817. else $isacompany=1;
  2818. }
  2819. return $isacompany;
  2820. }
  2821. /**
  2822. * Return if a company is inside the EEC (European Economic Community)
  2823. *
  2824. * @return boolean true = country inside EEC, false = country outside EEC
  2825. */
  2826. function isInEEC()
  2827. {
  2828. require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2829. return isInEEC($this);
  2830. }
  2831. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2832. /**
  2833. * Charge la liste des categories fournisseurs
  2834. *
  2835. * @return int 0 if success, <> 0 if error
  2836. */
  2837. function LoadSupplierCateg()
  2838. {
  2839. // phpcs:enable
  2840. $this->SupplierCategories = array();
  2841. $sql = "SELECT rowid, label";
  2842. $sql.= " FROM ".MAIN_DB_PREFIX."categorie";
  2843. $sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
  2844. $resql=$this->db->query($sql);
  2845. if ($resql)
  2846. {
  2847. while ($obj = $this->db->fetch_object($resql) )
  2848. {
  2849. $this->SupplierCategories[$obj->rowid] = $obj->label;
  2850. }
  2851. return 0;
  2852. }
  2853. else
  2854. {
  2855. return -1;
  2856. }
  2857. }
  2858. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2859. /**
  2860. * Insert link supplier - category
  2861. *
  2862. * @param int $categorie_id Id of category
  2863. * @return int 0 if success, <> 0 if error
  2864. */
  2865. function AddFournisseurInCategory($categorie_id)
  2866. {
  2867. // phpcs:enable
  2868. if ($categorie_id > 0 && $this->id > 0)
  2869. {
  2870. $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
  2871. $sql.= " VALUES (".$categorie_id.", ".$this->id.")";
  2872. if ($resql=$this->db->query($sql)) return 0;
  2873. }
  2874. else
  2875. {
  2876. return 0;
  2877. }
  2878. return -1;
  2879. }
  2880. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  2881. /**
  2882. * Create a third party into database from a member object
  2883. *
  2884. * @param Adherent $member Object member
  2885. * @param string $socname Name of third party to force
  2886. * @param string $socalias Alias name of third party to force
  2887. * @param string $customercode Customer code
  2888. * @return int <0 if KO, id of created account if OK
  2889. */
  2890. function create_from_member(Adherent $member, $socname='', $socalias='', $customercode='')
  2891. {
  2892. // phpcs:enable
  2893. global $user,$langs;
  2894. dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
  2895. $name = $socname?$socname:$member->societe;
  2896. if (empty($name)) $name=$member->getFullName($langs);
  2897. $alias = $socalias?$socalias:'';
  2898. // Positionne parametres
  2899. $this->nom=$name; // TODO deprecated
  2900. $this->name=$name;
  2901. $this->name_alias=$alias;
  2902. $this->address=$member->address;
  2903. $this->zip=$member->zip;
  2904. $this->town=$member->town;
  2905. $this->country_code=$member->country_code;
  2906. $this->country_id=$member->country_id;
  2907. $this->phone=$member->phone; // Prof phone
  2908. $this->email=$member->email;
  2909. $this->skype=$member->skype;
  2910. $this->twitter=$member->twitter;
  2911. $this->facebook=$member->facebook;
  2912. $this->client = 1; // A member is a customer by default
  2913. $this->code_client = ($customercode?$customercode:-1);
  2914. $this->code_fournisseur = -1;
  2915. $this->db->begin();
  2916. // Cree et positionne $this->id
  2917. $result=$this->create($user);
  2918. if ($result >= 0)
  2919. {
  2920. $sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
  2921. $sql.= " SET fk_soc=".$this->id;
  2922. $sql.= " WHERE rowid=".$member->id;
  2923. $resql=$this->db->query($sql);
  2924. if ($resql)
  2925. {
  2926. $this->db->commit();
  2927. return $this->id;
  2928. }
  2929. else
  2930. {
  2931. $this->error=$this->db->error();
  2932. $this->db->rollback();
  2933. return -1;
  2934. }
  2935. }
  2936. else
  2937. {
  2938. // $this->error deja positionne
  2939. dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
  2940. $this->db->rollback();
  2941. return $result;
  2942. }
  2943. }
  2944. /**
  2945. * Set properties with value into $conf
  2946. *
  2947. * @param Conf $conf Conf object (possibility to use another entity)
  2948. * @return void
  2949. */
  2950. function setMysoc(Conf $conf)
  2951. {
  2952. global $langs;
  2953. $this->id=0;
  2954. $this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
  2955. $this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
  2956. $this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
  2957. $this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
  2958. $this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE;
  2959. $this->region_code=empty($conf->global->MAIN_INFO_SOCIETE_REGION)?'':$conf->global->MAIN_INFO_SOCIETE_REGION;
  2960. $this->object=empty($conf->global->MAIN_INFO_SOCIETE_OBJECT)?'':$conf->global->MAIN_INFO_SOCIETE_OBJECT;
  2961. $this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
  2962. $this->nom=$this->name; // deprecated
  2963. // We define country_id, country_code and country
  2964. $country_id=$country_code=$country_label='';
  2965. if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
  2966. {
  2967. $tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
  2968. $country_id=$tmp[0];
  2969. if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
  2970. {
  2971. $country_code=$tmp[1];
  2972. $country_label=$tmp[2];
  2973. }
  2974. else // For backward compatibility
  2975. {
  2976. dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
  2977. include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2978. $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
  2979. $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
  2980. }
  2981. }
  2982. $this->country_id=$country_id;
  2983. $this->country_code=$country_code;
  2984. $this->country=$country_label;
  2985. if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
  2986. $this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
  2987. $this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
  2988. $this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
  2989. // Id prof generiques
  2990. $this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
  2991. $this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
  2992. $this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
  2993. $this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
  2994. $this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
  2995. $this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
  2996. $this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
  2997. $this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
  2998. $this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
  2999. $this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
  3000. $this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
  3001. $this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
  3002. $this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
  3003. $this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
  3004. // Define if company use vat or not
  3005. $this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
  3006. // Define if company use local taxes
  3007. $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);
  3008. $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);
  3009. }
  3010. /**
  3011. * Initialise an instance with random values.
  3012. * Used to build previews or test instances.
  3013. * id must be 0 if object instance is a specimen.
  3014. *
  3015. * @return void
  3016. */
  3017. function initAsSpecimen()
  3018. {
  3019. $now=dol_now();
  3020. // Initialize parameters
  3021. $this->id=0;
  3022. $this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
  3023. $this->nom = $this->name; // For backward compatibility
  3024. $this->ref_ext = 'Ref ext';
  3025. $this->specimen=1;
  3026. $this->address='21 jump street';
  3027. $this->zip='99999';
  3028. $this->town='MyTown';
  3029. $this->state_id=1;
  3030. $this->state_code='AA';
  3031. $this->state='MyState';
  3032. $this->country_id=1;
  3033. $this->country_code='FR';
  3034. $this->email='specimen@specimen.com';
  3035. $this->skype='tom.hanson';
  3036. $this->twitter='tomhanson';
  3037. $this->facebook='tomhanson';
  3038. $this->url='http://www.specimen.com';
  3039. $this->phone='0909090901';
  3040. $this->fax='0909090909';
  3041. $this->code_client='CC-'.dol_print_date($now,'dayhourlog');
  3042. $this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
  3043. $this->capital=10000;
  3044. $this->client=1;
  3045. $this->prospect=1;
  3046. $this->fournisseur=1;
  3047. $this->tva_assuj=1;
  3048. $this->tva_intra='EU1234567';
  3049. $this->note_public='This is a comment (public)';
  3050. $this->note_private='This is a comment (private)';
  3051. $this->idprof1='idprof1';
  3052. $this->idprof2='idprof2';
  3053. $this->idprof3='idprof3';
  3054. $this->idprof4='idprof4';
  3055. $this->idprof5='idprof5';
  3056. $this->idprof6='idprof6';
  3057. }
  3058. /**
  3059. * Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
  3060. *
  3061. * @param int $localTaxNum To get info for only localtax1 or localtax2
  3062. * @return boolean true or false
  3063. */
  3064. function useLocalTax($localTaxNum=0)
  3065. {
  3066. $sql = "SELECT t.localtax1, t.localtax2";
  3067. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  3068. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
  3069. $sql .= " AND t.active = 1";
  3070. if (empty($localTaxNum)) $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
  3071. elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
  3072. elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
  3073. dol_syslog("useLocalTax", LOG_DEBUG);
  3074. $resql=$this->db->query($sql);
  3075. if ($resql)
  3076. {
  3077. return ($this->db->num_rows($resql) > 0);
  3078. }
  3079. else return false;
  3080. }
  3081. /**
  3082. * Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
  3083. *
  3084. * @return boolean true or false
  3085. */
  3086. function useNPR()
  3087. {
  3088. $sql = "SELECT t.rowid";
  3089. $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
  3090. $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
  3091. $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
  3092. dol_syslog("useNPR", LOG_DEBUG);
  3093. $resql=$this->db->query($sql);
  3094. if ($resql)
  3095. {
  3096. return ($this->db->num_rows($resql) > 0);
  3097. }
  3098. else return false;
  3099. }
  3100. /**
  3101. * Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
  3102. *
  3103. * @return boolean true or false
  3104. */
  3105. function useRevenueStamp()
  3106. {
  3107. $sql = "SELECT COUNT(*) as nb";
  3108. $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
  3109. $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->db->escape($this->country_code)."'";
  3110. $sql .= " AND r.active = 1";
  3111. dol_syslog("useRevenueStamp", LOG_DEBUG);
  3112. $resql=$this->db->query($sql);
  3113. if ($resql)
  3114. {
  3115. $obj=$this->db->fetch_object($resql);
  3116. return (($obj->nb > 0)?true:false);
  3117. }
  3118. else
  3119. {
  3120. $this->error=$this->db->lasterror();
  3121. return false;
  3122. }
  3123. }
  3124. /**
  3125. * Return prostect level
  3126. *
  3127. * @return string Libelle
  3128. */
  3129. function getLibProspLevel()
  3130. {
  3131. return $this->LibProspLevel($this->fk_prospectlevel);
  3132. }
  3133. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3134. /**
  3135. * Return label of prospect level
  3136. *
  3137. * @param int $fk_prospectlevel Prospect level
  3138. * @return string label of level
  3139. */
  3140. function LibProspLevel($fk_prospectlevel)
  3141. {
  3142. // phpcs:enable
  3143. global $langs;
  3144. $lib=$langs->trans("ProspectLevel".$fk_prospectlevel);
  3145. // If lib not found in language file, we get label from cache/databse
  3146. if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
  3147. {
  3148. $lib=$langs->getLabelFromKey($this->db,$fk_prospectlevel,'c_prospectlevel','code','label');
  3149. }
  3150. return $lib;
  3151. }
  3152. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3153. /**
  3154. * Set prospect level
  3155. *
  3156. * @param User $user Utilisateur qui definie la remise
  3157. * @return int <0 if KO, >0 if OK
  3158. * @deprecated Use update function instead
  3159. */
  3160. function set_prospect_level(User $user)
  3161. {
  3162. // phpcs:enable
  3163. return $this->update($this->id, $user);
  3164. }
  3165. /**
  3166. * Return status of prospect
  3167. *
  3168. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
  3169. * @param string $label Label to use for status for added status
  3170. * @return string Libelle
  3171. */
  3172. function getLibProspCommStatut($mode=0, $label='')
  3173. {
  3174. return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
  3175. }
  3176. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3177. /**
  3178. * Return label of a given status
  3179. *
  3180. * @param int|string $statut Id or code for prospection status
  3181. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  3182. * @param string $label Label to use for status for added status
  3183. * @return string Libelle du statut
  3184. */
  3185. function LibProspCommStatut($statut, $mode=0, $label='')
  3186. {
  3187. // phpcs:enable
  3188. global $langs;
  3189. $langs->load('customers');
  3190. if ($mode == 2)
  3191. {
  3192. if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
  3193. elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
  3194. elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
  3195. elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
  3196. elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
  3197. else
  3198. {
  3199. return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
  3200. }
  3201. }
  3202. if ($mode == 3)
  3203. {
  3204. if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1);
  3205. elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
  3206. elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1);
  3207. elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2);
  3208. elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3);
  3209. else
  3210. {
  3211. return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
  3212. }
  3213. }
  3214. if ($mode == 4)
  3215. {
  3216. if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
  3217. elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
  3218. elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
  3219. elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
  3220. elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
  3221. else
  3222. {
  3223. return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
  3224. }
  3225. }
  3226. return "Error, mode/status not found";
  3227. }
  3228. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3229. /**
  3230. * Set outstanding value
  3231. *
  3232. * @param User $user User making change
  3233. * @return int <0 if KO, >0 if OK
  3234. * @deprecated Use update function instead
  3235. */
  3236. function set_OutstandingBill(User $user)
  3237. {
  3238. // phpcs:enable
  3239. return $this->update($this->id, $user);
  3240. }
  3241. /**
  3242. * Return amount of order not paid and total
  3243. *
  3244. * @param string $mode 'customer' or 'supplier'
  3245. * @return array array('opened'=>Amount, 'total'=>Total amount)
  3246. */
  3247. function getOutstandingProposals($mode='customer')
  3248. {
  3249. $table='propal';
  3250. if ($mode == 'supplier') $table = 'supplier_proposal';
  3251. $sql = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
  3252. $sql .= " WHERE fk_soc = ". $this->id;
  3253. if ($mode == 'supplier') {
  3254. $sql .= " AND entity IN (".getEntity('supplier_proposal').")";
  3255. } else {
  3256. $sql .= " AND entity IN (".getEntity('propal').")";
  3257. }
  3258. dol_syslog("getOutstandingProposals", LOG_DEBUG);
  3259. $resql=$this->db->query($sql);
  3260. if ($resql)
  3261. {
  3262. $outstandingOpened = 0;
  3263. $outstandingTotal = 0;
  3264. $outstandingTotalIncTax = 0;
  3265. while($obj=$this->db->fetch_object($resql)) {
  3266. $outstandingTotal+= $obj->total_ht;
  3267. $outstandingTotalIncTax+= $obj->total_ttc;
  3268. if ($obj->fk_statut != 0) // Not a draft
  3269. {
  3270. $outstandingOpened+=$obj->total_ttc;
  3271. }
  3272. }
  3273. return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes'
  3274. }
  3275. else
  3276. return array();
  3277. }
  3278. /**
  3279. * Return amount of order not paid and total
  3280. *
  3281. * @param string $mode 'customer' or 'supplier'
  3282. * @return array array('opened'=>Amount, 'total'=>Total amount)
  3283. */
  3284. function getOutstandingOrders($mode='customer')
  3285. {
  3286. $table='commande';
  3287. if ($mode == 'supplier') $table = 'commande_fournisseur';
  3288. $sql = "SELECT rowid, total_ht, total_ttc, fk_statut FROM ".MAIN_DB_PREFIX.$table." as f";
  3289. $sql .= " WHERE fk_soc = ". $this->id;
  3290. if ($mode == 'supplier') {
  3291. $sql .= " AND entity IN (".getEntity('supplier_order').")";
  3292. } else {
  3293. $sql .= " AND entity IN (".getEntity('commande').")";
  3294. }
  3295. dol_syslog("getOutstandingOrders", LOG_DEBUG);
  3296. $resql=$this->db->query($sql);
  3297. if ($resql)
  3298. {
  3299. $outstandingOpened = 0;
  3300. $outstandingTotal = 0;
  3301. $outstandingTotalIncTax = 0;
  3302. while($obj=$this->db->fetch_object($resql)) {
  3303. $outstandingTotal+= $obj->total_ht;
  3304. $outstandingTotalIncTax+= $obj->total_ttc;
  3305. if ($obj->fk_statut != 0) // Not a draft
  3306. {
  3307. $outstandingOpened+=$obj->total_ttc;
  3308. }
  3309. }
  3310. return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes'
  3311. }
  3312. else
  3313. return array();
  3314. }
  3315. /**
  3316. * Return amount of bill not paid and total
  3317. *
  3318. * @param string $mode 'customer' or 'supplier'
  3319. * @return array array('opened'=>Amount, 'total'=>Total amount)
  3320. */
  3321. function getOutstandingBills($mode='customer')
  3322. {
  3323. $table='facture';
  3324. if ($mode == 'supplier') $table = 'facture_fourn';
  3325. /* Accurate value of remain to pay is to sum remaintopay for each invoice
  3326. $paiement = $invoice->getSommePaiement();
  3327. $creditnotes=$invoice->getSumCreditNotesUsed();
  3328. $deposits=$invoice->getSumDepositsUsed();
  3329. $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
  3330. $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
  3331. */
  3332. if ($mode == 'supplier') $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
  3333. else $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM ".MAIN_DB_PREFIX.$table." as f";
  3334. $sql .= " WHERE fk_soc = ". $this->id;
  3335. if ($mode == 'supplier') {
  3336. $sql .= " AND entity IN (".getEntity('facture_fourn').")";
  3337. } else {
  3338. $sql .= " AND entity IN (".getEntity('facture').")";
  3339. }
  3340. dol_syslog("getOutstandingBills", LOG_DEBUG);
  3341. $resql=$this->db->query($sql);
  3342. if ($resql)
  3343. {
  3344. $outstandingOpened = 0;
  3345. $outstandingTotal = 0;
  3346. $outstandingTotalIncTax = 0;
  3347. if ($mode == 'supplier')
  3348. {
  3349. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  3350. $tmpobject=new FactureFournisseur($this->db);
  3351. }
  3352. else
  3353. {
  3354. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  3355. $tmpobject=new Facture($this->db);
  3356. }
  3357. while($obj=$this->db->fetch_object($resql)) {
  3358. $tmpobject->id=$obj->rowid;
  3359. if ($obj->fk_statut != 0 // Not a draft
  3360. && ! ($obj->fk_statut == 3 && $obj->close_code == 'replaced') // Not a replaced invoice
  3361. )
  3362. {
  3363. $outstandingTotal+= $obj->total_ht;
  3364. $outstandingTotalIncTax+= $obj->total_ttc;
  3365. }
  3366. if ($obj->paye == 0
  3367. && $obj->fk_statut != 0 // Not a draft
  3368. && $obj->fk_statut != 3 // Not abandonned
  3369. && $obj->fk_statut != 2) // Not classified as paid
  3370. //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
  3371. {
  3372. $paiement = $tmpobject->getSommePaiement();
  3373. $creditnotes = $tmpobject->getSumCreditNotesUsed();
  3374. $deposits = $tmpobject->getSumDepositsUsed();
  3375. $outstandingOpened+=$obj->total_ttc - $paiement - $creditnotes - $deposits;
  3376. }
  3377. }
  3378. return array('opened'=>$outstandingOpened, 'total_ht'=>$outstandingTotal, 'total_ttc'=>$outstandingTotalIncTax); // 'opened' is 'incl taxes'
  3379. }
  3380. else
  3381. {
  3382. return array();
  3383. }
  3384. }
  3385. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3386. /**
  3387. * Return amount of bill not paid
  3388. *
  3389. * @return int Amount in debt for thirdparty
  3390. * @deprecated
  3391. * @see getOutstandingBills()
  3392. */
  3393. function get_OutstandingBill()
  3394. {
  3395. // phpcs:enable
  3396. /* Accurate value of remain to pay is to sum remaintopay for each invoice
  3397. $paiement = $invoice->getSommePaiement();
  3398. $creditnotes=$invoice->getSumCreditNotesUsed();
  3399. $deposits=$invoice->getSumDepositsUsed();
  3400. $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
  3401. $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
  3402. */
  3403. $sql = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
  3404. $sql .= " WHERE fk_soc = ". $this->id;
  3405. $sql .= " AND paye = 0";
  3406. $sql .= " AND fk_statut <> 0"; // Not a draft
  3407. //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
  3408. $sql .= " AND fk_statut <> 3"; // Not abandonned
  3409. $sql .= " AND fk_statut <> 2"; // Not clasified as paid
  3410. dol_syslog("get_OutstandingBill", LOG_DEBUG);
  3411. $resql=$this->db->query($sql);
  3412. if ($resql)
  3413. {
  3414. $outstandingAmount = 0;
  3415. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  3416. $tmpobject=new Facture($this->db);
  3417. while($obj=$this->db->fetch_object($resql)) {
  3418. $tmpobject->id=$obj->rowid;
  3419. $paiement = $tmpobject->getSommePaiement();
  3420. $creditnotes = $tmpobject->getSumCreditNotesUsed();
  3421. $deposits = $tmpobject->getSumDepositsUsed();
  3422. $outstandingAmount+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
  3423. }
  3424. return $outstandingAmount;
  3425. }
  3426. else
  3427. return 0;
  3428. }
  3429. /**
  3430. * Return label of status customer is prospect/customer
  3431. *
  3432. * @return string Label
  3433. */
  3434. function getLibCustProspStatut()
  3435. {
  3436. return $this->LibCustProspStatut($this->client);
  3437. }
  3438. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
  3439. /**
  3440. * Renvoi le libelle d'un statut donne
  3441. *
  3442. * @param int $statut Id statut
  3443. * @return string Libelle du statut
  3444. */
  3445. function LibCustProspStatut($statut)
  3446. {
  3447. // phpcs:enable
  3448. global $langs;
  3449. $langs->load('companies');
  3450. if ($statut==0) return $langs->trans("NorProspectNorCustomer");
  3451. if ($statut==1) return $langs->trans("Customer");
  3452. if ($statut==2) return $langs->trans("Prospect");
  3453. if ($statut==3) return $langs->trans("ProspectCustomer");
  3454. }
  3455. /**
  3456. * Create a document onto disk according to template module.
  3457. *
  3458. * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
  3459. * @param Translate $outputlangs objet lang a utiliser pour traduction
  3460. * @param int $hidedetails Hide details of lines
  3461. * @param int $hidedesc Hide description
  3462. * @param int $hideref Hide ref
  3463. * @param null|array $moreparams Array to provide more information
  3464. * @return int <0 if KO, >0 if OK
  3465. */
  3466. public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
  3467. {
  3468. global $conf,$user,$langs;
  3469. if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
  3470. {
  3471. $modelpath = "core/modules/bank/doc/";
  3472. include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
  3473. $companybankaccount = new CompanyBankAccount($this->db);
  3474. $result = $companybankaccount->fetch($moreparams['use_companybankid']);
  3475. if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
  3476. $result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  3477. }
  3478. else
  3479. {
  3480. // Positionne le modele sur le nom du modele a utiliser
  3481. if (! dol_strlen($modele))
  3482. {
  3483. if (! empty($conf->global->COMPANY_ADDON_PDF))
  3484. {
  3485. $modele = $conf->global->COMPANY_ADDON_PDF;
  3486. }
  3487. else
  3488. {
  3489. print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
  3490. return 0;
  3491. }
  3492. }
  3493. $modelpath = "core/modules/societe/doc/";
  3494. $result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  3495. }
  3496. return $result;
  3497. }
  3498. /**
  3499. * Sets object to supplied categories.
  3500. *
  3501. * Deletes object from existing categories not supplied.
  3502. * Adds it to non existing supplied categories.
  3503. * Existing categories are left untouch.
  3504. *
  3505. * @param int[]|int $categories Category ID or array of Categories IDs
  3506. * @param string $type Category type ('customer' or 'supplier')
  3507. * @return int <0 if KO, >0 if OK
  3508. */
  3509. public function setCategories($categories, $type)
  3510. {
  3511. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  3512. // Decode type
  3513. if ($type == 'customer') {
  3514. $type_id = Categorie::TYPE_CUSTOMER;
  3515. $type_text = 'customer';
  3516. } elseif ($type == 'supplier') {
  3517. $type_id = Categorie::TYPE_SUPPLIER;
  3518. $type_text = 'supplier';
  3519. } else {
  3520. dol_syslog(__METHOD__ . ': Type ' . $type . 'is an unknown company category type. Done nothing.', LOG_ERR);
  3521. return -1;
  3522. }
  3523. // Handle single category
  3524. if (!is_array($categories)) {
  3525. $categories = array($categories);
  3526. }
  3527. // Get current categories
  3528. $c = new Categorie($this->db);
  3529. $existing = $c->containing($this->id, $type_id, 'id');
  3530. // Diff
  3531. if (is_array($existing)) {
  3532. $to_del = array_diff($existing, $categories);
  3533. $to_add = array_diff($categories, $existing);
  3534. } else {
  3535. $to_del = array(); // Nothing to delete
  3536. $to_add = $categories;
  3537. }
  3538. $error = 0;
  3539. // Process
  3540. foreach ($to_del as $del) {
  3541. if ($c->fetch($del) > 0) {
  3542. $c->del_type($this, $type_text);
  3543. }
  3544. }
  3545. foreach ($to_add as $add) {
  3546. if ($c->fetch($add) > 0)
  3547. {
  3548. $result = $c->add_type($this, $type_text);
  3549. if ($result < 0)
  3550. {
  3551. $error++;
  3552. $this->error = $c->error;
  3553. $this->errors = $c->errors;
  3554. break;
  3555. }
  3556. }
  3557. }
  3558. return $error ? -1 : 1;
  3559. }
  3560. /**
  3561. * Sets sales representatives of the thirdparty
  3562. *
  3563. * @param int[]|int $salesrep User ID or array of user IDs
  3564. * @return int <0 if KO, >0 if OK
  3565. */
  3566. public function setSalesRep($salesrep)
  3567. {
  3568. global $user;
  3569. // Handle single user
  3570. if (!is_array($salesrep)) {
  3571. $salesrep = array($salesrep);
  3572. }
  3573. // Get current users
  3574. $existing = $this->getSalesRepresentatives($user, 1);
  3575. // Diff
  3576. if (is_array($existing)) {
  3577. $to_del = array_diff($existing, $salesrep);
  3578. $to_add = array_diff($salesrep, $existing);
  3579. } else {
  3580. $to_del = array(); // Nothing to delete
  3581. $to_add = $salesrep;
  3582. }
  3583. $error = 0;
  3584. // Process
  3585. foreach ($to_del as $del) {
  3586. $this->del_commercial($user, $del);
  3587. }
  3588. foreach ($to_add as $add) {
  3589. $result = $this->add_commercial($user, $add);
  3590. if ($result < 0)
  3591. {
  3592. $error++;
  3593. $this->error = $c->error;
  3594. $this->errors = $c->errors;
  3595. break;
  3596. }
  3597. }
  3598. return $error ? -1 : 1;
  3599. }
  3600. /**
  3601. * Function used to replace a thirdparty id with another one.
  3602. * It must be used within a transaction to avoid trouble
  3603. *
  3604. * @param DoliDB $db Database handler
  3605. * @param int $origin_id Old thirdparty id (will be removed)
  3606. * @param int $dest_id New thirdparty id
  3607. * @return bool True if success, False if error
  3608. */
  3609. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  3610. {
  3611. if ($origin_id == $dest_id)
  3612. {
  3613. dol_syslog('Error: Try to merge a thirdparty into itself');
  3614. return false;
  3615. }
  3616. /**
  3617. * Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some to avoid duplicate.
  3618. * Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
  3619. */
  3620. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
  3621. $sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
  3622. $sql .= ' SELECT fk_user ';
  3623. $sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
  3624. $sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
  3625. $query = $db->query($sql);
  3626. while ($result = $db->fetch_object($query)) {
  3627. $db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$result->rowid);
  3628. }
  3629. /**
  3630. * llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
  3631. * Do not include llx_societe because it will be replaced later
  3632. */
  3633. $tables = array(
  3634. 'societe_address',
  3635. 'societe_commerciaux',
  3636. 'societe_log',
  3637. 'societe_prices',
  3638. 'societe_remise',
  3639. 'societe_remise_except',
  3640. 'societe_rib'
  3641. );
  3642. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  3643. }
  3644. }