account.class.php 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705
  1. <?php
  2. /* Copyright (C) 2001-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  4. * Copyright (C) 2004-2012 Laurent Destailleur <eldy@users.sourceforge.net>
  5. * Copyright (C) 2004 Christophe Combelles <ccomb@free.fr>
  6. * Copyright (C) 2005-2010 Regis Houssin <regis.houssin@inodbox.com>
  7. * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
  8. * Copyright (C) 2015-2016 Marcos García <marcosgdf@gmail.com>
  9. * Copyright (C) 2015-2017 Alexandre Spangaro <aspangaro@open-dsi.fr>
  10. * Copyright (C) 2016 Ferran Marcet <fmarcet@2byte.es>
  11. * Copyright (C) 2019 JC Prieto <jcprieto@virtual20.com><prietojc@gmail.com>
  12. * Copyright (C) 2022-2023 Frédéric France <frederic.france@netlogic.fr>
  13. *
  14. * This program is free software; you can redistribute it and/or modify
  15. * it under the terms of the GNU General Public License as published by
  16. * the Free Software Foundation; either version 3 of the License, or
  17. * (at your option) any later version.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU General Public License
  25. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  26. */
  27. /**
  28. * \file htdocs/compta/bank/class/account.class.php
  29. * \ingroup bank
  30. * \brief File of class to manage bank accounts
  31. */
  32. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  33. /**
  34. * Class to manage bank accounts
  35. */
  36. class Account extends CommonObject
  37. {
  38. /**
  39. * @var string ID to identify managed object
  40. */
  41. public $element = 'bank_account';
  42. /**
  43. * @var string Name of table without prefix where object is stored
  44. */
  45. public $table_element = 'bank_account';
  46. /**
  47. * @var int Does this object support multicompany module ?
  48. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  49. */
  50. public $ismultientitymanaged = 1;
  51. /**
  52. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  53. */
  54. public $picto = 'account';
  55. /**
  56. * @var int Use id instead of rowid
  57. * @deprecated
  58. * @see $id
  59. */
  60. public $rowid;
  61. /**
  62. * Account Label
  63. * @var string
  64. */
  65. public $label;
  66. /**
  67. * Bank account type. Check TYPE_ constants
  68. * @var int
  69. */
  70. public $courant;
  71. /**
  72. * Bank account type. Check TYPE_ constants
  73. * @var int
  74. */
  75. public $type;
  76. /**
  77. * Bank name
  78. * @var string
  79. */
  80. public $bank;
  81. /**
  82. * Status
  83. * @var int
  84. */
  85. public $clos = self::STATUS_OPEN;
  86. /**
  87. * Does it need to be conciliated?
  88. * @var int
  89. */
  90. public $rappro = 1;
  91. /**
  92. * Webpage
  93. * @var string
  94. */
  95. public $url;
  96. /**
  97. * Bank number. If in SEPA area, you should move to IBAN field
  98. * @var string
  99. */
  100. public $code_banque;
  101. /**
  102. * Branch number. If in SEPA area, you should move to IBAN field
  103. * @var string
  104. */
  105. public $code_guichet;
  106. /**
  107. * Account number. If in SEPA area, you should move to IBAN field
  108. * @var string
  109. */
  110. public $number;
  111. /**
  112. * Bank account number control digit. If in SEPA area, you should move to IBAN field
  113. * @var string
  114. */
  115. public $cle_rib;
  116. /**
  117. * BIC/Swift code
  118. * @var string
  119. */
  120. public $bic;
  121. /**
  122. * IBAN number (International Bank Account Number). Stored into iban_prefix field into database (TODO Rename field in database)
  123. * @var string
  124. */
  125. public $iban;
  126. /**
  127. * IBAN number
  128. *
  129. * @var string
  130. * @deprecated see $iban
  131. */
  132. public $iban_prefix;
  133. /**
  134. * XML SEPA format: place Payment Type Information (PmtTpInf) in Credit Transfer Transaction Information (CdtTrfTxInf)
  135. * @var int
  136. */
  137. public $pti_in_ctti = 0;
  138. /**
  139. * Name of account holder
  140. * @var string
  141. */
  142. public $proprio;
  143. /**
  144. * Address of account holder
  145. * @var string
  146. */
  147. public $owner_address;
  148. public $owner_zip;
  149. public $owner_town;
  150. public $owner_country_id;
  151. public $owner_country_code;
  152. /**
  153. * Address of the bank account
  154. * @var string
  155. */
  156. public $domiciliation; // deprecated, use now address
  157. public $address;
  158. public $state_id;
  159. public $state_code;
  160. public $state;
  161. /**
  162. * Variable containing all account types with their respective translated label.
  163. * Defined in __construct
  164. * @var array
  165. */
  166. public $type_lib = array();
  167. /**
  168. * Variable containing all account statuses with their respective translated label.
  169. * Defined in __construct
  170. * @var array
  171. */
  172. public $status = array();
  173. /**
  174. * Accountancy code
  175. * @var string
  176. */
  177. public $account_number;
  178. /**
  179. * @var int ID
  180. */
  181. public $fk_accountancy_journal;
  182. /**
  183. * @var string Label of journal
  184. */
  185. public $accountancy_journal;
  186. /**
  187. * Currency code
  188. * @var string
  189. */
  190. public $currency_code;
  191. /**
  192. * Currency code
  193. * @var string
  194. * @deprecated Use currency_code instead
  195. */
  196. public $account_currency_code;
  197. /**
  198. * Authorized minimum balance
  199. * @var float
  200. */
  201. public $min_allowed;
  202. /**
  203. * Desired minimum balance
  204. * @var float
  205. */
  206. public $min_desired;
  207. /**
  208. * Notes
  209. * @var string
  210. */
  211. public $comment;
  212. /**
  213. * Date of the initial balance. Used in Account::create
  214. * @var int
  215. */
  216. public $date_solde;
  217. /**
  218. * Balance. Used in Account::create
  219. * @var float
  220. * @deprecated
  221. * @see $balance
  222. */
  223. public $solde;
  224. /**
  225. * Balance. Used in Account::create
  226. * @var float
  227. */
  228. public $balance;
  229. /**
  230. * Creditor Identifier CI. Some banks use different ICS for direct debit and bank tranfer
  231. * @var string
  232. */
  233. public $ics;
  234. /**
  235. * Creditor Identifier for Bank Transfer.
  236. * @var string
  237. */
  238. public $ics_transfer;
  239. /**
  240. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  241. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  242. * 'label' the translation key.
  243. * 'enabled' is a condition when the field must be managed.
  244. * 'position' is the sort order of field.
  245. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  246. * '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)
  247. * 'noteditable' says if field is not editable (1 or 0)
  248. * '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.
  249. * 'index' if we want an index in database.
  250. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  251. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  252. * '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).
  253. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  254. * 'help' is a string visible as a tooltip on field
  255. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  256. * '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.
  257. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  258. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  259. *
  260. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  261. */
  262. // BEGIN MODULEBUILDER PROPERTIES
  263. /**
  264. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  265. */
  266. public $fields = array(
  267. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  268. 'ref' =>array('type'=>'varchar(12)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>25),
  269. 'label' =>array('type'=>'varchar(30)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>30),
  270. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>35, 'index'=>1),
  271. 'bank' =>array('type'=>'varchar(60)', 'label'=>'Bank', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
  272. 'code_banque' =>array('type'=>'varchar(128)', 'label'=>'Code banque', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  273. 'code_guichet' =>array('type'=>'varchar(6)', 'label'=>'Code guichet', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
  274. 'number' =>array('type'=>'varchar(255)', 'label'=>'Number', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
  275. 'cle_rib' =>array('type'=>'varchar(5)', 'label'=>'Cle rib', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
  276. 'bic' =>array('type'=>'varchar(11)', 'label'=>'Bic', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
  277. 'iban_prefix' =>array('type'=>'varchar(34)', 'label'=>'Iban prefix', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
  278. 'country_iban' =>array('type'=>'varchar(2)', 'label'=>'Country iban', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
  279. 'cle_iban' =>array('type'=>'varchar(2)', 'label'=>'Cle iban', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  280. 'domiciliation' =>array('type'=>'varchar(255)', 'label'=>'Domiciliation', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
  281. 'state_id' =>array('type'=>'integer', 'label'=>'StateId', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  282. 'fk_pays' =>array('type'=>'integer', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>95),
  283. 'proprio' =>array('type'=>'varchar(60)', 'label'=>'Proprio', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
  284. 'owner_address' =>array('type'=>'varchar(255)', 'label'=>'Owner address', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
  285. 'owner_zip' =>array('type'=>'varchar(25)', 'label'=>'Owner zip', 'enabled'=>1, 'visible'=>-1, 'position'=>106),
  286. 'owner_town' =>array('type'=>'varchar(50)', 'label'=>'Owner town', 'enabled'=>1, 'visible'=>-1, 'position'=>107),
  287. 'owner_country_id' =>array('type'=>'integer', 'label'=>'Owner country', 'enabled'=>1, 'visible'=>-1, 'position'=>108),
  288. 'courant' =>array('type'=>'smallint(6)', 'label'=>'Courant', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>110),
  289. 'clos' =>array('type'=>'smallint(6)', 'label'=>'Clos', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>115),
  290. 'rappro' =>array('type'=>'smallint(6)', 'label'=>'Rappro', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
  291. 'url' =>array('type'=>'varchar(128)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
  292. 'account_number' =>array('type'=>'varchar(32)', 'label'=>'Account number', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
  293. 'fk_accountancy_journal' =>array('type'=>'integer', 'label'=>'Accountancy journal ID', 'enabled'=>1, 'visible'=>-1, 'position'=>132),
  294. 'accountancy_journal' =>array('type'=>'varchar(20)', 'label'=>'Accountancy journal', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
  295. 'currency_code' =>array('type'=>'varchar(3)', 'label'=>'Currency code', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>140),
  296. 'min_allowed' =>array('type'=>'integer', 'label'=>'Min allowed', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
  297. 'min_desired' =>array('type'=>'integer', 'label'=>'Min desired', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
  298. 'comment' =>array('type'=>'text', 'label'=>'Comment', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
  299. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>156),
  300. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>157),
  301. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
  302. 'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>165),
  303. 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>170),
  304. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>175),
  305. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>180),
  306. 'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
  307. );
  308. // END MODULEBUILDER PROPERTIES
  309. /**
  310. * Current account
  311. */
  312. const TYPE_CURRENT = 1;
  313. /**
  314. * Cash account
  315. */
  316. const TYPE_CASH = 2;
  317. /**
  318. * Savings account
  319. */
  320. const TYPE_SAVINGS = 0;
  321. const STATUS_OPEN = 0;
  322. const STATUS_CLOSED = 1;
  323. /**
  324. * Constructor
  325. *
  326. * @param DoliDB $db Database handler
  327. */
  328. public function __construct(DoliDB $db)
  329. {
  330. global $langs;
  331. $this->db = $db;
  332. $this->solde = 0;
  333. $this->type_lib = array(
  334. self::TYPE_SAVINGS => $langs->trans("BankType0"),
  335. self::TYPE_CURRENT => $langs->trans("BankType1"),
  336. self::TYPE_CASH => $langs->trans("BankType2"),
  337. );
  338. $this->status = array(
  339. self::STATUS_OPEN => $langs->trans("StatusAccountOpened"),
  340. self::STATUS_CLOSED => $langs->trans("StatusAccountClosed")
  341. );
  342. }
  343. /**
  344. * Shows the account number in the appropriate format
  345. *
  346. * @return string
  347. */
  348. public function __toString()
  349. {
  350. $string = '';
  351. foreach ($this->getFieldsToShow() as $val) {
  352. if ($val == 'BankCode') {
  353. $string .= $this->code_banque.' ';
  354. } elseif ($val == 'BankAccountNumber') {
  355. $string .= $this->number.' ';
  356. } elseif ($val == 'DeskCode') {
  357. $string .= $this->code_guichet.' ';
  358. } elseif ($val == 'BankAccountNumberKey') {
  359. $string .= $this->cle_rib.' ';
  360. } elseif ($val == 'BIC') {
  361. $string .= $this->bic.' ';
  362. } elseif ($val == 'IBAN') {
  363. $string .= $this->iban.' ';
  364. }
  365. }
  366. return trim($string);
  367. }
  368. /**
  369. * Return if a bank account need to be conciliated
  370. *
  371. * @return int 1 if need to be concialiated, < 0 otherwise.
  372. */
  373. public function canBeConciliated()
  374. {
  375. global $conf;
  376. if (empty($this->rappro)) {
  377. return -1;
  378. }
  379. if ($this->courant == Account::TYPE_CASH && !getDolGlobalString('BANK_CAN_RECONCILIATE_CASHACCOUNT')) {
  380. return -2;
  381. }
  382. if ($this->clos) {
  383. return -3;
  384. }
  385. return 1;
  386. }
  387. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  388. /**
  389. * Add a link between bank line record and its source
  390. *
  391. * @param int $line_id Id of bank entry
  392. * @param int $url_id Id of object related to link
  393. * @param string $url Url (deprecated, we use now 'url_id' and 'type' instead)
  394. * @param string $label Link label
  395. * @param string $type Type of link ('payment', 'company', 'member', ...)
  396. * @return int <0 if KO, id line if OK
  397. */
  398. public function add_url_line($line_id, $url_id, $url, $label, $type)
  399. {
  400. // phpcs:enable
  401. $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url (";
  402. $sql .= "fk_bank";
  403. $sql .= ", url_id";
  404. $sql .= ", url"; // deprecated
  405. $sql .= ", label";
  406. $sql .= ", type";
  407. $sql .= ") VALUES (";
  408. $sql .= " ".((int) $line_id);
  409. $sql .= ", ".((int) $url_id);
  410. $sql .= ", '".$this->db->escape($url)."'"; // dperecated
  411. $sql .= ", '".$this->db->escape($label)."'";
  412. $sql .= ", '".$this->db->escape($type)."'";
  413. $sql .= ")";
  414. dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG);
  415. if ($this->db->query($sql)) {
  416. $rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url");
  417. return $rowid;
  418. } else {
  419. $this->error = $this->db->lasterror();
  420. return -1;
  421. }
  422. }
  423. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  424. /**
  425. * TODO Move this into AccountLine
  426. * Return array with links from llx_bank_url
  427. *
  428. * @param int $fk_bank To search using bank transaction id
  429. * @param int $url_id To search using link to
  430. * @param string $type To search using type
  431. * @return array|int Array of links array('url'=>, 'url_id'=>, 'label'=>, 'type'=> 'fk_bank'=> ) or -1 on error
  432. */
  433. public function get_url($fk_bank = '', $url_id = '', $type = '')
  434. {
  435. // phpcs:enable
  436. $lines = array();
  437. // Check parameters
  438. if (!empty($fk_bank) && (!empty($url_id) || !empty($type))) {
  439. $this->error = "ErrorBadParameter";
  440. return -1;
  441. }
  442. $sql = "SELECT fk_bank, url_id, url, label, type";
  443. $sql .= " FROM ".MAIN_DB_PREFIX."bank_url";
  444. if ($fk_bank > 0) {
  445. $sql .= " WHERE fk_bank = ".((int) $fk_bank);
  446. } else {
  447. $sql .= " WHERE url_id = ".((int) $url_id)." AND type = '".$this->db->escape($type)."'";
  448. }
  449. $sql .= " ORDER BY type, label";
  450. dol_syslog(get_class($this)."::get_url", LOG_DEBUG);
  451. $result = $this->db->query($sql);
  452. if ($result) {
  453. $i = 0;
  454. $num = $this->db->num_rows($result);
  455. while ($i < $num) {
  456. $obj = $this->db->fetch_object($result);
  457. // Anciens liens (pour compatibilite)
  458. $lines[$i][0] = $obj->url;
  459. $lines[$i][1] = $obj->url_id;
  460. $lines[$i][2] = $obj->label;
  461. $lines[$i][3] = $obj->type;
  462. // Nouveaux liens
  463. $lines[$i]['url'] = $obj->url;
  464. $lines[$i]['url_id'] = $obj->url_id;
  465. $lines[$i]['label'] = $obj->label;
  466. $lines[$i]['type'] = $obj->type;
  467. $lines[$i]['fk_bank'] = $obj->fk_bank;
  468. $i++;
  469. }
  470. } else {
  471. dol_print_error($this->db);
  472. }
  473. return $lines;
  474. }
  475. /**
  476. * Add an entry into table ".MAIN_DB_PREFIX."bank
  477. *
  478. * @param int $date Date operation
  479. * @param string $oper 'VIR','PRE','LIQ','VAD','CB','CHQ'...
  480. * @param string $label Descripton
  481. * @param float $amount Amount
  482. * @param string $num_chq Numero cheque or transfer
  483. * @param int $categorie Category id (optionnal)
  484. * @param User $user User that create
  485. * @param string $emetteur Name of cheque writer
  486. * @param string $banque Bank of cheque writer
  487. * @param string $accountancycode When we record a free bank entry, we must provide accounting account if accountancy module is on.
  488. * @param int $datev Date value
  489. * @param string $num_releve Label of bank receipt for reconciliation
  490. * @param float $amount_main_currency Amount
  491. * @return int Rowid of added entry, <0 if KO
  492. */
  493. public function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur = '', $banque = '', $accountancycode = '', $datev = null, $num_releve = '', $amount_main_currency = null)
  494. {
  495. // Deprecation warning
  496. if (is_numeric($oper)) {
  497. dol_syslog(__METHOD__.": using numeric operations is deprecated", LOG_WARNING);
  498. }
  499. if (empty($this->id) && !empty($this->rowid)) { // For backward compatibility
  500. $this->id = $this->rowid;
  501. }
  502. // Clean parameters
  503. $emetteur = trim($emetteur);
  504. $banque = trim($banque);
  505. $label = trim($label);
  506. $now = dol_now();
  507. if (is_numeric($oper)) { // Clean operation to have a code instead of a rowid
  508. $sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement";
  509. $sql .= " WHERE id = ".((int) $oper);
  510. $sql .= " AND entity IN (".getEntity('c_paiement').")";
  511. $resql = $this->db->query($sql);
  512. if ($resql) {
  513. $obj = $this->db->fetch_object($resql);
  514. $oper = $obj->code;
  515. } else {
  516. dol_print_error($this->db, 'Failed to get payment type code');
  517. return -1;
  518. }
  519. }
  520. // Check parameters
  521. if (!$oper) {
  522. $this->error = "oper not defined";
  523. return -1;
  524. }
  525. if (!$this->id) {
  526. $this->error = "this->id not defined";
  527. return -2;
  528. }
  529. if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ') {
  530. $this->error = "ErrorCashAccountAcceptsOnlyCashMoney";
  531. return -3;
  532. }
  533. $this->db->begin();
  534. if (is_null($datev) || empty($datev)) {
  535. $datev = $date;
  536. }
  537. $accline = new AccountLine($this->db);
  538. $accline->datec = $now;
  539. $accline->dateo = $date;
  540. $accline->datev = $datev;
  541. $accline->label = $label;
  542. $accline->amount = $amount;
  543. $accline->amount_main_currency = $amount_main_currency;
  544. $accline->fk_user_author = $user->id;
  545. $accline->fk_account = $this->id;
  546. $accline->fk_type = $oper;
  547. $accline->numero_compte = $accountancycode;
  548. $accline->num_releve = $num_releve;
  549. if ($num_chq) {
  550. $accline->num_chq = $num_chq;
  551. }
  552. if ($emetteur) {
  553. $accline->emetteur = $emetteur;
  554. }
  555. if ($banque) {
  556. $accline->bank_chq = $banque;
  557. }
  558. if ($accline->insert() > 0) {
  559. if ($categorie > 0) {
  560. $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class(";
  561. $sql .= "lineid, fk_categ";
  562. $sql .= ") VALUES (";
  563. $sql .= ((int) $accline->id).", '".$this->db->escape($categorie)."'";
  564. $sql .= ")";
  565. $result = $this->db->query($sql);
  566. if (!$result) {
  567. $this->error = $this->db->lasterror();
  568. $this->db->rollback();
  569. return -4;
  570. }
  571. }
  572. $this->db->commit();
  573. return $accline->id;
  574. } else {
  575. $this->error = $accline->error;
  576. $this->errors = $accline->errors;
  577. $this->db->rollback();
  578. return -5;
  579. }
  580. }
  581. /**
  582. * Create bank account into database
  583. *
  584. * @param User $user Object user making creation
  585. * @param int $notrigger 1=Disable triggers
  586. * @return int < 0 if KO, > 0 if OK
  587. */
  588. public function create(User $user, $notrigger = 0)
  589. {
  590. global $langs, $conf;
  591. $error = 0;
  592. // Clean parameters
  593. if (!$this->min_allowed) {
  594. $this->min_allowed = 0;
  595. }
  596. if (!$this->min_desired) {
  597. $this->min_desired = 0;
  598. }
  599. // Check parameters
  600. if (empty($this->country_id)) {
  601. $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Country"));
  602. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  603. return -1;
  604. }
  605. if (empty($this->ref)) {
  606. $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
  607. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  608. return -1;
  609. }
  610. if (empty($this->date_solde)) {
  611. $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateInitialBalance"));
  612. dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
  613. return -1;
  614. }
  615. // Load librairies to check BAN
  616. require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
  617. $now = dol_now();
  618. $this->db->begin();
  619. $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account (";
  620. $sql .= "datec";
  621. $sql .= ", ref";
  622. $sql .= ", label";
  623. $sql .= ", entity";
  624. $sql .= ", account_number";
  625. $sql .= ", fk_accountancy_journal";
  626. $sql .= ", bank";
  627. $sql .= ", code_banque";
  628. $sql .= ", code_guichet";
  629. $sql .= ", number";
  630. $sql .= ", cle_rib";
  631. $sql .= ", bic";
  632. $sql .= ", iban_prefix";
  633. $sql .= ", domiciliation";
  634. $sql .= ", pti_in_ctti";
  635. $sql .= ", proprio";
  636. $sql .= ", owner_address";
  637. $sql .= ", owner_zip";
  638. $sql .= ", owner_town";
  639. $sql .= ", owner_country_id";
  640. $sql .= ", currency_code";
  641. $sql .= ", rappro";
  642. $sql .= ", min_allowed";
  643. $sql .= ", min_desired";
  644. $sql .= ", comment";
  645. $sql .= ", state_id";
  646. $sql .= ", fk_pays";
  647. $sql .= ", ics";
  648. $sql .= ", ics_transfer";
  649. $sql .= ") VALUES (";
  650. $sql .= "'".$this->db->idate($now)."'";
  651. $sql .= ", '".$this->db->escape($this->ref)."'";
  652. $sql .= ", '".$this->db->escape($this->label)."'";
  653. $sql .= ", ".((int) $conf->entity);
  654. $sql .= ", '".$this->db->escape($this->account_number)."'";
  655. $sql .= ", ".($this->fk_accountancy_journal > 0 ? ((int) $this->fk_accountancy_journal) : "null");
  656. $sql .= ", '".$this->db->escape($this->bank)."'";
  657. $sql .= ", '".$this->db->escape($this->code_banque)."'";
  658. $sql .= ", '".$this->db->escape($this->code_guichet)."'";
  659. $sql .= ", '".$this->db->escape($this->number)."'";
  660. $sql .= ", '".$this->db->escape($this->cle_rib)."'";
  661. $sql .= ", '".$this->db->escape($this->bic)."'";
  662. $sql .= ", '".$this->db->escape($this->iban)."'";
  663. $sql .= ", '".$this->db->escape($this->domiciliation)."'";
  664. $sql .= ", ".((int) $this->pti_in_ctti);
  665. $sql .= ", '".$this->db->escape($this->proprio)."'";
  666. $sql .= ", '".$this->db->escape($this->owner_address)."'";
  667. $sql .= ", '".$this->db->escape($this->owner_zip)."'";
  668. $sql .= ", '".$this->db->escape($this->owner_town)."'";
  669. $sql .= ", ".($this->owner_country_id > 0 ? ((int) $this->owner_country_id) : "null");
  670. $sql .= ", '".$this->db->escape($this->currency_code)."'";
  671. $sql .= ", ".((int) $this->rappro);
  672. $sql .= ", ".price2num($this->min_allowed, 'MT');
  673. $sql .= ", ".price2num($this->min_desired, 'MT');
  674. $sql .= ", '".$this->db->escape($this->comment)."'";
  675. $sql .= ", ".($this->state_id > 0 ? ((int) $this->state_id) : "null");
  676. $sql .= ", ".($this->country_id > 0 ? ((int) $this->country_id) : "null");
  677. $sql .= ", '".$this->db->escape($this->ics)."'";
  678. $sql .= ", '".$this->db->escape($this->ics_transfer)."'";
  679. $sql .= ")";
  680. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  681. $resql = $this->db->query($sql);
  682. if ($resql) {
  683. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account");
  684. $result = $this->update($user, 1);
  685. if ($result > 0) {
  686. $accline = new AccountLine($this->db);
  687. $accline->datec = $now;
  688. $accline->label = '('.$langs->trans("InitialBankBalance").')';
  689. $accline->amount = price2num($this->solde);
  690. $accline->fk_user_author = $user->id;
  691. $accline->fk_account = $this->id;
  692. $accline->datev = $this->date_solde;
  693. $accline->dateo = $this->date_solde;
  694. $accline->fk_type = 'SOLD';
  695. if ($accline->insert() < 0) {
  696. $error++;
  697. $this->error = $accline->error;
  698. $this->errors = $accline->errors;
  699. }
  700. if (!$error) {
  701. $result = $this->insertExtraFields();
  702. if ($result < 0) {
  703. $error++;
  704. }
  705. }
  706. if (!$error && !$notrigger) {
  707. // Call trigger
  708. $result = $this->call_trigger('BANKACCOUNT_CREATE', $user);
  709. if ($result < 0) {
  710. $error++;
  711. }
  712. // End call triggers
  713. }
  714. } else {
  715. $error++;
  716. }
  717. } else {
  718. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  719. $this->error = $langs->trans("ErrorBankLabelAlreadyExists");
  720. $error++;
  721. } else {
  722. $this->error = $this->db->error()." sql=".$sql;
  723. $error++;
  724. }
  725. }
  726. if (!$error) {
  727. $this->db->commit();
  728. return $this->id;
  729. } else {
  730. $this->db->rollback();
  731. return -1 * $error;
  732. }
  733. }
  734. /**
  735. * Update bank account card
  736. *
  737. * @param User $user Object user making action
  738. * @param int $notrigger 1=Disable triggers
  739. * @return int Return integer <0 if KO, >0 if OK
  740. */
  741. public function update(User $user, $notrigger = 0)
  742. {
  743. global $langs, $conf;
  744. $error = 0;
  745. $this->db->begin();
  746. // Check parameters
  747. if (empty($this->country_id)) {
  748. $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Country"));
  749. dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
  750. return -1;
  751. }
  752. if (empty($this->ref)) {
  753. $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
  754. dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
  755. return -1;
  756. }
  757. if (!$this->label) {
  758. $this->label = "???";
  759. }
  760. $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET ";
  761. $sql .= " ref = '".$this->db->escape($this->ref)."'";
  762. $sql .= ",label = '".$this->db->escape($this->label)."'";
  763. $sql .= ",courant = ".((int) $this->courant);
  764. $sql .= ",clos = ".((int) $this->clos);
  765. $sql .= ",rappro = ".((int) $this->rappro);
  766. $sql .= ",url = ".($this->url ? "'".$this->db->escape($this->url)."'" : "null");
  767. $sql .= ",account_number = '".$this->db->escape($this->account_number)."'";
  768. $sql .= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? ((int) $this->fk_accountancy_journal) : "null");
  769. $sql .= ",bank = '".$this->db->escape($this->bank)."'";
  770. $sql .= ",code_banque='".$this->db->escape($this->code_banque)."'";
  771. $sql .= ",code_guichet='".$this->db->escape($this->code_guichet)."'";
  772. $sql .= ",number='".$this->db->escape($this->number)."'";
  773. $sql .= ",cle_rib='".$this->db->escape($this->cle_rib)."'";
  774. $sql .= ",bic='".$this->db->escape($this->bic)."'";
  775. $sql .= ",iban_prefix = '".$this->db->escape($this->iban)."'";
  776. $sql .= ",domiciliation='".$this->db->escape($this->domiciliation)."'";
  777. $sql .= ",pti_in_ctti=".((int) $this->pti_in_ctti);
  778. $sql .= ",proprio = '".$this->db->escape($this->proprio)."'";
  779. $sql .= ",owner_address = '".$this->db->escape($this->owner_address)."'";
  780. $sql .= ",owner_zip = '".$this->db->escape($this->owner_zip)."'";
  781. $sql .= ",owner_town = '".$this->db->escape($this->owner_town)."'";
  782. $sql .= ",owner_country_id = ".($this->owner_country_id > 0 ? ((int) $this->owner_country_id) : "null");
  783. $sql .= ",currency_code = '".$this->db->escape($this->currency_code)."'";
  784. $sql .= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null");
  785. $sql .= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null");
  786. $sql .= ",comment = '".$this->db->escape($this->comment)."'";
  787. $sql .= ",state_id = ".($this->state_id > 0 ? ((int) $this->state_id) : "null");
  788. $sql .= ",fk_pays = ".($this->country_id > 0 ? ((int) $this->country_id) : "null");
  789. $sql .= ",ics = '".$this->db->escape($this->ics)."'";
  790. $sql .= ",ics_transfer = '".$this->db->escape($this->ics_transfer)."'";
  791. $sql .= " WHERE rowid = ".((int) $this->id);
  792. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  793. $result = $this->db->query($sql);
  794. if ($result) {
  795. // Actions on extra fields (by external module or standard code)
  796. if (!$error) {
  797. $result = $this->insertExtraFields();
  798. if ($result < 0) {
  799. $error++;
  800. }
  801. }
  802. if (!$error && !$notrigger) {
  803. // Call trigger
  804. $result = $this->call_trigger('BANKACCOUNT_MODIFY', $user);
  805. if ($result < 0) {
  806. $error++;
  807. }
  808. // End call triggers
  809. }
  810. } else {
  811. $error++;
  812. $this->error = $this->db->lasterror();
  813. dol_print_error($this->db);
  814. }
  815. if (!$error) {
  816. $this->db->commit();
  817. return $this->id;
  818. } else {
  819. $this->db->rollback();
  820. return -1 * $error;
  821. }
  822. }
  823. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  824. /**
  825. * Update BBAN (RIB) account fields
  826. *
  827. * @param User|null $user Object user making update
  828. * @return int Return integer <0 if KO, >0 if OK
  829. */
  830. public function update_bban(User $user = null)
  831. {
  832. // phpcs:enable
  833. global $conf, $langs;
  834. // Load library to get BAN control function
  835. require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
  836. dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban");
  837. // Check parameters
  838. if (!$this->ref) {
  839. $this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->trans("Ref"));
  840. return -2;
  841. }
  842. $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET ";
  843. $sql .= " bank = '".$this->db->escape($this->bank)."'";
  844. $sql .= ",code_banque='".$this->db->escape($this->code_banque)."'";
  845. $sql .= ",code_guichet='".$this->db->escape($this->code_guichet)."'";
  846. $sql .= ",number='".$this->db->escape($this->number)."'";
  847. $sql .= ",cle_rib='".$this->db->escape($this->cle_rib)."'";
  848. $sql .= ",bic='".$this->db->escape($this->bic)."'";
  849. $sql .= ",iban_prefix = '".$this->db->escape($this->iban)."'";
  850. $sql .= ",domiciliation='".$this->db->escape($this->domiciliation)."'";
  851. $sql .= ",proprio = '".$this->db->escape($this->proprio)."'";
  852. $sql .= ",owner_address = '".$this->db->escape($this->owner_address)."'";
  853. $sql .= ",owner_zip = '".$this->db->escape($this->owner_zip)."'";
  854. $sql .= ",owner_town = '".$this->db->escape($this->owner_town)."'";
  855. $sql .= ",owner_country_id = ".($this->owner_country_id > 0 ? ((int) $this->owner_country_id) : "null");
  856. $sql .= ",state_id = ".($this->state_id > 0 ? $this->state_id : "null");
  857. $sql .= ",fk_pays = ".($this->country_id > 0 ? $this->country_id : "null");
  858. $sql .= " WHERE rowid = ".((int) $this->id);
  859. $sql .= " AND entity = ".((int) $conf->entity);
  860. dol_syslog(get_class($this)."::update_bban", LOG_DEBUG);
  861. $result = $this->db->query($sql);
  862. if ($result) {
  863. return 1;
  864. } else {
  865. $this->error = $this->db->lasterror();
  866. dol_print_error($this->db);
  867. return -1;
  868. }
  869. }
  870. /**
  871. * Load a bank account into memory from database
  872. *
  873. * @param int $id Id of bank account to get
  874. * @param string $ref Ref of bank account to get
  875. * @return int Return integer <0 if KO, >0 if OK
  876. */
  877. public function fetch($id, $ref = '')
  878. {
  879. if (empty($id) && empty($ref)) {
  880. $this->error = "ErrorBadParameters";
  881. return -1;
  882. }
  883. $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,";
  884. $sql .= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,";
  885. $sql .= " ba.domiciliation as address, ba.pti_in_ctti, ba.proprio, ba.owner_address, ba.owner_zip, ba.owner_town, ba.owner_country_id, ba.state_id, ba.fk_pays as country_id,";
  886. $sql .= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,";
  887. $sql .= " ba.min_allowed, ba.min_desired, ba.comment,";
  888. $sql .= " ba.datec as date_creation, ba.tms as date_modification, ba.ics, ba.ics_transfer,";
  889. $sql .= ' c.code as country_code, c.label as country,';
  890. $sql .= ' d.code_departement as state_code, d.nom as state,';
  891. $sql .= ' aj.code as accountancy_journal';
  892. $sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
  893. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid';
  894. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid';
  895. $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'accounting_journal as aj ON aj.rowid=ba.fk_accountancy_journal';
  896. $sql .= " WHERE ba.entity IN (".getEntity($this->element).")";
  897. if ($id) {
  898. $sql .= " AND ba.rowid = ".((int) $id);
  899. }
  900. if ($ref) {
  901. $sql .= " AND ba.ref = '".$this->db->escape($ref)."'";
  902. }
  903. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  904. $result = $this->db->query($sql);
  905. if ($result) {
  906. if ($this->db->num_rows($result)) {
  907. $obj = $this->db->fetch_object($result);
  908. $this->id = $obj->rowid;
  909. $this->rowid = $obj->rowid;
  910. $this->ref = $obj->ref;
  911. $this->label = $obj->label;
  912. $this->type = $obj->courant;
  913. $this->courant = $obj->courant;
  914. $this->bank = $obj->bank;
  915. $this->clos = $obj->clos;
  916. $this->rappro = $obj->rappro;
  917. $this->url = $obj->url;
  918. $this->code_banque = $obj->code_banque;
  919. $this->code_guichet = $obj->code_guichet;
  920. $this->number = $obj->number;
  921. $this->cle_rib = $obj->cle_rib;
  922. $this->bic = $obj->bic;
  923. $this->iban = $obj->iban;
  924. $this->domiciliation = $obj->address;
  925. $this->address = $obj->address;
  926. $this->pti_in_ctti = $obj->pti_in_ctti;
  927. $this->proprio = $obj->proprio;
  928. $this->owner_address = $obj->owner_address;
  929. $this->owner_zip = $obj->owner_zip;
  930. $this->owner_town = $obj->owner_town;
  931. $this->owner_country_id = $obj->owner_country_id;
  932. $this->state_id = $obj->state_id;
  933. $this->state_code = $obj->state_code;
  934. $this->state = $obj->state;
  935. $this->country_id = $obj->country_id;
  936. $this->country_code = $obj->country_code;
  937. $this->country = $obj->country;
  938. $this->account_number = $obj->account_number;
  939. $this->fk_accountancy_journal = $obj->fk_accountancy_journal;
  940. $this->accountancy_journal = $obj->accountancy_journal;
  941. $this->currency_code = $obj->currency_code;
  942. $this->account_currency_code = $obj->currency_code;
  943. $this->min_allowed = $obj->min_allowed;
  944. $this->min_desired = $obj->min_desired;
  945. $this->comment = $obj->comment;
  946. $this->date_creation = $this->db->jdate($obj->date_creation);
  947. $this->date_modification = $this->db->jdate($obj->date_modification);
  948. $this->date_update = $this->date_modification; // For compatibility
  949. $this->ics = $obj->ics;
  950. $this->ics_transfer = $obj->ics_transfer;
  951. // Retrieve all extrafield
  952. // fetch optionals attributes and labels
  953. $this->fetch_optionals();
  954. return 1;
  955. } else {
  956. return 0;
  957. }
  958. } else {
  959. $this->error = $this->db->lasterror();
  960. $this->errors[] = $this->error;
  961. return -1;
  962. }
  963. }
  964. /**
  965. * Sets object to supplied categories.
  966. *
  967. * Deletes object from existing categories not supplied.
  968. * Adds it to non existing supplied categories.
  969. * Existing categories are left untouch.
  970. *
  971. * @param int[]|int $categories Category or categories IDs
  972. * @return int Return integer <0 if KO, >0 if OK
  973. */
  974. public function setCategories($categories)
  975. {
  976. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  977. return parent::setCategoriesCommon($categories, Categorie::TYPE_ACCOUNT);
  978. }
  979. /**
  980. * Delete bank account from database
  981. *
  982. * @param User|null $user User deleting
  983. * @return int Return integer <0 if KO, >0 if OK
  984. */
  985. public function delete(User $user = null)
  986. {
  987. $error = 0;
  988. $this->db->begin();
  989. // @TODO Check there is no child into llx_payment_various, ... to allow deletion ?
  990. // Delete link between tag and bank account
  991. if (!$error) {
  992. $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account";
  993. $sql .= " WHERE fk_account = ".((int) $this->id);
  994. $resql = $this->db->query($sql);
  995. if (!$resql) {
  996. $error++;
  997. $this->error = "Error ".$this->db->lasterror();
  998. }
  999. }
  1000. if (!$error) {
  1001. $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
  1002. $sql .= " WHERE rowid = ".((int) $this->id);
  1003. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1004. $result = $this->db->query($sql);
  1005. if ($result) {
  1006. // Remove extrafields
  1007. if (!$error) {
  1008. $result = $this->deleteExtraFields();
  1009. if ($result < 0) {
  1010. $error++;
  1011. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  1012. }
  1013. }
  1014. } else {
  1015. $error++;
  1016. $this->error = "Error ".$this->db->lasterror();
  1017. }
  1018. }
  1019. if (!$error) {
  1020. $this->db->commit();
  1021. return 1;
  1022. } else {
  1023. $this->db->rollback();
  1024. return -1;
  1025. }
  1026. }
  1027. /**
  1028. * Return label of object status
  1029. *
  1030. * @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
  1031. * @return string Label
  1032. */
  1033. public function getLibStatut($mode = 0)
  1034. {
  1035. return $this->LibStatut($this->clos, $mode);
  1036. }
  1037. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1038. /**
  1039. * Return label of given object status
  1040. *
  1041. * @param int $status Id status
  1042. * @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
  1043. * @return string Label
  1044. */
  1045. public function LibStatut($status, $mode = 0)
  1046. {
  1047. // phpcs:enable
  1048. global $langs;
  1049. $langs->load('banks');
  1050. if ($status == self::STATUS_OPEN) {
  1051. $label = $langs->transnoentitiesnoconv("StatusAccountOpened");
  1052. $labelshort = $langs->transnoentitiesnoconv("StatusAccountOpened");
  1053. $statusType = 'status4';
  1054. } else {
  1055. $label = $langs->transnoentitiesnoconv("StatusAccountClosed");
  1056. $labelshort = $langs->transnoentitiesnoconv("StatusAccountClosed");
  1057. $statusType = 'status5';
  1058. }
  1059. return dolGetStatus($label, $labelshort, '', $statusType, $mode);
  1060. }
  1061. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1062. /**
  1063. * Renvoi si un compte peut etre supprimer ou non (sans mouvements)
  1064. *
  1065. * @return boolean vrai si peut etre supprime, faux sinon
  1066. */
  1067. public function can_be_deleted()
  1068. {
  1069. // phpcs:enable
  1070. $can_be_deleted = false;
  1071. $sql = "SELECT COUNT(rowid) as nb";
  1072. $sql .= " FROM ".MAIN_DB_PREFIX."bank";
  1073. $sql .= " WHERE fk_account = ".((int) $this->id);
  1074. $resql = $this->db->query($sql);
  1075. if ($resql) {
  1076. $obj = $this->db->fetch_object($resql);
  1077. if ($obj->nb <= 1) {
  1078. $can_be_deleted = true; // Juste le solde
  1079. }
  1080. } else {
  1081. dol_print_error($this->db);
  1082. }
  1083. return $can_be_deleted;
  1084. }
  1085. /**
  1086. * Return error
  1087. *
  1088. * @return string Error string
  1089. */
  1090. public function error()
  1091. {
  1092. return $this->error;
  1093. }
  1094. /**
  1095. * Return current sold
  1096. *
  1097. * @param int $option 1=Exclude future operation date (this is to exclude input made in advance and have real account sold)
  1098. * @param int $date_end Date until we want to get bank account sold
  1099. * @param string $field dateo or datev
  1100. * @return int current sold (value date <= today)
  1101. */
  1102. public function solde($option = 0, $date_end = '', $field = 'dateo')
  1103. {
  1104. $solde = 0;
  1105. $sql = "SELECT sum(amount) as amount";
  1106. $sql .= " FROM ".MAIN_DB_PREFIX."bank";
  1107. $sql .= " WHERE fk_account = ".((int) $this->id);
  1108. if ($option == 1) {
  1109. $sql .= " AND ".$this->db->escape($field)." <= '".(!empty($date_end) ? $this->db->idate($date_end) : $this->db->idate(dol_now()))."'";
  1110. }
  1111. $resql = $this->db->query($sql);
  1112. if ($resql) {
  1113. if ($this->db->num_rows($resql)) {
  1114. $obj = $this->db->fetch_object($resql);
  1115. $solde = $obj->amount;
  1116. }
  1117. $this->db->free($resql);
  1118. } else {
  1119. $this->errors[] = $this->db->lasterror;
  1120. return -1;
  1121. }
  1122. return price2num($solde, 'MU');
  1123. }
  1124. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1125. /**
  1126. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1127. *
  1128. * @param User $user Objet user
  1129. * @param int $filteraccountid To get info for a particular account id
  1130. * @return WorkboardResponse|int <0 if KO, WorkboardResponse if OK
  1131. */
  1132. public function load_board(User $user, $filteraccountid = 0)
  1133. {
  1134. // phpcs:enable
  1135. global $conf, $langs;
  1136. if ($user->socid) {
  1137. return -1; // protection pour eviter appel par utilisateur externe
  1138. }
  1139. $sql = "SELECT b.rowid, b.datev as datefin";
  1140. $sql .= " FROM ".MAIN_DB_PREFIX."bank as b,";
  1141. $sql .= " ".MAIN_DB_PREFIX."bank_account as ba";
  1142. $sql .= " WHERE b.rappro=0";
  1143. $sql .= " AND b.fk_account = ba.rowid";
  1144. $sql .= " AND ba.entity IN (".getEntity('bank_account').")";
  1145. $sql .= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable
  1146. $sql .= " AND clos = 0";
  1147. if ($filteraccountid) {
  1148. $sql .= " AND ba.rowid = ".((int) $filteraccountid);
  1149. }
  1150. $resql = $this->db->query($sql);
  1151. if ($resql) {
  1152. $langs->load("banks");
  1153. $now = dol_now();
  1154. require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php';
  1155. $response = new WorkboardResponse();
  1156. $response->warning_delay = $conf->bank->rappro->warning_delay / 60 / 60 / 24;
  1157. $response->label = $langs->trans("TransactionsToConciliate");
  1158. $response->labelShort = $langs->trans("TransactionsToConciliateShort");
  1159. $response->url = DOL_URL_ROOT.'/compta/bank/list.php?leftmenu=bank&amp;mainmenu=bank';
  1160. $response->img = img_object('', "payment");
  1161. while ($obj = $this->db->fetch_object($resql)) {
  1162. $response->nbtodo++;
  1163. if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) {
  1164. $response->nbtodolate++;
  1165. }
  1166. }
  1167. return $response;
  1168. } else {
  1169. dol_print_error($this->db);
  1170. $this->error = $this->db->error();
  1171. return -1;
  1172. }
  1173. }
  1174. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1175. /**
  1176. * Charge indicateurs this->nb de tableau de bord
  1177. *
  1178. * @param int $filteraccountid To get info for a particular account id
  1179. * @return int Return integer <0 if KO, >0 if OK
  1180. */
  1181. public function load_state_board($filteraccountid = 0)
  1182. {
  1183. // phpcs:enable
  1184. global $user;
  1185. if ($user->socid) {
  1186. return -1; // protection pour eviter appel par utilisateur externe
  1187. }
  1188. $sql = "SELECT count(b.rowid) as nb";
  1189. $sql .= " FROM ".MAIN_DB_PREFIX."bank as b,";
  1190. $sql .= " ".MAIN_DB_PREFIX."bank_account as ba";
  1191. $sql .= " WHERE b.fk_account = ba.rowid";
  1192. $sql .= " AND ba.entity IN (".getEntity('bank_account').")";
  1193. $sql .= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable
  1194. $sql .= " AND clos = 0";
  1195. if ($filteraccountid) {
  1196. $sql .= " AND ba.rowid = ".((int) $filteraccountid);
  1197. }
  1198. $resql = $this->db->query($sql);
  1199. if ($resql) {
  1200. while ($obj = $this->db->fetch_object($resql)) {
  1201. $this->nb["banklines"] = $obj->nb;
  1202. }
  1203. $this->db->free($resql);
  1204. return 1;
  1205. } else {
  1206. dol_print_error($this->db);
  1207. $this->error = $this->db->error();
  1208. return -1;
  1209. }
  1210. }
  1211. /**
  1212. * Load indicators for dashboard (this->nbtodo and this->nbtodolate)
  1213. *
  1214. * @return int Nb of account we can reconciliate
  1215. */
  1216. public function countAccountToReconcile()
  1217. {
  1218. global $db, $conf, $user;
  1219. //Protection against external users
  1220. if ($user->socid) {
  1221. return 0;
  1222. }
  1223. $nb = 0;
  1224. $sql = "SELECT COUNT(ba.rowid) as nb";
  1225. $sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
  1226. $sql .= " WHERE ba.rappro > 0 and ba.clos = 0";
  1227. $sql .= " AND ba.entity IN (".getEntity('bank_account').")";
  1228. if (!getDolGlobalString('BANK_CAN_RECONCILIATE_CASHACCOUNT')) {
  1229. $sql .= " AND ba.courant != 2";
  1230. }
  1231. $resql = $this->db->query($sql);
  1232. if ($resql) {
  1233. $obj = $this->db->fetch_object($resql);
  1234. $nb = $obj->nb;
  1235. } else {
  1236. dol_print_error($this->db);
  1237. }
  1238. return $nb;
  1239. }
  1240. /**
  1241. * getTooltipContentArray
  1242. *
  1243. * @param array $params Params to construct tooltip data
  1244. * @since v18
  1245. * @return array
  1246. */
  1247. public function getTooltipContentArray($params)
  1248. {
  1249. global $langs;
  1250. $langs->loadLangs(['banks', 'compta']);
  1251. include_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
  1252. $datas = array();
  1253. $nofetch = !empty($params['nofetch']);
  1254. $pictos = img_picto('', $this->picto).' <u class="paddingrightnow">'.$langs->trans("BankAccount").'</u>';
  1255. if (isset($this->status)) {
  1256. $pictos .= ' '.$this->getLibStatut(5);
  1257. }
  1258. $datas['picto'] = $pictos;
  1259. $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
  1260. $datas['accountnumber'] = '<br><b>'.$langs->trans('AccountNumber').':</b> '.$this->number;
  1261. $datas['iban'] = '<br><b>'.$langs->trans('IBAN').':</b> '.getIbanHumanReadable($this);
  1262. $datas['bic'] = '<br><b>'.$langs->trans('BIC').':</b> '.$this->bic;
  1263. $datas['accountcurrency'] = '<br><b>'.$langs->trans("AccountCurrency").':</b> '.$this->currency_code;
  1264. if (isModEnabled('accounting')) {
  1265. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  1266. $langs->load("accountancy");
  1267. $datas['accountaccounting'] = '<br><b>'.$langs->trans('AccountAccounting').':</b> '.length_accountg($this->account_number);
  1268. $datas['accountancyjournal'] = '<br><b>'.$langs->trans('AccountancyJournal').':</b> '.$this->accountancy_journal;
  1269. }
  1270. // show categories for this record only in ajax to not overload lists
  1271. if (isModEnabled('categorie') && !$nofetch) {
  1272. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  1273. $form = new Form($this->db);
  1274. $datas['categories'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_ACCOUNT, 1);
  1275. }
  1276. return $datas;
  1277. }
  1278. /**
  1279. * Return clicable name (with picto eventually)
  1280. *
  1281. * @param int $withpicto Include picto into link
  1282. * @param string $mode ''=Link to card, 'transactions'=Link to transactions card
  1283. * @param string $option ''=Show ref, 'reflabel'=Show ref+label
  1284. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1285. * @param int $notooltip 1=Disable tooltip
  1286. * @param string $morecss Add more css on link
  1287. * @return string Chaine avec URL
  1288. */
  1289. public function getNomUrl($withpicto = 0, $mode = '', $option = '', $save_lastsearch_value = -1, $notooltip = 0, $morecss = '')
  1290. {
  1291. global $conf, $langs;
  1292. if (!empty($conf->dol_no_mouse_hover)) {
  1293. $notooltip = 1; // Force disable tooltips
  1294. }
  1295. include_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
  1296. $result = '';
  1297. $classfortooltip = 'classfortooltip';
  1298. $dataparams = '';
  1299. $params = [
  1300. 'id' => $this->id,
  1301. 'objecttype' => $this->element,
  1302. 'option' => $option,
  1303. 'nofetch' => 1,
  1304. ];
  1305. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  1306. $classfortooltip = 'classforajaxtooltip';
  1307. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  1308. $label = '';
  1309. } else {
  1310. $label = implode($this->getTooltipContentArray($params));
  1311. }
  1312. $url = DOL_URL_ROOT.'/compta/bank/card.php?id='.$this->id;
  1313. if ($mode == 'transactions') {
  1314. $url = DOL_URL_ROOT.'/compta/bank/bankentries_list.php?id='.$this->id;
  1315. } elseif ($mode == 'receipts') {
  1316. $url = DOL_URL_ROOT.'/compta/bank/releve.php?account='.$this->id;
  1317. }
  1318. if ($option != 'nolink') {
  1319. // Add param to save lastsearch_values or not
  1320. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1321. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1322. $add_save_lastsearch_values = 1;
  1323. }
  1324. if ($add_save_lastsearch_values) {
  1325. $url .= '&save_lastsearch_values=1';
  1326. }
  1327. }
  1328. $linkclose = '';
  1329. if (empty($notooltip)) {
  1330. if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  1331. $label = $langs->trans("BankAccount");
  1332. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1333. }
  1334. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  1335. $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
  1336. } else {
  1337. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1338. }
  1339. if ($option == 'nolink' || empty($url)) {
  1340. $linkstart = '<span';
  1341. } else {
  1342. $linkstart = '<a href="'.$url.'"';
  1343. }
  1344. $linkstart .= $linkclose.'>';
  1345. if ($option == 'nolink' || empty($url)) {
  1346. $linkend = '</span>';
  1347. } else {
  1348. $linkend = '</a>';
  1349. }
  1350. $result .= $linkstart;
  1351. if ($withpicto) {
  1352. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
  1353. }
  1354. if ($withpicto != 2) {
  1355. $result .= $this->ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '');
  1356. }
  1357. $result .= $linkend;
  1358. return $result;
  1359. }
  1360. // Method after here are common to Account and CompanyBankAccount
  1361. /**
  1362. * Return if an account has valid information for Direct debit payment
  1363. *
  1364. * @return int 1 if correct, <=0 if wrong
  1365. */
  1366. public function verif()
  1367. {
  1368. require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
  1369. $error = 0;
  1370. // Call functions to check BAN
  1371. if (!checkIbanForAccount($this)) {
  1372. $error++;
  1373. $this->error = 'IBANNotValid';
  1374. }
  1375. if (!checkSwiftForAccount($this)) {
  1376. $error++;
  1377. $this->error = 'SwiftNotValid';
  1378. }
  1379. if (! $error) {
  1380. return 1;
  1381. } else {
  1382. return 0;
  1383. }
  1384. }
  1385. /**
  1386. * Return account country code
  1387. *
  1388. * @return string country code
  1389. */
  1390. public function getCountryCode()
  1391. {
  1392. global $mysoc;
  1393. // We return country code of bank account
  1394. if (!empty($this->country_code)) {
  1395. return $this->country_code;
  1396. }
  1397. // For backward compatibility, we try to guess country from other information
  1398. if (!empty($this->iban)) {
  1399. // If IBAN defined, we can know country of account from it
  1400. $reg = array();
  1401. if (preg_match("/^([a-zA-Z][a-zA-Z])/i", $this->iban, $reg)) {
  1402. return $reg[1];
  1403. }
  1404. }
  1405. // If this class is linked to a third party
  1406. if (!empty($this->socid)) {
  1407. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  1408. $company = new Societe($this->db);
  1409. $result = $company->fetch($this->socid);
  1410. if (!empty($company->country_code)) {
  1411. return $company->country_code;
  1412. }
  1413. }
  1414. // We return country code of managed company
  1415. if (!empty($mysoc->country_code)) {
  1416. return $mysoc->country_code;
  1417. }
  1418. return '';
  1419. }
  1420. /**
  1421. * Return if a bank account is defined with detailed information (bank code, desk code, number and key).
  1422. * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code
  1423. *
  1424. * @return int 0=No bank code need + Account number is enough
  1425. * 1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key
  1426. * 2=Need 1 field for bank code: Bank only (Sort code for Great Britain, BSB for Australia) + Account number
  1427. */
  1428. public function useDetailedBBAN()
  1429. {
  1430. $country_code = $this->getCountryCode();
  1431. if (in_array($country_code, array('FR', 'ES', 'GA', 'IT', 'NC'))) {
  1432. return 1; // France, Spain, Gabon, ... - Not valid for CH
  1433. }
  1434. if (in_array($country_code, array('AD', 'AU', 'BE', 'CA', 'DE', 'DK', 'GR', 'GB', 'ID', 'IE', 'IR', 'KR', 'NL', 'NZ', 'UK', 'US'))) {
  1435. return 2; // Australia, England...
  1436. }
  1437. return 0;
  1438. }
  1439. /**
  1440. * Return 1 if IBAN / BIC is mandatory (otherwise option)
  1441. *
  1442. * @return int 1 = mandatory / 0 = Not mandatory
  1443. */
  1444. public function needIBAN()
  1445. {
  1446. global $conf;
  1447. if (getDolGlobalString('MAIN_IBAN_IS_NEVER_MANDATORY')) {
  1448. return 0;
  1449. }
  1450. $country_code = $this->getCountryCode();
  1451. $country_code_in_EEC = array(
  1452. 'AT', // Austria
  1453. 'BE', // Belgium
  1454. 'BG', // Bulgaria
  1455. 'CY', // Cyprus
  1456. 'CZ', // Czech republic
  1457. 'DE', // Germany
  1458. 'DK', // Danemark
  1459. 'EE', // Estonia
  1460. 'ES', // Spain
  1461. 'FI', // Finland
  1462. 'FR', // France
  1463. 'GB', // United Kingdom
  1464. 'GR', // Greece
  1465. 'HR', // Croatia
  1466. 'NL', // Holland
  1467. 'HU', // Hungary
  1468. 'IE', // Ireland
  1469. 'IM', // Isle of Man - Included in UK
  1470. 'IT', // Italy
  1471. 'LT', // Lithuania
  1472. 'LU', // Luxembourg
  1473. 'LV', // Latvia
  1474. 'MC', // Monaco - Included in France
  1475. 'MT', // Malta
  1476. //'NO', // Norway
  1477. 'PL', // Poland
  1478. 'PT', // Portugal
  1479. 'RO', // Romania
  1480. 'SE', // Sweden
  1481. 'SK', // Slovakia
  1482. 'SI', // Slovenia
  1483. 'UK', // United Kingdom
  1484. //'CH', // Switzerland - No. Swizerland in not in EEC
  1485. );
  1486. if (in_array($country_code, $country_code_in_EEC)) {
  1487. return 1; // France, Spain, ...
  1488. }
  1489. return 0;
  1490. }
  1491. /**
  1492. * Load miscellaneous information for tab "Info"
  1493. *
  1494. * @param int $id Id of object to load
  1495. * @return void
  1496. */
  1497. public function info($id)
  1498. {
  1499. }
  1500. /**
  1501. * Returns the fields in order that this bank account should show to the user
  1502. * Will return an array with the following values:
  1503. * - BankAccountNumber
  1504. * - BankCode
  1505. * - BankAccountNumberKey
  1506. * - DeskCode
  1507. *
  1508. * Some countries show less or more bank account properties to the user
  1509. *
  1510. * @param int $includeibanbic 1=Return also key for IBAN and BIC
  1511. * @return array Array of fields to show
  1512. * @see useDetailedBBAN()
  1513. */
  1514. public function getFieldsToShow($includeibanbic = 0)
  1515. {
  1516. //Get the required properties depending on the country
  1517. $detailedBBAN = $this->useDetailedBBAN();
  1518. if ($detailedBBAN == 0) {
  1519. $fieldarray = array(
  1520. 'BankAccountNumber'
  1521. );
  1522. } elseif ($detailedBBAN == 2) {
  1523. $fieldarray = array(
  1524. 'BankCode',
  1525. 'BankAccountNumber'
  1526. );
  1527. } else {
  1528. $fieldarray = self::getAccountNumberOrder();
  1529. }
  1530. //if ($this->needIBAN()) { // return always IBAN and BIC (this was old behaviour)
  1531. if ($includeibanbic) {
  1532. $fieldarray[] = 'IBAN';
  1533. $fieldarray[] = 'BIC';
  1534. }
  1535. //}
  1536. //Get the order the properties are shown
  1537. return $fieldarray;
  1538. }
  1539. /**
  1540. * Returns the components of the bank account in order.
  1541. * Will return an array with the following values:
  1542. * - BankAccountNumber
  1543. * - BankCode
  1544. * - BankAccountNumberKey
  1545. * - DeskCode
  1546. *
  1547. * @return array
  1548. */
  1549. public static function getAccountNumberOrder()
  1550. {
  1551. global $conf;
  1552. $fieldlists = array(
  1553. 'BankCode',
  1554. 'DeskCode',
  1555. 'BankAccountNumber',
  1556. 'BankAccountNumberKey'
  1557. );
  1558. if (getDolGlobalString('BANK_SHOW_ORDER_OPTION')) {
  1559. if (is_numeric($conf->global->BANK_SHOW_ORDER_OPTION)) {
  1560. if (getDolGlobalString('BANK_SHOW_ORDER_OPTION') == '1') {
  1561. $fieldlists = array(
  1562. 'BankCode',
  1563. 'DeskCode',
  1564. 'BankAccountNumberKey',
  1565. 'BankAccountNumber'
  1566. );
  1567. }
  1568. } else {
  1569. //Replace the old AccountNumber key with the new BankAccountNumber key
  1570. $fieldlists = explode(
  1571. ' ',
  1572. preg_replace('/ ?[^Bank]AccountNumber ?/', 'BankAccountNumber', $conf->global->BANK_SHOW_ORDER_OPTION)
  1573. );
  1574. }
  1575. }
  1576. return $fieldlists;
  1577. }
  1578. /**
  1579. * Initialise an instance with random values.
  1580. * Used to build previews or test instances.
  1581. * id must be 0 if object instance is a specimen.
  1582. *
  1583. * @return void
  1584. */
  1585. public function initAsSpecimen()
  1586. {
  1587. // Example of IBAN FR7630001007941234567890185
  1588. $this->specimen = 1;
  1589. $this->ref = 'MBA';
  1590. $this->label = 'My Big Company Bank account';
  1591. $this->bank = 'MyBank';
  1592. $this->courant = Account::TYPE_CURRENT;
  1593. $this->clos = Account::STATUS_OPEN;
  1594. $this->code_banque = '30001';
  1595. $this->code_guichet = '00794';
  1596. $this->number = '12345678901';
  1597. $this->cle_rib = '85';
  1598. $this->bic = 'AA12';
  1599. $this->iban = 'FR7630001007941234567890185';
  1600. $this->domiciliation = 'Banque de France';
  1601. $this->proprio = 'Owner';
  1602. $this->owner_address = 'Owner address';
  1603. $this->owner_zip = 'Owner zip';
  1604. $this->owner_town = 'Owner town';
  1605. $this->owner_country_id = 'Owner country_id';
  1606. $this->country_id = 1;
  1607. }
  1608. /**
  1609. * Function used to replace a thirdparty id with another one.
  1610. *
  1611. * @param DoliDB $dbs Database handler
  1612. * @param int $origin_id Old thirdparty id
  1613. * @param int $dest_id New thirdparty id
  1614. * @return bool True=SQL success, False=SQL error
  1615. */
  1616. public static function replaceThirdparty($dbs, $origin_id, $dest_id)
  1617. {
  1618. $sql = "UPDATE ".MAIN_DB_PREFIX."bank_url SET url_id = ".((int) $dest_id)." WHERE url_id = ".((int) $origin_id)." AND type='company'";
  1619. if ($dbs->query($sql)) {
  1620. return true;
  1621. } else {
  1622. //if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdparty and B-C on old one, we must get A-B-C after merge. Not A-B.
  1623. //$this->errors = $dbs->lasterror();
  1624. return false;
  1625. }
  1626. }
  1627. /**
  1628. * Return clicable link of object (with eventually picto)
  1629. *
  1630. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  1631. * @param array $arraydata Array of data
  1632. * @return string HTML Code for Kanban thumb.
  1633. */
  1634. public function getKanbanView($option = '', $arraydata = null)
  1635. {
  1636. global $langs;
  1637. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  1638. $return = '<div class="box-flex-item box-flex-grow-zero">';
  1639. $return .= '<div class="info-box info-box-sm">';
  1640. $return .= '<span class="info-box-icon bg-infobox-action">';
  1641. $return .= img_picto('', $this->picto);
  1642. $return .= '</span>';
  1643. $return .= '<div class="info-box-content">';
  1644. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  1645. if ($selected >= 0) {
  1646. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  1647. }
  1648. if (property_exists($this, 'type_lib')) {
  1649. $return .= '<br><span class="info-box-label opacitymedium" title="'.$this->type_lib[$this->type].'">'.substr($this->type_lib[$this->type], 0, 24).'...</span>';
  1650. }
  1651. if (method_exists($this, 'solde')) {
  1652. $return .= '<br><a href="'.DOL_URL_ROOT.'/compta/bank/bankentries_list.php?id='.$this->id.'">';
  1653. $return .= '<span class="opacitymedium">'.$langs->trans("Balance").'</span> : <span class="amount">'.price(price2num($this->solde(1), 'MT'), 0, $langs, 1, -1, -1, $this->currency_code).'</span>';
  1654. }
  1655. if (method_exists($this, 'getLibStatut')) {
  1656. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
  1657. }
  1658. $return .= '</div>';
  1659. $return .= '</div>';
  1660. $return .= '</div>';
  1661. return $return;
  1662. }
  1663. }
  1664. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  1665. /**
  1666. * Class to manage bank transaction lines
  1667. */
  1668. class AccountLine extends CommonObjectLine
  1669. {
  1670. /**
  1671. * @var string Error code (or message)
  1672. */
  1673. public $error = '';
  1674. /**
  1675. * @var DoliDB Database handler.
  1676. */
  1677. public $db;
  1678. /**
  1679. * @var string ID to identify managed object
  1680. */
  1681. public $element = 'bank';
  1682. /**
  1683. * @var string Name of table without prefix where object is stored
  1684. */
  1685. public $table_element = 'bank';
  1686. /**
  1687. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  1688. */
  1689. public $picto = 'accountline';
  1690. /**
  1691. * @var int ID
  1692. */
  1693. public $id;
  1694. /**
  1695. * @var string Ref
  1696. */
  1697. public $ref;
  1698. /**
  1699. * Date creation record (datec)
  1700. *
  1701. * @var integer
  1702. */
  1703. public $datec;
  1704. /**
  1705. * Date (dateo)
  1706. *
  1707. * @var integer
  1708. */
  1709. public $dateo;
  1710. /**
  1711. * Date value (datev)
  1712. *
  1713. * @var integer
  1714. */
  1715. public $datev;
  1716. public $amount; /* Amount of payment in the bank account currency */
  1717. public $amount_main_currency; /* Amount in the currency of company if bank account use another currency */
  1718. /**
  1719. * @var int ID
  1720. */
  1721. public $fk_user_author;
  1722. /**
  1723. * @var int ID
  1724. */
  1725. public $fk_user_rappro;
  1726. /**
  1727. * @var int ID
  1728. */
  1729. public $fk_type;
  1730. /**
  1731. * @var int ID of cheque receipt
  1732. */
  1733. public $fk_bordereau;
  1734. /**
  1735. * @var int ID of bank account
  1736. */
  1737. public $fk_account;
  1738. /**
  1739. * @var string Ref of bank account
  1740. */
  1741. public $bank_account_ref;
  1742. /**
  1743. * @var string Label of bank account
  1744. */
  1745. public $bank_account_label;
  1746. /**
  1747. * @var string Bank account numero
  1748. */
  1749. public $numero_compte;
  1750. /**
  1751. * @var string Name of check issuer
  1752. */
  1753. public $emetteur;
  1754. public $rappro; // Is it conciliated
  1755. public $num_releve; // If conciliated, what is bank statement
  1756. public $num_chq; // Num of cheque
  1757. public $bank_chq; // Bank of cheque
  1758. /**
  1759. * @var string bank transaction lines label
  1760. */
  1761. public $label;
  1762. public $note;
  1763. /**
  1764. * User author of the rapprochement.
  1765. */
  1766. public $user_rappro;
  1767. /**
  1768. * Constructor
  1769. *
  1770. * @param DoliDB $db Database handler
  1771. */
  1772. public function __construct(DoliDB $db)
  1773. {
  1774. $this->db = $db;
  1775. }
  1776. /**
  1777. * Load into memory content of a bank transaction line
  1778. *
  1779. * @param int $rowid Id of bank transaction to load
  1780. * @param string $ref Ref of bank transaction to load
  1781. * @param string $num External num to load (ex: num of transaction for paypal fee)
  1782. * @return int <0 if KO, 0 if OK but not found, >0 if OK and found
  1783. */
  1784. public function fetch($rowid, $ref = '', $num = '')
  1785. {
  1786. // Check parameters
  1787. if (empty($rowid) && empty($ref) && empty($num)) {
  1788. return -1;
  1789. }
  1790. $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,";
  1791. $sql .= " b.fk_user_author, b.fk_user_rappro,";
  1792. $sql .= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,";
  1793. $sql .= " b.fk_bordereau, b.banque, b.emetteur,";
  1794. $sql .= " ba.ref as bank_account_ref, ba.label as bank_account_label";
  1795. $sql .= " FROM ".MAIN_DB_PREFIX."bank as b,";
  1796. $sql .= " ".MAIN_DB_PREFIX."bank_account as ba";
  1797. $sql .= " WHERE b.fk_account = ba.rowid";
  1798. $sql .= " AND ba.entity IN (".getEntity('bank_account').")";
  1799. if ($num) {
  1800. $sql .= " AND b.num_chq = '".$this->db->escape($num)."'";
  1801. } elseif ($ref) {
  1802. $sql .= " AND b.rowid = '".$this->db->escape($ref)."'";
  1803. } else {
  1804. $sql .= " AND b.rowid = ".((int) $rowid);
  1805. }
  1806. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  1807. $result = $this->db->query($sql);
  1808. if ($result) {
  1809. $ret = 0;
  1810. $obj = $this->db->fetch_object($result);
  1811. if ($obj) {
  1812. $this->id = $obj->rowid;
  1813. $this->rowid = $obj->rowid;
  1814. $this->ref = $obj->rowid;
  1815. $this->datec = $this->db->jdate($obj->datec);
  1816. $this->datev = $this->db->jdate($obj->datev);
  1817. $this->dateo = $this->db->jdate($obj->dateo);
  1818. $this->amount = $obj->amount;
  1819. $this->label = $obj->label;
  1820. $this->note = $obj->note;
  1821. $this->fk_user_author = $obj->fk_user_author;
  1822. $this->fk_user_rappro = $obj->fk_user_rappro;
  1823. $this->fk_type = $obj->fk_type; // Type of transaction
  1824. $this->rappro = $obj->rappro;
  1825. $this->num_releve = $obj->num_releve;
  1826. $this->num_chq = $obj->num_chq;
  1827. $this->bank_chq = $obj->banque;
  1828. $this->fk_bordereau = $obj->fk_bordereau;
  1829. $this->fk_account = $obj->fk_account;
  1830. $this->bank_account_ref = $obj->bank_account_ref;
  1831. $this->bank_account_label = $obj->bank_account_label;
  1832. // Retrieve all extrafield
  1833. // fetch optionals attributes and labels
  1834. $this->fetch_optionals();
  1835. $ret = 1;
  1836. }
  1837. $this->db->free($result);
  1838. return $ret;
  1839. } else {
  1840. return -1;
  1841. }
  1842. }
  1843. /**
  1844. * Inserts a transaction to a bank account
  1845. *
  1846. * @return int <0 if KO, rowid of the line if OK
  1847. */
  1848. public function insert()
  1849. {
  1850. $error = 0;
  1851. $this->db->begin();
  1852. $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank (";
  1853. $sql .= "datec";
  1854. $sql .= ", dateo";
  1855. $sql .= ", datev";
  1856. $sql .= ", label";
  1857. $sql .= ", amount";
  1858. $sql .= ", amount_main_currency";
  1859. $sql .= ", fk_user_author";
  1860. $sql .= ", num_chq";
  1861. $sql .= ", fk_account";
  1862. $sql .= ", fk_type";
  1863. $sql .= ", emetteur,banque";
  1864. $sql .= ", rappro";
  1865. $sql .= ", numero_compte";
  1866. $sql .= ", num_releve";
  1867. $sql .= ") VALUES (";
  1868. $sql .= "'".$this->db->idate($this->datec)."'";
  1869. $sql .= ", '".$this->db->idate($this->dateo)."'";
  1870. $sql .= ", '".$this->db->idate($this->datev)."'";
  1871. $sql .= ", '".$this->db->escape($this->label)."'";
  1872. $sql .= ", ".price2num($this->amount);
  1873. $sql .= ", ".(empty($this->amount_main_currency) ? "NULL" : price2num($this->amount_main_currency));
  1874. $sql .= ", ".($this->fk_user_author > 0 ? ((int) $this->fk_user_author) : "null");
  1875. $sql .= ", ".($this->num_chq ? "'".$this->db->escape($this->num_chq)."'" : "null");
  1876. $sql .= ", '".$this->db->escape($this->fk_account)."'";
  1877. $sql .= ", '".$this->db->escape($this->fk_type)."'";
  1878. $sql .= ", ".($this->emetteur ? "'".$this->db->escape($this->emetteur)."'" : "null");
  1879. $sql .= ", ".($this->bank_chq ? "'".$this->db->escape($this->bank_chq)."'" : "null");
  1880. $sql .= ", ".(int) $this->rappro;
  1881. $sql .= ", ".($this->numero_compte ? "'".$this->db->escape($this->numero_compte)."'" : "''");
  1882. $sql .= ", ".($this->num_releve ? "'".$this->db->escape($this->num_releve)."'" : "null");
  1883. $sql .= ")";
  1884. dol_syslog(get_class($this)."::insert", LOG_DEBUG);
  1885. $resql = $this->db->query($sql);
  1886. if ($resql) {
  1887. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'bank');
  1888. // Actions on extra fields (by external module or standard code)
  1889. $result = $this->insertExtraFields();
  1890. if ($result < 0) {
  1891. $error++;
  1892. }
  1893. } else {
  1894. $error++;
  1895. $this->error = $this->db->lasterror();
  1896. dol_print_error($this->db);
  1897. }
  1898. if (!$error) {
  1899. $this->db->commit();
  1900. return $this->id;
  1901. } else {
  1902. $this->db->rollback();
  1903. return -1 * $error;
  1904. }
  1905. }
  1906. /**
  1907. * Delete bank transaction record
  1908. *
  1909. * @param User|null $user User object that delete
  1910. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  1911. * @return int Return integer <0 if KO, >0 if OK
  1912. */
  1913. public function delete(User $user = null, $notrigger = 0)
  1914. {
  1915. $nbko = 0;
  1916. if ($this->rappro) {
  1917. // Protection to avoid any delete of consolidated lines
  1918. $this->error = "ErrorDeleteNotPossibleLineIsConsolidated";
  1919. return -1;
  1920. }
  1921. $this->db->begin();
  1922. if (!$notrigger) {
  1923. // Call trigger
  1924. $result = $this->call_trigger('BANKACCOUNTLINE_DELETE', $user);
  1925. if ($result < 0) {
  1926. $this->db->rollback();
  1927. return -1;
  1928. }
  1929. // End call triggers
  1930. }
  1931. // Protection to avoid any delete of accounted lines. Protection on by default
  1932. if (!getDolGlobalString('BANK_ALLOW_TRANSACTION_DELETION_EVEN_IF_IN_ACCOUNTING')) {
  1933. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping WHERE doc_type = 'bank' AND fk_doc = ".((int) $this->id);
  1934. $resql = $this->db->query($sql);
  1935. if ($resql) {
  1936. $obj = $this->db->fetch_object($resql);
  1937. if ($obj && $obj->nb) {
  1938. $this->error = 'ErrorRecordAlreadyInAccountingDeletionNotPossible';
  1939. $this->db->rollback();
  1940. return -1;
  1941. }
  1942. } else {
  1943. $this->error = $this->db->lasterror();
  1944. $this->db->rollback();
  1945. return -1;
  1946. }
  1947. }
  1948. // Delete urls
  1949. $result = $this->delete_urls($user);
  1950. if ($result < 0) {
  1951. $nbko++;
  1952. }
  1953. $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid;
  1954. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1955. $result = $this->db->query($sql);
  1956. if (!$result) {
  1957. $nbko++;
  1958. }
  1959. $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_extrafields WHERE fk_object=".(int) $this->rowid;
  1960. $result = $this->db->query($sql);
  1961. if (!$result) {
  1962. $nbko++;
  1963. }
  1964. $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid;
  1965. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  1966. $result = $this->db->query($sql);
  1967. if (!$result) {
  1968. $nbko++;
  1969. }
  1970. if (!$nbko) {
  1971. $this->db->commit();
  1972. return 1;
  1973. } else {
  1974. $this->db->rollback();
  1975. return -$nbko;
  1976. }
  1977. }
  1978. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1979. /**
  1980. * Delete bank line records
  1981. *
  1982. * @param User|null $user User object that delete
  1983. * @return int Return integer <0 if KO, >0 if OK
  1984. */
  1985. public function delete_urls(User $user = null)
  1986. {
  1987. // phpcs:enable
  1988. $nbko = 0;
  1989. if ($this->rappro) {
  1990. // Protection to avoid any delete of consolidated lines
  1991. $this->error = "ErrorDeleteNotPossibleLineIsConsolidated";
  1992. return -1;
  1993. }
  1994. $this->db->begin();
  1995. $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid;
  1996. dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG);
  1997. $result = $this->db->query($sql);
  1998. if (!$result) {
  1999. $nbko++;
  2000. }
  2001. if (!$nbko) {
  2002. $this->db->commit();
  2003. return 1;
  2004. } else {
  2005. $this->db->rollback();
  2006. return -$nbko;
  2007. }
  2008. }
  2009. /**
  2010. * Update bank account record in database
  2011. *
  2012. * @param User $user Object user making update
  2013. * @param int $notrigger 0=Disable all triggers
  2014. * @return int Return integer <0 if KO, >0 if OK
  2015. */
  2016. public function update(User $user, $notrigger = 0)
  2017. {
  2018. $this->db->begin();
  2019. $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
  2020. $sql .= " amount = ".price2num($this->amount).",";
  2021. $sql .= " datev='".$this->db->idate($this->datev)."',";
  2022. $sql .= " dateo='".$this->db->idate($this->dateo)."'";
  2023. $sql .= " WHERE rowid = ".((int) $this->rowid);
  2024. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  2025. $resql = $this->db->query($sql);
  2026. if ($resql) {
  2027. $this->db->commit();
  2028. return 1;
  2029. } else {
  2030. $this->db->rollback();
  2031. $this->error = $this->db->error();
  2032. return -1;
  2033. }
  2034. }
  2035. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2036. /**
  2037. * Update conciliation field
  2038. *
  2039. * @param User $user Objet user making update
  2040. * @param int $cat Category id
  2041. * @param int $conciliated 1=Set transaction to conciliated, 0=Keep transaction non conciliated
  2042. * @return int Return integer <0 if KO, >0 if OK
  2043. */
  2044. public function update_conciliation(User $user, $cat, $conciliated = 1)
  2045. {
  2046. // phpcs:enable
  2047. global $conf, $langs;
  2048. $this->db->begin();
  2049. // Check statement field
  2050. if (getDolGlobalString('BANK_STATEMENT_REGEX_RULE')) {
  2051. if (!preg_match('/' . getDolGlobalString('BANK_STATEMENT_REGEX_RULE').'/', $this->num_releve)) {
  2052. $this->errors[] = $langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE);
  2053. return -1;
  2054. }
  2055. }
  2056. $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
  2057. $sql .= " rappro = ".((int) $conciliated);
  2058. $sql .= ", num_releve = '".$this->db->escape($this->num_releve)."'";
  2059. if ($conciliated) {
  2060. $sql .= ", fk_user_rappro = ".$user->id;
  2061. }
  2062. $sql .= " WHERE rowid = ".((int) $this->id);
  2063. dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG);
  2064. $resql = $this->db->query($sql);
  2065. if ($resql) {
  2066. if (!empty($cat) && $cat > 0) {
  2067. $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class (";
  2068. $sql .= "lineid";
  2069. $sql .= ", fk_categ";
  2070. $sql .= ") VALUES (";
  2071. $sql .= $this->id;
  2072. $sql .= ", ".((int) $cat);
  2073. $sql .= ")";
  2074. dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG);
  2075. $this->db->query($sql);
  2076. // No error check. Can fail if category already affected
  2077. // TODO Do no try the insert if link already exists
  2078. }
  2079. $this->rappro = 1;
  2080. $this->db->commit();
  2081. return 1;
  2082. } else {
  2083. $this->db->rollback();
  2084. return -1;
  2085. }
  2086. }
  2087. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2088. /**
  2089. * Increase/decrease value date of a rowid
  2090. *
  2091. * @param int $rowid Id of line
  2092. * @param int $sign 1 or -1
  2093. * @return int >0 if OK, 0 if KO
  2094. */
  2095. public function datev_change($rowid, $sign = 1)
  2096. {
  2097. // phpcs:enable
  2098. $sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".((int) $rowid);
  2099. $resql = $this->db->query($sql);
  2100. if ($resql) {
  2101. $obj = $this->db->fetch_object($resql);
  2102. $newdate = $this->db->jdate($obj->datev) + (3600 * 24 * $sign);
  2103. $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
  2104. $sql .= " datev = '".$this->db->idate($newdate)."'";
  2105. $sql .= " WHERE rowid = ".((int) $rowid);
  2106. $result = $this->db->query($sql);
  2107. if ($result) {
  2108. if ($this->db->affected_rows($result)) {
  2109. return 1;
  2110. }
  2111. } else {
  2112. dol_print_error($this->db);
  2113. return 0;
  2114. }
  2115. } else {
  2116. dol_print_error($this->db);
  2117. }
  2118. return 0;
  2119. }
  2120. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2121. /**
  2122. * Increase value date of a rowid
  2123. *
  2124. * @param int $id Id of line to change
  2125. * @return int >0 if OK, 0 if KO
  2126. */
  2127. public function datev_next($id)
  2128. {
  2129. // phpcs:enable
  2130. return $this->datev_change($id, 1);
  2131. }
  2132. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2133. /**
  2134. * Decrease value date of a rowid
  2135. *
  2136. * @param int $id Id of line to change
  2137. * @return int >0 if OK, 0 if KO
  2138. */
  2139. public function datev_previous($id)
  2140. {
  2141. // phpcs:enable
  2142. return $this->datev_change($id, -1);
  2143. }
  2144. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2145. /**
  2146. * Increase/decrease operation date of a rowid
  2147. *
  2148. * @param int $rowid Id of line
  2149. * @param int $sign 1 or -1
  2150. * @return int >0 if OK, 0 if KO
  2151. */
  2152. public function dateo_change($rowid, $sign = 1)
  2153. {
  2154. // phpcs:enable
  2155. $sql = "SELECT dateo FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".((int) $rowid);
  2156. $resql = $this->db->query($sql);
  2157. if ($resql) {
  2158. $obj = $this->db->fetch_object($resql);
  2159. $newdate = $this->db->jdate($obj->dateo) + (3600 * 24 * $sign);
  2160. $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
  2161. $sql .= " dateo = '".$this->db->idate($newdate)."'";
  2162. $sql .= " WHERE rowid = ".((int) $rowid);
  2163. $result = $this->db->query($sql);
  2164. if ($result) {
  2165. if ($this->db->affected_rows($result)) {
  2166. return 1;
  2167. }
  2168. } else {
  2169. dol_print_error($this->db);
  2170. return 0;
  2171. }
  2172. } else {
  2173. dol_print_error($this->db);
  2174. }
  2175. return 0;
  2176. }
  2177. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2178. /**
  2179. * Increase operation date of a rowid
  2180. *
  2181. * @param int $id Id of line to change
  2182. * @return int >0 if OK, 0 if KO
  2183. */
  2184. public function dateo_next($id)
  2185. {
  2186. // phpcs:enable
  2187. return $this->dateo_change($id, 1);
  2188. }
  2189. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2190. /**
  2191. * Decrease operation date of a rowid
  2192. *
  2193. * @param int $id Id of line to change
  2194. * @return int >0 if OK, 0 if KO
  2195. */
  2196. public function dateo_previous($id)
  2197. {
  2198. // phpcs:enable
  2199. return $this->dateo_change($id, -1);
  2200. }
  2201. /**
  2202. * Load miscellaneous information for tab "Info"
  2203. *
  2204. * @param int $id Id of object to load
  2205. * @return void
  2206. */
  2207. public function info($id)
  2208. {
  2209. $sql = 'SELECT b.rowid, b.datec, b.tms as datem,';
  2210. $sql .= ' b.fk_user_author, b.fk_user_rappro';
  2211. $sql .= ' FROM '.MAIN_DB_PREFIX.'bank as b';
  2212. $sql .= ' WHERE b.rowid = '.((int) $id);
  2213. $result = $this->db->query($sql);
  2214. if ($result) {
  2215. if ($this->db->num_rows($result)) {
  2216. $obj = $this->db->fetch_object($result);
  2217. $this->id = $obj->rowid;
  2218. $this->user_creation_id = $obj->fk_user_author;
  2219. $this->user_rappro = $obj->fk_user_rappro;
  2220. $this->date_creation = $this->db->jdate($obj->datec);
  2221. $this->date_modification = $this->db->jdate($obj->datem);
  2222. //$this->date_rappro = $obj->daterappro; // Not yet managed
  2223. }
  2224. $this->db->free($result);
  2225. } else {
  2226. dol_print_error($this->db);
  2227. }
  2228. }
  2229. /**
  2230. * Return clickable name (with picto eventually)
  2231. *
  2232. * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto
  2233. * @param int $maxlen Longueur max libelle
  2234. * @param string $option Option ('', 'showall', 'showconciliated', 'showconciliatedandaccounted'). Options may be slow.
  2235. * @param int $notooltip 1=Disable tooltip
  2236. * @return string Chaine avec URL
  2237. */
  2238. public function getNomUrl($withpicto = 0, $maxlen = 0, $option = '', $notooltip = 0)
  2239. {
  2240. global $langs;
  2241. $result = '';
  2242. $label = img_picto('', $this->picto).' <u>'.$langs->trans("BankTransactionLine").'</u>:<br>';
  2243. $label .= '<b>'.$langs->trans("Ref").':</b> '.$this->ref;
  2244. $linkstart = '<a href="'.DOL_URL_ROOT.'/compta/bank/line.php?rowid='.((int) $this->id).'&save_lastsearch_values=1" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
  2245. $linkend = '</a>';
  2246. $result .= $linkstart;
  2247. if ($withpicto) {
  2248. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'account'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  2249. }
  2250. if ($withpicto != 2) {
  2251. $result .= ($this->ref ? $this->ref : $this->id);
  2252. }
  2253. $result .= $linkend;
  2254. if ($option == 'showall' || $option == 'showconciliated' || $option == 'showconciliatedandaccounted') {
  2255. $result .= ' <span class="opacitymedium">(';
  2256. }
  2257. if ($option == 'showall') {
  2258. $result .= $langs->trans("BankAccount").': ';
  2259. $accountstatic = new Account($this->db);
  2260. $accountstatic->id = $this->fk_account;
  2261. $accountstatic->ref = $this->bank_account_ref;
  2262. $accountstatic->label = $this->bank_account_label;
  2263. $result .= $accountstatic->getNomUrl(0).', ';
  2264. }
  2265. if ($option == 'showall' || $option == 'showconciliated' || $option == 'showconciliatedandaccounted') {
  2266. $result .= $langs->trans("BankLineConciliated").': ';
  2267. $result .= yn($this->rappro);
  2268. }
  2269. if (isModEnabled('accounting') && ($option == 'showall' || $option == 'showconciliatedandaccounted')) {
  2270. $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping";
  2271. $sql .= " WHERE doc_type = 'bank' AND fk_doc = ".((int) $this->id);
  2272. $resql = $this->db->query($sql);
  2273. if ($resql) {
  2274. $obj = $this->db->fetch_object($resql);
  2275. if ($obj && $obj->nb) {
  2276. $result .= ' - '.$langs->trans("Accounted").': '.yn(1);
  2277. } else {
  2278. $result .= ' - '.$langs->trans("Accounted").': '.yn(0);
  2279. }
  2280. }
  2281. }
  2282. if ($option == 'showall' || $option == 'showconciliated' || $option == 'showconciliatedandaccounted') {
  2283. $result .= ')</span>';
  2284. }
  2285. return $result;
  2286. }
  2287. /**
  2288. * Return the label of the status
  2289. *
  2290. * @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
  2291. * @return string Label of status
  2292. */
  2293. public function getLibStatut($mode = 0)
  2294. {
  2295. return $this->LibStatut($this->status, $mode);
  2296. }
  2297. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2298. /**
  2299. * Return the label of a given status
  2300. *
  2301. * @param int $status Id status
  2302. * @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
  2303. * @return string Label of status
  2304. */
  2305. public function LibStatut($status, $mode = 0)
  2306. {
  2307. // phpcs:enable
  2308. //global $langs;
  2309. //$langs->load('companies');
  2310. /*
  2311. if ($mode == 0)
  2312. {
  2313. if ($status==0) return $langs->trans("ActivityCeased");
  2314. if ($status==1) return $langs->trans("InActivity");
  2315. }
  2316. if ($mode == 1)
  2317. {
  2318. if ($status==0) return $langs->trans("ActivityCeased");
  2319. if ($status==1) return $langs->trans("InActivity");
  2320. }
  2321. if ($mode == 2)
  2322. {
  2323. if ($status==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
  2324. if ($status==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
  2325. }
  2326. if ($mode == 3)
  2327. {
  2328. if ($status==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
  2329. if ($status==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
  2330. }
  2331. if ($mode == 4)
  2332. {
  2333. if ($status==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
  2334. if ($status==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
  2335. }
  2336. if ($mode == 5)
  2337. {
  2338. if ($status==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
  2339. if ($status==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
  2340. }*/
  2341. return '';
  2342. }
  2343. /**
  2344. * Return if a bank line was dispatched into bookkeeping
  2345. *
  2346. * @return int <0 if KO, 0=no, 1=yes
  2347. */
  2348. public function getVentilExportCompta()
  2349. {
  2350. $alreadydispatched = 0;
  2351. $type = 'bank';
  2352. $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".((int) $this->id);
  2353. $resql = $this->db->query($sql);
  2354. if ($resql) {
  2355. $obj = $this->db->fetch_object($resql);
  2356. if ($obj) {
  2357. $alreadydispatched = $obj->nb;
  2358. }
  2359. } else {
  2360. $this->error = $this->db->lasterror();
  2361. return -1;
  2362. }
  2363. if ($alreadydispatched) {
  2364. return 1;
  2365. }
  2366. return 0;
  2367. }
  2368. }