bookkeeping.class.php 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071
  1. <?php
  2. /* Copyright (C) 2014-2017 Olivier Geffroy <jeff@jeffinfo.com>
  3. * Copyright (C) 2015-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
  4. * Copyright (C) 2015-2020 Florian Henry <florian.henry@open-concept.pro>
  5. * Copyright (C) 2018-2020 Frédéric France <frederic.france@netlogic.fr>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. /**
  21. * \file htdocs/accountancy/class/bookkeeping.class.php
  22. * \ingroup Accountancy (Double entries)
  23. * \brief File of class to manage Ledger (General Ledger and Subledger)
  24. */
  25. // Class
  26. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php';
  28. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
  29. require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
  30. /**
  31. * Class to manage Ledger (General Ledger and Subledger)
  32. */
  33. class BookKeeping extends CommonObject
  34. {
  35. /**
  36. * @var string Id to identify managed objects
  37. */
  38. public $element = 'accountingbookkeeping';
  39. /**
  40. * @var string Name of table without prefix where object is stored
  41. */
  42. public $table_element = 'accounting_bookkeeping';
  43. /**
  44. * @var int Entity
  45. */
  46. public $entity;
  47. /**
  48. * @var BookKeepingLine[] Lines
  49. */
  50. public $lines = array();
  51. /**
  52. * @var int ID
  53. */
  54. public $id;
  55. /**
  56. * @var string Date of source document, in db date NOT NULL
  57. */
  58. public $doc_date;
  59. /**
  60. * @var int Deadline for payment
  61. */
  62. public $date_lim_reglement;
  63. /**
  64. * @var string doc_type
  65. */
  66. public $doc_type;
  67. /**
  68. * @var string doc_ref
  69. */
  70. public $doc_ref;
  71. /**
  72. * @var int ID
  73. */
  74. public $fk_doc;
  75. /**
  76. * @var int ID
  77. */
  78. public $fk_docdet;
  79. /**
  80. * @var string thirdparty code
  81. */
  82. public $thirdparty_code;
  83. /**
  84. * @var string subledger account
  85. */
  86. public $subledger_account;
  87. /**
  88. * @var string subledger label
  89. */
  90. public $subledger_label;
  91. /**
  92. * @var string doc_type
  93. */
  94. public $numero_compte;
  95. /**
  96. * @var string label compte
  97. */
  98. public $label_compte;
  99. /**
  100. * @var string label operation
  101. */
  102. public $label_operation;
  103. /**
  104. * @var float FEC:Debit
  105. */
  106. public $debit;
  107. /**
  108. * @var float FEC:Credit
  109. */
  110. public $credit;
  111. /**
  112. * @var float FEC:Amount (Not necessary)
  113. * @deprecated No more used (we have info into debit/credit and sens)
  114. */
  115. public $montant;
  116. /**
  117. * @var float FEC:Amount (Not necessary)
  118. * @deprecated No more used (we have info into debit/credit and sens)
  119. */
  120. public $amount;
  121. /**
  122. * @var string FEC:Sens (Not necessary)
  123. */
  124. public $sens;
  125. /**
  126. * @var int ID
  127. */
  128. public $fk_user_author;
  129. /**
  130. * @var string key for import
  131. */
  132. public $import_key;
  133. /**
  134. * @var string code journal
  135. */
  136. public $code_journal;
  137. /**
  138. * @var string label journal
  139. */
  140. public $journal_label;
  141. /**
  142. * @var int accounting transaction id
  143. */
  144. public $piece_num;
  145. /**
  146. * @var BookKeepingLine[] Movement line array
  147. */
  148. public $linesmvt = array();
  149. /**
  150. * @var BookKeepingLine[] export line array
  151. */
  152. public $linesexport = array();
  153. /**
  154. * @var integer|string date of movement validated & lock
  155. */
  156. public $date_validation;
  157. /**
  158. * @var integer|string date of movement who are noticed like exported
  159. */
  160. public $date_export;
  161. /**
  162. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  163. */
  164. public $picto = 'generic';
  165. /**
  166. * @var string[] SQL filter used for check if the bookkeeping record can be created/inserted/modified/deleted (cached)
  167. */
  168. public static $can_modify_bookkeeping_sql_cached;
  169. /**
  170. * Constructor
  171. *
  172. * @param DoliDb $db Database handler
  173. */
  174. public function __construct(DoliDB $db)
  175. {
  176. $this->db = $db;
  177. }
  178. /**
  179. * Create object into database
  180. *
  181. * @param User $user User that creates
  182. * @param bool $notrigger false=launch triggers after, true=disable triggers
  183. * @return int Return integer <0 if KO, Id of created object if OK
  184. */
  185. public function create(User $user, $notrigger = false)
  186. {
  187. global $conf, $langs;
  188. dol_syslog(__METHOD__, LOG_DEBUG);
  189. $error = 0;
  190. // Clean parameters</center>
  191. if (isset($this->doc_type)) {
  192. $this->doc_type = trim($this->doc_type);
  193. }
  194. if (isset($this->doc_ref)) {
  195. $this->doc_ref = trim($this->doc_ref);
  196. }
  197. if (isset($this->fk_doc)) {
  198. $this->fk_doc = (int) $this->fk_doc;
  199. }
  200. if (isset($this->fk_docdet)) {
  201. $this->fk_docdet = (int) $this->fk_docdet;
  202. }
  203. if (isset($this->thirdparty_code)) {
  204. $this->thirdparty_code = trim($this->thirdparty_code);
  205. }
  206. if (isset($this->subledger_account)) {
  207. $this->subledger_account = trim($this->subledger_account);
  208. }
  209. if (isset($this->subledger_label)) {
  210. $this->subledger_label = trim($this->subledger_label);
  211. }
  212. if (isset($this->numero_compte)) {
  213. $this->numero_compte = trim($this->numero_compte);
  214. }
  215. if (isset($this->label_compte)) {
  216. $this->label_compte = trim($this->label_compte);
  217. }
  218. if (isset($this->label_operation)) {
  219. $this->label_operation = trim($this->label_operation);
  220. }
  221. if (isset($this->debit)) {
  222. $this->debit = (float) $this->debit;
  223. }
  224. if (isset($this->credit)) {
  225. $this->credit = (float) $this->credit;
  226. }
  227. if (isset($this->montant)) {
  228. $this->montant = (float) $this->montant;
  229. }
  230. if (isset($this->amount)) {
  231. $this->amount = (float) $this->amount;
  232. }
  233. if (isset($this->sens)) {
  234. $this->sens = trim($this->sens);
  235. }
  236. if (isset($this->import_key)) {
  237. $this->import_key = trim($this->import_key);
  238. }
  239. if (isset($this->code_journal)) {
  240. $this->code_journal = trim($this->code_journal);
  241. }
  242. if (isset($this->journal_label)) {
  243. $this->journal_label = trim($this->journal_label);
  244. }
  245. if (isset($this->piece_num)) {
  246. $this->piece_num = trim($this->piece_num);
  247. }
  248. if (empty($this->debit)) {
  249. $this->debit = 0.0;
  250. }
  251. if (empty($this->credit)) {
  252. $this->credit = 0.0;
  253. }
  254. $result = $this->validBookkeepingDate($this->doc_date);
  255. if ($result < 0) {
  256. return -1;
  257. } elseif ($result == 0) {
  258. if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') == 'blockedonclosed') {
  259. $this->errors[] = $langs->trans('ErrorBookkeepingDocDateIsOnAClosedFiscalPeriod');
  260. } else {
  261. $this->errors[] = $langs->trans('ErrorBookkeepingDocDateNotOnActiveFiscalPeriod');
  262. }
  263. return -1;
  264. }
  265. // Check parameters
  266. if (($this->numero_compte == "") || $this->numero_compte == '-1' || $this->numero_compte == 'NotDefined') {
  267. $langs->loadLangs(array("errors"));
  268. if (in_array($this->doc_type, array('bank', 'expense_report'))) {
  269. $this->errors[] = $langs->trans('ErrorFieldAccountNotDefinedForBankLine', $this->fk_docdet, $this->doc_type);
  270. } else {
  271. //$this->errors[]=$langs->trans('ErrorFieldAccountNotDefinedForInvoiceLine', $this->doc_ref, $this->label_compte);
  272. $mesg = $this->doc_ref.', '.$langs->trans("AccountAccounting").': '.($this->numero_compte != -1 ? $this->numero_compte : $langs->trans("Unknown"));
  273. if ($this->subledger_account && $this->subledger_account != $this->numero_compte) {
  274. $mesg .= ', '.$langs->trans("SubledgerAccount").': '.$this->subledger_account;
  275. }
  276. $this->errors[] = $langs->trans('ErrorFieldAccountNotDefinedForLine', $mesg);
  277. }
  278. return -1;
  279. }
  280. $this->db->begin();
  281. $this->piece_num = 0;
  282. // First check if line not yet already in bookkeeping.
  283. // Note that we must include 'doc_type - fk_doc - numero_compte - label' to be sure to have unicity of line (because we may have several lines
  284. // with same doc_type, fk_doc, numero_compte for 1 invoice line when using localtaxes with same account)
  285. // WARNING: This is not reliable, label may have been modified. This is just a small protection.
  286. // The page that make transfer make the test on couple (doc_type - fk_doc) only.
  287. $sql = "SELECT count(*) as nb";
  288. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  289. $sql .= " WHERE doc_type = '".$this->db->escape($this->doc_type)."'";
  290. $sql .= " AND fk_doc = ".((int) $this->fk_doc);
  291. if (getDolGlobalString('ACCOUNTANCY_ENABLE_FKDOCDET')) {
  292. // DO NOT USE THIS IN PRODUCTION. This will generate a lot of trouble into reports and will corrupt database (by generating duplicate entries.
  293. $sql .= " AND fk_docdet = ".((int) $this->fk_docdet); // This field can be 0 if record is for several lines
  294. }
  295. $sql .= " AND numero_compte = '".$this->db->escape($this->numero_compte)."'";
  296. $sql .= " AND label_operation = '".$this->db->escape($this->label_operation)."'";
  297. $sql .= " AND entity = ".$conf->entity; // Do not use getEntity for accounting features
  298. $resql = $this->db->query($sql);
  299. if ($resql) {
  300. $row = $this->db->fetch_object($resql);
  301. if ($row->nb == 0) { // Not already into bookkeeping
  302. // Check to know if piece_num already exists for data we try to insert to reuse the same value
  303. $sqlnum = "SELECT piece_num";
  304. $sqlnum .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  305. $sqlnum .= " WHERE doc_type = '".$this->db->escape($this->doc_type)."'"; // For example doc_type = 'bank'
  306. $sqlnum .= " AND fk_doc = ".((int) $this->fk_doc);
  307. if (getDolGlobalString('ACCOUNTANCY_ENABLE_FKDOCDET')) {
  308. // fk_docdet is rowid into llx_bank or llx_facturedet or llx_facturefourndet, or ...
  309. $sqlnum .= " AND fk_docdet = ".((int) $this->fk_docdet);
  310. }
  311. $sqlnum .= " AND doc_ref = '".$this->db->escape($this->doc_ref)."'"; // ref of source object
  312. $sqlnum .= " AND entity = ".$conf->entity; // Do not use getEntity for accounting features
  313. dol_syslog(get_class($this).":: create sqlnum=".$sqlnum, LOG_DEBUG);
  314. $resqlnum = $this->db->query($sqlnum);
  315. if ($resqlnum) {
  316. $objnum = $this->db->fetch_object($resqlnum);
  317. $this->piece_num = $objnum->piece_num;
  318. }
  319. dol_syslog(get_class($this)."::create this->piece_num=".$this->piece_num, LOG_DEBUG);
  320. if (empty($this->piece_num)) {
  321. $sqlnum = "SELECT MAX(piece_num)+1 as maxpiecenum";
  322. $sqlnum .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  323. $sqlnum .= " WHERE entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  324. $resqlnum = $this->db->query($sqlnum);
  325. if ($resqlnum) {
  326. $objnum = $this->db->fetch_object($resqlnum);
  327. $this->piece_num = $objnum->maxpiecenum;
  328. }
  329. dol_syslog(get_class($this).":: create now this->piece_num=".$this->piece_num, LOG_DEBUG);
  330. }
  331. if (empty($this->piece_num)) {
  332. $this->piece_num = 1;
  333. }
  334. $now = dol_now();
  335. $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
  336. $sql .= "doc_date";
  337. $sql .= ", date_lim_reglement";
  338. $sql .= ", doc_type";
  339. $sql .= ", doc_ref";
  340. $sql .= ", fk_doc";
  341. $sql .= ", fk_docdet";
  342. $sql .= ", thirdparty_code";
  343. $sql .= ", subledger_account";
  344. $sql .= ", subledger_label";
  345. $sql .= ", numero_compte";
  346. $sql .= ", label_compte";
  347. $sql .= ", label_operation";
  348. $sql .= ", debit";
  349. $sql .= ", credit";
  350. $sql .= ", montant";
  351. $sql .= ", sens";
  352. $sql .= ", fk_user_author";
  353. $sql .= ", date_creation";
  354. $sql .= ", code_journal";
  355. $sql .= ", journal_label";
  356. $sql .= ", piece_num";
  357. $sql .= ', entity';
  358. $sql .= ") VALUES (";
  359. $sql .= "'".$this->db->idate($this->doc_date)."'";
  360. $sql .= ", ".(!isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'".$this->db->idate($this->date_lim_reglement)."'");
  361. $sql .= ", '".$this->db->escape($this->doc_type)."'";
  362. $sql .= ", '".$this->db->escape($this->doc_ref)."'";
  363. $sql .= ", ".((int) $this->fk_doc);
  364. $sql .= ", ".((int) $this->fk_docdet);
  365. $sql .= ", ".(!empty($this->thirdparty_code) ? ("'".$this->db->escape($this->thirdparty_code)."'") : "NULL");
  366. $sql .= ", ".(!empty($this->subledger_account) ? ("'".$this->db->escape($this->subledger_account)."'") : "NULL");
  367. $sql .= ", ".(!empty($this->subledger_label) ? ("'".$this->db->escape($this->subledger_label)."'") : "NULL");
  368. $sql .= ", '".$this->db->escape($this->numero_compte)."'";
  369. $sql .= ", ".(!empty($this->label_compte) ? ("'".$this->db->escape($this->label_compte)."'") : "NULL");
  370. $sql .= ", '".$this->db->escape($this->label_operation)."'";
  371. $sql .= ", ".((float) $this->debit);
  372. $sql .= ", ".((float) $this->credit);
  373. $sql .= ", ".((float) $this->montant);
  374. $sql .= ", ".(!empty($this->sens) ? ("'".$this->db->escape($this->sens)."'") : "NULL");
  375. $sql .= ", '".$this->db->escape($this->fk_user_author)."'";
  376. $sql .= ", '".$this->db->idate($now)."'";
  377. $sql .= ", '".$this->db->escape($this->code_journal)."'";
  378. $sql .= ", ".(!empty($this->journal_label) ? ("'".$this->db->escape($this->journal_label)."'") : "NULL");
  379. $sql .= ", ".((int) $this->piece_num);
  380. $sql .= ", ".(!isset($this->entity) ? $conf->entity : $this->entity);
  381. $sql .= ")";
  382. $resql = $this->db->query($sql);
  383. if ($resql) {
  384. $id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
  385. if ($id > 0) {
  386. $this->id = $id;
  387. $result = 0;
  388. } else {
  389. $result = -2;
  390. $error++;
  391. $this->errors[] = 'Error Create Error '.$result.' lecture ID';
  392. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  393. }
  394. } else {
  395. $result = -1;
  396. $error++;
  397. $this->errors[] = 'Error '.$this->db->lasterror();
  398. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  399. }
  400. } else { // Already exists
  401. $result = -3;
  402. $error++;
  403. $this->error = 'BookkeepingRecordAlreadyExists';
  404. dol_syslog(__METHOD__.' '.$this->error, LOG_WARNING);
  405. }
  406. } else {
  407. $result = -5;
  408. $error++;
  409. $this->errors[] = 'Error '.$this->db->lasterror();
  410. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  411. }
  412. // Uncomment this and change MYOBJECT to your own tag if you
  413. // want this action to call a trigger.
  414. //if (! $error && ! $notrigger) {
  415. // // Call triggers
  416. // $result=$this->call_trigger('MYOBJECT_CREATE',$user);
  417. // if ($result < 0) $error++;
  418. // // End call triggers
  419. //}
  420. // Commit or rollback
  421. if ($error) {
  422. $this->db->rollback();
  423. return -1 * $error;
  424. } else {
  425. $this->db->commit();
  426. return $result;
  427. }
  428. }
  429. /**
  430. * Return a link to the object card (with optionally the picto)
  431. *
  432. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  433. * @param string $option On what the link point to ('nolink', ...)
  434. * @param int $notooltip 1=Disable tooltip
  435. * @param string $morecss Add more css on link
  436. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  437. * @return string String with URL
  438. */
  439. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  440. {
  441. global $db, $conf, $langs;
  442. global $dolibarr_main_authentication, $dolibarr_main_demo;
  443. global $menumanager, $hookmanager;
  444. if (!empty($conf->dol_no_mouse_hover)) {
  445. $notooltip = 1; // Force disable tooltips
  446. }
  447. $result = '';
  448. $companylink = '';
  449. $label = '<u>'.$langs->trans("Transaction").'</u>';
  450. $label .= '<br>';
  451. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->piece_num;
  452. $url = DOL_URL_ROOT.'/accountancy/bookkeeping/card.php?piece_num='.$this->piece_num;
  453. if ($option != 'nolink') {
  454. // Add param to save lastsearch_values or not
  455. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  456. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  457. $add_save_lastsearch_values = 1;
  458. }
  459. if ($add_save_lastsearch_values) {
  460. $url .= '&save_lastsearch_values=1';
  461. }
  462. }
  463. $linkclose = '';
  464. if (empty($notooltip)) {
  465. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  466. $label = $langs->trans("ShowTransaction");
  467. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  468. }
  469. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  470. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  471. } else {
  472. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  473. }
  474. $linkstart = '<a href="'.$url.'"';
  475. $linkstart .= $linkclose.'>';
  476. $linkend = '</a>';
  477. $result .= $linkstart;
  478. if ($withpicto) {
  479. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  480. }
  481. if ($withpicto != 2) {
  482. $result .= $this->piece_num;
  483. }
  484. $result .= $linkend;
  485. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  486. global $action;
  487. $hookmanager->initHooks(array($this->element . 'dao'));
  488. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  489. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  490. if ($reshook > 0) {
  491. $result = $hookmanager->resPrint;
  492. } else {
  493. $result .= $hookmanager->resPrint;
  494. }
  495. return $result;
  496. }
  497. /**
  498. * Create object into database
  499. *
  500. * @param User $user User that creates
  501. * @param bool $notrigger false=launch triggers after, true=disable triggers
  502. * @param string $mode Mode
  503. * @return int Return integer <0 if KO, Id of created object if OK
  504. */
  505. public function createStd(User $user, $notrigger = false, $mode = '')
  506. {
  507. global $conf, $langs;
  508. $langs->loadLangs(array("accountancy", "bills", "compta"));
  509. dol_syslog(__METHOD__, LOG_DEBUG);
  510. $error = 0;
  511. // Clean parameters
  512. if (isset($this->doc_type)) {
  513. $this->doc_type = trim($this->doc_type);
  514. }
  515. if (isset($this->doc_ref)) {
  516. $this->doc_ref = trim($this->doc_ref);
  517. }
  518. if (isset($this->fk_doc)) {
  519. $this->fk_doc = (int) $this->fk_doc;
  520. }
  521. if (isset($this->fk_docdet)) {
  522. $this->fk_docdet = (int) $this->fk_docdet;
  523. }
  524. if (isset($this->thirdparty_code)) {
  525. $this->thirdparty_code = trim($this->thirdparty_code);
  526. }
  527. if (isset($this->subledger_account)) {
  528. $this->subledger_account = trim($this->subledger_account);
  529. }
  530. if (isset($this->subledger_label)) {
  531. $this->subledger_label = trim($this->subledger_label);
  532. }
  533. if (isset($this->numero_compte)) {
  534. $this->numero_compte = trim($this->numero_compte);
  535. }
  536. if (isset($this->label_compte)) {
  537. $this->label_compte = trim($this->label_compte);
  538. }
  539. if (isset($this->label_operation)) {
  540. $this->label_operation = trim($this->label_operation);
  541. }
  542. if (isset($this->debit)) {
  543. $this->debit = trim($this->debit);
  544. }
  545. if (isset($this->credit)) {
  546. $this->credit = trim($this->credit);
  547. }
  548. if (isset($this->montant)) {
  549. $this->montant = trim($this->montant);
  550. }
  551. if (isset($this->amount)) {
  552. $this->amount = trim($this->amount);
  553. }
  554. if (isset($this->sens)) {
  555. $this->sens = trim($this->sens);
  556. }
  557. if (isset($this->import_key)) {
  558. $this->import_key = trim($this->import_key);
  559. }
  560. if (isset($this->code_journal)) {
  561. $this->code_journal = trim($this->code_journal);
  562. }
  563. if (isset($this->journal_label)) {
  564. $this->journal_label = trim($this->journal_label);
  565. }
  566. if (isset($this->piece_num)) {
  567. $this->piece_num = trim($this->piece_num);
  568. }
  569. if (empty($this->debit)) {
  570. $this->debit = 0;
  571. }
  572. if (empty($this->credit)) {
  573. $this->credit = 0;
  574. }
  575. if (empty($this->montant)) {
  576. $this->montant = 0;
  577. }
  578. $result = $this->validBookkeepingDate($this->doc_date);
  579. if ($result < 0) {
  580. return -1;
  581. } elseif ($result == 0) {
  582. if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') == 'blockedonclosed') {
  583. $this->errors[] = $langs->trans('ErrorBookkeepingDocDateIsOnAClosedFiscalPeriod');
  584. } else {
  585. $this->errors[] = $langs->trans('ErrorBookkeepingDocDateNotOnActiveFiscalPeriod');
  586. }
  587. return -1;
  588. }
  589. $this->debit = price2num($this->debit, 'MT');
  590. $this->credit = price2num($this->credit, 'MT');
  591. $this->montant = price2num($this->montant, 'MT');
  592. $now = dol_now();
  593. // Check parameters
  594. $this->journal_label = $langs->trans($this->journal_label);
  595. // Insert request
  596. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.$mode.' (';
  597. $sql .= 'doc_date,';
  598. $sql .= 'date_lim_reglement,';
  599. $sql .= 'doc_type,';
  600. $sql .= 'doc_ref,';
  601. $sql .= 'fk_doc,';
  602. $sql .= 'fk_docdet,';
  603. $sql .= 'thirdparty_code,';
  604. $sql .= 'subledger_account,';
  605. $sql .= 'subledger_label,';
  606. $sql .= 'numero_compte,';
  607. $sql .= 'label_compte,';
  608. $sql .= 'label_operation,';
  609. $sql .= 'debit,';
  610. $sql .= 'credit,';
  611. $sql .= 'montant,';
  612. $sql .= 'sens,';
  613. $sql .= 'fk_user_author,';
  614. $sql .= 'date_creation,';
  615. $sql .= 'code_journal,';
  616. $sql .= 'journal_label,';
  617. $sql .= 'piece_num,';
  618. $sql .= 'entity';
  619. $sql .= ') VALUES (';
  620. $sql .= ' '.(!isset($this->doc_date) || dol_strlen($this->doc_date) == 0 ? 'NULL' : "'".$this->db->idate($this->doc_date)."'").',';
  621. $sql .= ' '.(!isset($this->date_lim_reglement) || dol_strlen($this->date_lim_reglement) == 0 ? 'NULL' : "'".$this->db->idate($this->date_lim_reglement)."'").',';
  622. $sql .= ' '.(!isset($this->doc_type) ? 'NULL' : "'".$this->db->escape($this->doc_type)."'").',';
  623. $sql .= ' '.(!isset($this->doc_ref) ? 'NULL' : "'".$this->db->escape($this->doc_ref)."'").',';
  624. $sql .= ' '.(empty($this->fk_doc) ? '0' : (int) $this->fk_doc).',';
  625. $sql .= ' '.(empty($this->fk_docdet) ? '0' : (int) $this->fk_docdet).',';
  626. $sql .= ' '.(!isset($this->thirdparty_code) ? 'NULL' : "'".$this->db->escape($this->thirdparty_code)."'").',';
  627. $sql .= ' '.(!isset($this->subledger_account) ? 'NULL' : "'".$this->db->escape($this->subledger_account)."'").',';
  628. $sql .= ' '.(!isset($this->subledger_label) ? 'NULL' : "'".$this->db->escape($this->subledger_label)."'").',';
  629. $sql .= ' '.(!isset($this->numero_compte) ? 'NULL' : "'".$this->db->escape($this->numero_compte)."'").',';
  630. $sql .= ' '.(!isset($this->label_compte) ? 'NULL' : "'".$this->db->escape($this->label_compte)."'").',';
  631. $sql .= ' '.(!isset($this->label_operation) ? 'NULL' : "'".$this->db->escape($this->label_operation)."'").',';
  632. $sql .= ' '.(!isset($this->debit) ? 'NULL' : $this->debit).',';
  633. $sql .= ' '.(!isset($this->credit) ? 'NULL' : $this->credit).',';
  634. $sql .= ' '.(!isset($this->montant) ? 'NULL' : $this->montant).',';
  635. $sql .= ' '.(!isset($this->sens) ? 'NULL' : "'".$this->db->escape($this->sens)."'").',';
  636. $sql .= ' '.((int) $user->id).',';
  637. $sql .= ' '."'".$this->db->idate($now)."',";
  638. $sql .= ' '.(empty($this->code_journal) ? 'NULL' : "'".$this->db->escape($this->code_journal)."'").',';
  639. $sql .= ' '.(empty($this->journal_label) ? 'NULL' : "'".$this->db->escape($this->journal_label)."'").',';
  640. $sql .= ' '.(empty($this->piece_num) ? 'NULL' : $this->db->escape($this->piece_num)).',';
  641. $sql .= ' '.(!isset($this->entity) ? $conf->entity : $this->entity);
  642. $sql .= ')';
  643. $this->db->begin();
  644. $resql = $this->db->query($sql);
  645. if (!$resql) {
  646. $error++;
  647. $this->errors[] = 'Error '.$this->db->lasterror();
  648. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  649. }
  650. if (!$error) {
  651. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element.$mode);
  652. // Uncomment this and change MYOBJECT to your own tag if you
  653. // want this action to call a trigger.
  654. //if (! $notrigger) {
  655. // // Call triggers
  656. // $result=$this->call_trigger('MYOBJECT_CREATE',$user);
  657. // if ($result < 0) $error++;
  658. // // End call triggers
  659. //}
  660. }
  661. // Commit or rollback
  662. if ($error) {
  663. $this->db->rollback();
  664. return -1 * $error;
  665. } else {
  666. $this->db->commit();
  667. return $this->id;
  668. }
  669. }
  670. /**
  671. * Load object in memory from the database
  672. *
  673. * @param int $id Id object
  674. * @param string $ref Ref
  675. * @param string $mode Mode
  676. *
  677. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  678. */
  679. public function fetch($id, $ref = null, $mode = '')
  680. {
  681. global $conf;
  682. dol_syslog(__METHOD__, LOG_DEBUG);
  683. $sql = 'SELECT';
  684. $sql .= ' t.rowid,';
  685. $sql .= " t.doc_date,";
  686. $sql .= " t.date_lim_reglement,";
  687. $sql .= " t.doc_type,";
  688. $sql .= " t.doc_ref,";
  689. $sql .= " t.fk_doc,";
  690. $sql .= " t.fk_docdet,";
  691. $sql .= " t.thirdparty_code,";
  692. $sql .= " t.subledger_account,";
  693. $sql .= " t.subledger_label,";
  694. $sql .= " t.numero_compte,";
  695. $sql .= " t.label_compte,";
  696. $sql .= " t.label_operation,";
  697. $sql .= " t.debit,";
  698. $sql .= " t.credit,";
  699. $sql .= " t.montant as amount,";
  700. $sql .= " t.sens,";
  701. $sql .= " t.fk_user_author,";
  702. $sql .= " t.import_key,";
  703. $sql .= " t.code_journal,";
  704. $sql .= " t.journal_label,";
  705. $sql .= " t.piece_num,";
  706. $sql .= " t.date_creation,";
  707. // In llx_accounting_bookkeeping_tmp, field date_export doesn't exist
  708. if ($mode != "_tmp") {
  709. $sql .= " t.date_export,";
  710. }
  711. $sql .= " t.date_validated as date_validation";
  712. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.$mode.' as t';
  713. $sql .= ' WHERE 1 = 1';
  714. $sql .= " AND entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  715. if (null !== $ref) {
  716. $sql .= " AND t.rowid = ".((int) $ref);
  717. } else {
  718. $sql .= " AND t.rowid = ".((int) $id);
  719. }
  720. $resql = $this->db->query($sql);
  721. if ($resql) {
  722. $numrows = $this->db->num_rows($resql);
  723. if ($numrows) {
  724. $obj = $this->db->fetch_object($resql);
  725. $this->id = $obj->rowid;
  726. $this->doc_date = $this->db->jdate($obj->doc_date);
  727. $this->date_lim_reglement = $this->db->jdate($obj->date_lim_reglement);
  728. $this->doc_type = $obj->doc_type;
  729. $this->doc_ref = $obj->doc_ref;
  730. $this->fk_doc = $obj->fk_doc;
  731. $this->fk_docdet = $obj->fk_docdet;
  732. $this->thirdparty_code = $obj->thirdparty_code;
  733. $this->subledger_account = $obj->subledger_account;
  734. $this->subledger_label = $obj->subledger_label;
  735. $this->numero_compte = $obj->numero_compte;
  736. $this->label_compte = $obj->label_compte;
  737. $this->label_operation = $obj->label_operation;
  738. $this->debit = $obj->debit;
  739. $this->credit = $obj->credit;
  740. $this->montant = $obj->amount;
  741. $this->amount = $obj->amount;
  742. $this->sens = $obj->sens;
  743. $this->fk_user_author = $obj->fk_user_author;
  744. $this->import_key = $obj->import_key;
  745. $this->code_journal = $obj->code_journal;
  746. $this->journal_label = $obj->journal_label;
  747. $this->piece_num = $obj->piece_num;
  748. $this->date_creation = $this->db->jdate($obj->date_creation);
  749. $this->date_export = $this->db->jdate($obj->date_export);
  750. $this->date_validation = isset($obj->date_validation) ? $this->db->jdate($obj->date_validation) : '';
  751. }
  752. $this->db->free($resql);
  753. if ($numrows) {
  754. return 1;
  755. } else {
  756. return 0;
  757. }
  758. } else {
  759. $this->errors[] = 'Error '.$this->db->lasterror();
  760. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  761. return -1;
  762. }
  763. }
  764. /**
  765. * Load object in memory from the database in ->lines. Or just make a simple count if $countonly=1.
  766. *
  767. * @param string $sortorder Sort Order
  768. * @param string $sortfield Sort field
  769. * @param int $limit offset limit
  770. * @param int $offset offset limit
  771. * @param array $filter filter array
  772. * @param string $filtermode filter mode (AND or OR)
  773. * @param int $option option (0: general account or 1: subaccount)
  774. * @param int $countonly Do not fill the $object->lines, return only the count.
  775. * @return int Return integer <0 if KO, Number of lines if OK
  776. */
  777. public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $option = 0, $countonly = 0)
  778. {
  779. global $conf;
  780. dol_syslog(__METHOD__, LOG_DEBUG);
  781. $this->lines = array();
  782. $num = 0;
  783. $sql = 'SELECT';
  784. if ($countonly) {
  785. $sql .= ' COUNT(t.rowid) as nb';
  786. } else {
  787. $sql .= ' t.rowid,';
  788. $sql .= " t.doc_date,";
  789. $sql .= " t.doc_type,";
  790. $sql .= " t.doc_ref,";
  791. $sql .= " t.fk_doc,";
  792. $sql .= " t.fk_docdet,";
  793. $sql .= " t.thirdparty_code,";
  794. $sql .= " t.subledger_account,";
  795. $sql .= " t.subledger_label,";
  796. $sql .= " t.numero_compte,";
  797. $sql .= " t.label_compte,";
  798. $sql .= " t.label_operation,";
  799. $sql .= " t.debit,";
  800. $sql .= " t.credit,";
  801. $sql .= " t.montant as amount,";
  802. $sql .= " t.sens,";
  803. $sql .= " t.multicurrency_amount,";
  804. $sql .= " t.multicurrency_code,";
  805. $sql .= " t.lettering_code,";
  806. $sql .= " t.date_lettering,";
  807. $sql .= " t.fk_user_author,";
  808. $sql .= " t.import_key,";
  809. $sql .= " t.code_journal,";
  810. $sql .= " t.journal_label,";
  811. $sql .= " t.piece_num,";
  812. $sql .= " t.date_creation,";
  813. $sql .= " t.date_export,";
  814. $sql .= " t.date_validated as date_validation,";
  815. $sql .= " t.import_key";
  816. }
  817. // Manage filter
  818. $sqlwhere = array();
  819. if (count($filter) > 0) {
  820. foreach ($filter as $key => $value) {
  821. if ($key == 't.doc_date') {
  822. $sqlwhere[] = $key.'=\''.$this->db->idate($value).'\'';
  823. } elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') {
  824. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  825. } elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') {
  826. $sqlwhere[] = $key.'\''.$this->db->escape($value).'\'';
  827. } elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') {
  828. $sqlwhere[] = $key.'='.$value;
  829. } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') {
  830. $sqlwhere[] = $key.' LIKE \''.$this->db->escape($this->db->escapeforlike($value)).'%\'';
  831. } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') {
  832. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  833. } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') {
  834. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  835. } elseif ($key == 't.date_validated>=' || $key == 't.date_validated<=') {
  836. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  837. } elseif ($key == 't.credit' || $key == 't.debit') {
  838. $sqlwhere[] = natural_search($key, $value, 1, 1);
  839. } elseif ($key == 't.reconciled_option') {
  840. $sqlwhere[] = 't.lettering_code IS NULL';
  841. } elseif ($key == 't.code_journal' && !empty($value)) {
  842. if (is_array($value)) {
  843. $sqlwhere[] = natural_search("t.code_journal", join(',', $value), 3, 1);
  844. } else {
  845. $sqlwhere[] = natural_search("t.code_journal", $value, 3, 1);
  846. }
  847. } elseif ($key == 't.search_accounting_code_in' && !empty($value)) {
  848. $sqlwhere[] = 't.numero_compte IN ('.$this->db->sanitize($value, 1).')';
  849. } else {
  850. $sqlwhere[] = natural_search($key, $value, 0, 1);
  851. }
  852. }
  853. }
  854. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  855. $sql .= ' WHERE entity = ' . ((int) $conf->entity); // Do not use getEntity for accounting features
  856. if (count($sqlwhere) > 0) {
  857. $sql .= " AND ".implode(" ".$filtermode." ", $sqlwhere);
  858. }
  859. // Filter by ledger account or subledger account
  860. if (!empty($option)) {
  861. $sql .= " AND t.subledger_account IS NOT NULL";
  862. $sql .= " AND t.subledger_account <> ''";
  863. $sortfield = 't.subledger_account'.($sortfield ? ','.$sortfield : '');
  864. $sortorder = 'ASC'.($sortfield ? ','.$sortfield : '');
  865. } else {
  866. $sortfield = 't.numero_compte'.($sortfield ? ','.$sortfield : '');
  867. $sortorder = 'ASC'.($sortorder ? ','.$sortorder : '');
  868. }
  869. if (!$countonly) {
  870. $sql .= $this->db->order($sortfield, $sortorder);
  871. if (!empty($limit)) {
  872. $sql .= $this->db->plimit($limit + 1, $offset);
  873. }
  874. }
  875. $resql = $this->db->query($sql);
  876. if ($resql) {
  877. if ($countonly) {
  878. $obj = $this->db->fetch_object($resql);
  879. if ($obj) {
  880. $num = $obj->nb;
  881. }
  882. } else {
  883. $num = $this->db->num_rows($resql);
  884. $i = 0;
  885. while (($obj = $this->db->fetch_object($resql)) && (empty($limit) || $i < min($limit, $num))) {
  886. $line = new BookKeepingLine();
  887. $line->id = $obj->rowid;
  888. $line->doc_date = $this->db->jdate($obj->doc_date);
  889. $line->doc_type = $obj->doc_type;
  890. $line->doc_ref = $obj->doc_ref;
  891. $line->fk_doc = $obj->fk_doc;
  892. $line->fk_docdet = $obj->fk_docdet;
  893. $line->thirdparty_code = $obj->thirdparty_code;
  894. $line->subledger_account = $obj->subledger_account;
  895. $line->subledger_label = $obj->subledger_label;
  896. $line->numero_compte = $obj->numero_compte;
  897. $line->label_compte = $obj->label_compte;
  898. $line->label_operation = $obj->label_operation;
  899. $line->debit = $obj->debit;
  900. $line->credit = $obj->credit;
  901. $line->montant = $obj->amount; // deprecated
  902. $line->amount = $obj->amount;
  903. $line->sens = $obj->sens;
  904. $line->multicurrency_amount = $obj->multicurrency_amount;
  905. $line->multicurrency_code = $obj->multicurrency_code;
  906. $line->lettering_code = $obj->lettering_code;
  907. $line->date_lettering = $obj->date_lettering;
  908. $line->fk_user_author = $obj->fk_user_author;
  909. $line->import_key = $obj->import_key;
  910. $line->code_journal = $obj->code_journal;
  911. $line->journal_label = $obj->journal_label;
  912. $line->piece_num = $obj->piece_num;
  913. $line->date_creation = $this->db->jdate($obj->date_creation);
  914. $line->date_export = $this->db->jdate($obj->date_export);
  915. $line->date_validation = $this->db->jdate($obj->date_validation);
  916. $line->import_key = $obj->import_key;
  917. $this->lines[] = $line;
  918. $i++;
  919. }
  920. }
  921. $this->db->free($resql);
  922. return $num;
  923. } else {
  924. $this->errors[] = 'Error '.$this->db->lasterror();
  925. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  926. return -1;
  927. }
  928. }
  929. /**
  930. * Load object in memory from the database
  931. *
  932. * @param string $sortorder Sort Order
  933. * @param string $sortfield Sort field
  934. * @param int $limit Offset limit
  935. * @param int $offset Offset limit
  936. * @param array $filter Filter array
  937. * @param string $filtermode Filter mode (AND or OR)
  938. * @param int $showAlreadyExportMovements Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default))
  939. * @return int Return integer <0 if KO, >0 if OK
  940. */
  941. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1)
  942. {
  943. global $conf;
  944. dol_syslog(__METHOD__, LOG_DEBUG);
  945. $sql = 'SELECT';
  946. $sql .= ' t.rowid,';
  947. $sql .= " t.doc_date,";
  948. $sql .= " t.doc_type,";
  949. $sql .= " t.doc_ref,";
  950. $sql .= " t.fk_doc,";
  951. $sql .= " t.fk_docdet,";
  952. $sql .= " t.thirdparty_code,";
  953. $sql .= " t.subledger_account,";
  954. $sql .= " t.subledger_label,";
  955. $sql .= " t.numero_compte,";
  956. $sql .= " t.label_compte,";
  957. $sql .= " t.label_operation,";
  958. $sql .= " t.debit,";
  959. $sql .= " t.credit,";
  960. $sql .= " t.lettering_code,";
  961. $sql .= " t.date_lettering,";
  962. $sql .= " t.montant as amount,";
  963. $sql .= " t.sens,";
  964. $sql .= " t.fk_user_author,";
  965. $sql .= " t.import_key,";
  966. $sql .= " t.code_journal,";
  967. $sql .= " t.journal_label,";
  968. $sql .= " t.piece_num,";
  969. $sql .= " t.date_creation,";
  970. $sql .= " t.date_lim_reglement,";
  971. $sql .= " t.tms as date_modification,";
  972. $sql .= " t.date_export,";
  973. $sql .= " t.date_validated as date_validation";
  974. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  975. // Manage filter
  976. $sqlwhere = array();
  977. if (count($filter) > 0) {
  978. foreach ($filter as $key => $value) {
  979. if ($key == 't.doc_date') {
  980. $sqlwhere[] = $key.'=\''.$this->db->idate($value).'\'';
  981. } elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=') {
  982. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  983. } elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') {
  984. $sqlwhere[] = $key.'\''.$this->db->escape($value).'\'';
  985. } elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') {
  986. $sqlwhere[] = $key.'='.((int) $value);
  987. } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') {
  988. $sqlwhere[] = $key.' LIKE \''.$this->db->escape($value).'%\'';
  989. } elseif ($key == 't.date_creation>=' || $key == 't.date_creation<=') {
  990. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  991. } elseif ($key == 't.tms>=' || $key == 't.tms<=') {
  992. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  993. } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') {
  994. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  995. } elseif ($key == 't.date_validated>=' || $key == 't.date_validated<=') {
  996. $sqlwhere[] = $key.'\''.$this->db->idate($value).'\'';
  997. } elseif ($key == 't.credit' || $key == 't.debit') {
  998. $sqlwhere[] = natural_search($key, $value, 1, 1);
  999. } elseif ($key == 't.code_journal' && !empty($value)) {
  1000. if (is_array($value)) {
  1001. $sqlwhere[] = natural_search("t.code_journal", join(',', $value), 3, 1);
  1002. } else {
  1003. $sqlwhere[] = natural_search("t.code_journal", $value, 3, 1);
  1004. }
  1005. } else {
  1006. $sqlwhere[] = natural_search($key, $value, 0, 1);
  1007. }
  1008. }
  1009. }
  1010. $sql .= ' WHERE t.entity = ' . ((int) $conf->entity); // Do not use getEntity for accounting features
  1011. if ($showAlreadyExportMovements == 0) {
  1012. $sql .= " AND t.date_export IS NULL";
  1013. }
  1014. if (count($sqlwhere) > 0) {
  1015. $sql .= ' AND '.implode(" ".$filtermode." ", $sqlwhere);
  1016. }
  1017. if (!empty($sortfield)) {
  1018. $sql .= $this->db->order($sortfield, $sortorder);
  1019. }
  1020. if (!empty($limit)) {
  1021. $sql .= $this->db->plimit($limit + 1, $offset);
  1022. }
  1023. $this->lines = array();
  1024. $resql = $this->db->query($sql);
  1025. if ($resql) {
  1026. $num = $this->db->num_rows($resql);
  1027. $i = 0;
  1028. while (($obj = $this->db->fetch_object($resql)) && (empty($limit) || $i < min($limit, $num))) {
  1029. $line = new BookKeepingLine();
  1030. $line->id = $obj->rowid;
  1031. $line->doc_date = $this->db->jdate($obj->doc_date);
  1032. $line->doc_type = $obj->doc_type;
  1033. $line->doc_ref = $obj->doc_ref;
  1034. $line->fk_doc = $obj->fk_doc;
  1035. $line->fk_docdet = $obj->fk_docdet;
  1036. $line->thirdparty_code = $obj->thirdparty_code;
  1037. $line->subledger_account = $obj->subledger_account;
  1038. $line->subledger_label = $obj->subledger_label;
  1039. $line->numero_compte = $obj->numero_compte;
  1040. $line->label_compte = $obj->label_compte;
  1041. $line->label_operation = $obj->label_operation;
  1042. $line->debit = $obj->debit;
  1043. $line->credit = $obj->credit;
  1044. $line->montant = $obj->amount; // deprecated
  1045. $line->amount = $obj->amount;
  1046. $line->sens = $obj->sens;
  1047. $line->lettering_code = $obj->lettering_code;
  1048. $line->date_lettering = $obj->date_lettering;
  1049. $line->fk_user_author = $obj->fk_user_author;
  1050. $line->import_key = $obj->import_key;
  1051. $line->code_journal = $obj->code_journal;
  1052. $line->journal_label = $obj->journal_label;
  1053. $line->piece_num = $obj->piece_num;
  1054. $line->date_creation = $this->db->jdate($obj->date_creation);
  1055. $line->date_lim_reglement = $this->db->jdate($obj->date_lim_reglement);
  1056. $line->date_modification = $this->db->jdate($obj->date_modification);
  1057. $line->date_export = $this->db->jdate($obj->date_export);
  1058. $line->date_validation = $this->db->jdate($obj->date_validation);
  1059. $this->lines[] = $line;
  1060. $i++;
  1061. }
  1062. $this->db->free($resql);
  1063. return $num;
  1064. } else {
  1065. $this->errors[] = 'Error '.$this->db->lasterror();
  1066. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1067. return -1;
  1068. }
  1069. }
  1070. /**
  1071. * Load object in memory from the database
  1072. *
  1073. * @param string $sortorder Sort Order
  1074. * @param string $sortfield Sort field
  1075. * @param int $limit offset limit
  1076. * @param int $offset offset limit
  1077. * @param array $filter filter array
  1078. * @param string $filtermode filter mode (AND or OR)
  1079. * @param int $option option (0: aggregate by general account or 1: aggreegate by subaccount)
  1080. * @return int Return integer <0 if KO, >0 if OK
  1081. */
  1082. public function fetchAllBalance($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $option = 0)
  1083. {
  1084. global $conf;
  1085. $this->lines = array();
  1086. dol_syslog(__METHOD__, LOG_DEBUG);
  1087. $sql = 'SELECT';
  1088. $sql .= " t.numero_compte,";
  1089. if (!empty($option)) {
  1090. $sql .= " t.subledger_account,";
  1091. $sql .= " t.subledger_label,";
  1092. }
  1093. $sql .= " SUM(t.debit) as debit,";
  1094. $sql .= " SUM(t.credit) as credit";
  1095. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1096. // Manage filter
  1097. $sqlwhere = array();
  1098. if (count($filter) > 0) {
  1099. foreach ($filter as $key => $value) {
  1100. if ($key == 't.doc_date') {
  1101. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  1102. } elseif ($key == 't.doc_date>=' || $key == 't.doc_date<=' || $key == 't.doc_date>' || $key == 't.doc_date<') {
  1103. $sqlwhere[] = $key."'".$this->db->idate($value)."'";
  1104. } elseif ($key == 't.numero_compte>=' || $key == 't.numero_compte<=' || $key == 't.subledger_account>=' || $key == 't.subledger_account<=') {
  1105. $sqlwhere[] = $key."'".$this->db->escape($value)."'";
  1106. } elseif ($key == 't.fk_doc' || $key == 't.fk_docdet' || $key == 't.piece_num') {
  1107. $sqlwhere[] = $key." = ".((int) $value);
  1108. } elseif ($key == 't.subledger_account' || $key == 't.numero_compte') {
  1109. $sqlwhere[] = $key." LIKE '".$this->db->escape($value)."%'";
  1110. } elseif ($key == 't.subledger_label') {
  1111. $sqlwhere[] = $key." LIKE '".$this->db->escape($value)."%'";
  1112. } elseif ($key == 't.code_journal' && !empty($value)) {
  1113. if (is_array($value)) {
  1114. $sqlwhere[] = natural_search("t.code_journal", join(',', $value), 3, 1);
  1115. } else {
  1116. $sqlwhere[] = natural_search("t.code_journal", $value, 3, 1);
  1117. }
  1118. } elseif ($key == 't.reconciled_option') {
  1119. $sqlwhere[] = 't.lettering_code IS NULL';
  1120. } else {
  1121. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  1122. }
  1123. }
  1124. }
  1125. $sql .= ' WHERE entity = ' . ((int) $conf->entity); // Do not use getEntity for accounting features
  1126. if (count($sqlwhere) > 0) {
  1127. $sql .= " AND ".implode(" ".$filtermode." ", $sqlwhere);
  1128. }
  1129. if (!empty($option)) {
  1130. $sql .= " AND t.subledger_account IS NOT NULL";
  1131. $sql .= " AND t.subledger_account <> ''";
  1132. $sql .= " GROUP BY t.numero_compte, t.subledger_account, t.subledger_label";
  1133. $sortfield = 't.subledger_account'.($sortfield ? ','.$sortfield : '');
  1134. $sortorder = 'ASC'.($sortfield ? ','.$sortfield : '');
  1135. } else {
  1136. $sql .= ' GROUP BY t.numero_compte';
  1137. $sortfield = 't.numero_compte'.($sortfield ? ','.$sortfield : '');
  1138. $sortorder = 'ASC'.($sortorder ? ','.$sortorder : '');
  1139. }
  1140. if (!empty($sortfield)) {
  1141. $sql .= $this->db->order($sortfield, $sortorder);
  1142. }
  1143. if (!empty($limit)) {
  1144. $sql .= $this->db->plimit($limit + 1, $offset);
  1145. }
  1146. $resql = $this->db->query($sql);
  1147. if ($resql) {
  1148. $num = $this->db->num_rows($resql);
  1149. $i = 0;
  1150. while (($obj = $this->db->fetch_object($resql)) && (empty($limit) || $i < min($limit, $num))) {
  1151. $line = new BookKeepingLine();
  1152. $line->numero_compte = $obj->numero_compte;
  1153. //$line->label_compte = $obj->label_compte;
  1154. if (!empty($option)) {
  1155. $line->subledger_account = $obj->subledger_account;
  1156. $line->subledger_label = $obj->subledger_label;
  1157. }
  1158. $line->debit = $obj->debit;
  1159. $line->credit = $obj->credit;
  1160. $this->lines[] = $line;
  1161. $i++;
  1162. }
  1163. $this->db->free($resql);
  1164. return $num;
  1165. } else {
  1166. $this->errors[] = 'Error '.$this->db->lasterror();
  1167. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1168. return -1;
  1169. }
  1170. }
  1171. /**
  1172. * Update object into database
  1173. *
  1174. * @param User $user User that modifies
  1175. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1176. * @param string $mode Mode ('' or _tmp')
  1177. * @return int Return integer <0 if KO, >0 if OK
  1178. */
  1179. public function update(User $user, $notrigger = false, $mode = '')
  1180. {
  1181. global $langs;
  1182. $error = 0;
  1183. dol_syslog(__METHOD__, LOG_DEBUG);
  1184. // Clean parameters
  1185. if (isset($this->doc_type)) {
  1186. $this->doc_type = trim($this->doc_type);
  1187. }
  1188. if (isset($this->doc_ref)) {
  1189. $this->doc_ref = trim($this->doc_ref);
  1190. }
  1191. if (isset($this->fk_doc)) {
  1192. $this->fk_doc = (int) $this->fk_doc;
  1193. }
  1194. if (isset($this->fk_docdet)) {
  1195. $this->fk_docdet = (int) $this->fk_docdet;
  1196. }
  1197. if (isset($this->thirdparty_code)) {
  1198. $this->thirdparty_code = trim($this->thirdparty_code);
  1199. }
  1200. if (isset($this->subledger_account)) {
  1201. $this->subledger_account = trim($this->subledger_account);
  1202. }
  1203. if (isset($this->subledger_label)) {
  1204. $this->subledger_label = trim($this->subledger_label);
  1205. }
  1206. if (isset($this->numero_compte)) {
  1207. $this->numero_compte = trim($this->numero_compte);
  1208. }
  1209. if (isset($this->label_compte)) {
  1210. $this->label_compte = trim($this->label_compte);
  1211. }
  1212. if (isset($this->label_operation)) {
  1213. $this->label_operation = trim($this->label_operation);
  1214. }
  1215. if (isset($this->debit)) {
  1216. $this->debit = trim($this->debit);
  1217. }
  1218. if (isset($this->credit)) {
  1219. $this->credit = trim($this->credit);
  1220. }
  1221. if (isset($this->amount)) {
  1222. $this->amount = trim($this->amount);
  1223. }
  1224. if (isset($this->sens)) {
  1225. $this->sens = trim($this->sens);
  1226. }
  1227. if (isset($this->import_key)) {
  1228. $this->import_key = trim($this->import_key);
  1229. }
  1230. if (isset($this->code_journal)) {
  1231. $this->code_journal = trim($this->code_journal);
  1232. }
  1233. if (isset($this->journal_label)) {
  1234. $this->journal_label = trim($this->journal_label);
  1235. }
  1236. if (isset($this->piece_num)) {
  1237. $this->piece_num = trim($this->piece_num);
  1238. }
  1239. $result = $this->canModifyBookkeeping($this->id);
  1240. if ($result < 0) {
  1241. return -1;
  1242. } elseif ($result == 0) {
  1243. if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') == 'blockedonclosed') {
  1244. $this->errors[] = $langs->trans('ErrorBookkeepingDocDateIsOnAClosedFiscalPeriod');
  1245. } else {
  1246. $this->errors[] = $langs->trans('ErrorBookkeepingDocDateNotOnActiveFiscalPeriod');
  1247. }
  1248. return -1;
  1249. }
  1250. $this->debit = price2num($this->debit, 'MT');
  1251. $this->credit = price2num($this->credit, 'MT');
  1252. // Check parameters
  1253. // Put here code to add a control on parameters values
  1254. // Update request
  1255. $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.$mode.' SET';
  1256. $sql .= ' doc_date = '.(!isset($this->doc_date) || dol_strlen($this->doc_date) != 0 ? "'".$this->db->idate($this->doc_date)."'" : 'null').',';
  1257. $sql .= ' doc_type = '.(isset($this->doc_type) ? "'".$this->db->escape($this->doc_type)."'" : "null").',';
  1258. $sql .= ' doc_ref = '.(isset($this->doc_ref) ? "'".$this->db->escape($this->doc_ref)."'" : "null").',';
  1259. $sql .= ' fk_doc = '.(isset($this->fk_doc) ? $this->fk_doc : "null").',';
  1260. $sql .= ' fk_docdet = '.(isset($this->fk_docdet) ? $this->fk_docdet : "null").',';
  1261. $sql .= ' thirdparty_code = '.(isset($this->thirdparty_code) ? "'".$this->db->escape($this->thirdparty_code)."'" : "null").',';
  1262. $sql .= ' subledger_account = '.(isset($this->subledger_account) ? "'".$this->db->escape($this->subledger_account)."'" : "null").',';
  1263. $sql .= ' subledger_label = '.(isset($this->subledger_label) ? "'".$this->db->escape($this->subledger_label)."'" : "null").',';
  1264. $sql .= ' numero_compte = '.(isset($this->numero_compte) ? "'".$this->db->escape($this->numero_compte)."'" : "null").',';
  1265. $sql .= ' label_compte = '.(isset($this->label_compte) ? "'".$this->db->escape($this->label_compte)."'" : "null").',';
  1266. $sql .= ' label_operation = '.(isset($this->label_operation) ? "'".$this->db->escape($this->label_operation)."'" : "null").',';
  1267. $sql .= ' debit = '.(isset($this->debit) ? $this->debit : "null").',';
  1268. $sql .= ' credit = '.(isset($this->credit) ? $this->credit : "null").',';
  1269. $sql .= ' montant = '.(isset($this->montant) ? $this->montant : "null").',';
  1270. $sql .= ' sens = '.(isset($this->sens) ? "'".$this->db->escape($this->sens)."'" : "null").',';
  1271. $sql .= ' fk_user_author = '.(isset($this->fk_user_author) ? $this->fk_user_author : "null").',';
  1272. $sql .= ' import_key = '.(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null").',';
  1273. $sql .= ' code_journal = '.(isset($this->code_journal) ? "'".$this->db->escape($this->code_journal)."'" : "null").',';
  1274. $sql .= ' journal_label = '.(isset($this->journal_label) ? "'".$this->db->escape($this->journal_label)."'" : "null").',';
  1275. $sql .= ' piece_num = '.(isset($this->piece_num) ? $this->piece_num : "null");
  1276. $sql .= ' WHERE rowid='.((int) $this->id);
  1277. $this->db->begin();
  1278. $resql = $this->db->query($sql);
  1279. if (!$resql) {
  1280. $error++;
  1281. $this->errors[] = 'Error '.$this->db->lasterror();
  1282. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1283. }
  1284. // Uncomment this and change MYOBJECT to your own tag if you
  1285. // want this action calls a trigger.
  1286. //if (! $error && ! $notrigger) {
  1287. // // Call triggers
  1288. // $result=$this->call_trigger('MYOBJECT_MODIFY',$user);
  1289. // if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
  1290. // // End call triggers
  1291. //}
  1292. // Commit or rollback
  1293. if ($error) {
  1294. $this->db->rollback();
  1295. return -1 * $error;
  1296. } else {
  1297. $this->db->commit();
  1298. return 1;
  1299. }
  1300. }
  1301. /**
  1302. * Update accounting movement
  1303. *
  1304. * @param string $piece_num Piece num
  1305. * @param string $field Field
  1306. * @param string $value Value
  1307. * @param string $mode Mode ('' or _tmp')
  1308. * @return number Return integer <0 if KO, >0 if OK
  1309. */
  1310. public function updateByMvt($piece_num = '', $field = '', $value = '', $mode = '')
  1311. {
  1312. $error = 0;
  1313. $sql_filter = $this->getCanModifyBookkeepingSQL();
  1314. if (!isset($sql_filter)) {
  1315. return -1;
  1316. }
  1317. $this->db->begin();
  1318. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element.$mode;
  1319. $sql .= " SET ".$field." = ".(is_numeric($value) ? ((float) $value) : "'".$this->db->escape($value)."'");
  1320. $sql .= " WHERE piece_num = ".((int) $piece_num);
  1321. $sql .= $sql_filter;
  1322. $resql = $this->db->query($sql);
  1323. if (!$resql) {
  1324. $error++;
  1325. $this->errors[] = 'Error '.$this->db->lasterror();
  1326. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1327. }
  1328. if ($error) {
  1329. $this->db->rollback();
  1330. return -1 * $error;
  1331. } else {
  1332. $this->db->commit();
  1333. return 1;
  1334. }
  1335. }
  1336. /**
  1337. * Delete object in database
  1338. *
  1339. * @param User $user User that deletes
  1340. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1341. * @param string $mode Mode
  1342. * @return int Return integer <0 if KO, >0 if OK
  1343. */
  1344. public function delete(User $user, $notrigger = false, $mode = '')
  1345. {
  1346. global $langs;
  1347. dol_syslog(__METHOD__, LOG_DEBUG);
  1348. $result = $this->canModifyBookkeeping($this->id);
  1349. if ($result < 0) {
  1350. return -1;
  1351. } elseif ($result == 0) {
  1352. if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') == 'blockedonclosed') {
  1353. $this->errors[] = $langs->trans('ErrorBookkeepingDocDateIsOnAClosedFiscalPeriod');
  1354. } else {
  1355. $this->errors[] = $langs->trans('ErrorBookkeepingDocDateNotOnActiveFiscalPeriod');
  1356. }
  1357. return -1;
  1358. }
  1359. $error = 0;
  1360. $this->db->begin();
  1361. // Uncomment this and change MYOBJECT to your own tag if you
  1362. // want this action calls a trigger.
  1363. //if (! $error && ! $notrigger) {
  1364. // // Call triggers
  1365. // $result=$this->call_trigger('MYOBJECT_DELETE',$user);
  1366. // if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
  1367. // // End call triggers
  1368. //}
  1369. if (!$error) {
  1370. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.$mode;
  1371. $sql .= ' WHERE rowid='.((int) $this->id);
  1372. $resql = $this->db->query($sql);
  1373. if (!$resql) {
  1374. $error++;
  1375. $this->errors[] = 'Error '.$this->db->lasterror();
  1376. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1377. }
  1378. }
  1379. // Commit or rollback
  1380. if ($error) {
  1381. $this->db->rollback();
  1382. return -1 * $error;
  1383. } else {
  1384. $this->db->commit();
  1385. return 1;
  1386. }
  1387. }
  1388. /**
  1389. * Delete bookkeeping by importkey
  1390. *
  1391. * @param string $importkey Import key
  1392. * @param string $mode Mode
  1393. * @return int Result
  1394. */
  1395. public function deleteByImportkey($importkey, $mode = '')
  1396. {
  1397. $this->db->begin();
  1398. $sql_filter = $this->getCanModifyBookkeepingSQL();
  1399. if (!isset($sql_filter)) {
  1400. return -1;
  1401. }
  1402. // first check if line not yet in bookkeeping
  1403. $sql = "DELETE";
  1404. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
  1405. $sql .= " WHERE import_key = '".$this->db->escape($importkey)."'";
  1406. $sql .= $sql_filter;
  1407. $resql = $this->db->query($sql);
  1408. if (!$resql) {
  1409. $this->errors[] = "Error ".$this->db->lasterror();
  1410. dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR);
  1411. $this->db->rollback();
  1412. return -1;
  1413. }
  1414. $this->db->commit();
  1415. return 1;
  1416. }
  1417. /**
  1418. * Delete bookkeeping by year
  1419. *
  1420. * @param int $delyear Year to delete
  1421. * @param string $journal Journal to delete
  1422. * @param string $mode Mode
  1423. * @param int $delmonth Month
  1424. * @return int Return integer <0 if KO, >0 if OK
  1425. */
  1426. public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0)
  1427. {
  1428. global $conf, $langs;
  1429. if (empty($delyear) && empty($journal)) {
  1430. $this->error = 'ErrorOneFieldRequired';
  1431. return -1;
  1432. }
  1433. if (!empty($delmonth) && empty($delyear)) {
  1434. $this->error = 'YearRequiredIfMonthDefined';
  1435. return -2;
  1436. }
  1437. $sql_filter = $this->getCanModifyBookkeepingSQL();
  1438. if (!isset($sql_filter)) {
  1439. return -1;
  1440. }
  1441. $this->db->begin();
  1442. // Delete record in bookkeeping
  1443. $sql = "DELETE";
  1444. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
  1445. $sql .= " WHERE 1 = 1";
  1446. $sql .= dolSqlDateFilter('doc_date', 0, $delmonth, $delyear);
  1447. if (!empty($journal)) {
  1448. $sql .= " AND code_journal = '".$this->db->escape($journal)."'";
  1449. }
  1450. $sql .= " AND entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1451. // Exclusion of validated entries at the time of deletion
  1452. $sql .= " AND date_validated IS NULL";
  1453. $sql .= $sql_filter;
  1454. // TODO: In a future we must forbid deletion if record is inside a closed fiscal period.
  1455. $resql = $this->db->query($sql);
  1456. if (!$resql) {
  1457. $this->errors[] = "Error ".$this->db->lasterror();
  1458. foreach ($this->errors as $errmsg) {
  1459. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  1460. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1461. }
  1462. $this->db->rollback();
  1463. return -1;
  1464. }
  1465. $this->db->commit();
  1466. return 1;
  1467. }
  1468. /**
  1469. * Delete bookkeeping by piece number
  1470. *
  1471. * @param int $piecenum Piecenum to delete
  1472. * @param string $mode Mode
  1473. * @return int Result
  1474. */
  1475. public function deleteMvtNum($piecenum, $mode = '')
  1476. {
  1477. global $conf;
  1478. $sql_filter = $this->getCanModifyBookkeepingSQL();
  1479. if (!isset($sql_filter)) {
  1480. return -1;
  1481. }
  1482. $this->db->begin();
  1483. // first check if line not yet in bookkeeping
  1484. $sql = "DELETE";
  1485. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
  1486. $sql .= " WHERE piece_num = ".(int) $piecenum;
  1487. $sql .= " AND date_validated IS NULL"; // For security, exclusion of validated entries at the time of deletion
  1488. $sql .= " AND entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1489. $sql .= $sql_filter;
  1490. $resql = $this->db->query($sql);
  1491. if (!$resql) {
  1492. $this->errors[] = "Error ".$this->db->lasterror();
  1493. foreach ($this->errors as $errmsg) {
  1494. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  1495. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1496. }
  1497. $this->db->rollback();
  1498. return -1;
  1499. }
  1500. $this->db->commit();
  1501. return 1;
  1502. }
  1503. /**
  1504. * Load an object from its id and create a new one in database
  1505. *
  1506. * @param User $user User making the clone
  1507. * @param int $fromid Id of object to clone
  1508. * @return int New id of clone
  1509. */
  1510. public function createFromClone(User $user, $fromid)
  1511. {
  1512. dol_syslog(__METHOD__, LOG_DEBUG);
  1513. $error = 0;
  1514. $object = new BookKeeping($this->db);
  1515. $this->db->begin();
  1516. // Load source object
  1517. $object->fetch($fromid);
  1518. // Reset object
  1519. $object->id = 0;
  1520. // Clear fields
  1521. // ...
  1522. // Create clone
  1523. $object->context['createfromclone'] = 'createfromclone';
  1524. $result = $object->create($user);
  1525. // Other options
  1526. if ($result < 0) {
  1527. $error++;
  1528. $this->errors = $object->errors;
  1529. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1530. }
  1531. unset($object->context['createfromclone']);
  1532. // End
  1533. if (!$error) {
  1534. $this->db->commit();
  1535. return $object->id;
  1536. } else {
  1537. $this->db->rollback();
  1538. return -1;
  1539. }
  1540. }
  1541. /**
  1542. * Initialise object with example values
  1543. * Id must be 0 if object instance is a specimen
  1544. *
  1545. * @return void
  1546. */
  1547. public function initAsSpecimen()
  1548. {
  1549. global $user;
  1550. $now = dol_now();
  1551. $this->id = 0;
  1552. $this->doc_date = $now;
  1553. $this->doc_type = '';
  1554. $this->doc_ref = '';
  1555. $this->fk_doc = 0;
  1556. $this->fk_docdet = 0;
  1557. $this->thirdparty_code = 'CU001';
  1558. $this->subledger_account = '41100001';
  1559. $this->subledger_label = 'My customer company';
  1560. $this->numero_compte = '411';
  1561. $this->label_compte = 'Customer';
  1562. $this->label_operation = 'Sales of pea';
  1563. $this->debit = 99.9;
  1564. $this->credit = 0.0;
  1565. $this->amount = 0.0;
  1566. $this->sens = 'D';
  1567. $this->fk_user_author = $user->id;
  1568. $this->import_key = '20201027';
  1569. $this->code_journal = 'VT';
  1570. $this->journal_label = 'Journal de vente';
  1571. $this->piece_num = 1234;
  1572. $this->date_creation = $now;
  1573. }
  1574. /**
  1575. * Load an accounting document into memory from database
  1576. *
  1577. * @param int $piecenum Accounting document to get
  1578. * @param string $mode Mode
  1579. * @return int Return integer <0 if KO, >0 if OK
  1580. */
  1581. public function fetchPerMvt($piecenum, $mode = '')
  1582. {
  1583. global $conf;
  1584. $sql = "SELECT piece_num, doc_date,code_journal, journal_label, doc_ref, doc_type,";
  1585. $sql .= " date_creation, tms as date_modification, date_validated as date_validation";
  1586. // In llx_accounting_bookkeeping_tmp, field date_export doesn't exist
  1587. if ($mode != "_tmp") {
  1588. $sql .= ", date_export";
  1589. }
  1590. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
  1591. $sql .= " WHERE piece_num = ".((int) $piecenum);
  1592. $sql .= " AND entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1593. dol_syslog(__METHOD__, LOG_DEBUG);
  1594. $result = $this->db->query($sql);
  1595. if ($result) {
  1596. $obj = $this->db->fetch_object($result);
  1597. $this->piece_num = $obj->piece_num;
  1598. $this->code_journal = $obj->code_journal;
  1599. $this->journal_label = $obj->journal_label;
  1600. $this->doc_date = $this->db->jdate($obj->doc_date);
  1601. $this->doc_ref = $obj->doc_ref;
  1602. $this->doc_type = $obj->doc_type;
  1603. $this->date_creation = $this->db->jdate($obj->date_creation);
  1604. $this->date_modification = $this->db->jdate($obj->date_modification);
  1605. if ($mode != "_tmp") {
  1606. $this->date_export = $this->db->jdate($obj->date_export);
  1607. }
  1608. $this->date_validation = $this->db->jdate($obj->date_validation);
  1609. } else {
  1610. $this->error = "Error ".$this->db->lasterror();
  1611. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  1612. return -1;
  1613. }
  1614. return 1;
  1615. }
  1616. /**
  1617. * Return next number movement
  1618. *
  1619. * @param string $mode Mode
  1620. * @return string Next numero to use
  1621. */
  1622. public function getNextNumMvt($mode = '')
  1623. {
  1624. global $conf;
  1625. $sql = "SELECT MAX(piece_num)+1 as max FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
  1626. $sql .= " WHERE entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1627. dol_syslog(get_class($this)."::getNextNumMvt", LOG_DEBUG);
  1628. $result = $this->db->query($sql);
  1629. if ($result) {
  1630. $obj = $this->db->fetch_object($result);
  1631. if ($obj) {
  1632. $result = $obj->max;
  1633. }
  1634. if (empty($result)) {
  1635. $result = 1;
  1636. }
  1637. return $result;
  1638. } else {
  1639. $this->error = "Error ".$this->db->lasterror();
  1640. dol_syslog(get_class($this)."::getNextNumMvt ".$this->error, LOG_ERR);
  1641. return -1;
  1642. }
  1643. }
  1644. /**
  1645. * Load all informations of accountancy document
  1646. *
  1647. * @param int $piecenum Id of line to get
  1648. * @param string $mode Mode
  1649. * @return int Return integer <0 if KO, >0 if OK
  1650. */
  1651. public function fetchAllPerMvt($piecenum, $mode = '')
  1652. {
  1653. global $conf;
  1654. $sql = "SELECT rowid, doc_date, doc_type,";
  1655. $sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,";
  1656. $sql .= " numero_compte, label_compte, label_operation, debit, credit,";
  1657. $sql .= " montant as amount, sens, fk_user_author, import_key, code_journal, journal_label, piece_num,";
  1658. $sql .= " date_creation, tms as date_modification, date_validated as date_validation";
  1659. // In llx_accounting_bookkeeping_tmp, field date_export doesn't exist
  1660. if ($mode != "_tmp") {
  1661. $sql .= ", date_export";
  1662. }
  1663. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element.$mode;
  1664. $sql .= " WHERE piece_num = ".((int) $piecenum);
  1665. $sql .= " AND entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1666. dol_syslog(__METHOD__, LOG_DEBUG);
  1667. $result = $this->db->query($sql);
  1668. if ($result) {
  1669. while ($obj = $this->db->fetch_object($result)) {
  1670. $line = new BookKeepingLine();
  1671. $line->id = $obj->rowid;
  1672. $line->doc_date = $this->db->jdate($obj->doc_date);
  1673. $line->doc_type = $obj->doc_type;
  1674. $line->doc_ref = $obj->doc_ref;
  1675. $line->fk_doc = $obj->fk_doc;
  1676. $line->fk_docdet = $obj->fk_docdet;
  1677. $line->thirdparty_code = $obj->thirdparty_code;
  1678. $line->subledger_account = $obj->subledger_account;
  1679. $line->subledger_label = $obj->subledger_label;
  1680. $line->numero_compte = $obj->numero_compte;
  1681. $line->label_compte = $obj->label_compte;
  1682. $line->label_operation = $obj->label_operation;
  1683. $line->debit = $obj->debit;
  1684. $line->credit = $obj->credit;
  1685. $line->montant = $obj->amount;
  1686. $line->amount = $obj->amount;
  1687. $line->sens = $obj->sens;
  1688. $line->code_journal = $obj->code_journal;
  1689. $line->journal_label = $obj->journal_label;
  1690. $line->piece_num = $obj->piece_num;
  1691. $line->date_creation = $obj->date_creation;
  1692. $line->date_modification = $obj->date_modification;
  1693. if ($mode != "_tmp") {
  1694. $line->date_export = $obj->date_export;
  1695. }
  1696. $line->date_validation = $obj->date_validation;
  1697. $this->linesmvt[] = $line;
  1698. }
  1699. } else {
  1700. $this->error = "Error ".$this->db->lasterror();
  1701. dol_syslog(__METHOD__.$this->error, LOG_ERR);
  1702. return -1;
  1703. }
  1704. return 1;
  1705. }
  1706. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1707. /**
  1708. * Export bookkeeping
  1709. *
  1710. * @param string $model Model
  1711. * @return int Result
  1712. */
  1713. public function export_bookkeeping($model = 'ebp')
  1714. {
  1715. // phpcs:enable
  1716. global $conf;
  1717. $sql = "SELECT rowid, doc_date, doc_type,";
  1718. $sql .= " doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,";
  1719. $sql .= " numero_compte, label_compte, label_operation, debit, credit,";
  1720. $sql .= " montant as amount, sens, fk_user_author, import_key, code_journal, piece_num,";
  1721. $sql .= " date_validated as date_validation";
  1722. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
  1723. $sql .= " WHERE entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1724. dol_syslog(get_class($this)."::export_bookkeeping", LOG_DEBUG);
  1725. $resql = $this->db->query($sql);
  1726. if ($resql) {
  1727. $this->linesexport = array();
  1728. $num = $this->db->num_rows($resql);
  1729. while ($obj = $this->db->fetch_object($resql)) {
  1730. $line = new BookKeepingLine();
  1731. $line->id = $obj->rowid;
  1732. $line->doc_date = $this->db->jdate($obj->doc_date);
  1733. $line->doc_type = $obj->doc_type;
  1734. $line->doc_ref = $obj->doc_ref;
  1735. $line->fk_doc = $obj->fk_doc;
  1736. $line->fk_docdet = $obj->fk_docdet;
  1737. $line->thirdparty_code = $obj->thirdparty_code;
  1738. $line->subledger_account = $obj->subledger_account;
  1739. $line->subledger_label = $obj->subledger_label;
  1740. $line->numero_compte = $obj->numero_compte;
  1741. $line->label_compte = $obj->label_compte;
  1742. $line->label_operation = $obj->label_operation;
  1743. $line->debit = $obj->debit;
  1744. $line->credit = $obj->credit;
  1745. $line->montant = $obj->amount;
  1746. $line->amount = $obj->amount;
  1747. $line->sens = $obj->sens;
  1748. $line->code_journal = $obj->code_journal;
  1749. $line->piece_num = $obj->piece_num;
  1750. $line->date_validation = $obj->date_validation;
  1751. $this->linesexport[] = $line;
  1752. }
  1753. $this->db->free($resql);
  1754. return $num;
  1755. } else {
  1756. $this->error = "Error ".$this->db->lasterror();
  1757. dol_syslog(get_class($this)."::export_bookkeeping ".$this->error, LOG_ERR);
  1758. return -1;
  1759. }
  1760. }
  1761. /**
  1762. * Transform transaction
  1763. *
  1764. * @param number $direction If 0: tmp => real, if 1: real => tmp
  1765. * @param string $piece_num Piece num = Transaction ref
  1766. * @return int int Return integer <0 if KO, >0 if OK
  1767. */
  1768. public function transformTransaction($direction = 0, $piece_num = '')
  1769. {
  1770. global $conf;
  1771. $error = 0;
  1772. $sql_filter = $this->getCanModifyBookkeepingSQL();
  1773. if (!isset($sql_filter)) {
  1774. return -1;
  1775. }
  1776. $this->db->begin();
  1777. if ($direction == 0) {
  1778. $next_piecenum = $this->getNextNumMvt();
  1779. $now = dol_now();
  1780. if ($next_piecenum < 0) {
  1781. $error++;
  1782. }
  1783. if (!$error) {
  1784. // Delete if there is an empty line
  1785. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num).' AND entity = ' .((int) $conf->entity)." AND numero_compte IS NULL AND debit = 0 AND credit = 0";
  1786. $resql = $this->db->query($sql);
  1787. if (!$resql) {
  1788. $error++;
  1789. $this->errors[] = 'Error '.$this->db->lasterror();
  1790. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1791. }
  1792. }
  1793. if (!$error) {
  1794. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.' (doc_date, doc_type,';
  1795. $sql .= ' doc_ref, fk_doc, fk_docdet, entity, thirdparty_code, subledger_account, subledger_label,';
  1796. $sql .= ' numero_compte, label_compte, label_operation, debit, credit,';
  1797. $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num, date_creation)';
  1798. $sql .= ' SELECT doc_date, doc_type,';
  1799. $sql .= ' doc_ref, fk_doc, fk_docdet, entity, thirdparty_code, subledger_account, subledger_label,';
  1800. $sql .= ' numero_compte, label_compte, label_operation, debit, credit,';
  1801. $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, '.((int) $next_piecenum).", '".$this->db->idate($now)."'";
  1802. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num).' AND numero_compte IS NOT NULL AND entity = ' .((int) $conf->entity);
  1803. $sql .= $sql_filter;
  1804. $resql = $this->db->query($sql);
  1805. if (!$resql) {
  1806. $error++;
  1807. $this->errors[] = 'Error '.$this->db->lasterror();
  1808. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1809. }
  1810. }
  1811. if (!$error) {
  1812. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num).' AND entity = ' .((int) $conf->entity);
  1813. $resql = $this->db->query($sql);
  1814. if (!$resql) {
  1815. $error++;
  1816. $this->errors[] = 'Error '.$this->db->lasterror();
  1817. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1818. }
  1819. }
  1820. } elseif ($direction == 1) {
  1821. if (!$error) {
  1822. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num).' AND entity = ' .((int) $conf->entity);
  1823. $resql = $this->db->query($sql);
  1824. if (!$resql) {
  1825. $error++;
  1826. $this->errors[] = 'Error '.$this->db->lasterror();
  1827. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1828. }
  1829. }
  1830. if (!$error) {
  1831. $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'_tmp (doc_date, doc_type,';
  1832. $sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,';
  1833. $sql .= ' numero_compte, label_compte, label_operation, debit, credit,';
  1834. $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num)';
  1835. $sql .= ' SELECT doc_date, doc_type,';
  1836. $sql .= ' doc_ref, fk_doc, fk_docdet, thirdparty_code, subledger_account, subledger_label,';
  1837. $sql .= ' numero_compte, label_compte, label_operation, debit, credit,';
  1838. $sql .= ' montant, sens, fk_user_author, import_key, code_journal, journal_label, piece_num';
  1839. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE piece_num = '.((int) $piece_num).' AND entity = ' .((int) $conf->entity);
  1840. $sql .= $sql_filter;
  1841. $resql = $this->db->query($sql);
  1842. if (!$resql) {
  1843. $error++;
  1844. $this->errors[] = 'Error '.$this->db->lasterror();
  1845. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1846. }
  1847. }
  1848. if (!$error) {
  1849. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.'_tmp WHERE piece_num = '.((int) $piece_num).' AND entity = ' .((int) $conf->entity);
  1850. $sql .= $sql_filter;
  1851. $resql = $this->db->query($sql);
  1852. if (!$resql) {
  1853. $error++;
  1854. $this->errors[] = 'Error '.$this->db->lasterror();
  1855. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1856. }
  1857. }
  1858. }
  1859. if (!$error) {
  1860. $this->db->commit();
  1861. return 1;
  1862. } else {
  1863. $this->db->rollback();
  1864. return -1;
  1865. }
  1866. /*
  1867. $sql = "DELETE FROM ";
  1868. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab";
  1869. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.account_number = ab.numero_compte";
  1870. $sql .= " AND aa.active = 1";
  1871. $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
  1872. $sql .= " AND asy.rowid = " . ((int) $pcgver);
  1873. $sql .= " AND ab.entity IN (" . getEntity('accountancy') . ")";
  1874. $sql .= " ORDER BY account_number ASC";
  1875. */
  1876. }
  1877. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1878. /**
  1879. * Return list of accounts with label by chart of accounts
  1880. *
  1881. * @param string $selectid Preselected chart of accounts
  1882. * @param string $htmlname Name of field in html form
  1883. * @param int $showempty Add an empty field
  1884. * @param array $event Event options
  1885. * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1)
  1886. * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number
  1887. * @param string $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number
  1888. * @return string String with HTML select
  1889. */
  1890. public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '')
  1891. {
  1892. // phpcs:enable
  1893. global $conf;
  1894. require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  1895. $pcgver = getDolGlobalInt('CHARTOFACCOUNTS');
  1896. $sql = "SELECT DISTINCT ab.numero_compte as account_number, aa.label as label, aa.rowid as rowid, aa.fk_pcg_version";
  1897. $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab";
  1898. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.account_number = ab.numero_compte";
  1899. $sql .= " AND aa.active = 1";
  1900. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
  1901. $sql .= " AND asy.rowid = ".((int) $pcgver);
  1902. $sql .= " AND ab.entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1903. $sql .= " ORDER BY account_number ASC";
  1904. dol_syslog(get_class($this)."::select_account", LOG_DEBUG);
  1905. $resql = $this->db->query($sql);
  1906. if (!$resql) {
  1907. $this->error = "Error ".$this->db->lasterror();
  1908. dol_syslog(get_class($this)."::select_account ".$this->error, LOG_ERR);
  1909. return -1;
  1910. }
  1911. $out = ajax_combobox($htmlname, $event);
  1912. $options = array();
  1913. $selected = null;
  1914. while ($obj = $this->db->fetch_object($resql)) {
  1915. $label = length_accountg($obj->account_number).' - '.$obj->label;
  1916. $select_value_in = $obj->rowid;
  1917. $select_value_out = $obj->rowid;
  1918. if ($select_in == 1) {
  1919. $select_value_in = $obj->account_number;
  1920. }
  1921. if ($select_out == 1) {
  1922. $select_value_out = $obj->account_number;
  1923. }
  1924. // Remember guy's we store in database llx_facturedet the rowid of accounting_account and not the account_number
  1925. // Because same account_number can be share between different accounting_system and do have the same meaning
  1926. if (($selectid != '') && $selectid == $select_value_in) {
  1927. $selected = $select_value_out;
  1928. }
  1929. $options[$select_value_out] = $label;
  1930. }
  1931. $out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', 'maxwidth300');
  1932. $this->db->free($resql);
  1933. return $out;
  1934. }
  1935. /**
  1936. * Return id and description of a root accounting account.
  1937. * FIXME: This function takes the parent of parent to get the root account !
  1938. *
  1939. * @param string $account Accounting account
  1940. * @return array|int Array with root account information (max 2 upper level), <0 if KO
  1941. */
  1942. public function getRootAccount($account = null)
  1943. {
  1944. global $conf;
  1945. $pcgver = getDolGlobalInt('CHARTOFACCOUNTS');
  1946. $sql = "SELECT root.rowid, root.account_number, root.label as label,";
  1947. $sql .= " parent.rowid as parent_rowid, parent.account_number as parent_account_number, parent.label as parent_label";
  1948. $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa";
  1949. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
  1950. $sql .= " AND asy.rowid = ".((int) $pcgver);
  1951. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as parent ON aa.account_parent = parent.rowid AND parent.active = 1";
  1952. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as root ON parent.account_parent = root.rowid AND root.active = 1";
  1953. $sql .= " WHERE aa.account_number = '".$this->db->escape($account)."'";
  1954. $sql .= " AND aa.entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1955. dol_syslog(get_class($this)."::select_account", LOG_DEBUG);
  1956. $resql = $this->db->query($sql);
  1957. if ($resql) {
  1958. $obj = '';
  1959. if ($this->db->num_rows($resql)) {
  1960. $obj = $this->db->fetch_object($resql);
  1961. }
  1962. $result = array('id'=>$obj->rowid, 'account_number'=>$obj->account_number, 'label'=>$obj->label);
  1963. return $result;
  1964. } else {
  1965. $this->error = "Error ".$this->db->lasterror();
  1966. dol_syslog(__METHOD__." ".$this->error, LOG_ERR);
  1967. return -1;
  1968. }
  1969. }
  1970. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1971. /**
  1972. * Description of accounting account
  1973. *
  1974. * @param string $account Accounting account
  1975. * @return string Account desc
  1976. */
  1977. public function get_compte_desc($account = null)
  1978. {
  1979. // phpcs:enable
  1980. global $conf;
  1981. $pcgver = getDolGlobalInt('CHARTOFACCOUNTS');
  1982. $sql = "SELECT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version, cat.label as category";
  1983. $sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa ";
  1984. $sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
  1985. $sql .= " AND aa.account_number = '".$this->db->escape($account)."'";
  1986. $sql .= " AND asy.rowid = ".((int) $pcgver);
  1987. $sql .= " AND aa.active = 1";
  1988. $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_accounting_category as cat ON aa.fk_accounting_category = cat.rowid";
  1989. $sql .= " WHERE aa.entity = " . ((int) $conf->entity); // Do not use getEntity for accounting features
  1990. dol_syslog(get_class($this)."::select_account", LOG_DEBUG);
  1991. $resql = $this->db->query($sql);
  1992. if ($resql) {
  1993. $obj = '';
  1994. if ($this->db->num_rows($resql)) {
  1995. $obj = $this->db->fetch_object($resql);
  1996. }
  1997. if (empty($obj->category)) {
  1998. return $obj->label;
  1999. } else {
  2000. return $obj->label.' ('.$obj->category.')';
  2001. }
  2002. } else {
  2003. $this->error = "Error ".$this->db->lasterror();
  2004. dol_syslog(__METHOD__." ".$this->error, LOG_ERR);
  2005. return -1;
  2006. }
  2007. }
  2008. /**
  2009. * Get SQL string for check if the bookkeeping can be modified or deleted ? (cached)
  2010. *
  2011. * @param string $alias Bookkeeping alias table
  2012. * @param bool $force Force reload
  2013. * @return string SQL filter
  2014. */
  2015. public function getCanModifyBookkeepingSQL($alias = '', $force = false)
  2016. {
  2017. global $conf;
  2018. $alias = trim($alias);
  2019. $alias = !empty($alias) && strpos($alias, '.') < 0 ? $alias . "." : $alias;
  2020. if (!isset(self::$can_modify_bookkeeping_sql_cached[$alias]) || $force) {
  2021. $result = $this->loadFiscalPeriods($force, 'active');
  2022. if ($result < 0) {
  2023. return null;
  2024. }
  2025. $sql_list = array();
  2026. if (!empty($conf->cache['active_fiscal_period_cached']) && is_array($conf->cache['active_fiscal_period_cached'])) {
  2027. foreach ($conf->cache['active_fiscal_period_cached'] as $fiscal_period) {
  2028. $sql_list[] = "('" . $this->db->idate($fiscal_period['date_start']) . "' <= {$alias}doc_date AND {$alias}doc_date <= '" . $this->db->idate($fiscal_period['date_end']) . "')";
  2029. }
  2030. }
  2031. self::$can_modify_bookkeeping_sql_cached[$alias] = !empty($sql_list) ? ' AND (' . implode(' OR ', $sql_list) . ')' : '';
  2032. }
  2033. return self::$can_modify_bookkeeping_sql_cached[$alias];
  2034. }
  2035. /**
  2036. * Is the bookkeeping can be modified or deleted ?
  2037. *
  2038. * @param int $id Bookkeeping ID
  2039. * @return int Return integer <0 if KO, == 0 if No, == 1 if Yes
  2040. */
  2041. public function canModifyBookkeeping($id)
  2042. {
  2043. global $conf;
  2044. if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') == 'blockedonclosed') {
  2045. $result = $this->loadFiscalPeriods(false, 'closed');
  2046. if ($result < 0) {
  2047. return -1;
  2048. }
  2049. $bookkeeping = new BookKeeping($this->db);
  2050. $result = $bookkeeping->fetch($id);
  2051. if ($result <= 0) {
  2052. return $result;
  2053. }
  2054. if (!empty($conf->cache['closed_fiscal_period_cached']) && is_array($conf->cache['closed_fiscal_period_cached'])) {
  2055. foreach ($conf->cache['closed_fiscal_period_cached'] as $fiscal_period) {
  2056. if ($fiscal_period['date_start'] <= $bookkeeping->doc_date && $bookkeeping->doc_date <= $fiscal_period['date_end']) {
  2057. return 0;
  2058. }
  2059. }
  2060. }
  2061. return 1;
  2062. } else {
  2063. $result = $this->loadFiscalPeriods(false, 'active');
  2064. if ($result < 0) {
  2065. return -1;
  2066. }
  2067. $bookkeeping = new BookKeeping($this->db);
  2068. $result = $bookkeeping->fetch($id);
  2069. if ($result <= 0) {
  2070. return $result;
  2071. }
  2072. if (!empty($conf->cache['active_fiscal_period_cached']) && is_array($conf->cache['active_fiscal_period_cached'])) {
  2073. foreach ($conf->cache['active_fiscal_period_cached'] as $fiscal_period) {
  2074. if ($fiscal_period['date_start'] <= $bookkeeping->doc_date && $bookkeeping->doc_date <= $fiscal_period['date_end']) {
  2075. return 1;
  2076. }
  2077. }
  2078. }
  2079. return 0;
  2080. }
  2081. }
  2082. /**
  2083. * Is the bookkeeping date valid (on an open period or not on a closed period) ?
  2084. *
  2085. * @param int $date Bookkeeping date
  2086. * @return int Return integer <0 if KO, == 0 if No, == 1 if date is valid for a transfer
  2087. */
  2088. public function validBookkeepingDate($date)
  2089. {
  2090. global $conf;
  2091. if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') == 'blockedonclosed') {
  2092. $result = $this->loadFiscalPeriods(false, 'closed');
  2093. if ($result < 0) {
  2094. return -1;
  2095. }
  2096. if (!empty($conf->cache['closed_fiscal_period_cached']) && is_array($conf->cache['closed_fiscal_period_cached'])) {
  2097. foreach ($conf->cache['closed_fiscal_period_cached'] as $fiscal_period) {
  2098. if ($fiscal_period['date_start'] <= $date && $date <= $fiscal_period['date_end']) {
  2099. return 0;
  2100. }
  2101. }
  2102. }
  2103. return 1;
  2104. } else {
  2105. $result = $this->loadFiscalPeriods(false, 'active');
  2106. if ($result < 0) {
  2107. return -1;
  2108. }
  2109. if (!empty($conf->cache['active_fiscal_period_cached']) && is_array($conf->cache['active_fiscal_period_cached'])) {
  2110. foreach ($conf->cache['active_fiscal_period_cached'] as $fiscal_period) {
  2111. if ($fiscal_period['date_start'] <= $date && $date <= $fiscal_period['date_end']) {
  2112. return 1;
  2113. }
  2114. }
  2115. }
  2116. return 0;
  2117. }
  2118. }
  2119. /**
  2120. * Load list of active fiscal period
  2121. *
  2122. * @param bool $force Force reload
  2123. * @param string $mode active or closed ?
  2124. * @return int Return integer <0 if KO, >0 if OK
  2125. */
  2126. public function loadFiscalPeriods($force = false, $mode = 'active')
  2127. {
  2128. global $conf;
  2129. if ($mode == 'active') {
  2130. if (!isset($conf->cache['active_fiscal_period_cached']) || $force) {
  2131. $sql = "SELECT date_start, date_end";
  2132. $sql .= " FROM " . $this->db->prefix() . "accounting_fiscalyear";
  2133. $sql .= " WHERE entity = " . ((int) $conf->entity);
  2134. $sql .= " AND statut = 0";
  2135. $resql = $this->db->query($sql);
  2136. if (!$resql) {
  2137. $this->errors[] = $this->db->lasterror();
  2138. return -1;
  2139. }
  2140. $list = array();
  2141. while ($obj = $this->db->fetch_object($resql)) {
  2142. $list[] = array(
  2143. 'date_start' => $this->db->jdate($obj->date_start),
  2144. 'date_end' => $this->db->jdate($obj->date_end),
  2145. );
  2146. }
  2147. $conf->cache['active_fiscal_period_cached'] = $list;
  2148. }
  2149. }
  2150. if ($mode == 'closed') {
  2151. if (!isset($conf->cache['closed_fiscal_period_cached']) || $force) {
  2152. $sql = "SELECT date_start, date_end";
  2153. $sql .= " FROM " . $this->db->prefix() . "accounting_fiscalyear";
  2154. $sql .= " WHERE entity = " . ((int) $conf->entity);
  2155. $sql .= " AND statut = 1";
  2156. $resql = $this->db->query($sql);
  2157. if (!$resql) {
  2158. $this->errors[] = $this->db->lasterror();
  2159. return -1;
  2160. }
  2161. $list = array();
  2162. while ($obj = $this->db->fetch_object($resql)) {
  2163. $list[] = array(
  2164. 'date_start' => $this->db->jdate($obj->date_start),
  2165. 'date_end' => $this->db->jdate($obj->date_end),
  2166. );
  2167. }
  2168. $conf->cache['closed_fiscal_period_cached'] = $list;
  2169. }
  2170. }
  2171. return 1;
  2172. }
  2173. /**
  2174. * Get list of fiscal period
  2175. *
  2176. * @param string $filter Filter
  2177. * @return array|int Return integer <0 if KO, Fiscal periods : [[id, date_start, date_end, label], ...]
  2178. */
  2179. public function getFiscalPeriods($filter = '')
  2180. {
  2181. global $conf;
  2182. $list = array();
  2183. $sql = "SELECT rowid, label, date_start, date_end, statut";
  2184. $sql .= " FROM " . $this->db->prefix() . "accounting_fiscalyear";
  2185. $sql .= " WHERE entity = " . ((int) $conf->entity);
  2186. if (!empty($filter)) {
  2187. $sql .= " AND (" . $filter . ')';
  2188. }
  2189. $sql .= $this->db->order('date_start', 'ASC');
  2190. $resql = $this->db->query($sql);
  2191. if (!$resql) {
  2192. $this->errors[] = $this->db->lasterror();
  2193. return -1;
  2194. }
  2195. while ($obj = $this->db->fetch_object($resql)) {
  2196. $list[$obj->rowid] = array(
  2197. 'id' => $obj->rowid,
  2198. 'label' => $obj->label,
  2199. 'date_start' => $this->db->jdate($obj->date_start),
  2200. 'date_end' => $this->db->jdate($obj->date_end),
  2201. 'status' => $obj->statut,
  2202. );
  2203. }
  2204. return $list;
  2205. }
  2206. /**
  2207. * Get list of count by month into the fiscal period
  2208. *
  2209. * @param int $date_start Date start
  2210. * @param int $date_end Date end
  2211. * @return array|int Return integer <0 if KO, Fiscal periods : [[id, date_start, date_end, label], ...]
  2212. */
  2213. public function getCountByMonthForFiscalPeriod($date_start, $date_end)
  2214. {
  2215. $total = 0;
  2216. $list = array();
  2217. $sql = "SELECT YEAR(b.doc_date) as year";
  2218. for ($i = 1; $i <= 12; $i++) {
  2219. $sql .= ", SUM(" . $this->db->ifsql("MONTH(b.doc_date)=" . $i, "1", "0") . ") AS month" . $i;
  2220. }
  2221. $sql .= ", COUNT(b.rowid) as total";
  2222. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as b";
  2223. $sql .= " WHERE b.doc_date >= '" . $this->db->idate($date_start) . "'";
  2224. $sql .= " AND b.doc_date <= '" . $this->db->idate($date_end) . "'";
  2225. $sql .= " AND b.entity IN (" . getEntity('bookkeeping', 0) . ")"; // We don't share object for accountancy
  2226. // Get count for each month into the fiscal period
  2227. if (getDolGlobalString("ACCOUNTANCY_DISABLE_CLOSURE_LINE_BY_LINE")) {
  2228. // TODO Analyse is done by finding record not into a closed period
  2229. // Loop on each closed period
  2230. $sql .= " AND b.doc_date BETWEEN 0 AND 0";
  2231. } else {
  2232. // Analyse closed record using the unitary flag/date on each record
  2233. $sql .= " AND date_validated IS NULL";
  2234. }
  2235. $sql .= " GROUP BY YEAR(b.doc_date)";
  2236. $sql .= $this->db->order("year", 'ASC');
  2237. dol_syslog(__METHOD__, LOG_DEBUG);
  2238. $resql = $this->db->query($sql);
  2239. if (!$resql) {
  2240. $this->errors[] = $this->db->lasterror();
  2241. return -1;
  2242. }
  2243. while ($obj = $this->db->fetch_object($resql)) {
  2244. $total += (int) $obj->total;
  2245. $year_list = array(
  2246. 'year' => (int) $obj->year,
  2247. 'count' => array(),
  2248. 'total' => (int) $obj->total,
  2249. );
  2250. for ($i = 1; $i <= 12; $i++) {
  2251. $year_list['count'][$i] = (int) $obj->{'month' . $i};
  2252. }
  2253. $list[] = $year_list;
  2254. }
  2255. $this->db->free($resql);
  2256. return array(
  2257. 'total' => $total,
  2258. 'list' => $list,
  2259. );
  2260. }
  2261. /**
  2262. * Validate all movement between the specified dates
  2263. *
  2264. * @param int $date_start Date start
  2265. * @param int $date_end Date end
  2266. * @return int int Return integer <0 if KO, >0 if OK
  2267. */
  2268. public function validateMovementForFiscalPeriod($date_start, $date_end)
  2269. {
  2270. global $conf;
  2271. $now = dol_now();
  2272. // Specify as export : update field date_validated on selected month/year
  2273. $sql = " UPDATE " . MAIN_DB_PREFIX . "accounting_bookkeeping";
  2274. $sql .= " SET date_validated = '" . $this->db->idate($now) . "'";
  2275. $sql .= " WHERE entity = " . ((int) $conf->entity);
  2276. $sql .= " AND DATE(doc_date) >= '" . $this->db->idate($date_start) . "'";
  2277. $sql .= " AND DATE(doc_date) <= '" . $this->db->idate($date_end) . "'";
  2278. $sql .= " AND date_validated IS NULL";
  2279. dol_syslog(__METHOD__, LOG_DEBUG);
  2280. $resql = $this->db->query($sql);
  2281. if (!$resql) {
  2282. $this->errors[] = $this->db->lasterror();
  2283. return -1;
  2284. }
  2285. return 1;
  2286. }
  2287. /**
  2288. * Close fiscal period
  2289. *
  2290. * @param int $fiscal_period_id Fiscal year ID
  2291. * @param int $new_fiscal_period_id New fiscal year ID
  2292. * @param bool $separate_auxiliary_account Separate auxiliary account
  2293. * @param bool $generate_bookkeeping_records Generate closure bookkeeping records
  2294. * @return int int Return integer <0 if KO, >0 if OK
  2295. */
  2296. public function closeFiscalPeriod($fiscal_period_id, $new_fiscal_period_id, $separate_auxiliary_account = false, $generate_bookkeeping_records = true)
  2297. {
  2298. global $conf, $langs, $user;
  2299. // Current fiscal period
  2300. $fiscal_period_id = max(0, $fiscal_period_id);
  2301. if (empty($fiscal_period_id)) {
  2302. $langs->load('errors');
  2303. $this->errors[] = $langs->trans('ErrorBadParameters');
  2304. return -1;
  2305. }
  2306. $fiscal_period = new Fiscalyear($this->db);
  2307. $result = $fiscal_period->fetch($fiscal_period_id);
  2308. if ($result < 0) {
  2309. $this->error = $fiscal_period->error;
  2310. $this->errors = $fiscal_period->errors;
  2311. return -1;
  2312. } elseif (empty($fiscal_period->id)) {
  2313. $langs->loadLangs(array('errors', 'compta'));
  2314. $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('FiscalPeriod') . ' (' . $fiscal_period_id . ')';
  2315. return -1;
  2316. }
  2317. // New fiscal period
  2318. $new_fiscal_period_id = max(0, $new_fiscal_period_id);
  2319. if (empty($new_fiscal_period_id)) {
  2320. $langs->load('errors');
  2321. $this->errors[] = $langs->trans('ErrorBadParameters');
  2322. return -1;
  2323. }
  2324. $new_fiscal_period = new Fiscalyear($this->db);
  2325. $result = $new_fiscal_period->fetch($new_fiscal_period_id);
  2326. if ($result < 0) {
  2327. $this->error = $new_fiscal_period->error;
  2328. $this->errors = $new_fiscal_period->errors;
  2329. return -1;
  2330. } elseif (empty($new_fiscal_period->id)) {
  2331. $langs->loadLangs(array('errors', 'compta'));
  2332. $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('FiscalPeriod') . ' (' . $new_fiscal_period_id . ')';
  2333. return -1;
  2334. }
  2335. $error = 0;
  2336. $this->db->begin();
  2337. $fiscal_period->statut = Fiscalyear::STATUS_CLOSED;
  2338. $fiscal_period->status = Fiscalyear::STATUS_CLOSED; // Actually not used
  2339. $result = $fiscal_period->update($user);
  2340. if ($result < 0) {
  2341. $this->error = $fiscal_period->error;
  2342. $this->errors = $fiscal_period->errors;
  2343. $error++;
  2344. }
  2345. if (!$error && !empty($generate_bookkeeping_records)) {
  2346. $journal_id = max(0, getDolGlobalString('ACCOUNTING_CLOSURE_DEFAULT_JOURNAL'));
  2347. if (empty($journal_id)) {
  2348. $langs->loadLangs(array('errors', 'accountancy'));
  2349. $this->errors[] = $langs->trans('ErrorBadParameters') . ' - ' . $langs->trans('Codejournal') . ' (' . $langs->trans('AccountingJournalType9') . ')';
  2350. $error++;
  2351. }
  2352. // Fetch journal
  2353. if (!$error) {
  2354. $journal = new AccountingJournal($this->db);
  2355. $result = $journal->fetch($journal_id);
  2356. if ($result < 0) {
  2357. $this->error = $journal->error;
  2358. $this->errors = $journal->errors;
  2359. $error++;
  2360. } elseif ($result == 0) {
  2361. $langs->loadLangs(array('errors', 'accountancy'));
  2362. $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('Codejournal') . ' (' . $langs->trans('AccountingJournalType9') . ')';
  2363. $error++;
  2364. }
  2365. }
  2366. if (!$error) {
  2367. $accounting_groups_used_for_balance_sheet_account = array_filter(array_map('trim', explode(',', getDolGlobalString('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT'))), 'strlen');
  2368. $accounting_groups_used_for_income_statement = array_filter(array_map('trim', explode(',', getDolGlobalString('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT'))), 'strlen');
  2369. $pcg_type_filter = array();
  2370. $tmp = array_merge($accounting_groups_used_for_balance_sheet_account, $accounting_groups_used_for_income_statement);
  2371. foreach ($tmp as $item) {
  2372. $pcg_type_filter[] = "'" . $this->db->escape($item) . "'";
  2373. }
  2374. $sql = 'SELECT';
  2375. $sql .= " t.numero_compte,";
  2376. $sql .= " t.label_compte,";
  2377. if ($separate_auxiliary_account) {
  2378. $sql .= " t.subledger_account,";
  2379. $sql .= " t.subledger_label,";
  2380. }
  2381. $sql .= " aa.pcg_type,";
  2382. $sql .= " (SUM(t.credit) - SUM(t.debit)) as opening_balance";
  2383. $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
  2384. $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'accounting_account as aa ON aa.account_number = t.numero_compte';
  2385. $sql .= ' WHERE t.entity = ' . ((int) $conf->entity); // Do not use getEntity for accounting features
  2386. $sql .= " AND aa.entity = ". ((int) $conf->entity);
  2387. $sql .= ' AND aa.fk_pcg_version IN (SELECT pcg_version FROM '.MAIN_DB_PREFIX.'accounting_system WHERE rowid = '.((int) getDolGlobalInt('CHARTOFACCOUNTS')).')';
  2388. $sql .= ' AND aa.pcg_type IN (' . $this->db->sanitize(implode(',', $pcg_type_filter), 1) . ')';
  2389. $sql .= " AND DATE(t.doc_date) >= '" . $this->db->idate($fiscal_period->date_start) . "'";
  2390. $sql .= " AND DATE(t.doc_date) <= '" . $this->db->idate($fiscal_period->date_end) . "'";
  2391. $sql .= ' GROUP BY t.numero_compte, t.label_compte, aa.pcg_type';
  2392. if ($separate_auxiliary_account) {
  2393. $sql .= ' ,t.subledger_account, t.subledger_label';
  2394. }
  2395. $sql .= $this->db->order("t.numero_compte", "ASC");
  2396. $resql = $this->db->query($sql);
  2397. if (!$resql) {
  2398. $this->errors[] = 'Error ' . $this->db->lasterror();
  2399. dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
  2400. $error++;
  2401. } else {
  2402. $now = dol_now();
  2403. $income_statement_amount = 0;
  2404. while ($obj = $this->db->fetch_object($resql)) {
  2405. if (in_array($obj->pcg_type, $accounting_groups_used_for_income_statement)) {
  2406. $income_statement_amount += $obj->opening_balance;
  2407. } else {
  2408. // Insert bookkeeping record for balance sheet account
  2409. $mt = $obj->opening_balance;
  2410. $bookkeeping = new BookKeeping($this->db);
  2411. $bookkeeping->doc_date = $new_fiscal_period->date_start;
  2412. $bookkeeping->date_lim_reglement = '';
  2413. $bookkeeping->doc_ref = $new_fiscal_period->label;
  2414. $bookkeeping->date_creation = $now;
  2415. $bookkeeping->doc_type = 'closure';
  2416. $bookkeeping->fk_doc = $new_fiscal_period->id;
  2417. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  2418. $bookkeeping->thirdparty_code = '';
  2419. if ($separate_auxiliary_account) {
  2420. $bookkeeping->subledger_account = $obj->subledger_account;
  2421. $bookkeeping->subledger_label = $obj->subledger_label;
  2422. } else {
  2423. $bookkeeping->subledger_account = '';
  2424. $bookkeeping->subledger_label = '';
  2425. }
  2426. $bookkeeping->numero_compte = $obj->numero_compte;
  2427. $bookkeeping->label_compte = $obj->label_compte;
  2428. $bookkeeping->label_operation = $new_fiscal_period->label;
  2429. $bookkeeping->montant = $mt;
  2430. $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
  2431. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  2432. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  2433. $bookkeeping->code_journal = $journal->code;
  2434. $bookkeeping->journal_label = $langs->transnoentities($journal->label);
  2435. $bookkeeping->fk_user_author = $user->id;
  2436. $bookkeeping->entity = $conf->entity;
  2437. $result = $bookkeeping->create($user);
  2438. if ($result < 0) {
  2439. $this->error = $bookkeeping->error;
  2440. $this->errors = $bookkeeping->errors;
  2441. $error++;
  2442. break;
  2443. }
  2444. }
  2445. }
  2446. // Insert bookkeeping record for income statement
  2447. if (!$error && $income_statement_amount != 0) {
  2448. $mt = $income_statement_amount;
  2449. $accountingaccount = new AccountingAccount($this->db);
  2450. $accountingaccount->fetch(null, getDolGlobalString($income_statement_amount < 0 ? 'ACCOUNTING_RESULT_LOSS' : 'ACCOUNTING_RESULT_PROFIT'), true);
  2451. $bookkeeping = new BookKeeping($this->db);
  2452. $bookkeeping->doc_date = $new_fiscal_period->date_start;
  2453. $bookkeeping->date_lim_reglement = '';
  2454. $bookkeeping->doc_ref = $new_fiscal_period->label;
  2455. $bookkeeping->date_creation = $now;
  2456. $bookkeeping->doc_type = 'closure';
  2457. $bookkeeping->fk_doc = $new_fiscal_period->id;
  2458. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  2459. $bookkeeping->thirdparty_code = '';
  2460. if ($separate_auxiliary_account) {
  2461. $bookkeeping->subledger_label = '';
  2462. $bookkeeping->subledger_account = $obj->subledger_account;
  2463. $bookkeeping->subledger_label = $obj->subledger_label;
  2464. } else {
  2465. $bookkeeping->subledger_account = '';
  2466. $bookkeeping->subledger_label = '';
  2467. }
  2468. $bookkeeping->numero_compte = $accountingaccount->account_number;
  2469. $bookkeeping->label_compte = $accountingaccount->label;
  2470. $bookkeeping->label_operation = $new_fiscal_period->label;
  2471. $bookkeeping->montant = $mt;
  2472. $bookkeeping->sens = ($mt >= 0) ? 'C' : 'D';
  2473. $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
  2474. $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
  2475. $bookkeeping->code_journal = $journal->code;
  2476. $bookkeeping->journal_label = $langs->transnoentities($journal->label);
  2477. $bookkeeping->fk_user_author = $user->id;
  2478. $bookkeeping->entity = $conf->entity;
  2479. $result = $bookkeeping->create($user);
  2480. if ($result < 0) {
  2481. $this->error = $bookkeeping->error;
  2482. $this->errors = $bookkeeping->errors;
  2483. $error++;
  2484. }
  2485. }
  2486. $this->db->free($resql);
  2487. }
  2488. }
  2489. }
  2490. if ($error) {
  2491. $this->db->rollback();
  2492. return -1;
  2493. } else {
  2494. $this->db->commit();
  2495. return 1;
  2496. }
  2497. }
  2498. /**
  2499. * Insert accounting reversal into the inventory journal of the new fiscal period
  2500. *
  2501. * @param int $fiscal_period_id Fiscal year ID
  2502. * @param int $inventory_journal_id Inventory journal ID
  2503. * @param int $new_fiscal_period_id New fiscal year ID
  2504. * @param int $date_start Date start
  2505. * @param int $date_end Date end
  2506. * @return int int Return integer <0 if KO, >0 if OK
  2507. */
  2508. public function insertAccountingReversal($fiscal_period_id, $inventory_journal_id, $new_fiscal_period_id, $date_start, $date_end)
  2509. {
  2510. global $conf, $langs, $user;
  2511. // Current fiscal period
  2512. $fiscal_period_id = max(0, $fiscal_period_id);
  2513. if (empty($fiscal_period_id)) {
  2514. $langs->load('errors');
  2515. $this->errors[] = $langs->trans('ErrorBadParameters');
  2516. return -1;
  2517. }
  2518. $fiscal_period = new Fiscalyear($this->db);
  2519. $result = $fiscal_period->fetch($fiscal_period_id);
  2520. if ($result < 0) {
  2521. $this->error = $fiscal_period->error;
  2522. $this->errors = $fiscal_period->errors;
  2523. return -1;
  2524. } elseif (empty($fiscal_period->id)) {
  2525. $langs->loadLangs(array('errors', 'compta'));
  2526. $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('FiscalPeriod') . ' (' . $fiscal_period_id . ')';
  2527. return -1;
  2528. }
  2529. // New fiscal period
  2530. $new_fiscal_period_id = max(0, $new_fiscal_period_id);
  2531. if (empty($new_fiscal_period_id)) {
  2532. $langs->load('errors');
  2533. $this->errors[] = $langs->trans('ErrorBadParameters');
  2534. return -1;
  2535. }
  2536. $new_fiscal_period = new Fiscalyear($this->db);
  2537. $result = $new_fiscal_period->fetch($new_fiscal_period_id);
  2538. if ($result < 0) {
  2539. $this->error = $new_fiscal_period->error;
  2540. $this->errors = $new_fiscal_period->errors;
  2541. return -1;
  2542. } elseif (empty($new_fiscal_period->id)) {
  2543. $langs->loadLangs(array('errors', 'compta'));
  2544. $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('FiscalPeriod') . ' (' . $new_fiscal_period_id . ')';
  2545. return -1;
  2546. }
  2547. // Inventory journal
  2548. $inventory_journal_id = max(0, $inventory_journal_id);
  2549. if (empty($inventory_journal_id)) {
  2550. $langs->load('errors');
  2551. $this->errors[] = $langs->trans('ErrorBadParameters');
  2552. return -1;
  2553. }
  2554. // Fetch journal
  2555. $inventory_journal = new AccountingJournal($this->db);
  2556. $result = $inventory_journal->fetch($inventory_journal_id);
  2557. if ($result < 0) {
  2558. $this->error = $inventory_journal->error;
  2559. $this->errors = $inventory_journal->errors;
  2560. return -1;
  2561. } elseif ($result == 0) {
  2562. $langs->loadLangs(array('errors', 'accountancy'));
  2563. $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('InventoryJournal');
  2564. return -1;
  2565. }
  2566. $error = 0;
  2567. $this->db->begin();
  2568. $sql = 'SELECT t.rowid';
  2569. $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
  2570. $sql .= ' WHERE t.entity = ' . ((int) $conf->entity); // Do not use getEntity for accounting features
  2571. $sql .= " AND code_journal = '" . $this->db->escape($inventory_journal->code) . "'";
  2572. $sql .= " AND DATE(t.doc_date) >= '" . $this->db->idate($date_start) . "'";
  2573. $sql .= " AND DATE(t.doc_date) <= '" . $this->db->idate($date_end) . "'";
  2574. $sql .= " AND DATE(t.doc_date) >= '" . $this->db->idate($fiscal_period->date_start) . "'";
  2575. $sql .= " AND DATE(t.doc_date) <= '" . $this->db->idate($fiscal_period->date_end) . "'";
  2576. $resql = $this->db->query($sql);
  2577. if (!$resql) {
  2578. $this->errors[] = 'Error ' . $this->db->lasterror();
  2579. dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);
  2580. $error++;
  2581. } else {
  2582. $now = dol_now();
  2583. while ($obj = $this->db->fetch_object($resql)) {
  2584. $bookkeeping = new BookKeeping($this->db);
  2585. $result = $bookkeeping->fetch($obj->rowid);
  2586. if ($result < 0) {
  2587. $this->error = $inventory_journal->error;
  2588. $this->errors = $inventory_journal->errors;
  2589. $error++;
  2590. break;
  2591. } elseif ($result == 0) {
  2592. $langs->loadLangs(array('errors', 'accountancy'));
  2593. $this->errors[] = $langs->trans('ErrorRecordNotFound') . ' - ' . $langs->trans('LineId') . ': ' . $obj->rowid;
  2594. $error++;
  2595. break;
  2596. }
  2597. $bookkeeping->id = 0;
  2598. $bookkeeping->doc_date = $new_fiscal_period->date_start;
  2599. $bookkeeping->doc_ref = $new_fiscal_period->label;
  2600. $bookkeeping->date_creation = $now;
  2601. $bookkeeping->doc_type = 'accounting_reversal';
  2602. $bookkeeping->fk_doc = $new_fiscal_period->id;
  2603. $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
  2604. $bookkeeping->montant = -$bookkeeping->montant;
  2605. $bookkeeping->sens = ($bookkeeping->montant >= 0) ? 'C' : 'D';
  2606. $old_debit = $bookkeeping->debit;
  2607. $bookkeeping->debit = $bookkeeping->credit;
  2608. $bookkeeping->credit = $old_debit;
  2609. $bookkeeping->fk_user_author = $user->id;
  2610. $bookkeeping->entity = $conf->entity;
  2611. $result = $bookkeeping->create($user);
  2612. if ($result < 0) {
  2613. $this->error = $bookkeeping->error;
  2614. $this->errors = $bookkeeping->errors;
  2615. $error++;
  2616. break;
  2617. }
  2618. }
  2619. $this->db->free($resql);
  2620. }
  2621. if ($error) {
  2622. $this->db->rollback();
  2623. return -1;
  2624. } else {
  2625. $this->db->commit();
  2626. return 1;
  2627. }
  2628. }
  2629. }
  2630. /**
  2631. * Class BookKeepingLine
  2632. */
  2633. class BookKeepingLine
  2634. {
  2635. /**
  2636. * @var int ID
  2637. */
  2638. public $id;
  2639. public $doc_date = '';
  2640. public $doc_type;
  2641. public $doc_ref;
  2642. /**
  2643. * @var int ID
  2644. */
  2645. public $fk_doc;
  2646. /**
  2647. * @var int ID
  2648. */
  2649. public $fk_docdet;
  2650. public $thirdparty_code;
  2651. public $subledger_account;
  2652. public $subledger_label;
  2653. public $numero_compte;
  2654. public $label_compte;
  2655. public $label_operation;
  2656. public $debit;
  2657. public $credit;
  2658. /**
  2659. * @var float Amount
  2660. * @deprecated see $amount
  2661. */
  2662. public $montant;
  2663. /**
  2664. * @var float Amount
  2665. */
  2666. public $amount;
  2667. /**
  2668. * @var float Multicurrency amount
  2669. */
  2670. public $multicurrency_amount;
  2671. /**
  2672. * @var float Multicurrency code
  2673. */
  2674. public $multicurrency_code;
  2675. /**
  2676. * @var string Sens
  2677. */
  2678. public $sens;
  2679. public $lettering_code;
  2680. public $date_lettering;
  2681. /**
  2682. * @var int ID
  2683. */
  2684. public $fk_user_author;
  2685. public $import_key;
  2686. public $code_journal;
  2687. public $journal_label;
  2688. public $piece_num;
  2689. /**
  2690. * @var integer|string date_creation
  2691. */
  2692. public $date_creation;
  2693. /**
  2694. * @var integer|string $date_modification;
  2695. */
  2696. public $date_modification;
  2697. /**
  2698. * @var integer|string $date_export;
  2699. */
  2700. public $date_export;
  2701. /**
  2702. * @var integer|string $date_validation;
  2703. */
  2704. public $date_validation;
  2705. /**
  2706. * @var integer|string $date_lim_reglement;
  2707. */
  2708. public $date_lim_reglement;
  2709. }