dolibarr 25.0.0-alpha
sellsjournal.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-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
8 * Copyright (C) 2013-2016 Florian Henry <florian.henry@open-concept.pro>
9 * Copyright (C) 2013-2016 Olivier Geffroy <jeff@jeffinfo.com>
10 * Copyright (C) 2014 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
11 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
12 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
13 * Copyright (C) 2025 Vincent de Grandporé <vincent@de-grandpre.quebec>
14 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
15 *
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License as published by
18 * the Free Software Foundation; either version 3 of the License, or
19 * (at your option) any later version.
20 *
21 * This program is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 * GNU General Public License for more details.
25 *
26 * You should have received a copy of the GNU General Public License
27 * along with this program. If not, see <https://www.gnu.org/licenses/>.
28 */
29
36// Load Dolibarr environment
37require '../../main.inc.php';
46require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
47require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
48require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
49require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
50require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
51require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
52require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
53require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
54require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
55
56// Load translation files required by the page
57$langs->loadLangs(array("commercial", "compta", "bills", "other", "accountancy"));
58
59$id_journal = GETPOSTINT('id_journal');
60$action = GETPOST('action', 'aZ09');
61
62$date_startmonth = GETPOSTINT('date_startmonth');
63$date_startday = GETPOSTINT('date_startday');
64$date_startyear = GETPOSTINT('date_startyear');
65$date_endmonth = GETPOSTINT('date_endmonth');
66$date_endday = GETPOSTINT('date_endday');
67$date_endyear = GETPOSTINT('date_endyear');
68$in_bookkeeping = GETPOST('in_bookkeeping');
69if ($in_bookkeeping == '' || $action == 'writebookkeeping') { // Never transfer again documents already in bookkeeping
70 $in_bookkeeping = 'notyet';
71}
72
73$now = dol_now();
74
75$hookmanager->initHooks(array('sellsjournal'));
76$parameters = array();
77
78// Security check
79if (!isModEnabled('accounting')) {
81}
82if ($user->socid > 0) {
84}
85if (!$user->hasRight('accounting', 'bind', 'write')) {
87}
88
89$error = 0;
90
91$tabfac = array();
92$tabht = array();
93$tabtva = array();
94$tabwarranty = array();
95$tabttc = array();
96$tablocaltax1 = array();
97$tablocaltax2 = array();
98$tabCustomerDiscountHT = array();
99$tabCustomerDiscountVAT = array();
100$tabCustomerDiscountTTC = array();
101
102// When down payments are just payments, they are not journalized, so there is nothing to reverse from the down payment accounts
103$manageCustomerDepositInInvoice = (getDolGlobalInt('ACCOUNTING_MANAGE_CUSTOMER_DEPOSIT_IN_INVOICE') && !getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS'));
104$labelCustomerDiscountExtension = ' (AC)';
105
106$cptcli = 'NotDefined';
107$accountCustomerDeposit = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT', 'NotDefined');
108$accountCustomerDepositVAT = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT_FOR_VAT', 'NotDefined');
109
110/*
111 * Actions
112 */
113
114$reshook = $hookmanager->executeHooks('doActions', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
115
116$accountingaccount = new AccountingAccount($db);
117
118// Get information of a journal
119$accountingjournalstatic = new AccountingJournal($db);
120$accountingjournalstatic->fetch($id_journal);
121$journal = $accountingjournalstatic->code;
122$journal_label = $accountingjournalstatic->label;
123
124$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
125$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
126
127$pastmonth = null; // Initialise, could be unset
128$pastmonthyear = null; // Initialise, could be unset
129
130if (empty($date_startmonth)) {
131 // Period by default on transfer
133 $date_start = $dates['date_start'];
134 $pastmonthyear = $dates['pastmonthyear'];
135 $pastmonth = $dates['pastmonth'];
136}
137if (empty($date_endmonth)) {
138 // Period by default on transfer
140 $date_end = $dates['date_end'];
141 $pastmonthyear = $dates['pastmonthyear'];
142 $pastmonth = $dates['pastmonth'];
143}
144if (getDolGlobalString('ACCOUNTANCY_JOURNAL_USE_CURRENT_MONTH')) {
145 $pastmonth += 1;
146}
147
148if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
149 $date_start = dol_get_first_day((int) $pastmonthyear, (int) $pastmonth, false);
150 $date_end = dol_get_last_day((int) $pastmonthyear, (int) $pastmonth, false);
151}
152
153$sql = "SELECT f.rowid, f.ref, f.type, f.module_source, f.situation_cycle_ref, f.datef as df, f.ref_client, f.date_lim_reglement as dlr, f.close_code, f.retained_warranty, f.revenuestamp, f.situation_final,";
154$sql .= " fd.rowid as fdid, fd.description, fd.product_type, fd.total_ht, fd.total_tva, fd.total_localtax1, fd.total_localtax2, fd.tva_tx, fd.localtax1_tx, fd.localtax2_tx, fd.total_ttc, fd.situation_percent, fd.vat_src_code, fd.info_bits,";
155$sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur, s.fk_pays,";
156if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
157 $sql .= " spe.accountancy_code_customer_general,";
158 $sql .= " spe.accountancy_code_customer as code_compta_client,";
159 $sql .= " spe.accountancy_code_supplier_general,";
160 $sql .= " spe.accountancy_code_supplier as code_compta_fournisseur,";
161} else {
162 $sql .= " s.accountancy_code_customer_general,";
163 $sql .= " s.code_compta as code_compta_client,";
164 $sql .= " s.accountancy_code_supplier_general,";
165 $sql .= " s.code_compta_fournisseur,";
166}
167$sql .= " p.rowid as pid, p.ref as pref, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte,";
168if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
169 $sql .= " ppe.accountancy_code_sell";
170} else {
171 $sql .= " p.accountancy_code_sell";
172}
173$parameters = array();
174$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
175$sql .= $hookmanager->resPrint;
176$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
177$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
178if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
179 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
180}
181$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
182$sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
183$sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
184if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
185 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
186}
187$parameters = array();
188$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
189$sql .= $hookmanager->resPrint;
190$sql .= " WHERE fd.fk_code_ventilation > 0";
191$sql .= " AND f.entity IN (".getEntity('invoice', 0).')'; // We don't share object for accountancy, we use source object sharing
192$sql .= " AND f.fk_statut > 0";
193if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) { // Non common setup
194 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
195} else {
196 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
197}
198$sql .= " AND fd.product_type IN (0,1)";
199if ($date_start && $date_end) {
200 $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
201}
202if (getDolGlobalInt('ACCOUNTING_DISSOCIATE_CASH_SALES')) {
203 $sql .= " AND (f.module_source IS NULL OR f.module_source <> 'takepos')";
204}
205// Define begin binding date
206if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
207 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
208}
209// Already in bookkeeping or not
210if ($in_bookkeeping == 'already') {
211 $sql .= " AND f.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
212 // $sql .= " AND fd.rowid IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')"; // Useless, we save one line for all products with same account
213}
214if ($in_bookkeeping == 'notyet') {
215 $sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
216 // $sql .= " AND fd.rowid NOT IN (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')"; // Useless, we save one line for all products with same account
217}
218if ($manageCustomerDepositInInvoice) {
219 // Exclude the lines that consume a down payment, they are replaced by the reversal of the down payment (see $sql2).
220 // Same condition as $sql2: only discounts coming from a down payment invoice.
221 $sql .= " AND COALESCE(fd.fk_remise_except, 0) NOT IN (SELECT re.rowid FROM ".$db->prefix()."societe_remise_except as re";
222 $sql .= " INNER JOIN ".$db->prefix()."facture as fs ON fs.rowid = re.fk_facture_source";
223 $sql .= " WHERE fs.type = ".Facture::TYPE_DEPOSIT." AND re.description LIKE '(DEPOSIT)%')";
224}
225$parameters = array();
226$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
227$sql .= $hookmanager->resPrint;
228$sql .= " ORDER BY f.datef, f.ref";
229//print $sql;
230
231dol_syslog('accountancy/journal/sellsjournal.php', LOG_DEBUG);
232$tabfac = array();
233$tabht = array();
234$tabtva = array();
235$def_tva = array();
236$tabwarranty = array();
237$tabrevenuestamp = array();
238$tabttc = array();
239$tablocaltax1 = array();
240$tablocaltax2 = array();
241$tabcompany = array();
242$vatdata_cache = array();
243$tabCustomerDiscountHT = array();
244$tabCustomerDiscountVAT = array();
245$tabCustomerDiscountTTC = array();
246
247// Variables
248$cptcli = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER', 'NotDefined');
249$cpttva = getDolGlobalString('ACCOUNTING_VAT_SOLD_ACCOUNT', 'NotDefined');
250$cptlocaltax1 = getDolGlobalString('ACCOUNTING_LT1_SOLD_ACCOUNT', 'NotDefined');
251$cptlocaltax2 = getDolGlobalString('ACCOUNTING_LT2_SOLD_ACCOUNT', 'NotDefined');
252
253$result = $db->query($sql);
254if ($result) {
255 $num = $db->num_rows($result);
256
257 $i = 0;
258 while ($i < $num) {
259 $obj = $db->fetch_object($result);
260
261 // Controls
262 $accountancy_code_customer_general = (!empty($obj->accountancy_code_customer_general) && $obj->accountancy_code_customer_general != '-1') ? $obj->accountancy_code_customer_general : $cptcli;
263 $compta_soc = getSubledgerAccountWithDefault($obj->code_compta_client, 'customer');
264
265 $compta_prod = $obj->compte;
266 if (empty($compta_prod)) {
267 if ($obj->product_type == 0) {
268 $compta_prod = getDolGlobalString('ACCOUNTING_PRODUCT_SOLD_ACCOUNT', 'NotDefined');
269 } else {
270 $compta_prod = getDolGlobalString('ACCOUNTING_SERVICE_SOLD_ACCOUNT', 'NotDefined');
271 }
272 }
273
274 // $compta_revenuestamp = getDolGlobalString('ACCOUNTING_REVENUESTAMP_SOLD_ACCOUNT', 'NotDefined');
275
276 $tax_id = $obj->tva_tx . ($obj->vat_src_code ? ' (' . $obj->vat_src_code . ')' : '');
277 // SERVICE_ARE_ECOMMERCE_200238EC makes the chosen accountancy code depend on the buyer country,
278 // so the cache key must include the buyer country to avoid serving a previous buyer's result.
279 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
280 $vatdata_cache_key = $tax_id.'_'.(int) $obj->fk_pays;
281 } else {
282 $vatdata_cache_key = $tax_id;
283 }
284 if (array_key_exists($vatdata_cache_key, $vatdata_cache)) {
285 $vatdata = $vatdata_cache[$vatdata_cache_key];
286 } else {
287 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
288 $buyer = new Societe($db);
289 $buyer->fetch($obj->socid);
290 } else {
291 $buyer = null; // We don't need the buyer in this case
292 }
293 $seller = $mysoc;
294 $vatdata = getTaxesFromId($tax_id, $buyer, $seller, 0);
295 $vatdata_cache[$vatdata_cache_key] = $vatdata;
296 }
297 if (!empty(length_accountg($accountCustomerDepositVAT)) && $accountCustomerDepositVAT != 'NotDefined' && $obj->type == Facture::TYPE_DEPOSIT) {
298 // customer deposit account for VAT
299 $compta_tva = $accountCustomerDepositVAT;
300 } else {
301 $compta_tva = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
302 }
303 $compta_localtax1 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cptlocaltax1);
304 $compta_localtax2 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cptlocaltax2);
305
306 // Define the array to store the detail of each vat rate and code for lines
307 if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
308 $def_tva[$obj->rowid][$compta_tva][vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '')] = (vatrate($obj->tva_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
309 if ($obj->localtax1_tx > 0.0) {
310 $def_tva[$obj->rowid][$compta_localtax1][vatrate($obj->localtax1_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '').' LT1'] = (vatrate($obj->localtax1_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
311 }
312 if ($obj->localtax2_tx > 0.0) {
313 $def_tva[$obj->rowid][$compta_localtax2][vatrate($obj->localtax2_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : '').' LT2'] = (vatrate($obj->localtax2_tx).($obj->vat_src_code ? ' ('.$obj->vat_src_code.')' : ''));
314 }
315 }
316
317 // Create a compensation rate for situation invoice.
318 $situation_ratio = 1;
319 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
320 if ($obj->situation_cycle_ref) {
321 // Avoid divide by 0
322 if ($obj->situation_percent == 0) {
323 $situation_ratio = 0;
324 } else {
325 $line = new FactureLigne($db);
326 $line->fetch($obj->fdid);
327
328 // Situation invoices handling
329 $prev_progress = $line->get_prev_progress($obj->rowid);
330
331 $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
332 }
333 }
334 }
335
336 $revenuestamp = (float) price2num($obj->revenuestamp, 'MT');
337
338 if ($manageCustomerDepositInInvoice && $obj->type == Facture::TYPE_STANDARD && !isset($tabfac[$obj->rowid])) {
339 // Get all linked invoice deposit consumed by this invoice. Other discounts (credit note, excess received,
340 // fixed amount) are already in the journal with their own line or document, so they must not be reversed.
341 $sql2 = "SELECT re.rowid";
342 $sql2 .= " FROM " . $db->prefix() . "societe_remise_except as re";
343 $sql2 .= " INNER JOIN " . $db->prefix() . "facture as fs ON fs.rowid = re.fk_facture_source";
344 $sql2 .= " WHERE fs.type = " . Facture::TYPE_DEPOSIT . " AND re.description LIKE '(DEPOSIT)%'";
345 $sql2 .= " AND (re.fk_facture = " . ((int) $obj->rowid);
346 $sql2 .= " OR re.fk_facture_line IN (SELECT rowid FROM " . $db->prefix() . "facturedet WHERE fk_facture = " . ((int) $obj->rowid) . ")";
347 $sql2 .= ")";
348
349 $resql2 = $db->query($sql2);
350 if ($resql2) {
351 if ($db->num_rows($resql2) > 0) {
352 if (!isset($tabCustomerDiscountHT[$obj->rowid][$accountCustomerDeposit])) {
353 $tabCustomerDiscountHT[$obj->rowid][$accountCustomerDeposit] = 0;
354 }
355 if (!isset($tabCustomerDiscountVAT[$obj->rowid][$accountCustomerDepositVAT])) {
356 $tabCustomerDiscountVAT[$obj->rowid][$accountCustomerDepositVAT] = 0;
357 }
358 if (!isset($tabCustomerDiscountTTC[$obj->rowid][$compta_soc])) {
359 $tabCustomerDiscountTTC[$obj->rowid][$compta_soc] = 0;
360 }
361
362 while ($obj2 = $db->fetch_object($resql2)) {
363 $customerDiscount = new DiscountAbsolute($db);
364 $customerDiscount->fetch($obj2->rowid);
365 // Accumulate: an invoice can consume several deposits, and the (DEPOSIT) lines are
366 // excluded from the main query, so this reversal is their only trace in the journal.
367 $tabCustomerDiscountHT[$obj->rowid][$accountCustomerDeposit] -= $customerDiscount->total_ht;
368 $tabCustomerDiscountVAT[$obj->rowid][$accountCustomerDepositVAT] -= $customerDiscount->total_tva;
369 $tabCustomerDiscountTTC[$obj->rowid][$compta_soc] -= $customerDiscount->total_ttc;
370 }
371 }
372 $db->free($resql2);
373 } else {
374 dol_print_error($db);
375 }
376 }
377
378 // Invoice lines
379 $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
380 $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
381 $tabfac[$obj->rowid]["ref"] = $obj->ref;
382 $tabfac[$obj->rowid]["type"] = $obj->type;
383 $tabfac[$obj->rowid]["description"] = $obj->label_compte;
384 $tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
385 $tabfac[$obj->rowid]["revenuestamp"] = $revenuestamp;
386 //$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
387
388 // Avoid warnings
389 if (!isset($tabttc[$obj->rowid][$compta_soc])) {
390 $tabttc[$obj->rowid][$compta_soc] = 0;
391 }
392 if (!isset($tabht[$obj->rowid][$compta_prod])) {
393 $tabht[$obj->rowid][$compta_prod] = 0;
394 }
395 if (!isset($tabtva[$obj->rowid][$compta_tva])) {
396 $tabtva[$obj->rowid][$compta_tva] = 0;
397 }
398 if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
399 $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
400 }
401 if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
402 $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
403 }
404
405 // Compensation of data for invoice situation by using $situation_ratio. This works (nearly) for invoice that was not correctly recorded
406 // but it may introduces an error for situation invoices that were correctly saved. There is still rounding problem that differs between
407 // real data we should have stored and result obtained with a compensation.
408 // It also seems that credit notes on situation invoices are correctly saved (but it depends on the version used in fact).
409 // For credit notes, we hope to have situation_ratio = 1 so the compensation has no effect to avoid introducing troubles with credit notes.
410 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
411 $total_ttc = $obj->total_ttc * $situation_ratio;
412 $total_ht = $obj->total_ht * $situation_ratio;
413 } else {
414 $total_ttc = $obj->total_ttc;
415 $total_ht = $obj->total_ht;
416 }
417
418 // Move a part of the retained warrenty into the account of warranty
419 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && $obj->retained_warranty > 0 && (!getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION') || !empty($obj->situation_final))) {
420 $retained_warranty = (float) price2num($total_ttc * $obj->retained_warranty / 100, 'MT'); // Calculate the amount of warrenty for this line (using the percent value)
421 $tabwarranty[$obj->rowid][$compta_soc] += $retained_warranty;
422 $total_ttc -= $retained_warranty;
423 }
424
425 $tabttc[$obj->rowid][$compta_soc] += $total_ttc;
426 $tabht[$obj->rowid][$compta_prod] += $total_ht;
427 $tva_npr = ((($obj->info_bits & 1) == 1) ? 1 : 0);
428 if (!$tva_npr) { // We ignore line if VAT is a NPR
429 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
430 $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
431 $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
432 $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
433 } else {
434 $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
435 $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
436 $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
437 }
438 }
439
440 $compta_revenuestamp = 'NotDefined';
441 if (!empty($revenuestamp)) {
442 $sqlrevenuestamp = "SELECT accountancy_code_sell FROM ".MAIN_DB_PREFIX."c_revenuestamp";
443 $sqlrevenuestamp .= " WHERE fk_pays = ".((int) $mysoc->country_id);
444 $sqlrevenuestamp .= " AND taux = ".((float) $revenuestamp);
445 $sqlrevenuestamp .= " AND active = 1";
446 $resqlrevenuestamp = $db->query($sqlrevenuestamp);
447
448 if ($resqlrevenuestamp) {
449 $num_rows_revenuestamp = $db->num_rows($resqlrevenuestamp);
450 if ($num_rows_revenuestamp > 1) {
451 dol_print_error($db, 'Failed 2 or more lines for the revenue stamp of your country. Check the dictionary of revenue stamp.');
452 } else {
453 $objrevenuestamp = $db->fetch_object($resqlrevenuestamp);
454 if ($objrevenuestamp) {
455 $compta_revenuestamp = $objrevenuestamp->accountancy_code_sell;
456 }
457 }
458 }
459 }
460
461 if (empty($tabrevenuestamp[$obj->rowid][$compta_revenuestamp]) && !empty($revenuestamp)) {
462 // The revenue stamp was never seen for this invoice id=$obj->rowid
463 $tabttc[$obj->rowid][$compta_soc] += $obj->revenuestamp;
464 $tabrevenuestamp[$obj->rowid][$compta_revenuestamp] = $obj->revenuestamp;
465 }
466
467 $tabcompany[$obj->rowid] = array(
468 'id' => $obj->socid,
469 'name' => $obj->name,
470 'code_client' => $obj->code_client,
471 'accountancy_code_customer_general' => $accountancy_code_customer_general,
472 'code_compta' => $compta_soc
473 );
474
475 // After the line is processed
476 $parameters = array(
477 'obj' => $obj,
478 'tabfac' => &$tabfac,
479 'tabht' => &$tabht,
480 'tabtva' => &$tabtva,
481 'def_tva' => &$def_tva,
482 'tabwarranty' => &$tabwarranty,
483 'tabrevenuestamp' => &$tabrevenuestamp,
484 'tabttc' => &$tabttc,
485 'tablocaltax1' => &$tablocaltax1,
486 'tablocaltax2' => &$tablocaltax2,
487 'tabcompany' => &$tabcompany,
488 'vatdata_cache' => &$vatdata_cache,
489 );
490 $reshook = $hookmanager->executeHooks('processingJournalData', $parameters); // Note that $action and $object may have been modified by hook
491
492 $i++;
493
494 // Check for too many lines.
495 if ($i > getDolGlobalInt('ACCOUNTANCY_MAX_TOO_MANY_LINES_TO_PROCESS', 10000)) {
496 $error++;
497 setEventMessages("ErrorTooManyLinesToProcessPleaseUseAMoreSelectiveFilter", null, 'errors');
498 break;
499 }
500 }
501
502 // After the loop on each line
503 $parameters = array(
504 'tabfac' => &$tabfac,
505 'tabht' => &$tabht,
506 'tabtva' => &$tabtva,
507 'def_tva' => &$def_tva,
508 'tabwarranty' => &$tabwarranty,
509 'tabrevenuestamp' => &$tabrevenuestamp,
510 'tabttc' => &$tabttc,
511 'tablocaltax1' => &$tablocaltax1,
512 'tablocaltax2' => &$tablocaltax2,
513 'tabcompany' => &$tabcompany,
514 'vatdata_cache' => &$vatdata_cache,
515 );
516 $reshook = $hookmanager->executeHooks('processedJournalData', $parameters); // Note that $action and $object may have been modified by hook
517} else {
518 dol_print_error($db);
519}
520
521
522$errorforinvoice = array();
523
524/*
525// Old way, 1 query for each invoice
526// Loop on all invoices to detect lines without binded code (fk_code_ventilation <= 0)
527foreach ($tabfac as $key => $val) { // Loop on each invoice
528 $sql = "SELECT COUNT(fd.rowid) as nb";
529 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
530 $sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
531 $sql .= " AND fd.total_ttc <> 0 AND fk_facture = ".((int) $key);
532 $resql = $db->query($sql);
533 if ($resql) {
534 $obj = $db->fetch_object($resql);
535 if ($obj->nb > 0) {
536 $errorforinvoice[$key] = 'somelinesarenotbound';
537 }
538 } else {
539 dol_print_error($db);
540 }
541}
542*/
543// New way, single query, load all unbound lines
544if (!empty($tabfac)) {
545 $sql = "
546 SELECT
547 fk_facture,
548 COUNT(fd.rowid) as nb
549 FROM
550 ".MAIN_DB_PREFIX."facturedet as fd
551 WHERE
552 fd.product_type <= 2
553 AND fd.fk_code_ventilation <= 0
554 AND fd.total_ttc <> 0
555 AND fk_facture IN (".$db->sanitize(implode(",", array_keys($tabfac))).")
556 GROUP BY fk_facture
557 ";
558 $resql = $db->query($sql);
559 if ($resql) {
560 $num = $db->num_rows($resql);
561 $i = 0;
562 while ($i < $num) {
563 $obj = $db->fetch_object($resql);
564 if ($obj->nb > 0) {
565 $errorforinvoice[$obj->fk_facture] = 'somelinesarenotbound';
566 }
567 $i++;
568 }
569 }
570}
571//var_dump($errorforinvoice);exit;
572
573// Bookkeeping Write
574if ($action == 'writebookkeeping' && !$error && $user->hasRight('accounting', 'bind', 'write')) {
575 $now = dol_now();
576 $error = 0;
577
578 $companystatic = new Societe($db);
579 $invoicestatic = new Facture($db);
580 $bookkeepingstatic = new BookKeeping($db);
581
582 $accountingaccountcustomer = new AccountingAccount($db);
583 $accountingaccountcustomer->fetch(0, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), true);
584
585 $accountingaccountcustomerwarranty = new AccountingAccount($db);
586 $accountingaccountcustomerwarranty->fetch(0, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'), true);
587
588 foreach ($tabfac as $key => $val) { // Loop on each invoice
589 $errorforline = 0;
590
591 $totalcredit = 0;
592 $totaldebit = 0;
593
594 $db->begin(); // We accept transaction into loop, so if we hang, we can continue transfer from the last error
595
596 $companystatic->id = $tabcompany[$key]['id'];
597 $companystatic->name = $tabcompany[$key]['name'];
598 $companystatic->accountancy_code_customer_general = $tabcompany[$key]['accountancy_code_customer_general'];
599 $companystatic->code_compta = $tabcompany[$key]['code_compta'];
600 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
601 $companystatic->code_client = $tabcompany[$key]['code_client'];
602 $companystatic->client = 3;
603
604 $invoicestatic->id = (int) $key;
605 $invoicestatic->ref = (string) $val["ref"];
606 $invoicestatic->type = (int) ($val["type"] ?? 0);
607 $invoicestatic->close_code = (string) ($val["close_code"] ?? '');
608
609 $date = dol_print_date($val["date"], 'day');
610
611 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
612 $replacedinvoice = 0;
613 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
614 $replacedinvoice = 1;
615 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
616 if ($alreadydispatched) {
617 $replacedinvoice = 2;
618 }
619 }
620
621 // If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating a replacement is not possible if invoice is accounted)
622 if ($replacedinvoice == 1) {
623 $db->rollback();
624 continue;
625 }
626
627 // Error if some lines are not binded/ready to be journalized
628 if (isset($errorforinvoice[$key]) && $errorforinvoice[$key] == 'somelinesarenotbound') {
629 $error++;
630 $errorforline++;
631 setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', (string) ($val['ref'] ?? '')), null, 'errors');
632 }
633
634 // Warranty
635 if (!$errorforline && getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
636 if (isset($tabwarranty[$key]) && is_array($tabwarranty[$key])) {
637 foreach ($tabwarranty[$key] as $k => $mt) {
638 $bookkeeping = new BookKeeping($db);
639 $bookkeeping->doc_date = $val["date"];
640 $bookkeeping->date_lim_reglement = $val["datereg"];
641 $bookkeeping->doc_ref = $val["ref"];
642 $bookkeeping->date_creation = $now;
643 $bookkeeping->doc_type = 'customer_invoice';
644 $bookkeeping->fk_doc = (int) $key;
645 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are the source of this record to add
646 $bookkeeping->thirdparty_code = $companystatic->code_client;
647
648 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
649 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
650
651 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY');
652 $bookkeeping->label_compte = $accountingaccountcustomerwarranty->label;
653
654 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RetainedWarranty"));
655 $bookkeeping->montant = $mt;
656 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
657 $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
658 $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
659 $bookkeeping->code_journal = $journal;
660 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
661 $bookkeeping->fk_user_author = $user->id;
662 $bookkeeping->entity = $conf->entity;
663
664 $totaldebit += $bookkeeping->debit;
665 $totalcredit += $bookkeeping->credit;
666
667 $result = $bookkeeping->create($user);
668 if ($result < 0) {
669 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
670 $error++;
671 $errorforline++;
672 $errorforinvoice[$key] = 'alreadyjournalized';
673 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
674 } else {
675 $error++;
676 $errorforline++;
677 $errorforinvoice[$key] = 'other';
678 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
679 }
680 }
681 }
682 }
683 }
684
685 // Thirdparty
686 if (!$errorforline) {
687 foreach ($tabttc[$key] as $k => $mt) {
688 $bookkeeping = new BookKeeping($db);
689 $bookkeeping->doc_date = $val["date"];
690 $bookkeeping->date_lim_reglement = $val["datereg"];
691 $bookkeeping->doc_ref = $val["ref"];
692 $bookkeeping->date_creation = $now;
693 $bookkeeping->doc_type = 'customer_invoice';
694 $bookkeeping->fk_doc = (int) $key;
695 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
696 $bookkeeping->thirdparty_code = $companystatic->code_client;
697
698 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
699 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
700
701 $bookkeeping->numero_compte = (!empty($tabcompany[$key]['accountancy_code_customer_general']) && $tabcompany[$key]['accountancy_code_customer_general'] != '-1') ? $tabcompany[$key]['accountancy_code_customer_general'] : $cptcli;
702 $bookkeeping->label_compte = $accountingaccountcustomer->label;
703
704 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("SubledgerAccount"));
705 $bookkeeping->montant = $mt;
706 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
707 $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
708 $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
709 $bookkeeping->code_journal = $journal;
710 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
711 $bookkeeping->fk_user_author = $user->id;
712 $bookkeeping->entity = $conf->entity;
713
714 $totaldebit += $bookkeeping->debit;
715 $totalcredit += $bookkeeping->credit;
716
717 $result = $bookkeeping->create($user);
718 if ($result < 0) {
719 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
720 $error++;
721 $errorforline++;
722 $errorforinvoice[$key] = 'alreadyjournalized';
723 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
724 } else {
725 $error++;
726 $errorforline++;
727 $errorforinvoice[$key] = 'other';
728 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
729 }
730 } else {
731 if (getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
732 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
733 $lettering_static = new Lettering($db);
734
735 $nb_lettering = $lettering_static->bookkeepingLettering(array($bookkeeping->id));
736 }
737 }
738 }
739 }
740
741 // Product / Service
742 if (!$errorforline) {
743 foreach ($tabht[$key] as $k => $mt) {
744 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
745 $accountingaccount = new AccountingAccount($db);
746 $accountingaccount->fetch(0, $k, true);
747 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
748 } else {
749 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
750 }
751
752 $label_account = $accountingaccount->label;
753
754 // get compte id and label
755 if ($accountingaccount->id > 0) {
756 $bookkeeping = new BookKeeping($db);
757 $bookkeeping->doc_date = $val["date"];
758 $bookkeeping->date_lim_reglement = $val["datereg"];
759 $bookkeeping->doc_ref = $val["ref"];
760 $bookkeeping->date_creation = $now;
761 $bookkeeping->doc_type = 'customer_invoice';
762 $bookkeeping->fk_doc = (int) $key;
763 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
764 $bookkeeping->thirdparty_code = $companystatic->code_client;
765
766 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
767 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
768 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
769 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
770 } else {
771 $bookkeeping->subledger_account = '';
772 $bookkeeping->subledger_label = '';
773 }
774 } else {
775 $bookkeeping->subledger_account = '';
776 $bookkeeping->subledger_label = '';
777 }
778
779 $bookkeeping->numero_compte = $k;
780 $bookkeeping->label_compte = $label_account;
781
782 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $label_account);
783 $bookkeeping->montant = $mt;
784 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
785 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
786 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
787 $bookkeeping->code_journal = $journal;
788 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
789 $bookkeeping->fk_user_author = $user->id;
790 $bookkeeping->entity = $conf->entity;
791
792 $totaldebit += $bookkeeping->debit;
793 $totalcredit += $bookkeeping->credit;
794
795 $result = $bookkeeping->create($user);
796 if ($result < 0) {
797 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
798 $error++;
799 $errorforline++;
800 $errorforinvoice[$key] = 'alreadyjournalized';
801 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
802 } else {
803 $error++;
804 $errorforline++;
805 $errorforinvoice[$key] = 'other';
806 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
807 }
808 }
809 }
810 }
811 }
812
813 // VAT
814 if (!$errorforline) {
815 $listoftax = array(0, 1, 2);
816 foreach ($listoftax as $numtax) {
817 $arrayofvat = $tabtva;
818 if ($numtax == 1) {
819 $arrayofvat = $tablocaltax1;
820 }
821 if ($numtax == 2) {
822 $arrayofvat = $tablocaltax2;
823 }
824
825 foreach ($arrayofvat[$key] as $k => $mt) {
826 if ($mt) {
827 if (empty($conf->cache['accountingaccountincurrententity_vat'][$k])) {
828 $accountingaccount = new AccountingAccount($db);
829 $accountingaccount->fetch(0, $k, true);
830 $conf->cache['accountingaccountincurrententity_vat'][$k] = $accountingaccount;
831 } else {
832 $accountingaccount = $conf->cache['accountingaccountincurrententity_vat'][$k];
833 }
834
835 $label_account = $accountingaccount->label;
836
837 $bookkeeping = new BookKeeping($db);
838 $bookkeeping->doc_date = $val["date"];
839 $bookkeeping->date_lim_reglement = $val["datereg"];
840 $bookkeeping->doc_ref = $val["ref"];
841 $bookkeeping->date_creation = $now;
842 $bookkeeping->doc_type = 'customer_invoice';
843 $bookkeeping->fk_doc = (int) $key;
844 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
845 $bookkeeping->thirdparty_code = $companystatic->code_client;
846
847 $bookkeeping->subledger_account = '';
848 $bookkeeping->subledger_label = '';
849
850 $bookkeeping->numero_compte = $k;
851 $bookkeeping->label_compte = $label_account;
852
853
854 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
855 $labelvataccount = $langs->trans("Taxes").' '.$tmpvatrate.' %';
856 $labelvataccount .= ($numtax ? ' - Localtax '.$numtax : '');
857 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $labelvataccount);
858
859 $bookkeeping->montant = $mt;
860 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
861 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
862 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
863 $bookkeeping->code_journal = $journal;
864 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
865 $bookkeeping->fk_user_author = $user->id;
866 $bookkeeping->entity = $conf->entity;
867
868 $totaldebit += $bookkeeping->debit;
869 $totalcredit += $bookkeeping->credit;
870
871 $result = $bookkeeping->create($user);
872 if ($result < 0) {
873 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
874 $error++;
875 $errorforline++;
876 $errorforinvoice[$key] = 'alreadyjournalized';
877 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
878 } else {
879 $error++;
880 $errorforline++;
881 $errorforinvoice[$key] = 'other';
882 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
883 }
884 }
885 }
886 }
887 }
888 }
889
890 // Revenue stamp
891 if (!$errorforline) {
892 if (isset($tabrevenuestamp[$key]) && is_array($tabrevenuestamp[$key])) {
893 foreach ($tabrevenuestamp[$key] as $k => $mt) {
894 if ($mt) {
895 if (empty($conf->cache['accountingaccountincurrententity_rs'][$k])) {
896 $accountingaccount = new AccountingAccount($db);
897 $accountingaccount->fetch(0, $k, true);
898 $conf->cache['accountingaccountincurrententity_rs'][$k] = $accountingaccount;
899 } else {
900 $accountingaccount = $conf->cache['accountingaccountincurrententity_rs'][$k];
901 }
902
903 $label_account = $accountingaccount->label;
904
905 $bookkeeping = new BookKeeping($db);
906 $bookkeeping->doc_date = $val["date"];
907 $bookkeeping->date_lim_reglement = $val["datereg"];
908 $bookkeeping->doc_ref = $val["ref"];
909 $bookkeeping->date_creation = $now;
910 $bookkeeping->doc_type = 'customer_invoice';
911 $bookkeeping->fk_doc = (int) $key;
912 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
913 $bookkeeping->thirdparty_code = $companystatic->code_client;
914
915 $bookkeeping->subledger_account = '';
916 $bookkeeping->subledger_label = '';
917
918 $bookkeeping->numero_compte = $k;
919 $bookkeeping->label_compte = $label_account;
920
921 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RevenueStamp"));
922 $bookkeeping->montant = $mt;
923 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
924 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
925 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
926 $bookkeeping->code_journal = $journal;
927 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
928 $bookkeeping->fk_user_author = $user->id;
929 $bookkeeping->entity = $conf->entity;
930
931 $totaldebit += $bookkeeping->debit;
932 $totalcredit += $bookkeeping->credit;
933
934 $result = $bookkeeping->create($user);
935 if ($result < 0) {
936 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
937 $error++;
938 $errorforline++;
939 $errorforinvoice[$key] = 'alreadyjournalized';
940 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
941 } else {
942 $error++;
943 $errorforline++;
944 $errorforinvoice[$key] = 'other';
945 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
946 }
947 }
948 }
949 }
950 }
951 }
952
953 if ($manageCustomerDepositInInvoice) {
954 // customer discount consumed TTC amount (like Third-party section)
955 if (!$errorforline && isset($tabCustomerDiscountTTC[$key])) {
956 foreach ($tabCustomerDiscountTTC[$key] as $k => $mt) {
957 $bookkeeping = new BookKeeping($db);
958 $bookkeeping->doc_date = $val["date"];
959 $bookkeeping->date_lim_reglement = $val["datereg"];
960 $bookkeeping->doc_ref = $val["ref"];
961 $bookkeeping->date_creation = $now;
962 $bookkeeping->doc_type = 'customer_invoice';
963 $bookkeeping->fk_doc = $key;
964 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
965 $bookkeeping->thirdparty_code = $companystatic->code_client;
966
967 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
968 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
969
970 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER');
971
972 $bookkeeping->label_compte = $accountingaccountcustomer->label;
973
974 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("SubledgerAccount") . $labelCustomerDiscountExtension);
975 $bookkeeping->montant = $mt;
976 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
977 $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
978 $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
979 $bookkeeping->code_journal = $journal;
980 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
981 $bookkeeping->fk_user_author = $user->id;
982 $bookkeeping->entity = $conf->entity;
983
984 $totaldebit += $bookkeeping->debit;
985 $totalcredit += $bookkeeping->credit;
986
987 $result = $bookkeeping->create($user);
988 if ($result < 0) {
989 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
990 $error++;
991 $errorforline++;
992 $errorforinvoice[$key] = 'alreadyjournalized';
993 } else {
994 $error++;
995 $errorforline++;
996 $errorforinvoice[$key] = 'other';
997 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
998 }
999 } else {
1000 if (getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
1001 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
1002 $lettering_static = new Lettering($db);
1003
1004 $nb_lettering = $lettering_static->bookkeepingLettering(array($bookkeeping->id));
1005 }
1006 }
1007 }
1008 }
1009
1010 // customer discount consumed HT (like Product / Service section)
1011 if (!$errorforline && isset($tabCustomerDiscountHT[$key])) {
1012 foreach ($tabCustomerDiscountHT[$key] as $k => $mt) {
1013 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
1014 $accountingaccount = new AccountingAccount($db);
1015 $accountingaccount->fetch(0, $k, true);
1016 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
1017 } else {
1018 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
1019 }
1020
1021 $label_account = $accountingaccount->label;
1022
1023 // get compte id and label
1024 if ($accountingaccount->id > 0) {
1025 $bookkeeping = new BookKeeping($db);
1026 $bookkeeping->doc_date = $val["date"];
1027 $bookkeeping->date_lim_reglement = $val["datereg"];
1028 $bookkeeping->doc_ref = $val["ref"];
1029 $bookkeeping->date_creation = $now;
1030 $bookkeeping->doc_type = 'customer_invoice';
1031 $bookkeeping->fk_doc = $key;
1032 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
1033 $bookkeeping->thirdparty_code = $companystatic->code_client;
1034
1035 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
1036 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1037 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
1038 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
1039 } else {
1040 $bookkeeping->subledger_account = '';
1041 $bookkeeping->subledger_label = '';
1042 }
1043 } else {
1044 $bookkeeping->subledger_account = '';
1045 $bookkeeping->subledger_label = '';
1046 }
1047
1048 $bookkeeping->numero_compte = $k;
1049 $bookkeeping->label_compte = $label_account;
1050
1051 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $label_account) . $labelCustomerDiscountExtension;
1052 $bookkeeping->montant = $mt;
1053 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
1054 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
1055 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
1056 $bookkeeping->code_journal = $journal;
1057 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
1058 $bookkeeping->fk_user_author = $user->id;
1059 $bookkeeping->entity = $conf->entity;
1060
1061 $totaldebit += $bookkeeping->debit;
1062 $totalcredit += $bookkeeping->credit;
1063
1064 $result = $bookkeeping->create($user);
1065 if ($result < 0) {
1066 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
1067 $error++;
1068 $errorforline++;
1069 $errorforinvoice[$key] = 'alreadyjournalized';
1070 } else {
1071 $error++;
1072 $errorforline++;
1073 $errorforinvoice[$key] = 'other';
1074 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
1075 }
1076 }
1077 }
1078 }
1079 }
1080
1081 // customer discount consumed VAT amount (like VAT section)
1082 if (!$errorforline && isset($tabCustomerDiscountVAT[$key])) {
1083 foreach ($tabCustomerDiscountVAT[$key] as $k => $mt) {
1084 if (empty($conf->cache['accountingaccountincurrententity_vat'][$k])) {
1085 $accountingaccount = new AccountingAccount($db);
1086 $accountingaccount->fetch(0, $k, true);
1087 $conf->cache['accountingaccountincurrententity_vat'][$k] = $accountingaccount;
1088 } else {
1089 $accountingaccount = $conf->cache['accountingaccountincurrententity_vat'][$k];
1090 }
1091
1092 $label_account = $accountingaccount->label;
1093
1094 $bookkeeping = new BookKeeping($db);
1095 $bookkeeping->doc_date = $val["date"];
1096 $bookkeeping->date_lim_reglement = $val["datereg"];
1097 $bookkeeping->doc_ref = $val["ref"];
1098 $bookkeeping->date_creation = $now;
1099 $bookkeeping->doc_type = 'customer_invoice';
1100 $bookkeeping->fk_doc = $key;
1101 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
1102 $bookkeeping->thirdparty_code = $companystatic->code_client;
1103
1104 $bookkeeping->subledger_account = '';
1105 $bookkeeping->subledger_label = '';
1106
1107 $bookkeeping->numero_compte = $k;
1108 $bookkeeping->label_compte = $label_account;
1109
1110 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
1111 $labelvataccount = $langs->trans("Taxes") . ' ' . $tmpvatrate . ' %';
1112 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $labelvataccount) . $labelCustomerDiscountExtension;
1113
1114 $bookkeeping->montant = $mt;
1115 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
1116 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
1117 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
1118 $bookkeeping->code_journal = $journal;
1119 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
1120 $bookkeeping->fk_user_author = $user->id;
1121 $bookkeeping->entity = $conf->entity;
1122
1123 $totaldebit += $bookkeeping->debit;
1124 $totalcredit += $bookkeeping->credit;
1125
1126 $result = $bookkeeping->create($user);
1127 if ($result < 0) {
1128 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
1129 $error++;
1130 $errorforline++;
1131 $errorforinvoice[$key] = 'alreadyjournalized';
1132 } else {
1133 $error++;
1134 $errorforline++;
1135 $errorforinvoice[$key] = 'other';
1136 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
1137 }
1138 }
1139 }
1140 }
1141 }
1142
1143 // Protection against a bug on lines before
1144 if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
1145 $error++;
1146 $errorforline++;
1147 $errorforinvoice[$key] = 'amountsnotbalanced';
1148 setEventMessages('We Tried to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
1149 }
1150
1151 if (!$errorforline) {
1152 $db->commit();
1153 } else {
1154 $db->rollback();
1155
1156 if ($error >= 10) {
1157 $langs->load('errors');
1158 setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
1159 break; // Break in the foreach
1160 }
1161 }
1162 }
1163
1164 $tabpay = $tabfac;
1165
1166 if (empty($error) && count($tabpay) > 0) {
1167 setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
1168 } elseif (count($tabpay) == $error) {
1169 setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
1170 } else {
1171 setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
1172 }
1173
1174 $action = '';
1175
1176 // Must reload data, so we make a redirect
1177 if (count($tabpay) != $error) {
1178 $param = 'id_journal='.$id_journal;
1179 $param .= '&date_startday='.$date_startday;
1180 $param .= '&date_startmonth='.$date_startmonth;
1181 $param .= '&date_startyear='.$date_startyear;
1182 $param .= '&date_endday='.$date_endday;
1183 $param .= '&date_endmonth='.$date_endmonth;
1184 $param .= '&date_endyear='.$date_endyear;
1185 $param .= '&in_bookkeeping='.$in_bookkeeping;
1186 header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
1187 exit;
1188 }
1189}
1190
1191
1192
1193/*
1194 * View
1195 */
1196
1197$form = new Form($db);
1198
1199// Export
1200if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 !
1201 // Note that to have the button to get this feature enabled, you must enable ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL
1202 $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
1203
1204 $filename = 'journal';
1205 $type_export = 'journal';
1206 include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
1207
1208 $companystatic = new Client($db);
1209 $invoicestatic = new Facture($db);
1210 $bookkeepingstatic = new BookKeeping($db);
1211
1212 foreach ($tabfac as $key => $val) {
1213 $companystatic->id = $tabcompany[$key]['id'];
1214 $companystatic->name = $tabcompany[$key]['name'];
1215 $companystatic->accountancy_code_customer_general = (!empty($tabcompany[$key]['accountancy_code_customer_general']) && $tabcompany[$key]['accountancy_code_customer_general'] != '-1') ? $tabcompany[$key]['accountancy_code_customer_general'] : $cptcli;
1216 $companystatic->code_compta = $tabcompany[$key]['code_compta']; // deprecated
1217 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
1218 $companystatic->code_client = $tabcompany[$key]['code_client'];
1219 $companystatic->client = 3;
1220
1221 $invoicestatic->id = (int) $key;
1222 $invoicestatic->ref = (string) $val["ref"];
1223 $invoicestatic->type = (int) ($val["type"] ?? 0);
1224 $invoicestatic->close_code = (string) ($val["close_code"] ?? '');
1225
1226 $date = dol_print_date($val["date"], 'day');
1227
1228 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
1229 $replacedinvoice = 0;
1230 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
1231 $replacedinvoice = 1;
1232 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
1233 if ($alreadydispatched) {
1234 $replacedinvoice = 2;
1235 }
1236 }
1237
1238 // If not already into bookkeeping, we won't add it. If yes, do nothing (should not happen because creating replacement not possible if invoice is accounted)
1239 if ($replacedinvoice == 1) {
1240 continue;
1241 }
1242
1243 // Warranty
1244 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && isset($tabwarranty[$key])) {
1245 foreach ($tabwarranty[$key] as $k => $mt) {
1246 //if ($mt) {
1247 print '"'.$key.'"'.$sep;
1248 print '"'.$date.'"'.$sep;
1249 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1250 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1251 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1252 print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY')).'"'.$sep;
1253 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1254 print '"'.$langs->trans("ThirdParty").'"'.$sep;
1255 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RetainedWarranty"))).'"'.$sep;
1256 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1257 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1258 print '"'.$journal.'"';
1259 print "\n";
1260 //}
1261 }
1262 }
1263
1264 // Third party
1265 foreach ($tabttc[$key] as $k => $mt) {
1266 //if ($mt) {
1267 print '"'.$key.'"'.$sep;
1268 print '"'.$date.'"'.$sep;
1269 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1270 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1271 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1272 print '"'.length_accountg($companystatic->accountancy_code_customer_general).'"'.$sep;
1273 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1274 print '"'.$langs->trans("ThirdParty").'"'.$sep;
1275 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("ThirdParty"))).'"'.$sep;
1276 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1277 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1278 print '"'.$journal.'"';
1279 print "\n";
1280 //}
1281 }
1282
1283 // Product / Service
1284 foreach ($tabht[$key] as $k => $mt) {
1285 $accountingaccount = new AccountingAccount($db);
1286 $accountingaccount->fetch(0, $k, true);
1287 //if ($mt) {
1288 print '"'.$key.'"'.$sep;
1289 print '"'.$date.'"'.$sep;
1290 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1291 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1292 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1293 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1294 print '""'.$sep;
1295 print '"'.csvClean(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
1296 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $accountingaccount->label)).'"'.$sep;
1297 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1298 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1299 print '"'.$journal.'"';
1300 print "\n";
1301 //}
1302 }
1303
1304 // VAT
1305 $listoftax = array(0, 1, 2);
1306 foreach ($listoftax as $numtax) {
1307 $arrayofvat = $tabtva;
1308 if ($numtax == 1) {
1309 $arrayofvat = $tablocaltax1;
1310 }
1311 if ($numtax == 2) {
1312 $arrayofvat = $tablocaltax2;
1313 }
1314
1315 foreach ($arrayofvat[$key] as $k => $mt) {
1316 if ($mt) {
1317 print '"'.$key.'"'.$sep;
1318 print '"'.$date.'"'.$sep;
1319 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1320 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1321 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1322 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1323 print '""'.$sep;
1324 print '"'.$langs->trans("VAT").' - '.implode(', ', $def_tva[$key][$k]).' %"'.$sep;
1325 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("VAT").implode($def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : ''))).'"'.$sep;
1326 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1327 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1328 print '"'.$journal.'"';
1329 print "\n";
1330 }
1331 }
1332 }
1333
1334 // Revenue stamp
1335 if (isset($tabrevenuestamp[$key])) {
1336 foreach ($tabrevenuestamp[$key] as $k => $mt) {
1337 //if ($mt) {
1338 print '"'.$key.'"'.$sep;
1339 print '"'.$date.'"'.$sep;
1340 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1341 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1342 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1343 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1344 print '""'.$sep;
1345 print '"'.$langs->trans("RevenueStamp").'"'.$sep;
1346 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RevenueStamp"))).'"'.$sep;
1347 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1348 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1349 print '"'.$journal.'"';
1350 print "\n";
1351 //}
1352 }
1353 }
1354
1355 if ($manageCustomerDepositInInvoice) {
1356 // customer discount consumed TTC amount (like Third-party section)
1357 if (isset($tabCustomerDiscountTTC[$key])) {
1358 foreach ($tabCustomerDiscountTTC[$key] as $k => $mt) {
1359 //if ($mt) {
1360 print '"' . $key . '"' . $sep;
1361 print '"' . $date . '"' . $sep;
1362 print '"' . ((string) ($val["ref"] ?? '')) . '"' . $sep;
1363 print '"' . csvClean(dol_trunc($companystatic->name, 32)) . '"' . $sep;
1364 print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
1365 print '"' . length_accountg($companystatic->accountancy_code_customer_general) . '"' . $sep;
1366 print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
1367 print '"' . $langs->trans("ThirdParty") . '"' . $sep;
1368 print '"' . csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("ThirdParty")) . $labelCustomerDiscountExtension) . '"' . $sep;
1369 print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
1370 print '"' . ($mt < 0 ? price(-$mt) : '') . '"' . $sep;
1371 print '"' . $journal . '"';
1372 print "\n";
1373 //}
1374 }
1375 }
1376
1377 // customer discount consumed HT (like Product / Service section)
1378 if (isset($tabCustomerDiscountHT[$key])) {
1379 foreach ($tabCustomerDiscountHT[$key] as $k => $mt) {
1380 $accountingaccount = new AccountingAccount($db);
1381 $accountingaccount->fetch(0, $k, true);
1382 //if ($mt) {
1383 print '"' . $key . '"' . $sep;
1384 print '"' . $date . '"' . $sep;
1385 print '"' . ((string) ($val["ref"] ?? '')) . '"' . $sep;
1386 print '"' . csvClean(dol_trunc($companystatic->name, 32)) . '"' . $sep;
1387 print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
1388 print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
1389 print '""' . $sep;
1390 print '"' . csvClean(dol_trunc($accountingaccount->label, 32)) . '"' . $sep;
1391 print '"' . csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $accountingaccount->label) . $labelCustomerDiscountExtension) . '"' . $sep;
1392 print '"' . ($mt < 0 ? price(-$mt) : '') . '"' . $sep;
1393 print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
1394 print '"' . $journal . '"';
1395 print "\n";
1396 //}
1397 }
1398 }
1399
1400 // customer discount consumed VAT amount (like VAT section)
1401 if (isset($tabCustomerDiscountVAT[$key])) {
1402 foreach ($tabCustomerDiscountVAT[$key] as $k => $mt) {
1403 if ($mt) {
1404 print '"' . $key . '"' . $sep;
1405 print '"' . $date . '"' . $sep;
1406 print '"' . ((string) ($val["ref"] ?? '')) . '"' . $sep;
1407 print '"' . csvClean(dol_trunc($companystatic->name, 32)) . '"' . $sep;
1408 print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
1409 print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
1410 print '""' . $sep;
1411 print '"' . $langs->trans("VAT") . ' - ' . implode(', ', $def_tva[$key][$k]) . ' %"' . $sep;
1412 print '"' . csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("VAT") . implode($def_tva[$key][$k]) . ' %') . $labelCustomerDiscountExtension) . '"' . $sep;
1413 print '"' . ($mt < 0 ? price(-$mt) : '') . '"' . $sep;
1414 print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
1415 print '"' . $journal . '"';
1416 print "\n";
1417 }
1418 }
1419 }
1420 }
1421 }
1422}
1423
1424
1425
1426if (empty($action) || $action == 'view') {
1427 $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
1428 $help_url = 'EN:Module_Double_Entry_Accounting|FR:Module_Comptabilit&eacute;_en_Partie_Double#G&eacute;n&eacute;ration_des_&eacute;critures_en_comptabilit&eacute;';
1429 llxHeader('', dol_string_nohtmltag($title), $help_url, '', 0, 0, '', '', '', 'mod-accountancy accountancy-generation page-sellsjournal');
1430
1431 $nom = $title;
1432 $nomlink = '';
1433 $periodlink = '';
1434 $exportlink = '';
1435 $builddate = dol_now();
1436 $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
1437 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
1438 $description .= $langs->trans("DepositsAreNotIncluded");
1439 } else {
1440 $description .= $langs->trans("DepositsAreIncluded");
1441 }
1442
1443 $listofchoices = array('notyet' => $langs->trans("NotYetInGeneralLedger"), 'already' => $langs->trans("AlreadyInGeneralLedger"));
1444 $period = $form->selectDate($date_start ? $date_start : -1, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end ? $date_end : -1, 'date_end', 0, 0, 0, '', 1, 0);
1445 $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
1446
1447 $varlink = 'id_journal='.$id_journal;
1448
1449 journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
1450
1451 if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') != 'blockedonclosed') {
1452 // Test that setup is complete (we are in accounting, so test on entity is always on $conf->entity only, no sharing allowed)
1453 // Fiscal period test
1454 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE entity = ".((int) $conf->entity);
1455 $resql = $db->query($sql);
1456 if ($resql) {
1457 $obj = $db->fetch_object($resql);
1458 if ($obj->nb == 0) {
1459 print '<br><div class="warning">'.img_warning().' '.$langs->trans("TheFiscalPeriodIsNotDefined");
1460 $desc = ' : '.$langs->trans("AccountancyAreaDescFiscalPeriod", 4, '{link}');
1461 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("FiscalPeriod").'</strong>', $desc);
1462 print $desc;
1463 print '</div>';
1464 }
1465 } else {
1466 dol_print_error($db);
1467 }
1468 }
1469
1470 // Button to write into Ledger
1471 $acctCustomerNotConfigured = in_array(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), ['','-1']);
1472 if ($acctCustomerNotConfigured) {
1473 print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
1474 $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
1475 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
1476 print $desc;
1477 print '</div>';
1478 }
1479 print '<br><div class="tabsAction tabsActionNoBottom centerimp">';
1480 if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL') && $in_bookkeeping == 'notyet') {
1481 print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
1482 }
1483 if ($acctCustomerNotConfigured) {
1484 print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
1485 } else {
1486 if ($in_bookkeeping == 'notyet') {
1487 print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
1488 } else {
1489 print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
1490 }
1491 }
1492 print '</div>';
1493
1494 // TODO Avoid using js. We can use a direct link with $param
1495 print '
1496 <script type="text/javascript">
1497 function launch_export() {
1498 $("div.fiche form input[name=\"action\"]").val("exportcsv");
1499 $("div.fiche form input[type=\"submit\"]").click();
1500 $("div.fiche form input[name=\"action\"]").val("");
1501 }
1502 function writebookkeeping() {
1503 console.log("click on writebookkeeping");
1504 $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
1505 $("div.fiche form input[type=\"submit\"]").click();
1506 $("div.fiche form input[name=\"action\"]").val("");
1507 }
1508 </script>';
1509
1510 /*
1511 * Show result array
1512 */
1513 print '<br>';
1514
1515 print '<div class="div-table-responsive">';
1516 print "<table class=\"noborder\" width=\"100%\">";
1517 print "<tr class=\"liste_titre\">";
1518 print "<td>".$langs->trans("Date")."</td>";
1519 print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
1520 print "<td>".$langs->trans("AccountAccounting")."</td>";
1521 print "<td>".$langs->trans("SubledgerAccount")."</td>";
1522 print "<td>".$langs->trans("LabelOperation")."</td>";
1523 print '<td class="center">'.$langs->trans("AccountingDebit")."</td>";
1524 print '<td class="center">'.$langs->trans("AccountingCredit")."</td>";
1525 print "</tr>\n";
1526
1527 $i = 0;
1528
1529 $companystatic = new Client($db);
1530 $invoicestatic = new Facture($db);
1531 $bookkeepingstatic = new BookKeeping($db);
1532
1533 foreach ($tabfac as $key => $val) {
1534 $companystatic->id = $tabcompany[$key]['id'];
1535 $companystatic->name = $tabcompany[$key]['name'];
1536 $companystatic->accountancy_code_customer_general = (!empty($tabcompany[$key]['accountancy_code_customer_general']) && $tabcompany[$key]['accountancy_code_customer_general'] != '-1') ? $tabcompany[$key]['accountancy_code_customer_general'] : $cptcli;
1537 $companystatic->code_compta = $tabcompany[$key]['code_compta'];
1538 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
1539 $companystatic->code_client = $tabcompany[$key]['code_client'];
1540 $companystatic->client = 3;
1541
1542 $invoicestatic->id = (int) $key;
1543 $invoicestatic->ref = (string) $val["ref"];
1544 $invoicestatic->type = (int) ($val["type"] ?? 0);
1545 $invoicestatic->close_code = (string) ($val["close_code"] ?? '');
1546
1547 $date = dol_print_date($val["date"], 'day');
1548
1549 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
1550 $replacedinvoice = 0;
1551 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
1552 $replacedinvoice = 1;
1553 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
1554 if ($alreadydispatched) {
1555 $replacedinvoice = 2;
1556 }
1557 }
1558
1559 // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
1560 if ($replacedinvoice == 1) {
1561 print '<tr class="oddeven">';
1562 print "<!-- Replaced invoice -->";
1563 print "<td>".$date."</td>";
1564 print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
1565 // Account
1566 print "<td>";
1567 print $langs->trans("Replaced");
1568 print '</td>';
1569 // Subledger account
1570 print "<td>";
1571 print '</td>';
1572 print "<td>";
1573 print "</td>";
1574 print '<td class="right"></td>';
1575 print '<td class="right"></td>';
1576 print "</tr>";
1577
1578 $i++;
1579 continue;
1580 }
1581 if (isset($errorforinvoice[$key]) && $errorforinvoice[$key] == 'somelinesarenotbound') {
1582 print '<tr class="oddeven">';
1583 print "<!-- Some lines are not bound -->";
1584 print "<td>".$date."</td>";
1585 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1586 // Account
1587 print "<td>";
1588 print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $invoicestatic->ref).'</span>';
1589 print '</td>';
1590 // Subledger account
1591 print "<td>";
1592 print '</td>';
1593 print "<td>";
1594 print "</td>";
1595 print '<td class="right"></td>';
1596 print '<td class="right"></td>';
1597 print "</tr>";
1598
1599 $i++;
1600 }
1601
1602 // Warranty
1603 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && isset($tabwarranty[$key]) && is_array($tabwarranty[$key])) {
1604 foreach ($tabwarranty[$key] as $k => $mt) {
1605 print '<tr class="oddeven">';
1606 print "<!-- Thirdparty warranty -->";
1607 print "<td>" . $date . "</td>";
1608 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1609 // Account
1610 print "<td>";
1611 $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'));
1612 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1613 print '<span class="error">' . $langs->trans("MainAccountForRetainedWarrantyNotDefined") . '</span>';
1614 } else {
1615 print $accountoshow;
1616 }
1617 print '</td>';
1618 // Subledger account
1619 print "<td>";
1620 $accountoshow = length_accounta($k);
1621 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1622 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1623 } else {
1624 print $accountoshow;
1625 }
1626 print '</td>';
1627 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0), $invoicestatic->ref, $langs->trans("RetainedWarranty"), 1) . "</td>";
1628 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1629 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1630 print "</tr>";
1631 }
1632 }
1633
1634 // Third party
1635 foreach ($tabttc[$key] as $k => $mt) {
1636 print '<tr class="oddeven">';
1637 print "<!-- Thirdparty -->";
1638 print "<td>".$date."</td>";
1639 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1640 // Account
1641 print "<td>";
1642 $accountoshow = length_accountg($companystatic->accountancy_code_customer_general);
1643 if (($accountoshow == "") || $accountoshow == "-1" || $accountoshow == 'NotDefined') {
1644 print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
1645 } else {
1646 print $accountoshow;
1647 }
1648 print '</td>';
1649 // Subledger account
1650 print "<td>";
1651 $accountoshow = length_accounta($k);
1652 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1653 print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
1654 } else {
1655 print $accountoshow;
1656 }
1657 print '</td>';
1658 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $langs->trans("SubledgerAccount"), 1) . "</td>";
1659 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1660 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1661 print "</tr>";
1662
1663 $i++;
1664 }
1665
1666 // Product / Service
1667 foreach ($tabht[$key] as $k => $mt) {
1668 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
1669 $accountingaccount = new AccountingAccount($db);
1670 $accountingaccount->fetch(0, $k, true);
1671 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
1672 } else {
1673 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
1674 }
1675
1676 print '<tr class="oddeven">';
1677 print "<!-- Product -->";
1678 print "<td>".$date."</td>";
1679 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1680 // Account
1681 print "<td>";
1682 $accountoshow = length_accountg($k);
1683 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1684 print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
1685 } else {
1686 print $accountoshow;
1687 }
1688 print "</td>";
1689 // Subledger account
1690 print "<td>";
1691 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
1692 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1693 print length_accounta($tabcompany[$key]['code_compta']);
1694 }
1695 } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
1696 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1697 }
1698 print '</td>';
1699 $companystatic->id = $tabcompany[$key]['id'];
1700 $companystatic->name = $tabcompany[$key]['name'];
1701 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $accountingaccount->label, 1) . "</td>";
1702 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1703 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1704 print "</tr>";
1705
1706 $i++;
1707 }
1708
1709 // VAT
1710 $listoftax = array(0, 1, 2);
1711 foreach ($listoftax as $numtax) {
1712 $arrayofvat = $tabtva;
1713 if ($numtax == 1) {
1714 $arrayofvat = $tablocaltax1;
1715 }
1716 if ($numtax == 2) {
1717 $arrayofvat = $tablocaltax2;
1718 }
1719
1720 // $key is id of invoice
1721 foreach ($arrayofvat[$key] as $k => $mt) {
1722 if ($mt) {
1723 print '<tr class="oddeven">';
1724 print "<!-- VAT -->";
1725 print "<td>".$date."</td>";
1726 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1727 // Account
1728 print "<td>";
1729 $accountoshow = length_accountg($k);
1730 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1731 print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("AccountingJournalType2").')</span>';
1732 } else {
1733 print $accountoshow;
1734 }
1735 print "</td>";
1736 // Subledger account
1737 print "<td>";
1738 print '</td>';
1739 // $def_tva is array[invoiceid][accountancy_code_sell_of_vat_rate_found][vatrate]=vatrate
1740 //var_dump($arrayofvat[$key]); //var_dump($key); //var_dump($k);
1741 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
1742 $labelvatrate = $langs->trans("Taxes").' '.$tmpvatrate.' %';
1743 $labelvatrate .= ($numtax ? ' - Localtax '.$numtax : '');
1744 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $labelvatrate, 1) . "</td>";
1745 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1746 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1747 print "</tr>";
1748
1749 $i++;
1750 }
1751 }
1752 }
1753
1754 // Revenue stamp
1755 if (isset($tabrevenuestamp[$key]) && is_array($tabrevenuestamp[$key])) {
1756 foreach ($tabrevenuestamp[$key] as $k => $mt) {
1757 print '<tr class="oddeven">';
1758 print "<!-- Thirdparty revenuestamp -->";
1759 print "<td>" . $date . "</td>";
1760 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1761 // Account
1762 print "<td>";
1763 $accountoshow = length_accountg($k);
1764 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1765 print '<span class="error">' . $langs->trans("MainAccountForRevenueStampSaleNotDefined") . '</span>';
1766 } else {
1767 print $accountoshow;
1768 }
1769 print '</td>';
1770 // Subledger account
1771 print "<td>";
1772 print '</td>';
1773 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $langs->trans("RevenueStamp"), 1) . "</td>";
1774 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1775 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1776 print "</tr>";
1777 }
1778 }
1779
1780 if ($manageCustomerDepositInInvoice) {
1781 // customer discount consumed TTC amount (like Third-party section)
1782 if (isset($tabCustomerDiscountTTC[$key])) {
1783 foreach ($tabCustomerDiscountTTC[$key] as $k => $mt) {
1784 print '<tr class="oddeven">';
1785 print "<!-- Discount TTC -->";
1786 print "<td>" . $date . "</td>";
1787 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1788 // Account
1789 print "<td>";
1790 $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'));
1791 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1792 print '<span class="error">' . $langs->trans("MainAccountForCustomersNotDefined") . '</span>';
1793 } else {
1794 print $accountoshow;
1795 }
1796 print '</td>';
1797 // Subledger account
1798 print "<td>";
1799 $accountoshow = length_accounta($k);
1800 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1801 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1802 } else {
1803 print $accountoshow;
1804 }
1805 print '</td>';
1806 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $langs->trans("SubledgerAccount") . $labelCustomerDiscountExtension, 1) . "</td>";
1807 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1808 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1809 print "</tr>";
1810
1811 $i++;
1812 }
1813 }
1814
1815 // customer discount consumed HT (like Product / Service section)
1816 if (isset($tabCustomerDiscountHT[$key])) {
1817 foreach ($tabCustomerDiscountHT[$key] as $k => $mt) {
1818 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
1819 $accountingaccount = new AccountingAccount($db);
1820 $accountingaccount->fetch(0, $k, true);
1821 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
1822 } else {
1823 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
1824 }
1825
1826 print '<tr class="oddeven">';
1827 print "<!-- Discount HT -->";
1828 print "<td>" . $date . "</td>";
1829 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1830 // Account
1831 print "<td>";
1832 $accountoshow = length_accountg($k);
1833 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1834 print '<span class="error">' . $langs->trans("ProductNotDefined") . '</span>';
1835 } else {
1836 print $accountoshow;
1837 }
1838 print "</td>";
1839 // Subledger account
1840 print "<td>";
1841 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
1842 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1843 print length_accounta($tabcompany[$key]['code_compta']);
1844 }
1845 } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
1846 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1847 }
1848 print '</td>';
1849 $companystatic->id = $tabcompany[$key]['id'];
1850 $companystatic->name = $tabcompany[$key]['name'];
1851 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $accountingaccount->label, 1) . $labelCustomerDiscountExtension . "</td>";
1852 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1853 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1854 print "</tr>";
1855
1856 $i++;
1857 }
1858 }
1859
1860 // customer discount consumed VAT amount (like VAT section)
1861 if (isset($tabCustomerDiscountVAT[$key])) {
1862 foreach ($tabCustomerDiscountVAT[$key] as $k => $mt) {
1863 print '<tr class="oddeven">';
1864 print "<!-- Discount VAT -->";
1865 print "<td>" . $date . "</td>";
1866 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1867 // Account
1868 print "<td>";
1869 $accountoshow = length_accountg($k);
1870 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1871 print '<span class="error">' . $langs->trans("VATAccountNotDefined") . ' (' . $langs->trans("AccountingJournalType2") . ')</span>';
1872 } else {
1873 print $accountoshow;
1874 }
1875 print "</td>";
1876 // Subledger account
1877 print "<td>";
1878 print '</td>';
1879 $tmpvatrate = (empty($def_tva[$key][$k]) ? '' : implode(', ', $def_tva[$key][$k]));
1880 $labelvatrate = $langs->trans("Taxes") . ' ' . $tmpvatrate . ' %';
1881 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $labelvatrate, 1) . $labelCustomerDiscountExtension . "</td>";
1882 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1883 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1884 print "</tr>";
1885
1886 $i++;
1887 }
1888 }
1889 }
1890 }
1891
1892 if (!$i) {
1893 print '<tr class="oddeven"><td colspan="7"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
1894 }
1895
1896 print "</table>";
1897 print '</div>';
1898
1899 // End of page
1900 llxFooter();
1901}
1902
1903$db->close();
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
getSubledgerAccountWithDefault($thirdpartyCode, $type='customer')
Return the subledger account to use for a thirdparty.
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.
length_accounta($accounta)
Return Auxiliary accounting account of thirdparties with defined length.
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 accounting accounts.
Class to manage accounting journals.
Class to manage Ledger (General Ledger and Subledger)
Class to manage customers or prospects.
Class to manage absolute discounts.
Class to manage invoices.
const TYPE_REPLACEMENT
Replacement invoice.
const TYPE_STANDARD
Standard invoice.
const TYPE_SITUATION
Situation invoice.
const TYPE_DEPOSIT
Deposit invoice.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage invoice lines.
Class to manage generation of HTML components Only common components must be here.
Class Lettering.
Class to manage third parties objects (customers, suppliers, prospects...)
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:
csvClean($newvalue, $charset='', $separator='')
Clean a cell to respect rules of CSV file cells.
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...
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.