societe.class.php 113 KB

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