societe.class.php 126 KB

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