account.class.php 80 KB

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