dolibarr 24.0.3
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", "errors"));
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 == '') {
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 = (!empty($obj->code_compta_client)) ? $obj->code_compta_client : $cptcli;
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 {
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 } else {
413 $total_ttc = $obj->total_ttc;
414 }
415
416 // Move a part of the retained warrenty into the account of warranty
417 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && $obj->retained_warranty > 0 && (!getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION') || !empty($obj->situation_final))) {
418 $retained_warranty = (float) price2num($total_ttc * $obj->retained_warranty / 100, 'MT'); // Calculate the amount of warrenty for this line (using the percent value)
419 $tabwarranty[$obj->rowid][$compta_soc] += $retained_warranty;
420 $total_ttc -= $retained_warranty;
421 }
422
423 $tabttc[$obj->rowid][$compta_soc] += $total_ttc;
424 $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
425 $tva_npr = ((($obj->info_bits & 1) == 1) ? 1 : 0);
426 if (!$tva_npr) { // We ignore line if VAT is a NPR
427 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
428 $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
429 $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
430 $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
431 } else {
432 $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
433 $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
434 $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
435 }
436 }
437
438 $compta_revenuestamp = 'NotDefined';
439 if (!empty($revenuestamp)) {
440 $sqlrevenuestamp = "SELECT accountancy_code_sell FROM ".MAIN_DB_PREFIX."c_revenuestamp";
441 $sqlrevenuestamp .= " WHERE fk_pays = ".((int) $mysoc->country_id);
442 $sqlrevenuestamp .= " AND taux = ".((float) $revenuestamp);
443 $sqlrevenuestamp .= " AND active = 1";
444 $resqlrevenuestamp = $db->query($sqlrevenuestamp);
445
446 if ($resqlrevenuestamp) {
447 $num_rows_revenuestamp = $db->num_rows($resqlrevenuestamp);
448 if ($num_rows_revenuestamp > 1) {
449 dol_print_error($db, 'Failed 2 or more lines for the revenue stamp of your country. Check the dictionary of revenue stamp.');
450 } else {
451 $objrevenuestamp = $db->fetch_object($resqlrevenuestamp);
452 if ($objrevenuestamp) {
453 $compta_revenuestamp = $objrevenuestamp->accountancy_code_sell;
454 }
455 }
456 }
457 }
458
459 if (empty($tabrevenuestamp[$obj->rowid][$compta_revenuestamp]) && !empty($revenuestamp)) {
460 // The revenue stamp was never seen for this invoice id=$obj->rowid
461 $tabttc[$obj->rowid][$compta_soc] += $obj->revenuestamp;
462 $tabrevenuestamp[$obj->rowid][$compta_revenuestamp] = $obj->revenuestamp;
463 }
464
465 $tabcompany[$obj->rowid] = array(
466 'id' => $obj->socid,
467 'name' => $obj->name,
468 'code_client' => $obj->code_client,
469 'accountancy_code_customer_general' => $accountancy_code_customer_general,
470 'code_compta' => $compta_soc
471 );
472
473 // After the line is processed
474 $parameters = array(
475 'obj' => $obj,
476 'tabfac' => &$tabfac,
477 'tabht' => &$tabht,
478 'tabtva' => &$tabtva,
479 'def_tva' => &$def_tva,
480 'tabwarranty' => &$tabwarranty,
481 'tabrevenuestamp' => &$tabrevenuestamp,
482 'tabttc' => &$tabttc,
483 'tablocaltax1' => &$tablocaltax1,
484 'tablocaltax2' => &$tablocaltax2,
485 'tabcompany' => &$tabcompany,
486 'vatdata_cache' => &$vatdata_cache,
487 );
488 $reshook = $hookmanager->executeHooks('processingJournalData', $parameters); // Note that $action and $object may have been modified by hook
489
490 $i++;
491
492 // Check for too many lines.
493 if ($i > getDolGlobalInt('ACCOUNTANCY_MAX_TOO_MANY_LINES_TO_PROCESS', 10000)) {
494 $error++;
495 setEventMessages("ErrorTooManyLinesToProcessPleaseUseAMoreSelectiveFilter", null, 'errors');
496 break;
497 }
498 }
499
500 // After the loop on each line
501 $parameters = array(
502 'tabfac' => &$tabfac,
503 'tabht' => &$tabht,
504 'tabtva' => &$tabtva,
505 'def_tva' => &$def_tva,
506 'tabwarranty' => &$tabwarranty,
507 'tabrevenuestamp' => &$tabrevenuestamp,
508 'tabttc' => &$tabttc,
509 'tablocaltax1' => &$tablocaltax1,
510 'tablocaltax2' => &$tablocaltax2,
511 'tabcompany' => &$tabcompany,
512 'vatdata_cache' => &$vatdata_cache,
513 );
514 $reshook = $hookmanager->executeHooks('processedJournalData', $parameters); // Note that $action and $object may have been modified by hook
515} else {
517}
518
519
520$errorforinvoice = array();
521
522/*
523// Old way, 1 query for each invoice
524// Loop on all invoices to detect lines without binded code (fk_code_ventilation <= 0)
525foreach ($tabfac as $key => $val) { // Loop on each invoice
526 $sql = "SELECT COUNT(fd.rowid) as nb";
527 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
528 $sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
529 $sql .= " AND fd.total_ttc <> 0 AND fk_facture = ".((int) $key);
530 $resql = $db->query($sql);
531 if ($resql) {
532 $obj = $db->fetch_object($resql);
533 if ($obj->nb > 0) {
534 $errorforinvoice[$key] = 'somelinesarenotbound';
535 }
536 } else {
537 dol_print_error($db);
538 }
539}
540*/
541// New way, single query, load all unbound lines
542if (!empty($tabfac)) {
543 $sql = "
544 SELECT
545 fk_facture,
546 COUNT(fd.rowid) as nb
547 FROM
548 ".MAIN_DB_PREFIX."facturedet as fd
549 WHERE
550 fd.product_type <= 2
551 AND fd.fk_code_ventilation <= 0
552 AND fd.total_ttc <> 0
553 AND fk_facture IN (".$db->sanitize(implode(",", array_keys($tabfac))).")
554 GROUP BY fk_facture
555 ";
556 $resql = $db->query($sql);
557 if ($resql) {
558 $num = $db->num_rows($resql);
559 $i = 0;
560 while ($i < $num) {
561 $obj = $db->fetch_object($resql);
562 if ($obj->nb > 0) {
563 $errorforinvoice[$obj->fk_facture] = 'somelinesarenotbound';
564 }
565 $i++;
566 }
567 }
568}
569//var_dump($errorforinvoice);exit;
570
571// Bookkeeping Write
572if ($action == 'writebookkeeping' && !$error && $user->hasRight('accounting', 'bind', 'write')) {
573 $now = dol_now();
574 $error = 0;
575
576 $companystatic = new Societe($db);
577 $invoicestatic = new Facture($db);
578 $bookkeepingstatic = new BookKeeping($db);
579
580 $accountingaccountcustomer = new AccountingAccount($db);
581 $accountingaccountcustomer->fetch(0, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), true);
582
583 $accountingaccountcustomerwarranty = new AccountingAccount($db);
584 $accountingaccountcustomerwarranty->fetch(0, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'), true);
585
586 foreach ($tabfac as $key => $val) { // Loop on each invoice
587 $errorforline = 0;
588
589 $totalcredit = 0;
590 $totaldebit = 0;
591
592 $db->begin(); // We accept transaction into loop, so if we hang, we can continue transfer from the last error
593
594 $companystatic->id = $tabcompany[$key]['id'];
595 $companystatic->name = $tabcompany[$key]['name'];
596 $companystatic->accountancy_code_customer_general = $tabcompany[$key]['accountancy_code_customer_general'];
597 $companystatic->code_compta = $tabcompany[$key]['code_compta'];
598 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
599 $companystatic->code_client = $tabcompany[$key]['code_client'];
600 $companystatic->client = 3;
601
602 $invoicestatic->id = (int) $key;
603 $invoicestatic->ref = (string) $val["ref"];
604 $invoicestatic->type = (int) ($val["type"] ?? 0);
605 $invoicestatic->close_code = (string) ($val["close_code"] ?? '');
606
607 $date = dol_print_date($val["date"], 'day');
608
609 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
610 $replacedinvoice = 0;
611 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
612 $replacedinvoice = 1;
613 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
614 if ($alreadydispatched) {
615 $replacedinvoice = 2;
616 }
617 }
618
619 // 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)
620 if ($replacedinvoice == 1) {
621 $db->rollback();
622 continue;
623 }
624
625 // Error if some lines are not binded/ready to be journalized
626 if (isset($errorforinvoice[$key]) && $errorforinvoice[$key] == 'somelinesarenotbound') {
627 $error++;
628 $errorforline++;
629 setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', (string) ($val['ref'] ?? '')), null, 'errors');
630 }
631
632 // Warranty
633 if (!$errorforline && getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
634 if (isset($tabwarranty[$key]) && is_array($tabwarranty[$key])) {
635 foreach ($tabwarranty[$key] as $k => $mt) {
636 $bookkeeping = new BookKeeping($db);
637 $bookkeeping->doc_date = $val["date"];
638 $bookkeeping->date_lim_reglement = $val["datereg"];
639 $bookkeeping->doc_ref = $val["ref"];
640 $bookkeeping->date_creation = $now;
641 $bookkeeping->doc_type = 'customer_invoice';
642 $bookkeeping->fk_doc = (int) $key;
643 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are the source of this record to add
644 $bookkeeping->thirdparty_code = $companystatic->code_client;
645
646 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
647 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
648
649 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY');
650 $bookkeeping->label_compte = $accountingaccountcustomerwarranty->label;
651
652 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RetainedWarranty"));
653 $bookkeeping->montant = $mt;
654 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
655 $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
656 $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
657 $bookkeeping->code_journal = $journal;
658 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
659 $bookkeeping->fk_user_author = $user->id;
660 $bookkeeping->entity = $conf->entity;
661
662 $totaldebit += $bookkeeping->debit;
663 $totalcredit += $bookkeeping->credit;
664
665 $result = $bookkeeping->create($user);
666 if ($result < 0) {
667 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
668 $error++;
669 $errorforline++;
670 $errorforinvoice[$key] = 'alreadyjournalized';
671 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
672 } else {
673 $error++;
674 $errorforline++;
675 $errorforinvoice[$key] = 'other';
676 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
677 }
678 }
679 }
680 }
681 }
682
683 // Thirdparty
684 if (!$errorforline) {
685 foreach ($tabttc[$key] as $k => $mt) {
686 $bookkeeping = new BookKeeping($db);
687 $bookkeeping->doc_date = $val["date"];
688 $bookkeeping->date_lim_reglement = $val["datereg"];
689 $bookkeeping->doc_ref = $val["ref"];
690 $bookkeeping->date_creation = $now;
691 $bookkeeping->doc_type = 'customer_invoice';
692 $bookkeeping->fk_doc = (int) $key;
693 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
694 $bookkeeping->thirdparty_code = $companystatic->code_client;
695
696 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
697 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
698
699 $bookkeeping->numero_compte = (!empty($tabcompany[$key]['accountancy_code_customer_general']) && $tabcompany[$key]['accountancy_code_customer_general'] != '-1') ? $tabcompany[$key]['accountancy_code_customer_general'] : $cptcli;
700 $bookkeeping->label_compte = $accountingaccountcustomer->label;
701
702 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("SubledgerAccount"));
703 $bookkeeping->montant = $mt;
704 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
705 $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
706 $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
707 $bookkeeping->code_journal = $journal;
708 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
709 $bookkeeping->fk_user_author = $user->id;
710 $bookkeeping->entity = $conf->entity;
711
712 $totaldebit += $bookkeeping->debit;
713 $totalcredit += $bookkeeping->credit;
714
715 $result = $bookkeeping->create($user);
716 if ($result < 0) {
717 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
718 $error++;
719 $errorforline++;
720 $errorforinvoice[$key] = 'alreadyjournalized';
721 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
722 } else {
723 $error++;
724 $errorforline++;
725 $errorforinvoice[$key] = 'other';
726 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
727 }
728 } else {
729 if (getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
730 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
731 $lettering_static = new Lettering($db);
732
733 $nb_lettering = $lettering_static->bookkeepingLettering(array($bookkeeping->id));
734 }
735 }
736 }
737 }
738
739 // Product / Service
740 if (!$errorforline) {
741 foreach ($tabht[$key] as $k => $mt) {
742 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
743 $accountingaccount = new AccountingAccount($db);
744 $accountingaccount->fetch(0, $k, true);
745 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
746 } else {
747 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
748 }
749
750 $label_account = $accountingaccount->label;
751
752 // get compte id and label
753 if ($accountingaccount->id > 0) {
754 $bookkeeping = new BookKeeping($db);
755 $bookkeeping->doc_date = $val["date"];
756 $bookkeeping->date_lim_reglement = $val["datereg"];
757 $bookkeeping->doc_ref = $val["ref"];
758 $bookkeeping->date_creation = $now;
759 $bookkeeping->doc_type = 'customer_invoice';
760 $bookkeeping->fk_doc = (int) $key;
761 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
762 $bookkeeping->thirdparty_code = $companystatic->code_client;
763
764 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
765 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
766 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
767 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
768 } else {
769 $bookkeeping->subledger_account = '';
770 $bookkeeping->subledger_label = '';
771 }
772 } else {
773 $bookkeeping->subledger_account = '';
774 $bookkeeping->subledger_label = '';
775 }
776
777 $bookkeeping->numero_compte = $k;
778 $bookkeeping->label_compte = $label_account;
779
780 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $label_account);
781 $bookkeeping->montant = $mt;
782 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
783 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
784 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
785 $bookkeeping->code_journal = $journal;
786 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
787 $bookkeeping->fk_user_author = $user->id;
788 $bookkeeping->entity = $conf->entity;
789
790 $totaldebit += $bookkeeping->debit;
791 $totalcredit += $bookkeeping->credit;
792
793 $result = $bookkeeping->create($user);
794 if ($result < 0) {
795 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
796 $error++;
797 $errorforline++;
798 $errorforinvoice[$key] = 'alreadyjournalized';
799 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
800 } else {
801 $error++;
802 $errorforline++;
803 $errorforinvoice[$key] = 'other';
804 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
805 }
806 }
807 }
808 }
809 }
810
811 // VAT
812 if (!$errorforline) {
813 $listoftax = array(0, 1, 2);
814 foreach ($listoftax as $numtax) {
815 $arrayofvat = $tabtva;
816 if ($numtax == 1) {
817 $arrayofvat = $tablocaltax1;
818 }
819 if ($numtax == 2) {
820 $arrayofvat = $tablocaltax2;
821 }
822
823 foreach ($arrayofvat[$key] as $k => $mt) {
824 if ($mt) {
825 if (empty($conf->cache['accountingaccountincurrententity_vat'][$k])) {
826 $accountingaccount = new AccountingAccount($db);
827 $accountingaccount->fetch(0, $k, true);
828 $conf->cache['accountingaccountincurrententity_vat'][$k] = $accountingaccount;
829 } else {
830 $accountingaccount = $conf->cache['accountingaccountincurrententity_vat'][$k];
831 }
832
833 $label_account = $accountingaccount->label;
834
835 $bookkeeping = new BookKeeping($db);
836 $bookkeeping->doc_date = $val["date"];
837 $bookkeeping->date_lim_reglement = $val["datereg"];
838 $bookkeeping->doc_ref = $val["ref"];
839 $bookkeeping->date_creation = $now;
840 $bookkeeping->doc_type = 'customer_invoice';
841 $bookkeeping->fk_doc = (int) $key;
842 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
843 $bookkeeping->thirdparty_code = $companystatic->code_client;
844
845 $bookkeeping->subledger_account = '';
846 $bookkeeping->subledger_label = '';
847
848 $bookkeeping->numero_compte = $k;
849 $bookkeeping->label_compte = $label_account;
850
851
852 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
853 $labelvataccount = $langs->trans("Taxes").' '.$tmpvatrate.' %';
854 $labelvataccount .= ($numtax ? ' - Localtax '.$numtax : '');
855 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $labelvataccount);
856
857 $bookkeeping->montant = $mt;
858 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
859 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
860 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
861 $bookkeeping->code_journal = $journal;
862 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
863 $bookkeeping->fk_user_author = $user->id;
864 $bookkeeping->entity = $conf->entity;
865
866 $totaldebit += $bookkeeping->debit;
867 $totalcredit += $bookkeeping->credit;
868
869 $result = $bookkeeping->create($user);
870 if ($result < 0) {
871 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
872 $error++;
873 $errorforline++;
874 $errorforinvoice[$key] = 'alreadyjournalized';
875 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
876 } else {
877 $error++;
878 $errorforline++;
879 $errorforinvoice[$key] = 'other';
880 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
881 }
882 }
883 }
884 }
885 }
886 }
887
888 // Revenue stamp
889 if (!$errorforline) {
890 if (isset($tabrevenuestamp[$key]) && is_array($tabrevenuestamp[$key])) {
891 foreach ($tabrevenuestamp[$key] as $k => $mt) {
892 if ($mt) {
893 if (empty($conf->cache['accountingaccountincurrententity_rs'][$k])) {
894 $accountingaccount = new AccountingAccount($db);
895 $accountingaccount->fetch(0, $k, true);
896 $conf->cache['accountingaccountincurrententity_rs'][$k] = $accountingaccount;
897 } else {
898 $accountingaccount = $conf->cache['accountingaccountincurrententity_rs'][$k];
899 }
900
901 $label_account = $accountingaccount->label;
902
903 $bookkeeping = new BookKeeping($db);
904 $bookkeeping->doc_date = $val["date"];
905 $bookkeeping->date_lim_reglement = $val["datereg"];
906 $bookkeeping->doc_ref = $val["ref"];
907 $bookkeeping->date_creation = $now;
908 $bookkeeping->doc_type = 'customer_invoice';
909 $bookkeeping->fk_doc = (int) $key;
910 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
911 $bookkeeping->thirdparty_code = $companystatic->code_client;
912
913 $bookkeeping->subledger_account = '';
914 $bookkeeping->subledger_label = '';
915
916 $bookkeeping->numero_compte = $k;
917 $bookkeeping->label_compte = $label_account;
918
919 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RevenueStamp"));
920 $bookkeeping->montant = $mt;
921 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
922 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
923 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
924 $bookkeeping->code_journal = $journal;
925 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
926 $bookkeeping->fk_user_author = $user->id;
927 $bookkeeping->entity = $conf->entity;
928
929 $totaldebit += $bookkeeping->debit;
930 $totalcredit += $bookkeeping->credit;
931
932 $result = $bookkeeping->create($user);
933 if ($result < 0) {
934 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
935 $error++;
936 $errorforline++;
937 $errorforinvoice[$key] = 'alreadyjournalized';
938 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
939 } else {
940 $error++;
941 $errorforline++;
942 $errorforinvoice[$key] = 'other';
943 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
944 }
945 }
946 }
947 }
948 }
949 }
950
951 if ($manageCustomerDepositInInvoice) {
952 // customer discount consumed TTC amount (like Third-party section)
953 if (!$errorforline && isset($tabCustomerDiscountTTC[$key])) {
954 foreach ($tabCustomerDiscountTTC[$key] as $k => $mt) {
955 $bookkeeping = new BookKeeping($db);
956 $bookkeeping->doc_date = $val["date"];
957 $bookkeeping->date_lim_reglement = $val["datereg"];
958 $bookkeeping->doc_ref = $val["ref"];
959 $bookkeeping->date_creation = $now;
960 $bookkeeping->doc_type = 'customer_invoice';
961 $bookkeeping->fk_doc = $key;
962 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
963 $bookkeeping->thirdparty_code = $companystatic->code_client;
964
965 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
966 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
967
968 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER');
969
970 $bookkeeping->label_compte = $accountingaccountcustomer->label;
971
972 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("SubledgerAccount") . $labelCustomerDiscountExtension);
973 $bookkeeping->montant = $mt;
974 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
975 $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
976 $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
977 $bookkeeping->code_journal = $journal;
978 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
979 $bookkeeping->fk_user_author = $user->id;
980 $bookkeeping->entity = $conf->entity;
981
982 $totaldebit += $bookkeeping->debit;
983 $totalcredit += $bookkeeping->credit;
984
985 $result = $bookkeeping->create($user);
986 if ($result < 0) {
987 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
988 $error++;
989 $errorforline++;
990 $errorforinvoice[$key] = 'alreadyjournalized';
991 } else {
992 $error++;
993 $errorforline++;
994 $errorforinvoice[$key] = 'other';
995 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
996 }
997 } else {
998 if (getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
999 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
1000 $lettering_static = new Lettering($db);
1001
1002 $nb_lettering = $lettering_static->bookkeepingLettering(array($bookkeeping->id));
1003 }
1004 }
1005 }
1006 }
1007
1008 // customer discount consumed HT (like Product / Service section)
1009 if (!$errorforline && isset($tabCustomerDiscountHT[$key])) {
1010 foreach ($tabCustomerDiscountHT[$key] as $k => $mt) {
1011 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
1012 $accountingaccount = new AccountingAccount($db);
1013 $accountingaccount->fetch(0, $k, true);
1014 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
1015 } else {
1016 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
1017 }
1018
1019 $label_account = $accountingaccount->label;
1020
1021 // get compte id and label
1022 if ($accountingaccount->id > 0) {
1023 $bookkeeping = new BookKeeping($db);
1024 $bookkeeping->doc_date = $val["date"];
1025 $bookkeeping->date_lim_reglement = $val["datereg"];
1026 $bookkeeping->doc_ref = $val["ref"];
1027 $bookkeeping->date_creation = $now;
1028 $bookkeeping->doc_type = 'customer_invoice';
1029 $bookkeeping->fk_doc = $key;
1030 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
1031 $bookkeeping->thirdparty_code = $companystatic->code_client;
1032
1033 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
1034 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1035 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
1036 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
1037 } else {
1038 $bookkeeping->subledger_account = '';
1039 $bookkeeping->subledger_label = '';
1040 }
1041 } else {
1042 $bookkeeping->subledger_account = '';
1043 $bookkeeping->subledger_label = '';
1044 }
1045
1046 $bookkeeping->numero_compte = $k;
1047 $bookkeeping->label_compte = $label_account;
1048
1049 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $label_account) . $labelCustomerDiscountExtension;
1050 $bookkeeping->montant = $mt;
1051 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
1052 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
1053 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
1054 $bookkeeping->code_journal = $journal;
1055 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
1056 $bookkeeping->fk_user_author = $user->id;
1057 $bookkeeping->entity = $conf->entity;
1058
1059 $totaldebit += $bookkeeping->debit;
1060 $totalcredit += $bookkeeping->credit;
1061
1062 $result = $bookkeeping->create($user);
1063 if ($result < 0) {
1064 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
1065 $error++;
1066 $errorforline++;
1067 $errorforinvoice[$key] = 'alreadyjournalized';
1068 } else {
1069 $error++;
1070 $errorforline++;
1071 $errorforinvoice[$key] = 'other';
1072 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
1073 }
1074 }
1075 }
1076 }
1077 }
1078
1079 // customer discount consumed VAT amount (like VAT section)
1080 if (!$errorforline && isset($tabCustomerDiscountVAT[$key])) {
1081 foreach ($tabCustomerDiscountVAT[$key] as $k => $mt) {
1082 if (empty($conf->cache['accountingaccountincurrententity_vat'][$k])) {
1083 $accountingaccount = new AccountingAccount($db);
1084 $accountingaccount->fetch(0, $k, true);
1085 $conf->cache['accountingaccountincurrententity_vat'][$k] = $accountingaccount;
1086 } else {
1087 $accountingaccount = $conf->cache['accountingaccountincurrententity_vat'][$k];
1088 }
1089
1090 $label_account = $accountingaccount->label;
1091
1092 $bookkeeping = new BookKeeping($db);
1093 $bookkeeping->doc_date = $val["date"];
1094 $bookkeeping->date_lim_reglement = $val["datereg"];
1095 $bookkeeping->doc_ref = $val["ref"];
1096 $bookkeeping->date_creation = $now;
1097 $bookkeeping->doc_type = 'customer_invoice';
1098 $bookkeeping->fk_doc = $key;
1099 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
1100 $bookkeeping->thirdparty_code = $companystatic->code_client;
1101
1102 $bookkeeping->subledger_account = '';
1103 $bookkeeping->subledger_label = '';
1104
1105 $bookkeeping->numero_compte = $k;
1106 $bookkeeping->label_compte = $label_account;
1107
1108 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
1109 $labelvataccount = $langs->trans("Taxes") . ' ' . $tmpvatrate . ' %';
1110 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $labelvataccount) . $labelCustomerDiscountExtension;
1111
1112 $bookkeeping->montant = $mt;
1113 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
1114 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
1115 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
1116 $bookkeeping->code_journal = $journal;
1117 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
1118 $bookkeeping->fk_user_author = $user->id;
1119 $bookkeeping->entity = $conf->entity;
1120
1121 $totaldebit += $bookkeeping->debit;
1122 $totalcredit += $bookkeeping->credit;
1123
1124 $result = $bookkeeping->create($user);
1125 if ($result < 0) {
1126 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
1127 $error++;
1128 $errorforline++;
1129 $errorforinvoice[$key] = 'alreadyjournalized';
1130 } else {
1131 $error++;
1132 $errorforline++;
1133 $errorforinvoice[$key] = 'other';
1134 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
1135 }
1136 }
1137 }
1138 }
1139 }
1140
1141 // Protection against a bug on lines before
1142 if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
1143 $error++;
1144 $errorforline++;
1145 $errorforinvoice[$key] = 'amountsnotbalanced';
1146 setEventMessages('We Tried to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
1147 }
1148
1149 if (!$errorforline) {
1150 $db->commit();
1151 } else {
1152 $db->rollback();
1153
1154 if ($error >= 10) {
1155 setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
1156 break; // Break in the foreach
1157 }
1158 }
1159 }
1160
1161 $tabpay = $tabfac;
1162
1163 if (empty($error) && count($tabpay) > 0) {
1164 setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
1165 } elseif (count($tabpay) == $error) {
1166 setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
1167 } else {
1168 setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
1169 }
1170
1171 $action = '';
1172
1173 // Must reload data, so we make a redirect
1174 if (count($tabpay) != $error) {
1175 $param = 'id_journal='.$id_journal;
1176 $param .= '&date_startday='.$date_startday;
1177 $param .= '&date_startmonth='.$date_startmonth;
1178 $param .= '&date_startyear='.$date_startyear;
1179 $param .= '&date_endday='.$date_endday;
1180 $param .= '&date_endmonth='.$date_endmonth;
1181 $param .= '&date_endyear='.$date_endyear;
1182 $param .= '&in_bookkeeping='.$in_bookkeeping;
1183 header("Location: ".$_SERVER['PHP_SELF'].($param ? '?'.$param : ''));
1184 exit;
1185 }
1186}
1187
1188
1189
1190/*
1191 * View
1192 */
1193
1194$form = new Form($db);
1195
1196// Export
1197if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 !
1198 // Note that to have the button to get this feature enabled, you must enable ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL
1199 $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
1200
1201 $filename = 'journal';
1202 $type_export = 'journal';
1203 include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
1204
1205 $companystatic = new Client($db);
1206 $invoicestatic = new Facture($db);
1207 $bookkeepingstatic = new BookKeeping($db);
1208
1209 foreach ($tabfac as $key => $val) {
1210 $companystatic->id = $tabcompany[$key]['id'];
1211 $companystatic->name = $tabcompany[$key]['name'];
1212 $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;
1213 $companystatic->code_compta = $tabcompany[$key]['code_compta']; // deprecated
1214 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
1215 $companystatic->code_client = $tabcompany[$key]['code_client'];
1216 $companystatic->client = 3;
1217
1218 $invoicestatic->id = (int) $key;
1219 $invoicestatic->ref = (string) $val["ref"];
1220 $invoicestatic->type = (int) ($val["type"] ?? 0);
1221 $invoicestatic->close_code = (string) ($val["close_code"] ?? '');
1222
1223 $date = dol_print_date($val["date"], 'day');
1224
1225 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
1226 $replacedinvoice = 0;
1227 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
1228 $replacedinvoice = 1;
1229 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
1230 if ($alreadydispatched) {
1231 $replacedinvoice = 2;
1232 }
1233 }
1234
1235 // 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)
1236 if ($replacedinvoice == 1) {
1237 continue;
1238 }
1239
1240 // Warranty
1241 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && isset($tabwarranty[$key])) {
1242 foreach ($tabwarranty[$key] as $k => $mt) {
1243 //if ($mt) {
1244 print '"'.$key.'"'.$sep;
1245 print '"'.$date.'"'.$sep;
1246 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1247 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1248 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1249 print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY')).'"'.$sep;
1250 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1251 print '"'.$langs->trans("ThirdParty").'"'.$sep;
1252 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RetainedWarranty"))).'"'.$sep;
1253 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1254 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1255 print '"'.$journal.'"';
1256 print "\n";
1257 //}
1258 }
1259 }
1260
1261 // Third party
1262 foreach ($tabttc[$key] as $k => $mt) {
1263 //if ($mt) {
1264 print '"'.$key.'"'.$sep;
1265 print '"'.$date.'"'.$sep;
1266 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1267 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1268 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1269 print '"'.length_accountg($companystatic->accountancy_code_customer_general).'"'.$sep;
1270 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1271 print '"'.$langs->trans("ThirdParty").'"'.$sep;
1272 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("ThirdParty"))).'"'.$sep;
1273 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1274 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1275 print '"'.$journal.'"';
1276 print "\n";
1277 //}
1278 }
1279
1280 // Product / Service
1281 foreach ($tabht[$key] as $k => $mt) {
1282 $accountingaccount = new AccountingAccount($db);
1283 $accountingaccount->fetch(0, $k, true);
1284 //if ($mt) {
1285 print '"'.$key.'"'.$sep;
1286 print '"'.$date.'"'.$sep;
1287 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1288 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1289 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1290 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1291 print '""'.$sep;
1292 print '"'.csvClean(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
1293 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $accountingaccount->label)).'"'.$sep;
1294 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1295 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1296 print '"'.$journal.'"';
1297 print "\n";
1298 //}
1299 }
1300
1301 // VAT
1302 $listoftax = array(0, 1, 2);
1303 foreach ($listoftax as $numtax) {
1304 $arrayofvat = $tabtva;
1305 if ($numtax == 1) {
1306 $arrayofvat = $tablocaltax1;
1307 }
1308 if ($numtax == 2) {
1309 $arrayofvat = $tablocaltax2;
1310 }
1311
1312 foreach ($arrayofvat[$key] as $k => $mt) {
1313 if ($mt) {
1314 print '"'.$key.'"'.$sep;
1315 print '"'.$date.'"'.$sep;
1316 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1317 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1318 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1319 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1320 print '""'.$sep;
1321 print '"'.$langs->trans("VAT").' - '.implode(', ', $def_tva[$key][$k]).' %"'.$sep;
1322 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("VAT").implode($def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : ''))).'"'.$sep;
1323 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1324 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1325 print '"'.$journal.'"';
1326 print "\n";
1327 }
1328 }
1329 }
1330
1331 // Revenue stamp
1332 if (isset($tabrevenuestamp[$key])) {
1333 foreach ($tabrevenuestamp[$key] as $k => $mt) {
1334 //if ($mt) {
1335 print '"'.$key.'"'.$sep;
1336 print '"'.$date.'"'.$sep;
1337 print '"'.((string) ($val["ref"] ?? '')).'"'.$sep;
1338 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1339 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1340 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1341 print '""'.$sep;
1342 print '"'.$langs->trans("RevenueStamp").'"'.$sep;
1343 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RevenueStamp"))).'"'.$sep;
1344 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1345 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1346 print '"'.$journal.'"';
1347 print "\n";
1348 //}
1349 }
1350 }
1351
1352 if ($manageCustomerDepositInInvoice) {
1353 // customer discount consumed TTC amount (like Third-party section)
1354 if (isset($tabCustomerDiscountTTC[$key])) {
1355 foreach ($tabCustomerDiscountTTC[$key] as $k => $mt) {
1356 //if ($mt) {
1357 print '"' . $key . '"' . $sep;
1358 print '"' . $date . '"' . $sep;
1359 print '"' . ((string) ($val["ref"] ?? '')) . '"' . $sep;
1360 print '"' . csvClean(dol_trunc($companystatic->name, 32)) . '"' . $sep;
1361 print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
1362 print '"' . length_accountg($companystatic->accountancy_code_customer_general) . '"' . $sep;
1363 print '"' . length_accounta(html_entity_decode($k)) . '"' . $sep;
1364 print '"' . $langs->trans("ThirdParty") . '"' . $sep;
1365 print '"' . csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("ThirdParty")) . $labelCustomerDiscountExtension) . '"' . $sep;
1366 print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
1367 print '"' . ($mt < 0 ? price(-$mt) : '') . '"' . $sep;
1368 print '"' . $journal . '"';
1369 print "\n";
1370 //}
1371 }
1372 }
1373
1374 // customer discount consumed HT (like Product / Service section)
1375 if (isset($tabCustomerDiscountHT[$key])) {
1376 foreach ($tabCustomerDiscountHT[$key] as $k => $mt) {
1377 $accountingaccount = new AccountingAccount($db);
1378 $accountingaccount->fetch(0, $k, true);
1379 //if ($mt) {
1380 print '"' . $key . '"' . $sep;
1381 print '"' . $date . '"' . $sep;
1382 print '"' . ((string) ($val["ref"] ?? '')) . '"' . $sep;
1383 print '"' . csvClean(dol_trunc($companystatic->name, 32)) . '"' . $sep;
1384 print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
1385 print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
1386 print '""' . $sep;
1387 print '"' . csvClean(dol_trunc($accountingaccount->label, 32)) . '"' . $sep;
1388 print '"' . csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $accountingaccount->label) . $labelCustomerDiscountExtension) . '"' . $sep;
1389 print '"' . ($mt < 0 ? price(-$mt) : '') . '"' . $sep;
1390 print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
1391 print '"' . $journal . '"';
1392 print "\n";
1393 //}
1394 }
1395 }
1396
1397 // customer discount consumed VAT amount (like VAT section)
1398 if (isset($tabCustomerDiscountVAT[$key])) {
1399 foreach ($tabCustomerDiscountVAT[$key] as $k => $mt) {
1400 if ($mt) {
1401 print '"' . $key . '"' . $sep;
1402 print '"' . $date . '"' . $sep;
1403 print '"' . ((string) ($val["ref"] ?? '')) . '"' . $sep;
1404 print '"' . csvClean(dol_trunc($companystatic->name, 32)) . '"' . $sep;
1405 print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
1406 print '"' . length_accountg(html_entity_decode($k)) . '"' . $sep;
1407 print '""' . $sep;
1408 print '"' . $langs->trans("VAT") . ' - ' . implode(', ', $def_tva[$key][$k]) . ' %"' . $sep;
1409 print '"' . csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("VAT") . implode($def_tva[$key][$k]) . ' %') . $labelCustomerDiscountExtension) . '"' . $sep;
1410 print '"' . ($mt < 0 ? price(-$mt) : '') . '"' . $sep;
1411 print '"' . ($mt >= 0 ? price($mt) : '') . '"' . $sep;
1412 print '"' . $journal . '"';
1413 print "\n";
1414 }
1415 }
1416 }
1417 }
1418 }
1419}
1420
1421
1422
1423if (empty($action) || $action == 'view') {
1424 $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
1425 $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;';
1426 llxHeader('', dol_string_nohtmltag($title), $help_url, '', 0, 0, '', '', '', 'mod-accountancy accountancy-generation page-sellsjournal');
1427
1428 $nom = $title;
1429 $nomlink = '';
1430 $periodlink = '';
1431 $exportlink = '';
1432 $builddate = dol_now();
1433 $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
1434 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
1435 $description .= $langs->trans("DepositsAreNotIncluded");
1436 } else {
1437 $description .= $langs->trans("DepositsAreIncluded");
1438 }
1439
1440 $listofchoices = array('notyet' => $langs->trans("NotYetInGeneralLedger"), 'already' => $langs->trans("AlreadyInGeneralLedger"));
1441 $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);
1442 $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
1443
1444 $varlink = 'id_journal='.$id_journal;
1445
1446 journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
1447
1448 if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') != 'blockedonclosed') {
1449 // Test that setup is complete (we are in accounting, so test on entity is always on $conf->entity only, no sharing allowed)
1450 // Fiscal period test
1451 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE entity = ".((int) $conf->entity);
1452 $resql = $db->query($sql);
1453 if ($resql) {
1454 $obj = $db->fetch_object($resql);
1455 if ($obj->nb == 0) {
1456 print '<br><div class="warning">'.img_warning().' '.$langs->trans("TheFiscalPeriodIsNotDefined");
1457 $desc = ' : '.$langs->trans("AccountancyAreaDescFiscalPeriod", 4, '{link}');
1458 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("FiscalPeriod").'</strong>', $desc);
1459 print $desc;
1460 print '</div>';
1461 }
1462 } else {
1464 }
1465 }
1466
1467 // Button to write into Ledger
1468 $acctCustomerNotConfigured = in_array(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), ['','-1']);
1469 if ($acctCustomerNotConfigured) {
1470 print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
1471 $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
1472 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
1473 print $desc;
1474 print '</div>';
1475 }
1476 print '<br><div class="tabsAction tabsActionNoBottom centerimp">';
1477 if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL') && $in_bookkeeping == 'notyet') {
1478 print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
1479 }
1480 if ($acctCustomerNotConfigured) {
1481 print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
1482 } else {
1483 if ($in_bookkeeping == 'notyet') {
1484 print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
1485 } else {
1486 print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
1487 }
1488 }
1489 print '</div>';
1490
1491 // TODO Avoid using js. We can use a direct link with $param
1492 print '
1493 <script type="text/javascript">
1494 function launch_export() {
1495 $("div.fiche form input[name=\"action\"]").val("exportcsv");
1496 $("div.fiche form input[type=\"submit\"]").click();
1497 $("div.fiche form input[name=\"action\"]").val("");
1498 }
1499 function writebookkeeping() {
1500 console.log("click on writebookkeeping");
1501 $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
1502 $("div.fiche form input[type=\"submit\"]").click();
1503 $("div.fiche form input[name=\"action\"]").val("");
1504 }
1505 </script>';
1506
1507 /*
1508 * Show result array
1509 */
1510 print '<br>';
1511
1512 print '<div class="div-table-responsive">';
1513 print "<table class=\"noborder\" width=\"100%\">";
1514 print "<tr class=\"liste_titre\">";
1515 print "<td>".$langs->trans("Date")."</td>";
1516 print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
1517 print "<td>".$langs->trans("AccountAccounting")."</td>";
1518 print "<td>".$langs->trans("SubledgerAccount")."</td>";
1519 print "<td>".$langs->trans("LabelOperation")."</td>";
1520 print '<td class="center">'.$langs->trans("AccountingDebit")."</td>";
1521 print '<td class="center">'.$langs->trans("AccountingCredit")."</td>";
1522 print "</tr>\n";
1523
1524 $i = 0;
1525
1526 $companystatic = new Client($db);
1527 $invoicestatic = new Facture($db);
1528 $bookkeepingstatic = new BookKeeping($db);
1529
1530 foreach ($tabfac as $key => $val) {
1531 $companystatic->id = $tabcompany[$key]['id'];
1532 $companystatic->name = $tabcompany[$key]['name'];
1533 $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;
1534 $companystatic->code_compta = $tabcompany[$key]['code_compta'];
1535 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
1536 $companystatic->code_client = $tabcompany[$key]['code_client'];
1537 $companystatic->client = 3;
1538
1539 $invoicestatic->id = (int) $key;
1540 $invoicestatic->ref = (string) $val["ref"];
1541 $invoicestatic->type = (int) ($val["type"] ?? 0);
1542 $invoicestatic->close_code = (string) ($val["close_code"] ?? '');
1543
1544 $date = dol_print_date($val["date"], 'day');
1545
1546 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
1547 $replacedinvoice = 0;
1548 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
1549 $replacedinvoice = 1;
1550 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
1551 if ($alreadydispatched) {
1552 $replacedinvoice = 2;
1553 }
1554 }
1555
1556 // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
1557 if ($replacedinvoice == 1) {
1558 print '<tr class="oddeven">';
1559 print "<!-- Replaced invoice -->";
1560 print "<td>".$date."</td>";
1561 print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
1562 // Account
1563 print "<td>";
1564 print $langs->trans("Replaced");
1565 print '</td>';
1566 // Subledger account
1567 print "<td>";
1568 print '</td>';
1569 print "<td>";
1570 print "</td>";
1571 print '<td class="right"></td>';
1572 print '<td class="right"></td>';
1573 print "</tr>";
1574
1575 $i++;
1576 continue;
1577 }
1578 if (isset($errorforinvoice[$key]) && $errorforinvoice[$key] == 'somelinesarenotbound') {
1579 print '<tr class="oddeven">';
1580 print "<!-- Some lines are not bound -->";
1581 print "<td>".$date."</td>";
1582 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1583 // Account
1584 print "<td>";
1585 print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $invoicestatic->ref).'</span>';
1586 print '</td>';
1587 // Subledger account
1588 print "<td>";
1589 print '</td>';
1590 print "<td>";
1591 print "</td>";
1592 print '<td class="right"></td>';
1593 print '<td class="right"></td>';
1594 print "</tr>";
1595
1596 $i++;
1597 }
1598
1599 // Warranty
1600 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && isset($tabwarranty[$key]) && is_array($tabwarranty[$key])) {
1601 foreach ($tabwarranty[$key] as $k => $mt) {
1602 print '<tr class="oddeven">';
1603 print "<!-- Thirdparty warranty -->";
1604 print "<td>" . $date . "</td>";
1605 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1606 // Account
1607 print "<td>";
1608 $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'));
1609 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1610 print '<span class="error">' . $langs->trans("MainAccountForRetainedWarrantyNotDefined") . '</span>';
1611 } else {
1612 print $accountoshow;
1613 }
1614 print '</td>';
1615 // Subledger account
1616 print "<td>";
1617 $accountoshow = length_accounta($k);
1618 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1619 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1620 } else {
1621 print $accountoshow;
1622 }
1623 print '</td>';
1624 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0), $invoicestatic->ref, $langs->trans("RetainedWarranty"), 1) . "</td>";
1625 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1626 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1627 print "</tr>";
1628 }
1629 }
1630
1631 // Third party
1632 foreach ($tabttc[$key] as $k => $mt) {
1633 print '<tr class="oddeven">';
1634 print "<!-- Thirdparty -->";
1635 print "<td>".$date."</td>";
1636 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1637 // Account
1638 print "<td>";
1639 $accountoshow = length_accountg($companystatic->accountancy_code_customer_general);
1640 if (($accountoshow == "") || $accountoshow == "-1" || $accountoshow == 'NotDefined') {
1641 print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
1642 } else {
1643 print $accountoshow;
1644 }
1645 print '</td>';
1646 // Subledger account
1647 print "<td>";
1648 $accountoshow = length_accounta($k);
1649 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1650 print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
1651 } else {
1652 print $accountoshow;
1653 }
1654 print '</td>';
1655 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $langs->trans("SubledgerAccount"), 1) . "</td>";
1656 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1657 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1658 print "</tr>";
1659
1660 $i++;
1661 }
1662
1663 // Product / Service
1664 foreach ($tabht[$key] as $k => $mt) {
1665 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
1666 $accountingaccount = new AccountingAccount($db);
1667 $accountingaccount->fetch(0, $k, true);
1668 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
1669 } else {
1670 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
1671 }
1672
1673 print '<tr class="oddeven">';
1674 print "<!-- Product -->";
1675 print "<td>".$date."</td>";
1676 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1677 // Account
1678 print "<td>";
1679 $accountoshow = length_accountg($k);
1680 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1681 print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
1682 } else {
1683 print $accountoshow;
1684 }
1685 print "</td>";
1686 // Subledger account
1687 print "<td>";
1688 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
1689 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1690 print length_accounta($tabcompany[$key]['code_compta']);
1691 }
1692 } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
1693 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1694 }
1695 print '</td>';
1696 $companystatic->id = $tabcompany[$key]['id'];
1697 $companystatic->name = $tabcompany[$key]['name'];
1698 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $accountingaccount->label, 1) . "</td>";
1699 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1700 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1701 print "</tr>";
1702
1703 $i++;
1704 }
1705
1706 // VAT
1707 $listoftax = array(0, 1, 2);
1708 foreach ($listoftax as $numtax) {
1709 $arrayofvat = $tabtva;
1710 if ($numtax == 1) {
1711 $arrayofvat = $tablocaltax1;
1712 }
1713 if ($numtax == 2) {
1714 $arrayofvat = $tablocaltax2;
1715 }
1716
1717 // $key is id of invoice
1718 foreach ($arrayofvat[$key] as $k => $mt) {
1719 if ($mt) {
1720 print '<tr class="oddeven">';
1721 print "<!-- VAT -->";
1722 print "<td>".$date."</td>";
1723 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1724 // Account
1725 print "<td>";
1726 $accountoshow = length_accountg($k);
1727 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1728 print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("AccountingJournalType2").')</span>';
1729 } else {
1730 print $accountoshow;
1731 }
1732 print "</td>";
1733 // Subledger account
1734 print "<td>";
1735 print '</td>';
1736 // $def_tva is array[invoiceid][accountancy_code_sell_of_vat_rate_found][vatrate]=vatrate
1737 //var_dump($arrayofvat[$key]); //var_dump($key); //var_dump($k);
1738 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
1739 $labelvatrate = $langs->trans("Taxes").' '.$tmpvatrate.' %';
1740 $labelvatrate .= ($numtax ? ' - Localtax '.$numtax : '');
1741 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $labelvatrate, 1) . "</td>";
1742 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1743 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1744 print "</tr>";
1745
1746 $i++;
1747 }
1748 }
1749 }
1750
1751 // Revenue stamp
1752 if (isset($tabrevenuestamp[$key]) && is_array($tabrevenuestamp[$key])) {
1753 foreach ($tabrevenuestamp[$key] as $k => $mt) {
1754 print '<tr class="oddeven">';
1755 print "<!-- Thirdparty revenuestamp -->";
1756 print "<td>" . $date . "</td>";
1757 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1758 // Account
1759 print "<td>";
1760 $accountoshow = length_accountg($k);
1761 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1762 print '<span class="error">' . $langs->trans("MainAccountForRevenueStampSaleNotDefined") . '</span>';
1763 } else {
1764 print $accountoshow;
1765 }
1766 print '</td>';
1767 // Subledger account
1768 print "<td>";
1769 print '</td>';
1770 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $langs->trans("RevenueStamp"), 1) . "</td>";
1771 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1772 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1773 print "</tr>";
1774 }
1775 }
1776
1777 if ($manageCustomerDepositInInvoice) {
1778 // customer discount consumed TTC amount (like Third-party section)
1779 if (isset($tabCustomerDiscountTTC[$key])) {
1780 foreach ($tabCustomerDiscountTTC[$key] as $k => $mt) {
1781 print '<tr class="oddeven">';
1782 print "<!-- Discount TTC -->";
1783 print "<td>" . $date . "</td>";
1784 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1785 // Account
1786 print "<td>";
1787 $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'));
1788 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1789 print '<span class="error">' . $langs->trans("MainAccountForCustomersNotDefined") . '</span>';
1790 } else {
1791 print $accountoshow;
1792 }
1793 print '</td>';
1794 // Subledger account
1795 print "<td>";
1796 $accountoshow = length_accounta($k);
1797 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1798 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1799 } else {
1800 print $accountoshow;
1801 }
1802 print '</td>';
1803 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $langs->trans("SubledgerAccount") . $labelCustomerDiscountExtension, 1) . "</td>";
1804 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1805 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1806 print "</tr>";
1807
1808 $i++;
1809 }
1810 }
1811
1812 // customer discount consumed HT (like Product / Service section)
1813 if (isset($tabCustomerDiscountHT[$key])) {
1814 foreach ($tabCustomerDiscountHT[$key] as $k => $mt) {
1815 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
1816 $accountingaccount = new AccountingAccount($db);
1817 $accountingaccount->fetch(0, $k, true);
1818 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
1819 } else {
1820 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
1821 }
1822
1823 print '<tr class="oddeven">';
1824 print "<!-- Discount HT -->";
1825 print "<td>" . $date . "</td>";
1826 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1827 // Account
1828 print "<td>";
1829 $accountoshow = length_accountg($k);
1830 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1831 print '<span class="error">' . $langs->trans("ProductNotDefined") . '</span>';
1832 } else {
1833 print $accountoshow;
1834 }
1835 print "</td>";
1836 // Subledger account
1837 print "<td>";
1838 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
1839 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1840 print length_accounta($tabcompany[$key]['code_compta']);
1841 }
1842 } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
1843 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1844 }
1845 print '</td>';
1846 $companystatic->id = $tabcompany[$key]['id'];
1847 $companystatic->name = $tabcompany[$key]['name'];
1848 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $accountingaccount->label, 1) . $labelCustomerDiscountExtension . "</td>";
1849 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1850 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1851 print "</tr>";
1852
1853 $i++;
1854 }
1855 }
1856
1857 // customer discount consumed VAT amount (like VAT section)
1858 if (isset($tabCustomerDiscountVAT[$key])) {
1859 foreach ($tabCustomerDiscountVAT[$key] as $k => $mt) {
1860 print '<tr class="oddeven">';
1861 print "<!-- Discount VAT -->";
1862 print "<td>" . $date . "</td>";
1863 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1864 // Account
1865 print "<td>";
1866 $accountoshow = length_accountg($k);
1867 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1868 print '<span class="error">' . $langs->trans("VATAccountNotDefined") . ' (' . $langs->trans("AccountingJournalType2") . ')</span>';
1869 } else {
1870 print $accountoshow;
1871 }
1872 print "</td>";
1873 // Subledger account
1874 print "<td>";
1875 print '</td>';
1876 $tmpvatrate = (empty($def_tva[$key][$k]) ? '' : implode(', ', $def_tva[$key][$k]));
1877 $labelvatrate = $langs->trans("Taxes") . ' ' . $tmpvatrate . ' %';
1878 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $labelvatrate, 1) . $labelCustomerDiscountExtension . "</td>";
1879 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1880 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1881 print "</tr>";
1882
1883 $i++;
1884 }
1885 }
1886 }
1887 }
1888
1889 if (!$i) {
1890 print '<tr class="oddeven"><td colspan="7"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
1891 }
1892
1893 print "</table>";
1894 print '</div>';
1895
1896 // End of page
1897 llxFooter();
1898}
1899
1900$db->close();
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
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
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:620
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:639
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
$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...
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
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.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price2num($amount, $rounding='', $option=0)
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_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.