dolibarr 25.0.0-alpha
treasuryjournal.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2007-2010 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2007-2010 Jean Heimburger <jean@tiaris.info>
4 * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2013 Christophe Battarel <christophe.battarel@altairis.fr>
7 * Copyright (C) 2013-2025 Alexandre Spangaro <alexandre@inovea-conseil.com>
8 * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
9 * Copyright (C) 2013-2014 Olivier Geffroy <jeff@jeffinfo.com>
10 * Copyright (C) 2017-2025 Frédéric France <frederic.france@free.fr>
11 * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
12 * Copyright (C) 2025 Hannes Hieronimi <hannes@innwerk.org>
13 * Copyright (C) 2025-2026 MDW <mdeweerd@users.noreply.github.com>
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27 */
28
35// Load Dolibarr environment
36require '../../main.inc.php';
45require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
46require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
47require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
48require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
49require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
50require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
51require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
52require_once DOL_DOCUMENT_ROOT.'/core/lib/loan.lib.php';
53
54// Load translation files required by the page
55$langs->loadLangs(array("companies", "other", "compta", "banks", "bills", "donations", "loan", "accountancy", "trips", "salaries", "hrm", "members"));
56
57// Multi journal
58$id_journal = GETPOSTINT('id_journal');
59
60$date_startmonth = GETPOSTINT('date_startmonth');
61$date_startday = GETPOSTINT('date_startday');
62$date_startyear = GETPOSTINT('date_startyear');
63$date_endmonth = GETPOSTINT('date_endmonth');
64$date_endday = GETPOSTINT('date_endday');
65$date_endyear = GETPOSTINT('date_endyear');
66$in_bookkeeping = GETPOST('in_bookkeeping', 'aZ09');
67
68$only_rappro = GETPOSTINT('only_rappro');
69if ($only_rappro == 0) {
70 //GET page for the first time, use default settings
71 $only_rappro = getDolGlobalInt('ACCOUNTING_BANK_CONCILIATED');
72}
73
74$now = dol_now();
75
76$action = GETPOST('action', 'aZ09');
77
78if ($in_bookkeeping == '' || $action == 'writebookkeeping') { // Never transfer again documents already in bookkeeping
79 $in_bookkeeping = 'notyet';
80}
81
82// Security check
83if (!isModEnabled('accounting')) {
85}
86if ($user->socid > 0) {
88}
89if (!$user->hasRight('accounting', 'bind', 'write')) {
91}
92
93
94/*
95 * Actions
96 */
97
98$error = 0;
99
100$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
101$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
102
103$pastmonth = null; // Initialise for static analysis (could be really unseg)
104$pastmonthyear = null;
105
106if (empty($date_startmonth)) {
107 // Period by default on transfer
109 $date_start = $dates['date_start'];
110 $pastmonthyear = $dates['pastmonthyear'];
111 $pastmonth = $dates['pastmonth'];
112}
113if (empty($date_endmonth)) {
114 // Period by default on transfer
116 $date_end = $dates['date_end'];
117 $pastmonthyear = $dates['pastmonthyear'];
118 $pastmonth = $dates['pastmonth'];
119}
120
121if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
122 $date_start = dol_get_first_day((int) $pastmonthyear, (int) $pastmonth, false);
123 $date_end = dol_get_last_day((int) $pastmonthyear, (int) $pastmonth, false);
124}
125
126// Get all bank lines
127//-------------------------------------
128$sql = "SELECT b.rowid, b.dateo as do, b.datev as dv, b.amount, b.amount_main_currency, b.label, b.rappro, b.num_releve, b.num_chq, b.fk_type, b.fk_account,";
129$sql .= " ba.courant, ba.ref as baref, ba.account_number, ba.fk_accountancy_journal,";
130$sql .= " bu.type as bu_type";
131$sql .= " FROM ".$db->prefix()."bank as b";
132$sql .= " JOIN ".$db->prefix()."bank_account as ba on b.fk_account = ba.rowid";
133$sql .= " LEFT JOIN ".$db->prefix()."bank_url as bu ON bu.fk_bank = b.rowid";
134$sql .= " WHERE ba.fk_accountancy_journal = ".((int) $id_journal);
135$sql .= " AND b.amount <> 0 AND ba.entity IN (".getEntity('bank_account').")"; // We don't share object for accountancy, we use source object sharing
136if ($date_start && $date_end) {
137 $sql .= " AND b.dateo >= '".$db->idate($date_start)."' AND b.dateo <= '".$db->idate($date_end)."'";
138}
139// Define begin binding date
140if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
141 $sql .= " AND b.dateo >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
142}
143// Already in bookkeeping or not
144if ($in_bookkeeping == 'already') {
145 $sql .= " AND (b.rowid IN (SELECT fk_doc FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type='bank') )";
146}
147if ($in_bookkeeping == 'notyet') {
148 $sql .= " AND (b.rowid NOT IN (SELECT fk_doc FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type='bank') )";
149}
150if ($only_rappro == 2) {
151 $sql .= " AND (b.rappro = '1')";
152}
153$sql .= " ORDER BY b.dateo";
154//print $sql;
155
156$result_lines = array();
157
158// Data cached
159$payment_ids = array();
160$tabpay = array();
161$tabaccount = array();
162$tabobject = array();
163$tabaccountingaccount = array();
164$tabvatdata = array();
165
166dol_syslog("accountancy/journal/treasuryjournal.php", LOG_DEBUG);
167$resql = $db->query($sql);
168if ($resql) {
169 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
170 $static_account = new Account($db);
171
172 while ($obj = $db->fetch_object($resql)) {
173 // Get payment infos (rowid is bank ID)
174 if (!isset($tabpay[$obj->rowid])) {
175 $tabpay[$obj->rowid] = array(
176 'id' => $obj->rowid,
177 'date' => $db->jdate($obj->do),
178 'type_payment' => $obj->fk_type,// CHQ, VIR, LIQ, CB, ...
179 'ref' => $obj->label, // by default, not unique. May be changed later
180 'fk_bank_account' => $obj->fk_account,
181 'objects' => array(),
182 );
183 $reg = array();
184 if (preg_match('/^\‍((.*)\‍)$/i', $obj->label, $reg)) {
185 $tabpay[$obj->rowid]["lib"] = $langs->trans($reg[1]);
186 } else {
187 $tabpay[$obj->rowid]["lib"] = dol_trunc($obj->label, 60);
188 }
189 }
190 $payment_ids[$obj->bu_type][$obj->rowid] = $obj->rowid;
191
192 // Get bank account infos (rowid is bank ID)
193 if (!isset($tabaccount[$obj->fk_account])) {
194 $static_account->id = $obj->fk_account;
195 $static_account->ref = $obj->baref;
196 $tabaccount[$obj->fk_account] = [
197 'id' => $obj->fk_account,
198 'account_ref' => $obj->baref,
199 'account_number' => $obj->account_number,
200 'url' => $static_account->getNomUrl(1),
201 ];
202 }
203 }
204 $db->free($resql);
205
206 // Loop on each bank_url record that is already or not yet transferred.
207 foreach ($payment_ids as $type => $ids) {
208 switch ($type) {
209 case 'payment':
210 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
211
212 // Customer invoices
213 //------------------------------------------
214 $sql = "SELECT f.rowid, f.ref AS ref, f.total_ht AS invoice_total_ht, f.total_ttc AS invoice_total_ttc,";
215 $sql .= " pf.amount AS amount_payment, pf.fk_paiement AS payment_id,";
216 $sql .= " fd.rowid AS row_id, fd.total_ht, fd.total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.vat_src_code,";
217 $sql .= " aa.account_number as accountancy_code, aa.label as accountancy_code_label,";
218 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
219 $sql .= " FROM ".$db->prefix()."facturedet as fd";
220 $sql .= " INNER JOIN ".$db->prefix()."facture as f ON f.rowid = fd.fk_facture";
221 $sql .= " INNER JOIN ".$db->prefix()."paiement_facture as pf ON pf.fk_facture = f.rowid";
222 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = pf.fk_paiement AND bu.type = '".$db->escape($type)."'";
223 $sql .= " LEFT JOIN ".$db->prefix()."product as p ON p.rowid = fd.fk_product";
224 $sql .= " LEFT JOIN ".$db->prefix()."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
225 // bu.fk_bank = b.rowid = ab.fk_doc = ID in llx_bank and bu_type = 'payment'
226 $sql .= " WHERE f.entity IN (".getEntity('facture', 0).')'; // We don't share object for accountancy, we use source object sharing
227 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
228 if ($in_bookkeeping == 'already') {
229 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
230 }
231 if ($in_bookkeeping == 'notyet') {
232 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
233 }
234 $sql .= " AND fd.fk_code_ventilation > 0";
235 $sql .= " AND f.fk_statut > 0";
236 $sql .= " AND fd.product_type IN (0,1)";
237 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".(!getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS') ? Facture::TYPE_DEPOSIT."," : "").Facture::TYPE_SITUATION.")";
238 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
239 //$sql .= " GROUP BY fd.rowid, bu.fk_bank, pf.amount, bu.url_id, f.rowid, f.ref, f.total_ht, f.total_ttc, fd.total_ht, fd.total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.total_ttc, fd.vat_src_code, aa.account_number, aa.label, bu.type";
240 $sql .= " ORDER BY aa.account_number";
241
242 $resql = $db->query($sql);
243 if ($resql) {
244 $langs->load("bills");
245 $static_invoice = new Facture($db);
246 $already_sum = array();
247 $account_vat_sold = getDolGlobalString('ACCOUNTING_VAT_SOLD_ACCOUNT', 'NotDefined'); // NotDefined is a reserved word
248
249 while ($obj = $db->fetch_object($resql)) {
250 $object_key = $obj->bu_type.'_'.$obj->rowid; // ->bu_type is "payment", ->rowid is invoice ID
251
252 // If 1 invoice has 2 payments at 2 different date, we have 2 record $tabpay because $obj->fk_bank is different (obj->fk_bank is ID of payment in bank record table).
253 // If 2 invoices are paid in the same payment, we have 1 $tabpay with 2 objects. Lines are written per object, with the ref of the object in the label (see $label_suffix).
254
255 // Add object in $tabpay payment table
256 // bu.fk_bank = b.rowid = ab.fk_doc = ID in llx_bank
257 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
258 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
259 'amount' => $obj->amount_payment,
260 'bu_url_id' => $obj->bu_url_id,
261 );
262 }
263
264 if (isset($already_sum[$obj->row_id])) {
265 continue;
266 }
267 $already_sum[$obj->row_id] = $obj->row_id;
268
269 // Set object infos
270 if (!isset($tabobject[$object_key])) {
271 $static_invoice->id = $obj->rowid;
272 $static_invoice->ref = $obj->ref;
273 $tabobject[$object_key] = array(
274 'id' => $obj->rowid,
275 'ref' => $obj->ref, // It would be better to have a doc_ref that is 'BankId '.$obj->fk_bank.' - Facture FAzzz' and not just 'FAzzz' to be protected against duplicate, where xxx = $obj->fk_bank
276 'total_ht' => $obj->invoice_total_ht,
277 'total_ttc' => $obj->invoice_total_ttc,
278 'url' => $static_invoice->getNomUrl(1),
279 'operations' => array(),
280 'vats' => array(),
281 );
282 }
283
284 // Set accounting account infos
285 if (!isset($tabaccountingaccount[$obj->accountancy_code])) {
286 $tabaccountingaccount[$obj->accountancy_code] = array(
287 'label' => !empty($obj->accountancy_code_label) ? $obj->accountancy_code_label : $langs->trans('NotDefined'),
288 );
289 }
290
291 // Add amount for the accountancy code
292 if (!isset($tabobject[$object_key]['operations'][$obj->accountancy_code])) {
293 $tabobject[$object_key]['operations'][$obj->accountancy_code] = array(
294 'total_ht' => 0,
295 );
296 }
297 $tabobject[$object_key]['operations'][$obj->accountancy_code]['total_ht'] += $obj->total_ht;
298
299 if ($obj->total_tva + $obj->total_localtax1 + $obj->total_localtax2 != 0) {
300 // Get vat code compta
301 if (!isset($tabvatdata[$obj->tva_tx][$obj->vat_src_code])) {
302 $tabvatdata[$obj->tva_tx][$obj->vat_src_code] = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
303 }
304 $compta_tva = (!empty($tabvatdata[$obj->tva_tx][$obj->vat_src_code]['accountancy_code_sell']) ? $tabvatdata[$obj->tva_tx][$obj->vat_src_code]['accountancy_code_sell'] : $account_vat_sold);
305
306 // Add amount VAT for the code compta
307 if (!isset($tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx])) {
308 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx] = array(
309 'tva_tx' => $obj->tva_tx,
310 'total_tva' => 0,
311 'total_localtax1' => 0,
312 'total_localtax2' => 0,
313 );
314 }
315 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_tva'] += $obj->total_tva;
316 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_localtax1'] += $obj->total_localtax1;
317 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_localtax2'] += $obj->total_localtax2;
318 }
319 }
320 } else {
321 dol_print_error($db);
322 }
323 break;
324 case 'payment_supplier':
325 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
326
327 // Supplier invoices
328 //------------------------------------------
329 $sql = "SELECT ff.rowid, ff.ref, ff.total_ht AS supplier_invoice_total_ht, ff.total_ttc AS supplier_invoice_total_ttc,";
330 $sql .= " pff.amount AS amount_payment, pff.fk_paiementfourn AS payment_id,";
331 $sql .= " ffd.rowid AS row_id, ffd.total_ht, ffd.tva AS total_tva, ffd.total_localtax1, ffd.total_localtax2, ffd.tva_tx, ffd.total_ttc, ffd.vat_src_code,";
332 $sql .= " aa.account_number as accountancy_code, aa.label as accountancy_code_label,";
333 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
334 $sql .= " FROM ".$db->prefix()."facture_fourn_det as ffd";
335 $sql .= " INNER JOIN ".$db->prefix()."facture_fourn as ff ON ff.rowid = ffd.fk_facture_fourn";
336 $sql .= " INNER JOIN ".$db->prefix()."paiementfourn_facturefourn as pff ON pff.fk_facturefourn = ff.rowid";
337 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = pff.fk_paiementfourn AND bu.type = '".$db->escape($type)."'";
338 $sql .= " LEFT JOIN ".$db->prefix()."product as p ON p.rowid = ffd.fk_product";
339 $sql .= " LEFT JOIN ".$db->prefix()."accounting_account as aa ON aa.rowid = ffd.fk_code_ventilation";
340 $sql .= " WHERE ff.entity IN (".getEntity('facture_fourn', 0).')'; // We don't share object for accountancy, we use source object sharing
341 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
342 if ($in_bookkeeping == 'already') {
343 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
344 }
345 if ($in_bookkeeping == 'notyet') {
346 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
347 }
348 $sql .= " AND ffd.fk_code_ventilation > 0";
349 $sql .= " AND ff.fk_statut > 0";
350 $sql .= " AND ffd.product_type IN (0,1)";
351 $sql .= " AND ff.type IN (".FactureFournisseur::TYPE_STANDARD.",".FactureFournisseur::TYPE_REPLACEMENT.",".FactureFournisseur::TYPE_CREDIT_NOTE.",".(!getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS') ? FactureFournisseur::TYPE_DEPOSIT."," : "").FactureFournisseur::TYPE_SITUATION.")";
352 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
353 //$sql .= " GROUP BY ffd.rowid, bu.fk_bank, ff.rowid, ff.ref, ff.total_ht, ff.total_ttc, pff.amount, ffd.total_ht, ffd.tva, ffd.total_localtax1, ffd.total_localtax2, ffd.tva_tx, ffd.total_ttc, ffd.vat_src_code, aa.account_number, aa.label, bu.url_id, bu.type";
354 $sql .= " ORDER BY aa.account_number";
355
356 $resql = $db->query($sql);
357 if ($resql) {
358 $langs->load("suppliers");
359 $static_supplier_invoice = new FactureFournisseur($db);
360 $already_sum = array();
361 $account_vat_buy = getDolGlobalString('ACCOUNTING_VAT_BUY_ACCOUNT', 'NotDefined'); // NotDefined is a reserved word
362
363 while ($obj = $db->fetch_object($resql)) {
364 $object_key = $obj->bu_type.'_'.$obj->rowid;
365
366 // Add object in payment
367 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
368 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
369 'amount' => -$obj->amount_payment,
370 'bu_url_id' => $obj->bu_url_id,
371 );
372 }
373
374 if (isset($already_sum[$obj->row_id])) {
375 continue;
376 }
377 $already_sum[$obj->row_id] = $obj->row_id;
378
379 // Set object infos
380 if (!isset($tabobject[$object_key])) {
381 $static_supplier_invoice->id = $obj->rowid;
382 $static_supplier_invoice->ref = $obj->ref;
383 $tabobject[$object_key] = array(
384 'id' => $obj->rowid,
385 'ref' => $obj->ref, // It would be better to have a doc_ref that is 'BankId '.$obj->fk_bank.' - Facture FAzzz' and not just 'FAzzz' to be protected against duplicate, where xxx = $obj->fk_bank
386 'total_ht' => -$obj->supplier_invoice_total_ht,
387 'total_ttc' => -$obj->supplier_invoice_total_ttc,
388 'url' => $static_supplier_invoice->getNomUrl(1),
389 'operations' => array(),
390 'vats' => array(),
391 );
392 }
393
394 // Set accounting account infos
395 if (!isset($tabaccountingaccount[$obj->accountancy_code])) {
396 $tabaccountingaccount[$obj->accountancy_code] = array(
397 'label' => !empty($obj->accountancy_code_label) ? $obj->accountancy_code_label : $langs->trans('NotDefined'),
398 );
399 }
400
401 // Add amount for the accountancy code
402 if (!isset($tabobject[$object_key]['operations'][$obj->accountancy_code])) {
403 $tabobject[$object_key]['operations'][$obj->accountancy_code] = array(
404 'total_ht' => 0,
405 );
406 }
407 $tabobject[$object_key]['operations'][$obj->accountancy_code]['total_ht'] -= $obj->total_ht;
408
409 if ($obj->total_tva + $obj->total_localtax1 + $obj->total_localtax2 != 0) {
410 // Get vat code compta
411 if (!isset($tabvatdata[$obj->tva_tx][$obj->vat_src_code])) {
412 $tabvatdata[$obj->tva_tx][$obj->vat_src_code] = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
413 }
414 $compta_tva = (!empty($tabvatdata[$obj->tva_tx][$obj->vat_src_code]['accountancy_code_buy']) ? $tabvatdata[$obj->tva_tx][$obj->vat_src_code]['accountancy_code_buy'] : $account_vat_buy);
415
416 // Add amount VAT for the code compta
417 if (!isset($tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx])) {
418 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx] = array(
419 'tva_tx' => $obj->tva_tx,
420 'total_tva' => 0,
421 'total_localtax1' => 0,
422 'total_localtax2' => 0,
423 );
424 }
425 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_tva'] -= $obj->total_tva;
426 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_localtax1'] -= $obj->total_localtax1;
427 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_localtax2'] -= $obj->total_localtax2;
428 }
429 }
430 } else {
431 dol_print_error($db);
432 }
433 break;
434 case 'payment_expensereport':
435 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
436
437 // Expense reports
438 //------------------------------------------
439 $sql = "SELECT er.rowid, er.ref, er.total_ht AS expense_report_total_ht, er.total_ttc AS expense_report_total_ttc,";
440 $sql .= " per.amount AS amount_payment, per.rowid AS payment_id,";
441 $sql .= " erf.rowid AS row_id, erf.total_ht, erf.total_tva, erf.total_localtax1, erf.total_localtax2, erf.tva_tx, erf.total_ttc, erf.vat_src_code,";
442 $sql .= " ctf.accountancy_code,";
443 $sql .= " aa.label as accountancy_code_label,";
444 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
445 $sql .= " FROM ".$db->prefix()."expensereport_det as erf";
446 $sql .= " INNER JOIN ".$db->prefix()."expensereport as er ON er.rowid = erf.fk_expensereport";
447 $sql .= " INNER JOIN ".$db->prefix()."payment_expensereport as per ON per.fk_expensereport = er.rowid";
448 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = per.rowid AND bu.type = '".$db->escape($type)."'";
449 $sql .= " LEFT JOIN ".$db->prefix()."c_type_fees as ctf ON ctf.id = erf.fk_c_type_fees";
450 $sql .= " LEFT JOIN ".$db->prefix()."accounting_account as aa ON aa.account_number = ctf.accountancy_code";
451 $sql .= " WHERE er.entity IN (".getEntity('expensereport', 0).')'; // We don't share object for accountancy, we use source object sharing
452 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
453 if ($in_bookkeeping == 'already') {
454 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
455 }
456 if ($in_bookkeeping == 'notyet') {
457 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
458 }
459 $sql .= " AND er.fk_statut >= ".ExpenseReport::STATUS_APPROVED;
460 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
461 //$sql .= " GROUP BY erf.rowid, bu.fk_bank, per.amount, aa.label, bu.url_id, er.rowid, er.ref, er.total_ht, er.total_ttc, erf.total_ht, erf.total_tva, erf.total_localtax1, erf.total_localtax2, erf.tva_tx, erf.total_ttc, erf.vat_src_code, ctf.accountancy_code, bu.type, aa.account_number";
462 $sql .= " ORDER BY aa.account_number";
463
464 $resql = $db->query($sql);
465 if ($resql) {
466 $langs->load("trips");
467 $static_expense_report = new ExpenseReport($db);
468 $already_sum = array();
469 $account_vat_buy = getDolGlobalString('ACCOUNTING_VAT_BUY_ACCOUNT', 'NotDefined'); // NotDefined is a reserved word
470
471 while ($obj = $db->fetch_object($resql)) {
472 $object_key = $obj->bu_type.'_'.$obj->rowid;
473
474 // Add object in payment
475 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
476 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
477 'amount' => -$obj->amount_payment,
478 'bu_url_id' => $obj->bu_url_id,
479 );
480 }
481
482 if (isset($already_sum[$obj->row_id])) {
483 continue;
484 }
485 $already_sum[$obj->row_id] = $obj->row_id;
486
487 // Set object infos
488 if (!isset($tabobject[$object_key])) {
489 $static_expense_report->id = $obj->rowid;
490 $static_expense_report->ref = $obj->ref;
491 $tabobject[$object_key] = array(
492 'id' => $obj->rowid,
493 'ref' => $obj->ref,
494 'total_ht' => -$obj->expense_report_total_ht,
495 'total_ttc' => -$obj->expense_report_total_ttc,
496 'url' => $static_expense_report->getNomUrl(1),
497 'operations' => array(),
498 'vats' => array(),
499 );
500 }
501
502 // Set accounting account infos
503 $accountancy_code = !empty($obj->accountancy_code) ? $obj->accountancy_code : 'NotDefined';
504 if (!isset($tabaccountingaccount[$accountancy_code])) {
505 $tabaccountingaccount[$accountancy_code] = array(
506 'label' => !empty($obj->accountancy_code_label) ? $obj->accountancy_code_label : $langs->trans('NotDefined'),
507 );
508 }
509
510 // Add amount for the accountancy code
511 if (!isset($tabobject[$object_key]['operations'][$accountancy_code])) {
512 $tabobject[$object_key]['operations'][$accountancy_code] = array(
513 'total_ht' => 0,
514 );
515 }
516 $tabobject[$object_key]['operations'][$accountancy_code]['total_ht'] -= $obj->total_ht;
517
518 if ($obj->total_tva + $obj->total_localtax1 + $obj->total_localtax2 != 0) {
519 // Get vat code compta
520 if (!isset($tabvatdata[$obj->tva_tx][$obj->vat_src_code])) {
521 $tabvatdata[$obj->tva_tx][$obj->vat_src_code] = getTaxesFromId($obj->tva_tx.($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''), $mysoc, $mysoc, 0);
522 }
523 $compta_tva = (!empty($tabvatdata[$obj->tva_tx][$obj->vat_src_code]['accountancy_code_buy']) ? $tabvatdata[$obj->tva_tx][$obj->vat_src_code]['accountancy_code_buy'] : $account_vat_buy);
524
525 // Add amount VAT for the code compta
526 if (!isset($tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx])) {
527 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx] = array(
528 'tva_tx' => $obj->tva_tx,
529 'total_tva' => 0,
530 'total_localtax1' => 0,
531 'total_localtax2' => 0,
532 );
533 }
534 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_tva'] -= $obj->total_tva;
535 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_localtax1'] -= $obj->total_localtax1;
536 $tabobject[$object_key]['vats'][$compta_tva][$obj->tva_tx]['total_localtax2'] -= $obj->total_localtax2;
537 }
538 }
539 } else {
540 dol_print_error($db);
541 }
542 break;
543 case 'payment_salary':
544 // Payment salaries
545 //------------------------------------------
546 $sql = "SELECT ps.rowid,";
547 $sql .= " ps.amount AS amount_payment, ps.rowid as payment_id, ps.label AS label,";
548 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
549 $sql .= " FROM ".$db->prefix()."payment_salary as ps";
550 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = ps.rowid AND bu.type = '".$db->escape($type)."'";
551 $sql .= " WHERE ps.entity IN (".getEntity('user', 0).')'; // We don't share object for accountancy, we use source object sharing
552 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
553 if ($in_bookkeeping == 'already') {
554 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
555 }
556 if ($in_bookkeeping == 'notyet') {
557 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
558 }
559 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
560
561 $resql = $db->query($sql);
562 if ($resql) {
563 require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php';
564 $langs->load("salaries");
565 $static_payment_salary = new PaymentSalary($db);
566 $account_employee = getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', 'NotDefined'); // NotDefined is a reserved word
567 $prefix_ref = getDolGlobalString('MAIN_PAYMENT_SALARY_REF_PREFIX', 'PS');
568
569 while ($obj = $db->fetch_object($resql)) {
570 $object_key = $obj->bu_type.'_'.$obj->rowid;
571
572 // Add object in payment
573 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
574 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
575 'amount' => -$obj->amount_payment,
576 'bu_url_id' => $obj->bu_url_id,
577 );
578 }
579
580 // Set object infos
581 if (!isset($tabobject[$object_key])) {
582 $static_payment_salary->id = $obj->rowid;
583 $static_payment_salary->ref = $prefix_ref.$obj->rowid;
584 $tabobject[$object_key] = array(
585 'id' => $obj->rowid,
586 'ref' => $prefix_ref.$obj->rowid,
587 'total_ht' => -$obj->amount_payment,
588 'total_ttc' => -$obj->amount_payment,
589 'url' => $static_payment_salary->getNomUrl(1),
590 'operations' => array(),
591 'vats' => array(),
592 );
593 }
594
595 // Add amount for the accountancy code
596 $tabobject[$object_key]['operations'][$account_employee] = array(
597 'total_ht' => -$obj->amount_payment,
598 'label' => $obj->label,
599 );
600 }
601 } else {
602 dol_print_error($db);
603 }
604 break;
605 case 'payment_sc':
606 // Socials contributions
607 //------------------------------------------
608 $sql = "SELECT cs.rowid, cs.ref, cs.libelle AS label, cs.amount AS sociales_contributions_amount,";
609 $sql .= " pc.amount AS amount_payment, pc.rowid as payement_id,";
610 $sql .= " ccs.accountancy_code,";
611 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
612 $sql .= " FROM ".$db->prefix()."paiementcharge as pc";
613 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = pc.rowid AND bu.type = '".$db->escape($type)."'";
614 $sql .= " INNER JOIN ".$db->prefix()."chargesociales AS cs ON cs.rowid = pc.fk_charge";
615 $sql .= " LEFT JOIN ".$db->prefix()."c_chargesociales as ccs ON ccs.id = cs.fk_type";
616 $sql .= " WHERE cs.entity = ".((int) $conf->entity); // We don't share object for accountancy, we use source object sharing
617 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
618 if ($in_bookkeeping == 'already') {
619 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
620 }
621 if ($in_bookkeeping == 'notyet') {
622 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
623 }
624 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
625
626 $resql = $db->query($sql);
627 if ($resql) {
628 require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
629
630 $langs->load("bills");
631 $static_sociales_contributions = new ChargeSociales($db);
632 $prefix_ref = getDolGlobalString('MAIN_PAYMENT_SOCIALES_CONTRIBUTIONS_REF_PREFIX', 'SC');
633
634 while ($obj = $db->fetch_object($resql)) {
635 $object_key = $obj->bu_type.'_'.$obj->rowid;
636
637 // Add object in payment
638 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
639 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
640 'amount' => -$obj->amount_payment,
641 'bu_url_id' => $obj->bu_url_id,
642 );
643 }
644
645 // Set object infos
646 if (!isset($tabobject[$object_key])) {
647 $static_sociales_contributions->id = $obj->rowid;
648 $static_sociales_contributions->ref = $prefix_ref.$obj->rowid;
649 $tabobject[$object_key] = array(
650 'id' => $obj->rowid,
651 'ref' => $prefix_ref.$obj->rowid,
652 'total_ht' => -$obj->sociales_contributions_amount,
653 'total_ttc' => -$obj->sociales_contributions_amount,
654 'url' => $static_sociales_contributions->getNomUrl(1),
655 'operations' => array(),
656 'vats' => array(),
657 );
658 }
659
660 $accountancy_code = !empty($obj->accountancy_code) ? $obj->accountancy_code : 'NotDefined';
661
662 // Add amount for the accountancy code
663 $tabobject[$object_key]['operations'][$accountancy_code] = array(
664 'total_ht' => -$obj->sociales_contributions_amount,
665 'label' => $obj->label,
666 );
667 }
668 } else {
669 dol_print_error($db);
670 }
671 break;
672 case 'payment_vat':
673 // Payment VAT
674 //------------------------------------------
675 // The bank link of type 'payment_vat' is on the payment (llx_payment_vat), not on the VAT declaration (llx_tva)
676 $sql = "SELECT pv.rowid, t.rowid AS tva_id,";
677 $sql .= " pv.amount AS amount_payment, t.label AS label,";
678 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
679 $sql .= " FROM ".$db->prefix()."payment_vat as pv";
680 $sql .= " INNER JOIN ".$db->prefix()."tva as t ON t.rowid = pv.fk_tva";
681 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = pv.rowid AND bu.type = '".$db->escape($type)."'";
682 $sql .= " WHERE bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
683 // $sql .= " AND t.entity = " . ((int) $conf->entity); // TODO when entity is managed in tva
684 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
685 if ($in_bookkeeping == 'already') {
686 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
687 }
688 if ($in_bookkeeping == 'notyet') {
689 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
690 }
691
692 $resql = $db->query($sql);
693 if ($resql) {
694 require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php';
695
696 $langs->load("salaries");
697 $static_tva = new Tva($db);
698 $account_pay_vat = getDolGlobalString('ACCOUNTING_VAT_PAY_ACCOUNT', 'NotDefined'); // NotDefined is a reserved word
699 $prefix_ref = getDolGlobalString('MAIN_PAYMENT_VAT_REF_PREFIX', 'VAT');
700
701 while ($obj = $db->fetch_object($resql)) {
702 $object_key = $obj->bu_type.'_'.$obj->rowid;
703
704 // Add object in payment
705 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
706 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
707 'amount' => -$obj->amount_payment,
708 'bu_url_id' => $obj->bu_url_id,
709 );
710 }
711
712 // Set object infos (the object is the VAT declaration paid by this payment)
713 if (!isset($tabobject[$object_key])) {
714 $static_tva->id = $obj->tva_id;
715 $static_tva->ref = $prefix_ref.$obj->tva_id;
716 $tabobject[$object_key] = array(
717 'id' => $obj->tva_id,
718 'ref' => $prefix_ref.$obj->tva_id,
719 'total_ht' => -$obj->amount_payment,
720 'total_ttc' => -$obj->amount_payment,
721 'url' => $static_tva->getNomUrl(1),
722 'operations' => array(),
723 'vats' => array(),
724 );
725 }
726
727 // Add amount for the accountancy code
728 $tabobject[$object_key]['operations'][$account_pay_vat] = array(
729 'total_ht' => -$obj->amount_payment,
730 'label' => $obj->label,
731 );
732 }
733 } else {
734 dol_print_error($db);
735 }
736 break;
737 case 'payment_donation':
738 // Payment donation
739 //------------------------------------------
740 $sql = "SELECT d.rowid, d.amount AS don_amount,";
741 $sql .= " pd.amount AS amount_payment, pd.rowid as payment_id,";
742 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
743 $sql .= " FROM ".$db->prefix()."payment_donation as pd";
744 $sql .= " INNER JOIN ".$db->prefix()."don as d ON pd.fk_donation = d.rowid";
745 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = pd.rowid AND bu.type = '".$db->escape($type)."'";
746 $sql .= " WHERE d.entity IN (".getEntity('donation', 0).')'; // We don't share object for accountancy, we use source object sharing
747 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
748 if ($in_bookkeeping == 'already') {
749 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
750 }
751 if ($in_bookkeeping == 'notyet') {
752 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
753 }
754 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
755
756 $resql = $db->query($sql);
757 if ($resql) {
758 require_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
759
760 $langs->load("donations");
761 $static_don = new Don($db);
762 $account_pay_donation = getDolGlobalString('DONATION_ACCOUNTINGACCOUNT', 'NotDefined'); // NotDefined is a reserved word
763 $prefix_ref = getDolGlobalString('MAIN_PAYMENT_DONATION_REF_PREFIX', 'D');
764
765 while ($obj = $db->fetch_object($resql)) {
766 $object_key = $obj->bu_type.'_'.$obj->rowid;
767
768 // Add object in payment
769 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
770 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
771 'amount' => $obj->amount_payment,
772 'bu_url_id' => $obj->bu_url_id,
773 );
774 }
775
776 // Set object infos
777 if (!isset($tabobject[$object_key])) {
778 $static_don->id = $obj->rowid;
779 $static_don->ref = $prefix_ref.$obj->rowid;
780 $tabobject[$object_key] = array(
781 'id' => $obj->rowid,
782 'ref' => $prefix_ref.$obj->rowid,
783 'total_ht' => $obj->don_amount,
784 'total_ttc' => $obj->don_amount,
785 'url' => $static_don->getNomUrl(1),
786 'operations' => array(),
787 'vats' => array(),
788 );
789 }
790
791 // Add amount for the accountancy code
792 $tabobject[$object_key]['operations'][$account_pay_donation] = array(
793 'total_ht' => $obj->don_amount,
794 'label' => $langs->trans('Donation').' '.$prefix_ref.$obj->rowid,
795 );
796 }
797 } else {
798 dol_print_error($db);
799 }
800 break;
801 case 'payment_loan':
802 // Payment loan
803 //------------------------------------------
804 $sql = "SELECT l.rowid, l.capital AS loan_capital, l.accountancy_account_capital, l.accountancy_account_interest, l.accountancy_account_insurance, l.label, l.charge_type,";
805 $sql .= " pl.amount_capital, pl.rowid as payment_id, pl.amount_interest, pl.amount_insurance,";
806 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
807 $sql .= " FROM ".$db->prefix()."payment_loan as pl";
808 $sql .= " INNER JOIN ".$db->prefix()."loan as l ON pl.fk_loan = l.rowid";
809 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = pl.rowid AND bu.type = '".$db->escape($type)."'";
810 $sql .= " WHERE l.entity = ".((int) $conf->entity); // We don't share object for accountancy, we use source object sharing
811 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
812 if ($in_bookkeeping == 'already') {
813 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
814 }
815 if ($in_bookkeeping == 'notyet') {
816 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
817 }
818 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
819
820 $resql = $db->query($sql);
821 if ($resql) {
822 require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
823
824 $langs->load("loan");
825 $static_loan = new Loan($db);
826 $account_pay_loan_capital = getDolGlobalString('LOAN_ACCOUNTING_ACCOUNT_CAPITAL', 'NotDefined'); // NotDefined is a reserved word
827 $account_pay_loan_interest = getDolGlobalString('LOAN_ACCOUNTING_ACCOUNT_INTEREST', 'NotDefined'); // NotDefined is a reserved word
828 $account_pay_loan_insurance = getDolGlobalString('LOAN_ACCOUNTING_ACCOUNT_INSURANCE', 'NotDefined'); // NotDefined is a reserved word
829 $prefix_ref = getDolGlobalString('MAIN_PAYMENT_LOAN_REF_PREFIX', 'L');
830
831 while ($obj = $db->fetch_object($resql)) {
832 $object_key = $obj->bu_type.'_'.$obj->rowid;
833
834 // Add object in payment
835 $payment_amount = $obj->amount_capital + $obj->amount_interest + $obj->amount_insurance;
836 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
837 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
838 'amount' => -$payment_amount,
839 'bu_url_id' => $obj->bu_url_id,
840 );
841 }
842
843 // Set object infos
844 if (!isset($tabobject[$object_key])) {
845 $static_loan->id = $obj->rowid;
846 $static_loan->ref = $prefix_ref.$obj->rowid;
847 $tabobject[$object_key] = array(
848 'id' => $obj->rowid,
849 'ref' => $prefix_ref.$obj->rowid,
850 'total_ht' => -$obj->loan_capital,
851 'total_ttc' => -$obj->loan_capital,
852 'url' => $static_loan->getNomUrl(1),
853 'operations' => array(),
854 'vats' => array(),
855 );
856 }
857
858 // Add amount for the accountancy code
859 $accountancy_account_capital = !empty($obj->accountancy_account_capital) ? $obj->accountancy_account_capital : $account_pay_loan_capital;
860 $tabobject[$object_key]['operations'][$accountancy_account_capital] = array(
861 // virtual total = loan_capital * amount_capital / payment_amount
862 'total_ht' => -($obj->loan_capital * $obj->amount_capital / $payment_amount),
863 'label' => $obj->label.' '.$langs->trans('LoanCapital'),
864 );
865
866 // Add amount for the accountancy code
867 $accountancy_account_interest = !empty($obj->accountancy_account_interest) ? $obj->accountancy_account_interest : $account_pay_loan_interest;
868 $tabobject[$object_key]['operations'][$accountancy_account_interest] = array(
869 // virtual total = loan_capital * amount_interest / payment_amount
870 'total_ht' => -($obj->loan_capital * $obj->amount_interest / $payment_amount),
871 'label' => $obj->label.' '.$langs->trans('Interest'),
872 );
873
874 // 526,23 = 569,74 * x / 15 000,00
875
876 // Add amount for the accountancy code
877 $accountancy_account_insurance = !empty($obj->accountancy_account_insurance) ? $obj->accountancy_account_insurance : $account_pay_loan_insurance;
878 $tabobject[$object_key]['operations'][$accountancy_account_insurance] = array(
879 // virtual total = loan_capital * amount_insurance / payment_amount
880 'total_ht' => -($obj->loan_capital * $obj->amount_insurance / $payment_amount),
881 'label' => $obj->label.' '.loanChargeLabel($obj->charge_type, $langs),
882 );
883 }
884 } else {
885 dol_print_error($db);
886 }
887 break;
888 case 'payment_various':
889 // Payment various
890 //------------------------------------------
891 $sql = "SELECT pv.rowid,";
892 $sql .= " pv.sens AS sens_payment, pv.amount AS amount_payment, pv.rowid as payment_id, pv.label, pv.accountancy_code,";
893 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
894 $sql .= " FROM ".$db->prefix()."payment_various as pv";
895 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.url_id = pv.rowid AND bu.type = '".$db->escape($type)."'";
896 $sql .= " WHERE pv.entity IN (".getEntity('payment_various', 0).')'; // We don't share object for accountancy, we use source object sharing
897 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
898 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
899 if ($in_bookkeeping == 'already') {
900 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
901 }
902 if ($in_bookkeeping == 'notyet') {
903 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
904 }
905
906 $resql = $db->query($sql);
907 if ($resql) {
908 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/paymentvarious.class.php';
909
910 $static_payment_various = new PaymentVarious($db);
911 $prefix_ref = getDolGlobalString('MAIN_PAYMENT_VARIOUS_REF_PREFIX', 'PM');
912
913 while ($obj = $db->fetch_object($resql)) {
914 $object_key = $obj->bu_type.'_'.$obj->rowid;
915
916 $payment_amount = (empty($obj->sens_payment) ? -1 : 1) * $obj->amount_payment;
917 // Add object in payment
918 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
919 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
920 'amount' => $payment_amount,
921 'bu_url_id' => $obj->bu_url_id,
922 );
923 }
924
925 // Set object infos
926 if (!isset($tabobject[$object_key])) {
927 $static_payment_various->id = $obj->rowid;
928 $static_payment_various->ref = $prefix_ref.$obj->rowid;
929 $tabobject[$object_key] = array(
930 'id' => $obj->rowid,
931 'ref' => $prefix_ref.$obj->rowid,
932 'total_ht' => $payment_amount,
933 'total_ttc' => $payment_amount,
934 'url' => $static_payment_various->getNomUrl(1),
935 'operations' => array(),
936 'vats' => array(),
937 );
938 }
939
940 // Add amount for the accountancy code
941 $accountancy_code = !empty($obj->accountancy_code) ? $obj->accountancy_code : 'NotDefined';
942 $tabobject[$object_key]['operations'][$obj->accountancy_code] = array(
943 'total_ht' => $payment_amount,
944 'label' => $obj->label,
945 );
946 }
947 } else {
948 dol_print_error($db);
949 }
950 break;
951 case 'member':
952 // Subscription member
953 //------------------------------------------
954 $sql = "SELECT su.rowid,";
955 $sql .= " su.subscription AS amount_payment, su.rowid as payment_id, su.note AS label,";
956 $sql .= " adh.lastname, adh.firstname,";
957 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
958 $sql .= " FROM ".$db->prefix()."subscription as su";
959 $sql .= " INNER JOIN ".$db->prefix()."adherent as adh ON adh.rowid = su.fk_adherent";
960 $sql .= " INNER JOIN ".$db->prefix()."bank_url as bu ON bu.fk_bank = su.fk_bank AND bu.type = '".$db->escape($type)."'";
961 $sql .= " WHERE bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
962 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
963 if ($in_bookkeeping == 'already') {
964 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
965 }
966 if ($in_bookkeeping == 'notyet') {
967 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
968 }
969
970 $resql = $db->query($sql);
971 if ($resql) {
972 require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
973
974 $langs->load("members");
975 $static_subscription = new Subscription($db);
976 $account_subscription = getDolGlobalString('ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT', 'NotDefined'); // NotDefined is a reserved word
977 $prefix_ref = getDolGlobalString('MAIN_PAYMENT_SUBSCRIPTION_REF_PREFIX', 'SU');
978
979 while ($obj = $db->fetch_object($resql)) {
980 $object_key = $obj->bu_type.'_'.$obj->rowid;
981
982 // Add object in payment
983 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
984 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
985 'amount' => $obj->amount_payment,
986 'bu_url_id' => $obj->bu_url_id,
987 );
988 }
989
990 // Set object infos
991 if (!isset($tabobject[$object_key])) {
992 $static_subscription->id = $obj->rowid;
993 $static_subscription->ref = $prefix_ref.$obj->rowid;
994 $tabobject[$object_key] = array(
995 'id' => $obj->rowid,
996 'ref' => $prefix_ref.$obj->rowid,
997 'total_ht' => -$obj->amount_payment,
998 'total_ttc' => -$obj->amount_payment,
999 'url' => $static_subscription->getNomUrl(1),
1000 'operations' => array(),
1001 'vats' => array(),
1002 );
1003 }
1004
1005 // Add amount for the accountancy code
1006 $tabobject[$object_key]['operations'][$account_subscription] = array(
1007 'total_ht' => -$obj->amount_payment,
1008 'label' => $obj->label.' - '.$obj->lastname.' '.$obj->firstname,
1009 );
1010 }
1011 } else {
1012 dol_print_error($db);
1013 }
1014 break;
1015 case 'banktransfert':
1016 // Bank transfer
1017 //------------------------------------------
1018 $sql = "SELECT b.rowid, b.amount, b.label,";
1019 $sql .= " bu.fk_bank, bu.url_id AS bu_url_id, bu.type AS bu_type";
1020 $sql .= " FROM ".$db->prefix()."bank_url as bu";
1021 $sql .= " INNER JOIN ".$db->prefix()."bank as b ON bu.url_id = b.rowid";
1022 $sql .= " LEFT JOIN ".$db->prefix()."bank_account as ba ON ba.rowid = b.fk_account";
1023 $sql .= " WHERE ba.entity IN (".getEntity('bank_account', 0).')'; // We don't share object for accountancy, we use source object sharing
1024 $sql .= " AND bu.fk_bank IN (".$db->sanitize(implode(',', $ids)).")";
1025 $sql .= " AND bu.type = '".$db->escape($type)."'";
1026 // Already in bookkeeping or not. Records are saved with doc_type = 'bank' and fk_doc = ID in llx_bank (fk_docdet is 0)
1027 if ($in_bookkeeping == 'already') {
1028 $sql .= " AND EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
1029 }
1030 if ($in_bookkeeping == 'notyet') {
1031 $sql .= " AND NOT EXISTS (SELECT ab.rowid FROM ".$db->prefix()."accounting_bookkeeping as ab WHERE ab.doc_type = 'bank' AND ab.fk_doc = bu.fk_bank)";
1032 }
1033
1034 $resql = $db->query($sql);
1035 if ($resql) {
1036 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
1037
1038 $static_account_line = new AccountLine($db);
1039 $account_transfer = getDolGlobalString('ACCOUNTING_ACCOUNT_TRANSFER_CASH', 'NotDefined'); // NotDefined is a reserved word
1040 $prefix_ref = getDolGlobalString('MAIN_PAYMENT_TRANSFER_CASH_REF_PREFIX', 'T');
1041
1042 while ($obj = $db->fetch_object($resql)) {
1043 $object_key = $obj->bu_type.'_'.$obj->rowid;
1044
1045 // Add object in payment
1046 if (!isset($tabpay[$obj->fk_bank]['objects'][$object_key])) {
1047 $tabpay[$obj->fk_bank]['objects'][$object_key] = array(
1048 'amount' => -$obj->amount,
1049 'bu_url_id' => $obj->bu_url_id,
1050 );
1051 }
1052
1053 // Set object infos
1054 if (!isset($tabobject[$object_key])) {
1055 $static_account_line->id = $obj->rowid;
1056 $static_account_line->rowid = $obj->rowid;
1057 $static_account_line->ref = $prefix_ref.$obj->rowid;
1058 $tabobject[$object_key] = array(
1059 'id' => $obj->rowid,
1060 'ref' => $prefix_ref.$obj->rowid,
1061 'total_ht' => -$obj->amount,
1062 'total_ttc' => -$obj->amount,
1063 'url' => $static_account_line->getNomUrl(1),
1064 'operations' => array(),
1065 'vats' => array(),
1066 );
1067 }
1068
1069 // Add amount for the accountancy code
1070 $tabobject[$object_key]['operations'][$account_transfer] = array(
1071 'total_ht' => -$obj->amount,
1072 'label' => $obj->label,
1073 );
1074 }
1075 } else {
1076 dol_print_error($db);
1077 }
1078 break;
1079 }
1080 }
1081} else {
1082 dol_print_error($db);
1083}
1084
1091function payment_filter($v)
1092{
1093 return isset($v['objects']) && count($v['objects']) > 0;
1094}
1095
1096$tabpay = array_filter($tabpay, 'payment_filter');
1097
1098$accountingaccount = new AccountingAccount($db);
1099
1100// Get code of finance journal
1101$accountingjournalstatic = new AccountingJournal($db);
1102$accountingjournalstatic->fetch($id_journal);
1103$journal = $accountingjournalstatic->code;
1104$journal_label = $langs->transnoentitiesnoconv($accountingjournalstatic->label);
1105$MAXNBERRORS = 5;
1106
1107// Write bookkeeping
1108if ($action == 'writebookkeeping' /* && $user->hasRight('accounting', 'bind', 'write') */) { // Test on permission already done
1109 foreach ($tabpay as $bid => $payment) { // $bid is bu.fk_bank = b.rowid = ab.fk_doc = ID in llx_bank
1110 $accountInfos = $tabaccount[$payment["fk_bank_account"]];
1111
1112 // Set accounting account infos
1113 if (!isset($tabaccountingaccount[$accountInfos['account_number']])) {
1114 $result = $accountingaccount->fetch(0, $accountInfos['account_number'], true);
1115 if ($result < 0) {
1116 setEventMessages($accountingaccount->error, $accountingaccount->errors, 'errors');
1117 $error++;
1118 break;
1119 }
1120 $tabaccountingaccount[$accountInfos['account_number']] = array(
1121 'label' => $result > 0 ? $accountingaccount->label : $langs->trans('NotDefined'),
1122 );
1123 }
1124
1125
1126 $errorforline = 0;
1127
1128 $db->begin();
1129
1130 foreach ($payment['objects'] as $object_key => $object_data) { // 1 customer payment on 2 invoices has 2 objects with dispatched amount
1131 $objectInfos = $tabobject[$object_key];
1132 // When one bank line pays several objects, add the ref of the object to the labels, so the lines of each object are not seen as duplicates by BookKeeping::create()
1133 $label_suffix = (count($payment['objects']) > 1 ? ' - '.$objectInfos['ref'] : '');
1134
1135 $total_check = 0;
1136
1137 // Show bank line
1138 if ($object_data['amount'] >= 0) {
1139 $amount = (float) price2num($object_data['amount'], 'MT');
1140 $total_check += $amount;
1141
1142 $bookkeepingToCreate = new BookKeeping($db);
1143
1144 // Unique key is on couple: $bid, $objectInfos['id']
1145 // For record in llx_accounting_bookkeeping, for record with doc_type = 'bank', the value of fk_doc is ID in llx_bank and fk_docdet too. We try a fix this way;
1146 //$result = $bookkeepingToCreate->createFromValues($payment["date"], $objectInfos['ref'], 'bank', $bid, $objectInfos['id'], $accountInfos['account_number'], $tabaccountingaccount[$accountInfos['account_number']]['label'], $accountInfos['account_ref'], $amount, $journal, $journal_label, '');
1147 $result = $bookkeepingToCreate->createFromValues($payment["date"], $objectInfos['ref'], 'bank', $bid, 0, $accountInfos['account_number'], $tabaccountingaccount[$accountInfos['account_number']]['label'], $accountInfos['account_ref'].$label_suffix, $amount, $journal, $journal_label, '');
1148
1149 if ($result < 0) {
1150 $errorforline++;
1151
1152 if (!empty($bookkeepingToCreate->warnings)) {
1153 setEventMessages(null, $bookkeepingToCreate->warnings, 'warnings');
1154 }
1155 if (!empty($bookkeepingToCreate->errors)) {
1156 setEventMessages(null, $bookkeepingToCreate->errors, 'errors');
1157 }
1158 }
1159 }
1160
1161 // Operations
1162 $payment_total_vat = (float) price2num($object_data['amount'] * ($objectInfos['total_ttc'] - $objectInfos['total_ht']) / $objectInfos['total_ttc'], 'MT');
1163 $payment_total_ht = $object_data['amount'] - $payment_total_vat;
1164 $total_operation = 0;
1165 $idx = 1;
1166 $nb_operation = count($objectInfos['operations']);
1167 foreach ($objectInfos['operations'] as $accountancy_code => $operation) {
1168 if (!empty($operation['total_ht'])) {
1169 // Set accounting account infos
1170 if (!isset($tabaccountingaccount[$accountancy_code])) {
1171 $result = $accountingaccount->fetch(0, $accountancy_code, true);
1172 if ($result < 0) {
1173 setEventMessages($accountingaccount->error, $accountingaccount->errors, 'errors');
1174 $accountancy_code_label = $accountingaccount->errorsToString();
1175 $errorforline++;
1176 } elseif ($result > 0) {
1177 $accountancy_code_label = $accountingaccount->label;
1178 } else {
1179 $accountancy_code_label = $langs->trans('NotDefined');
1180 }
1181 $tabaccountingaccount[$accountancy_code] = array('label' => $accountancy_code_label);
1182 }
1183 $accountingAccountInfos = $tabaccountingaccount[$accountancy_code];
1184 if ($idx < $nb_operation) {
1185 $amount = price2num($payment_total_ht * $operation['total_ht'] / $objectInfos['total_ht'], 'MT');
1186 $total_operation += (float) $amount;
1187 } else {
1188 $amount = $payment_total_ht - $total_operation;
1189 }
1190 $total_check -= (float) $amount;
1191
1192 $bookkeepingToCreate = new BookKeeping($db);
1193 //$result = $bookkeepingToCreate->createFromValues($payment["date"], $objectInfos['ref'], 'bank', $bid, $objectInfos['id'], $accountancy_code, $accountingAccountInfos['label'], (!empty($operation['label']) ? $operation['label'] : $accountingAccountInfos['label']), -$amount, $journal, $journal_label, '');
1194 $result = $bookkeepingToCreate->createFromValues($payment["date"], $objectInfos['ref'], 'bank', $bid, 0, $accountancy_code, $accountingAccountInfos['label'], (!empty($operation['label']) ? $operation['label'] : $accountingAccountInfos['label']).$label_suffix, - (float) $amount, $journal, $journal_label, '');
1195 if ($result < 0) {
1196 $errorforline++;
1197
1198 if (!empty($bookkeepingToCreate->warnings)) {
1199 setEventMessages(null, $bookkeepingToCreate->warnings, 'warnings');
1200 }
1201 if (!empty($bookkeepingToCreate->errors)) {
1202 setEventMessages(null, $bookkeepingToCreate->errors, 'errors');
1203 }
1204 }
1205 }
1206 $idx++;
1207 }
1208
1209 // VATs
1210 $total_vat = 0;
1211 $idx = 1;
1212 $nb_vat = 0;
1213 foreach ($objectInfos['vats'] as $accountancy_code => $vats) {
1214 foreach ($vats as $vat_tx => $vat_infos) {
1215 $nb_vat++;
1216 }
1217 }
1218 foreach ($objectInfos['vats'] as $accountancy_code => $vats) {
1219 foreach ($vats as $vat_tx => $vat_infos) {
1220 $amount = $vat_infos['total_tva'] + $vat_infos['total_localtax1'] + $vat_infos['total_localtax2'];
1221 if (!empty($amount)) {
1222 // Set accounting account infos
1223 if (!isset($tabaccountingaccount[$accountancy_code])) {
1224 $result = $accountingaccount->fetch(0, $accountancy_code, true);
1225 if ($result < 0) {
1226 setEventMessages($accountingaccount->error, $accountingaccount->errors, 'errors');
1227 $accountancy_code_label = $accountingaccount->errorsToString();
1228 $errorforline++;
1229 } elseif ($result > 0) {
1230 $accountancy_code_label = $accountingaccount->label;
1231 } else {
1232 $accountancy_code_label = $langs->trans('NotDefined');
1233 }
1234 $tabaccountingaccount[$accountancy_code] = array('label' => $accountancy_code_label);
1235 }
1236 $accountingAccountInfos = $tabaccountingaccount[$accountancy_code];
1237 $amount = (float) price2num($payment_total_vat * $amount / ($objectInfos['total_ttc'] - $objectInfos['total_ht']), 'MT');
1238 $total_vat += $amount;
1239 $total_check -= $amount;
1240
1241 $bookkeepingToCreate = new BookKeeping($db);
1242 //$result = $bookkeepingToCreate->createFromValues($payment["date"], $objectInfos['ref'], 'bank', $bid, $objectInfos['id'], $accountancy_code, $accountingAccountInfos['label'], $langs->trans('VAT').' '.price($vat_infos['tva_tx']).'%', -$amount, $journal, $journal_label, '');
1243 $result = $bookkeepingToCreate->createFromValues($payment["date"], $objectInfos['ref'], 'bank', $bid, 0, $accountancy_code, $accountingAccountInfos['label'], $langs->trans('VAT').' '.price($vat_infos['tva_tx']).'%'.$label_suffix, -$amount, $journal, $journal_label, '');
1244 if ($result < 0) {
1245 $errorforline++;
1246
1247 if (!empty($bookkeepingToCreate->warnings)) {
1248 setEventMessages(null, $bookkeepingToCreate->warnings, 'warnings');
1249 }
1250 if (!empty($bookkeepingToCreate->errors)) {
1251 setEventMessages(null, $bookkeepingToCreate->errors, 'errors');
1252 }
1253 }
1254 }
1255 $idx++;
1256 }
1257 }
1258
1259 // Show bank line
1260 if ($object_data['amount'] < 0) {
1261 $amount = (float) price2num($object_data['amount'], 'MT');
1262 $total_check += $amount;
1263
1264 $bookkeepingToCreate = new BookKeeping($db);
1265 //$result = $bookkeepingToCreate->createFromValues($payment["date"], $objectInfos['ref'], 'bank', $bid, $objectInfos['id'], $accountInfos['account_number'], $tabaccountingaccount[$accountInfos['account_number']]['label'], $accountInfos['account_ref'], $amount, $journal, $journal_label, '');
1266 $result = $bookkeepingToCreate->createFromValues($payment["date"], $objectInfos['ref'], 'bank', $bid, 0, $accountInfos['account_number'], $tabaccountingaccount[$accountInfos['account_number']]['label'], $accountInfos['account_ref'].$label_suffix, $amount, $journal, $journal_label, '');
1267 if ($result < 0) {
1268 $errorforline++;
1269
1270 if (!empty($bookkeepingToCreate->warnings)) {
1271 setEventMessages(null, $bookkeepingToCreate->warnings, 'warnings');
1272 }
1273 if (!empty($bookkeepingToCreate->errors)) {
1274 setEventMessages(null, $bookkeepingToCreate->errors, 'errors');
1275 }
1276 }
1277 }
1278
1279 $total_check = price2num($total_check, 'MT');
1280 if (!empty($total_check)) {
1281 $errorforline++;
1282 setEventMessages($langs->trans('ErrorBookkeepingTryInsertNotBalancedTransactionAndCanceled', $objectInfos['ref'], $object_data['bu_url_id']), null, 'errors');
1283 }
1284
1285 if ($errorforline) {
1286 $error++;
1287
1288 if ($error >= $MAXNBERRORS) {
1289 break; // Break in the foreach
1290 }
1291 }
1292 }
1293
1294 if (!$errorforline) {
1295 $db->commit();
1296 } else {
1297 //print 'KO for line '.$key.' '.$error.'<br>';
1298 $db->rollback();
1299
1300 $MAXNBERRORS = 5;
1301 if ($error >= $MAXNBERRORS) {
1302 setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped").' (>'.$MAXNBERRORS.')', null, 'errors');
1303 break; // Break in the foreach
1304 }
1305 }
1306 }
1307
1308 if (empty($error) && count($tabpay) > 0) {
1309 setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
1310 } elseif (count($tabpay) == $error) {
1311 setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
1312 } else {
1313 setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
1314 }
1315
1316 $action = '';
1317
1318 // Must reload data, so we make a redirect
1319 if (count($tabpay) != $error) {
1320 $param = 'id_journal='.$id_journal;
1321 $param .= '&date_startday='.$date_startday;
1322 $param .= '&date_startmonth='.$date_startmonth;
1323 $param .= '&date_startyear='.$date_startyear;
1324 $param .= '&date_endday='.$date_endday;
1325 $param .= '&date_endmonth='.$date_endmonth;
1326 $param .= '&date_endyear='.$date_endyear;
1327 $param .= '&in_bookkeeping='.$in_bookkeeping;
1328 header("Location: " . $_SERVER['PHP_SELF'] . '?' . $param);
1329 exit;
1330 }
1331}
1332
1333
1334/*
1335 * View
1336 */
1337
1338$form = new Form($db);
1339$description = null;
1340
1341if (empty($action) || $action == 'view') {
1342 llxHeader('', $langs->trans("FinanceJournal"));
1343
1344 $nom = $langs->trans("FinanceJournal").' | '.$accountingjournalstatic->getNomUrl(0, 1, 1, '', 1);
1345 $nomlink = '';
1346 $builddate = dol_now();
1347 $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
1348
1349 $listofchoices = array(
1350 'notyet' => $langs->trans("NotYetInGeneralLedger"),
1351 'already' => $langs->trans("AlreadyInGeneralLedger")
1352 );
1353 $period = $form->selectDate($date_start ?: -1, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end ?: -1, 'date_end', 0, 0, 0, '', 1, 0);
1354 $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
1355
1356 $varlink = 'id_journal='.$id_journal;
1357 $periodlink = '';
1358 $exportlink = '';
1359
1360 journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
1361
1362 // Test that setup is complete
1363 $sql = "SELECT COUNT(rowid) as nb FROM ".$db->prefix()."bank_account WHERE fk_accountancy_journal IS NULL AND clos = 0";
1364 $resql = $db->query($sql);
1365 if ($resql) {
1366 $obj = $db->fetch_object($resql);
1367 if ($obj->nb > 0) {
1368 print '<br>'.img_warning().' '.$langs->trans("TheJournalCodeIsNotDefinedOnSomeBankAccount");
1369 print ' : '.$langs->trans("AccountancyAreaDescBank", 9, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("BankAccounts").'</strong>');
1370 }
1371 } else {
1372 dol_print_error($db);
1373 }
1374
1375 // Button to write into Ledger
1376 if (!getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') || getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == '-1'
1377 || !getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == '-1'
1378 || !getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT') || getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT') == '-1') {
1379 print '<br>'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
1380 print ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>');
1381 }
1382
1383 print '<br><div class="tabsAction tabsActionNoBottom centerimp">';
1384
1385 if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL')) {
1386 print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
1387 }
1388
1389 if (!getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') || getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') == '-1'
1390 || !getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') || getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') == '-1'
1391 || !getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT') || getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT') == '-1') {
1392 print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
1393 } else {
1394 if ($in_bookkeeping == 'notyet') {
1395 print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
1396 } else {
1397 print '<a class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
1398 }
1399 }
1400 print '</div>';
1401
1402 // TODO Avoid using js. We can use a direct link with $param
1403 print '
1404 <script type="text/javascript">
1405 function writebookkeeping() {
1406 console.log("Set value into form and submit");
1407 $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
1408 $("div.fiche form input[type=\"submit\"]").click();
1409 $("div.fiche form input[name=\"action\"]").val("");
1410 }
1411 </script>';
1412
1413 /*
1414 * Show result array
1415 */
1416 print '<br>';
1417
1418 $i = 0;
1419 print '<div class="div-table-responsive">';
1420 print '<table class="noborder centpercent">';
1421 print '<tr class="liste_titre">';
1422 print "<td>".$langs->trans("Date")."</td>";
1423 print "<td>".$langs->trans("Piece").' ('.$langs->trans("ObjectsRef").')</td>';
1424 print "<td>".$langs->trans("AccountAccounting")."</td>";
1425 print "<td>".$langs->trans("LabelOperation")."</td>";
1426 print '<td class="center">'.$langs->trans("PaymentMode")."</td>";
1427 print '<td class="right">'.$langs->trans("AccountingDebit")."</td>";
1428 print '<td class="right">'.$langs->trans("AccountingCredit")."</td>";
1429 print "</tr>\n";
1430
1431 foreach ($tabpay as $bid => $payment) {
1432 $accountInfos = $tabaccount[$payment["fk_bank_account"]];
1433 $date = dol_print_date($payment["date"], 'day');
1434 $i++;
1435
1436 foreach ($payment['objects'] as $object_key => $object_data) {
1437 $objectInfos = $tabobject[$object_key];
1438 // When one bank line pays several objects, add the ref of the object to the labels, so the lines of each object are not seen as duplicates by BookKeeping::create()
1439 $label_suffix = (count($payment['objects']) > 1 ? ' - '.$objectInfos['ref'] : '');
1440
1441 // Show bank line
1442 if ($object_data['amount'] >= 0) {
1443 FormAccounting::printJournalLine($langs, $date, $objectInfos['url'], $accountInfos['account_number'], $accountInfos['account_ref'].$label_suffix, $payment['type_payment'], $object_data['amount']);
1444 }
1445
1446 // Operations
1447 $payment_total_vat = (float) price2num($object_data['amount'] * ($objectInfos['total_ttc'] - $objectInfos['total_ht']) / $objectInfos['total_ttc'], 'MT');
1448 $payment_total_ht = $object_data['amount'] - $payment_total_vat;
1449 $total_operation = 0;
1450 $idx = 1;
1451 $nb_operation = count($objectInfos['operations']);
1452 foreach ($objectInfos['operations'] as $accountancy_code => $operation) {
1453 // Set accounting account infos
1454 if (!isset($tabaccountingaccount[$accountancy_code])) {
1455 $result = $accountingaccount->fetch(0, $accountancy_code, true);
1456 $tabaccountingaccount[$accountancy_code] = array(
1457 'label' => $result < 0 ? $accountingaccount->errorsToString() : ($result > 0 ? $accountingaccount->label : $langs->trans('NotDefined')),
1458 );
1459 }
1460 $accountingAccountInfos = $tabaccountingaccount[$accountancy_code];
1461 if (!empty($operation['total_ht'])) {
1462 if ($idx < $nb_operation) {
1463 $value = price2num($payment_total_ht * $operation['total_ht'] / $objectInfos['total_ht'], 'MT');
1464 $total_operation += (float) $value;
1465 } else {
1466 $value = $payment_total_ht - $total_operation;
1467 }
1468 FormAccounting::printJournalLine($langs, $date, $objectInfos['url'], (string) $accountancy_code, (!empty($operation['label']) ? $operation['label'] : $accountingAccountInfos['label']).$label_suffix, $payment['type_payment'], - (float) $value);
1469 }
1470 $idx++;
1471 }
1472
1473 // VATs
1474 $total_vat = 0;
1475 $idx = 1;
1476 $nb_vat = 0;
1477 foreach ($objectInfos['vats'] as $accountancy_code => $vats) {
1478 foreach ($vats as $vat_tx => $vat_infos) {
1479 $nb_vat++;
1480 }
1481 }
1482 foreach ($objectInfos['vats'] as $accountancy_code => $vats) {
1483 foreach ($vats as $vat_tx => $vat_infos) {
1484 $amount_vat = $vat_infos['total_tva'] + $vat_infos['total_localtax1'] + $vat_infos['total_localtax2'];
1485 if (!empty($amount_vat)) {
1486 $amount_vat = (float) price2num($payment_total_vat * $amount_vat / ($objectInfos['total_ttc'] - $objectInfos['total_ht']), 'MT');
1487 $total_vat += $amount_vat;
1488 FormAccounting::printJournalLine($langs, $date, $objectInfos['url'], $accountancy_code, $langs->trans('VAT').' '.price($vat_infos['tva_tx']).'%'.$label_suffix, $payment['type_payment'], -$amount_vat);
1489 }
1490 $idx++;
1491 }
1492 }
1493
1494 // Show bank line
1495 if ($object_data['amount'] < 0) {
1496 FormAccounting::printJournalLine($langs, $date, $objectInfos['url'], $accountInfos['account_number'], $accountInfos['account_ref'].$label_suffix, $payment['type_payment'], $object_data['amount']);
1497 }
1498 }
1499 }
1500
1501 if (!$i) {
1502 $colspan = 8;
1503 print '<tr class="oddeven"><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
1504 }
1505
1506 print "</table>";
1507 print '</div>';
1508
1509 llxFooter();
1510}
1511
1512$db->close();
journalHead($nom, $variant, $period, $periodlink, $description, $builddate, $exportlink='', $moreparam=array(), $calcmode='', $varlink='', $moreoptions=array())
Show header of a page used to transfer/dispatch data in accounting.
getDefaultDatesForTransfer()
Return Default dates for transfer based on periodicity option in accountancy setup.
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage bank accounts.
Class to manage bank transaction lines.
Class to manage accounting accounts.
Class to manage accounting journals.
Class to manage Ledger (General Ledger and Subledger)
Class for managing the social charges.
const TYPE_SITUATION
Situation invoice.
Class to manage donations.
Definition don.class.php:42
Class to manage Trips and Expenses.
Class to manage suppliers invoices.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
const TYPE_REPLACEMENT
Replacement invoice.
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
static printJournalLine($langs, $date, $ref, $accountAccounting, $labelOperation, $paymentMode, $amount)
Print line into the journal table.
Class to manage generation of HTML components Only common components must be here.
Loan.
Class to manage payments of salaries.
Class to manage various payments.
Class to manage subscriptions of foundation members.
Class to manage VAT - Value-added tax (also known in French as TVA)
Definition tva.class.php:39
global $mysoc
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:626
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:645
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
getTaxesFromId($vatrate, $buyer=null, $seller=null, $firstparamisid=1)
Get tax (VAT) main information from Id.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
loanChargeLabel($charge_type, $outputlangs)
Label of the charge of a loan (Insurance, Account-keeping fee, Other fee).
Definition loan.lib.php:328
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
payment_filter($v)
Filter for payment.