societe.class.php 170 KB

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