dolibarr 24.0.0-beta
cashsellsjournal.php
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 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27 */
28
35// Load Dolibarr environment
36require '../../main.inc.php';
37require_once DOL_DOCUMENT_ROOT.'/core/lib/report.lib.php';
38require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
39require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
40require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php';
41require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
42require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
43require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php';
44require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
45
55// Load translation files required by the page
56$langs->loadLangs(array("commercial", "compta", "bills", "other", "accountancy", "errors"));
57
58$id_journal = GETPOSTINT('id_journal');
59$action = GETPOST('action', 'aZ09');
60
61$date_startmonth = GETPOSTINT('date_startmonth');
62$date_startday = GETPOSTINT('date_startday');
63$date_startyear = GETPOSTINT('date_startyear');
64$date_endmonth = GETPOSTINT('date_endmonth');
65$date_endday = GETPOSTINT('date_endday');
66$date_endyear = GETPOSTINT('date_endyear');
67$in_bookkeeping = GETPOST('in_bookkeeping');
68if ($in_bookkeeping == '') {
69 $in_bookkeeping = 'notyet';
70}
71
72$now = dol_now();
73
74$hookmanager->initHooks(array('sellsjournal'));
75$parameters = array();
76
77// Security check
78if (!isModEnabled('accounting')) {
80}
81if ($user->socid > 0) {
83}
84if (!$user->hasRight('accounting', 'bind', 'write')) {
86}
87
88$error = 0;
89
90$tabfac = array();
91$tabht = array();
92$tabtva = array();
93$tabwarranty = array();
94$tabttc = array();
95$tablocaltax1 = array();
96$tablocaltax2 = array();
97
98$cptcli = 'NotDefined';
99
100/*
101 * Actions
102 */
103
104$reshook = $hookmanager->executeHooks('doActions', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
105
106$accountingaccount = new AccountingAccount($db);
107
108// Get information of a journal
109$accountingjournalstatic = new AccountingJournal($db);
110$accountingjournalstatic->fetch($id_journal);
111$journal = $accountingjournalstatic->code;
112$journal_label = $accountingjournalstatic->label;
113
114$date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear);
115$date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear);
116
117$pastmonth = null; // Initialise, could be unset
118$pastmonthyear = null; // Initialise, could be unset
119
120if (empty($date_startmonth)) {
121 // Period by default on transfer
123 $date_start = $dates['date_start'];
124 $pastmonthyear = $dates['pastmonthyear'];
125 $pastmonth = $dates['pastmonth'];
126}
127if (empty($date_endmonth)) {
128 // Period by default on transfer
130 $date_end = $dates['date_end'];
131 $pastmonthyear = $dates['pastmonthyear'];
132 $pastmonth = $dates['pastmonth'];
133}
134if (getDolGlobalString('ACCOUNTANCY_JOURNAL_USE_CURRENT_MONTH')) {
135 $pastmonth += 1;
136}
137
138if (!GETPOSTISSET('date_startmonth') && (empty($date_start) || empty($date_end))) { // We define date_start and date_end, only if we did not submit the form
139 $date_start = dol_get_first_day((int) $pastmonthyear, (int) $pastmonth, false);
140 $date_end = dol_get_last_day((int) $pastmonthyear, (int) $pastmonth, false);
141}
142
143$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,";
144$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,";
145$sql .= " s.rowid as socid, s.nom as name, s.code_client, s.code_fournisseur,";
146if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
147 $sql .= " spe.accountancy_code_customer_general,";
148 $sql .= " spe.accountancy_code_customer as code_compta_client,";
149 $sql .= " spe.accountancy_code_supplier_general,";
150 $sql .= " spe.accountancy_code_supplier as code_compta_fournisseur,";
151} else {
152 $sql .= " s.accountancy_code_customer_general,";
153 $sql .= " s.code_compta as code_compta_client,";
154 $sql .= " s.accountancy_code_supplier_general,";
155 $sql .= " s.code_compta_fournisseur,";
156}
157$sql .= " p.rowid as pid, p.ref as pref, aa.rowid as fk_compte, aa.account_number as compte, aa.label as label_compte,";
158if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
159 $sql .= " ppe.accountancy_code_sell";
160} else {
161 $sql .= " p.accountancy_code_sell";
162}
163$parameters = array();
164$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
165$sql .= $hookmanager->resPrint;
166$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
167$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product";
168if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
169 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
170}
171$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
172$sql .= " JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
173$sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc";
174if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
175 $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
176}
177$parameters = array();
178$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters); // Note that $action and $object may have been modified by hook
179$sql .= $hookmanager->resPrint;
180$sql .= " WHERE fd.fk_code_ventilation > 0";
181$sql .= " AND f.entity IN (".getEntity('invoice', 0).')'; // We don't share object for accountancy, we use source object sharing
182$sql .= " AND f.fk_statut > 0";
183if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) { // Non common setup
184 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
185} else {
186 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
187}
188$sql .= " AND fd.product_type IN (0,1)";
189if ($date_start && $date_end) {
190 $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'";
191}
192if (getDolGlobalInt('ACCOUNTING_DISSOCIATE_CASH_SALES')) {
193 $sql .= " AND f.module_source = 'takepos'";
194}
195// Define begin binding date
196if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
197 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
198}
199// Already in bookkeeping or not
200if ($in_bookkeeping == 'already') {
201 $sql .= " AND f.rowid IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
202 // $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
203}
204if ($in_bookkeeping == 'notyet') {
205 $sql .= " AND f.rowid NOT IN (SELECT fk_doc FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='customer_invoice')";
206 // $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
207}
208$parameters = array();
209$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
210$sql .= $hookmanager->resPrint;
211$sql .= " ORDER BY f.datef, f.ref";
212//print $sql;
213
214dol_syslog('accountancy/journal/sellsjournal.php', LOG_DEBUG);
215$tabfac = array();
216$tabht = array();
217$tabtva = array();
218$def_tva = array();
219$tabwarranty = array();
220$tabrevenuestamp = array();
221$tabttc = array();
222$tablocaltax1 = array();
223$tablocaltax2 = array();
224$tabcompany = array();
225$vatdata_cache = array();
226
227// Variables
228$cptcli = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER', 'NotDefined');
229$cpttva = getDolGlobalString('ACCOUNTING_VAT_SOLD_ACCOUNT', 'NotDefined');
230$cptlocaltax1 = getDolGlobalString('ACCOUNTING_LT1_SOLD_ACCOUNT', 'NotDefined');
231$cptlocaltax2 = getDolGlobalString('ACCOUNTING_LT2_SOLD_ACCOUNT', 'NotDefined');
232
233$result = $db->query($sql);
234if ($result) {
235 $num = $db->num_rows($result);
236
237 $i = 0;
238 while ($i < $num) {
239 $obj = $db->fetch_object($result);
240
241 // Controls
242 $accountancy_code_customer_general = (!empty($obj->accountancy_code_customer_general) && $obj->accountancy_code_customer_general != '-1') ? $obj->accountancy_code_customer_general : $cptcli;
243 $compta_soc = (!empty($obj->code_compta_client)) ? $obj->code_compta_client : $cptcli;
244
245 $compta_prod = $obj->compte;
246 if (empty($compta_prod)) {
247 if ($obj->product_type == 0) {
248 $compta_prod = getDolGlobalString('ACCOUNTING_PRODUCT_SOLD_ACCOUNT', 'NotDefined');
249 } else {
250 $compta_prod = getDolGlobalString('ACCOUNTING_SERVICE_SOLD_ACCOUNT', 'NotDefined');
251 }
252 }
253
254 // $compta_revenuestamp = getDolGlobalString('ACCOUNTING_REVENUESTAMP_SOLD_ACCOUNT', 'NotDefined');
255
256 $tax_id = $obj->tva_tx . ($obj->vat_src_code ? ' (' . $obj->vat_src_code . ')' : '');
257 if (array_key_exists($tax_id, $vatdata_cache)) {
258 $vatdata = $vatdata_cache[$tax_id];
259 } else {
260 if (getDolGlobalString('SERVICE_ARE_ECOMMERCE_200238EC')) {
261 $buyer = new Societe($db);
262 $buyer->fetch($obj->socid);
263 } else {
264 $buyer = null; // We don't need the buyer in this case
265 }
266 $seller = $mysoc;
267 $vatdata = getTaxesFromId($tax_id, $buyer, $seller, 0);
268 $vatdata_cache[$tax_id] = $vatdata;
269 }
270 $compta_tva = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cpttva);
271 $compta_localtax1 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cptlocaltax1);
272 $compta_localtax2 = (!empty($vatdata['accountancy_code_sell']) ? $vatdata['accountancy_code_sell'] : $cptlocaltax2);
273
274 // Define the array to store the detail of each vat rate and code for lines
275 if (price2num($obj->tva_tx) || !empty($obj->vat_src_code)) {
276 $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.')' : ''));
277 if ($obj->localtax1_tx > 0.0) {
278 $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.')' : ''));
279 }
280 if ($obj->localtax2_tx > 0.0) {
281 $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.')' : ''));
282 }
283 }
284
285 // Create a compensation rate for situation invoice.
286 $situation_ratio = 1;
287 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
288 if ($obj->situation_cycle_ref) {
289 // Avoid divide by 0
290 if ($obj->situation_percent == 0) {
291 $situation_ratio = 0;
292 } else {
293 $line = new FactureLigne($db);
294 $line->fetch($obj->fdid);
295
296 // Situation invoices handling
297 $prev_progress = $line->get_prev_progress($obj->rowid);
298
299 $situation_ratio = ($obj->situation_percent - $prev_progress) / $obj->situation_percent;
300 }
301 }
302 }
303
304 $revenuestamp = (float) price2num($obj->revenuestamp, 'MT');
305
306 // Invoice lines
307 $tabfac[$obj->rowid]["date"] = $db->jdate($obj->df);
308 $tabfac[$obj->rowid]["datereg"] = $db->jdate($obj->dlr);
309 $tabfac[$obj->rowid]["ref"] = $obj->ref;
310 $tabfac[$obj->rowid]["type"] = $obj->type;
311 $tabfac[$obj->rowid]["description"] = $obj->label_compte;
312 $tabfac[$obj->rowid]["close_code"] = $obj->close_code; // close_code = 'replaced' for replacement invoices (not used in most european countries)
313 $tabfac[$obj->rowid]["revenuestamp"] = $revenuestamp;
314 //$tabfac[$obj->rowid]["fk_facturedet"] = $obj->fdid;
315
316 // Avoid warnings
317 if (!isset($tabttc[$obj->rowid][$compta_soc])) {
318 $tabttc[$obj->rowid][$compta_soc] = 0;
319 }
320 if (!isset($tabht[$obj->rowid][$compta_prod])) {
321 $tabht[$obj->rowid][$compta_prod] = 0;
322 }
323 if (!isset($tabtva[$obj->rowid][$compta_tva])) {
324 $tabtva[$obj->rowid][$compta_tva] = 0;
325 }
326 if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) {
327 $tablocaltax1[$obj->rowid][$compta_localtax1] = 0;
328 }
329 if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) {
330 $tablocaltax2[$obj->rowid][$compta_localtax2] = 0;
331 }
332
333 // Compensation of data for invoice situation by using $situation_ratio. This works (nearly) for invoice that was not correctly recorded
334 // but it may introduces an error for situation invoices that were correctly saved. There is still rounding problem that differs between
335 // real data we should have stored and result obtained with a compensation.
336 // It also seems that credit notes on situation invoices are correctly saved (but it depends on the version used in fact).
337 // For credit notes, we hope to have situation_ratio = 1 so the compensation has no effect to avoid introducing troubles with credit notes.
338 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
339 $total_ttc = $obj->total_ttc * $situation_ratio;
340 } else {
341 $total_ttc = $obj->total_ttc;
342 }
343
344 // Move a part of the retained warrenty into the account of warranty
345 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && $obj->retained_warranty > 0 && (!getDolGlobalString('INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION') || !empty($obj->situation_final))) {
346 $retained_warranty = (float) price2num($total_ttc * $obj->retained_warranty / 100, 'MT'); // Calculate the amount of warrenty for this line (using the percent value)
347 $tabwarranty[$obj->rowid][$compta_soc] += $retained_warranty;
348 $total_ttc -= $retained_warranty;
349 }
350
351 $tabttc[$obj->rowid][$compta_soc] += $total_ttc;
352 $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio;
353 $tva_npr = ((($obj->info_bits & 1) == 1) ? 1 : 0);
354 if (!$tva_npr) { // We ignore line if VAT is a NPR
355 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 2) {
356 $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva;
357 $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1;
358 $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2;
359 } else {
360 $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio;
361 $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1 * $situation_ratio;
362 $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2 * $situation_ratio;
363 }
364 }
365
366 $compta_revenuestamp = 'NotDefined';
367 if (!empty($revenuestamp)) {
368 $sqlrevenuestamp = "SELECT accountancy_code_sell FROM ".MAIN_DB_PREFIX."c_revenuestamp";
369 $sqlrevenuestamp .= " WHERE fk_pays = ".((int) $mysoc->country_id);
370 $sqlrevenuestamp .= " AND taux = ".((float) $revenuestamp);
371 $sqlrevenuestamp .= " AND active = 1";
372 $resqlrevenuestamp = $db->query($sqlrevenuestamp);
373
374 if ($resqlrevenuestamp) {
375 $num_rows_revenuestamp = $db->num_rows($resqlrevenuestamp);
376 if ($num_rows_revenuestamp > 1) {
377 dol_print_error($db, 'Failed 2 or more lines for the revenue stamp of your country. Check the dictionary of revenue stamp.');
378 } else {
379 $objrevenuestamp = $db->fetch_object($resqlrevenuestamp);
380 if ($objrevenuestamp) {
381 $compta_revenuestamp = $objrevenuestamp->accountancy_code_sell;
382 }
383 }
384 }
385 }
386
387 if (empty($tabrevenuestamp[$obj->rowid][$compta_revenuestamp]) && !empty($revenuestamp)) {
388 // The revenue stamp was never seen for this invoice id=$obj->rowid
389 $tabttc[$obj->rowid][$compta_soc] += $obj->revenuestamp;
390 $tabrevenuestamp[$obj->rowid][$compta_revenuestamp] = $obj->revenuestamp;
391 }
392
393 $tabcompany[$obj->rowid] = array(
394 'id' => $obj->socid,
395 'name' => $obj->name,
396 'code_client' => $obj->code_client,
397 'accountancy_code_customer_general' => $accountancy_code_customer_general,
398 'code_compta' => $compta_soc
399 );
400
401 // After the line is processed
402 $parameters = array(
403 'obj' => $obj,
404 'tabfac' => &$tabfac,
405 'tabht' => &$tabht,
406 'tabtva' => &$tabtva,
407 'def_tva' => &$def_tva,
408 'tabwarranty' => &$tabwarranty,
409 'tabrevenuestamp' => &$tabrevenuestamp,
410 'tabttc' => &$tabttc,
411 'tablocaltax1' => &$tablocaltax1,
412 'tablocaltax2' => &$tablocaltax2,
413 'tabcompany' => &$tabcompany,
414 'vatdata_cache' => &$vatdata_cache,
415 );
416 $reshook = $hookmanager->executeHooks('processingJournalData', $parameters); // Note that $action and $object may have been modified by hook
417
418 $i++;
419
420 // Check for too many lines.
421 if ($i > getDolGlobalInt('ACCOUNTANCY_MAX_TOO_MANY_LINES_TO_PROCESS', 10000)) {
422 $error++;
423 setEventMessages("ErrorTooManyLinesToProcessPleaseUseAMoreSelectiveFilter", null, 'errors');
424 break;
425 }
426 }
427
428 // After the loop on each line
429 $parameters = array(
430 'tabfac' => &$tabfac,
431 'tabht' => &$tabht,
432 'tabtva' => &$tabtva,
433 'def_tva' => &$def_tva,
434 'tabwarranty' => &$tabwarranty,
435 'tabrevenuestamp' => &$tabrevenuestamp,
436 'tabttc' => &$tabttc,
437 'tablocaltax1' => &$tablocaltax1,
438 'tablocaltax2' => &$tablocaltax2,
439 'tabcompany' => &$tabcompany,
440 'vatdata_cache' => &$vatdata_cache,
441 );
442 $reshook = $hookmanager->executeHooks('processedJournalData', $parameters); // Note that $action and $object may have been modified by hook
443} else {
445}
446
447
448$errorforinvoice = array();
449
450/*
451// Old way, 1 query for each invoice
452// Loop on all invoices to detect lines without binded code (fk_code_ventilation <= 0)
453foreach ($tabfac as $key => $val) { // Loop on each invoice
454 $sql = "SELECT COUNT(fd.rowid) as nb";
455 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
456 $sql .= " WHERE fd.product_type <= 2 AND fd.fk_code_ventilation <= 0";
457 $sql .= " AND fd.total_ttc <> 0 AND fk_facture = ".((int) $key);
458 $resql = $db->query($sql);
459 if ($resql) {
460 $obj = $db->fetch_object($resql);
461 if ($obj->nb > 0) {
462 $errorforinvoice[$key] = 'somelinesarenotbound';
463 }
464 } else {
465 dol_print_error($db);
466 }
467}
468*/
469// New way, single query, load all unbound lines
470if (!empty($tabfac)) {
471 $sql = "
472 SELECT
473 fk_facture,
474 COUNT(fd.rowid) as nb
475 FROM
476 ".MAIN_DB_PREFIX."facturedet as fd
477 WHERE
478 fd.product_type <= 2
479 AND fd.fk_code_ventilation <= 0
480 AND fd.total_ttc <> 0
481 AND fk_facture IN (".$db->sanitize(implode(",", array_keys($tabfac))).")
482 GROUP BY fk_facture
483 ";
484 $resql = $db->query($sql);
485 if ($resql) {
486 $num = $db->num_rows($resql);
487 $i = 0;
488 while ($i < $num) {
489 $obj = $db->fetch_object($resql);
490 if ($obj->nb > 0) {
491 $errorforinvoice[$obj->fk_facture] = 'somelinesarenotbound';
492 }
493 $i++;
494 }
495 }
496}
497//var_dump($errorforinvoice);exit;
498
499// Bookkeeping Write
500if ($action == 'writebookkeeping' && !$error && $user->hasRight('accounting', 'bind', 'write')) {
501 $now = dol_now();
502 $error = 0;
503
504 $companystatic = new Societe($db);
505 $invoicestatic = new Facture($db);
506 $bookkeepingstatic = new BookKeeping($db);
507
508 $accountingaccountcustomer = new AccountingAccount($db);
509 $accountingaccountcustomer->fetch(0, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), true);
510
511 $accountingaccountcustomerwarranty = new AccountingAccount($db);
512 $accountingaccountcustomerwarranty->fetch(0, getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'), true);
513
514 foreach ($tabfac as $key => $val) { // Loop on each invoice
515 $errorforline = 0;
516
517 $totalcredit = 0;
518 $totaldebit = 0;
519
520 $db->begin(); // We accept transaction into loop, so if we hang, we can continue transfer from the last error
521
522 $companystatic->id = $tabcompany[$key]['id'];
523 $companystatic->name = $tabcompany[$key]['name'];
524 $companystatic->accountancy_code_customer_general = $tabcompany[$key]['accountancy_code_customer_general'];
525 $companystatic->code_compta = $tabcompany[$key]['code_compta'];
526 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
527 $companystatic->code_client = $tabcompany[$key]['code_client'];
528 $companystatic->client = 3;
529
530 $invoicestatic->id = (int) $key;
531 $invoicestatic->ref = (string) $val["ref"];
532 $invoicestatic->type = $val["type"];
533 $invoicestatic->close_code = $val["close_code"];
534
535 $date = dol_print_date($val["date"], 'day');
536
537 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
538 $replacedinvoice = 0;
539 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
540 $replacedinvoice = 1;
541 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
542 if ($alreadydispatched) {
543 $replacedinvoice = 2;
544 }
545 }
546
547 // 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)
548 if ($replacedinvoice == 1) {
549 $db->rollback();
550 continue;
551 }
552
553 // Error if some lines are not binded/ready to be journalized
554 if (isset($errorforinvoice[$key]) && $errorforinvoice[$key] == 'somelinesarenotbound') {
555 $error++;
556 $errorforline++;
557 setEventMessages($langs->trans('ErrorInvoiceContainsLinesNotYetBounded', $val['ref']), null, 'errors');
558 }
559
560 // Warranty
561 if (!$errorforline && getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) {
562 if (isset($tabwarranty[$key]) && is_array($tabwarranty[$key])) {
563 foreach ($tabwarranty[$key] as $k => $mt) {
564 $bookkeeping = new BookKeeping($db);
565 $bookkeeping->doc_date = $val["date"];
566 $bookkeeping->date_lim_reglement = $val["datereg"];
567 $bookkeeping->doc_ref = $val["ref"];
568 $bookkeeping->date_creation = $now;
569 $bookkeeping->doc_type = 'customer_invoice';
570 $bookkeeping->fk_doc = (int) $key;
571 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are the source of this record to add
572 $bookkeeping->thirdparty_code = $companystatic->code_client;
573
574 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
575 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
576
577 $bookkeeping->numero_compte = getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY');
578 $bookkeeping->label_compte = $accountingaccountcustomerwarranty->label;
579
580 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RetainedWarranty"));
581 $bookkeeping->montant = $mt;
582 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
583 $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
584 $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
585 $bookkeeping->code_journal = $journal;
586 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
587 $bookkeeping->fk_user_author = $user->id;
588 $bookkeeping->entity = $conf->entity;
589
590 $totaldebit += $bookkeeping->debit;
591 $totalcredit += $bookkeeping->credit;
592
593 $result = $bookkeeping->create($user);
594 if ($result < 0) {
595 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
596 $error++;
597 $errorforline++;
598 $errorforinvoice[$key] = 'alreadyjournalized';
599 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
600 } else {
601 $error++;
602 $errorforline++;
603 $errorforinvoice[$key] = 'other';
604 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
605 }
606 }
607 }
608 }
609 }
610
611 // Thirdparty
612 if (!$errorforline) {
613 foreach ($tabttc[$key] as $k => $mt) {
614 $bookkeeping = new BookKeeping($db);
615 $bookkeeping->doc_date = $val["date"];
616 $bookkeeping->date_lim_reglement = $val["datereg"];
617 $bookkeeping->doc_ref = $val["ref"];
618 $bookkeeping->date_creation = $now;
619 $bookkeeping->doc_type = 'customer_invoice';
620 $bookkeeping->fk_doc = (int) $key;
621 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
622 $bookkeeping->thirdparty_code = $companystatic->code_client;
623
624 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
625 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
626
627 $bookkeeping->numero_compte = (!empty($tabcompany[$key]['accountancy_code_customer_general']) && $tabcompany[$key]['accountancy_code_customer_general'] != '-1') ? $tabcompany[$key]['accountancy_code_customer_general'] : $cptcli;
628 $bookkeeping->label_compte = $accountingaccountcustomer->label;
629
630 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("SubledgerAccount"));
631 $bookkeeping->montant = $mt;
632 $bookkeeping->sens = ($mt >= 0) ? 'D' : 'C';
633 $bookkeeping->debit = ($mt >= 0) ? $mt : 0;
634 $bookkeeping->credit = ($mt < 0) ? -$mt : 0;
635 $bookkeeping->code_journal = $journal;
636 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
637 $bookkeeping->fk_user_author = $user->id;
638 $bookkeeping->entity = $conf->entity;
639
640 $totaldebit += $bookkeeping->debit;
641 $totalcredit += $bookkeeping->credit;
642
643 $result = $bookkeeping->create($user);
644 if ($result < 0) {
645 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
646 $error++;
647 $errorforline++;
648 $errorforinvoice[$key] = 'alreadyjournalized';
649 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
650 } else {
651 $error++;
652 $errorforline++;
653 $errorforinvoice[$key] = 'other';
654 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
655 }
656 } else {
657 if (getDolGlobalInt('ACCOUNTING_ENABLE_LETTERING') && getDolGlobalInt('ACCOUNTING_ENABLE_AUTOLETTERING')) {
658 require_once DOL_DOCUMENT_ROOT . '/accountancy/class/lettering.class.php';
659 $lettering_static = new Lettering($db);
660
661 $nb_lettering = $lettering_static->bookkeepingLettering(array($bookkeeping->id));
662 }
663 }
664 }
665 }
666
667 // Product / Service
668 if (!$errorforline) {
669 foreach ($tabht[$key] as $k => $mt) {
670 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
671 $accountingaccount = new AccountingAccount($db);
672 $accountingaccount->fetch(0, $k, true);
673 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
674 } else {
675 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
676 }
677
678 $label_account = $accountingaccount->label;
679
680 // get compte id and label
681 if ($accountingaccount->id > 0) {
682 $bookkeeping = new BookKeeping($db);
683 $bookkeeping->doc_date = $val["date"];
684 $bookkeeping->date_lim_reglement = $val["datereg"];
685 $bookkeeping->doc_ref = $val["ref"];
686 $bookkeeping->date_creation = $now;
687 $bookkeeping->doc_type = 'customer_invoice';
688 $bookkeeping->fk_doc = (int) $key;
689 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
690 $bookkeeping->thirdparty_code = $companystatic->code_client;
691
692 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
693 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
694 $bookkeeping->subledger_account = $tabcompany[$key]['code_compta'];
695 $bookkeeping->subledger_label = $tabcompany[$key]['name'];
696 } else {
697 $bookkeeping->subledger_account = '';
698 $bookkeeping->subledger_label = '';
699 }
700 } else {
701 $bookkeeping->subledger_account = '';
702 $bookkeeping->subledger_label = '';
703 }
704
705 $bookkeeping->numero_compte = $k;
706 $bookkeeping->label_compte = $label_account;
707
708 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $label_account);
709 $bookkeeping->montant = $mt;
710 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
711 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
712 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
713 $bookkeeping->code_journal = $journal;
714 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
715 $bookkeeping->fk_user_author = $user->id;
716 $bookkeeping->entity = $conf->entity;
717
718 $totaldebit += $bookkeeping->debit;
719 $totalcredit += $bookkeeping->credit;
720
721 $result = $bookkeeping->create($user);
722 if ($result < 0) {
723 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
724 $error++;
725 $errorforline++;
726 $errorforinvoice[$key] = 'alreadyjournalized';
727 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
728 } else {
729 $error++;
730 $errorforline++;
731 $errorforinvoice[$key] = 'other';
732 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
733 }
734 }
735 }
736 }
737 }
738
739 // VAT
740 if (!$errorforline) {
741 $listoftax = array(0, 1, 2);
742 foreach ($listoftax as $numtax) {
743 $arrayofvat = $tabtva;
744 if ($numtax == 1) {
745 $arrayofvat = $tablocaltax1;
746 }
747 if ($numtax == 2) {
748 $arrayofvat = $tablocaltax2;
749 }
750
751 foreach ($arrayofvat[$key] as $k => $mt) {
752 if ($mt) {
753 if (empty($conf->cache['accountingaccountincurrententity_vat'][$k])) {
754 $accountingaccount = new AccountingAccount($db);
755 $accountingaccount->fetch(0, $k, true);
756 $conf->cache['accountingaccountincurrententity_vat'][$k] = $accountingaccount;
757 } else {
758 $accountingaccount = $conf->cache['accountingaccountincurrententity_vat'][$k];
759 }
760
761 $label_account = $accountingaccount->label;
762
763 $bookkeeping = new BookKeeping($db);
764 $bookkeeping->doc_date = $val["date"];
765 $bookkeeping->date_lim_reglement = $val["datereg"];
766 $bookkeeping->doc_ref = $val["ref"];
767 $bookkeeping->date_creation = $now;
768 $bookkeeping->doc_type = 'customer_invoice';
769 $bookkeeping->fk_doc = (int) $key;
770 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
771 $bookkeeping->thirdparty_code = $companystatic->code_client;
772
773 $bookkeeping->subledger_account = '';
774 $bookkeeping->subledger_label = '';
775
776 $bookkeeping->numero_compte = $k;
777 $bookkeeping->label_compte = $label_account;
778
779
780 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
781 $labelvataccount = $langs->trans("Taxes").' '.$tmpvatrate.' %';
782 $labelvataccount .= ($numtax ? ' - Localtax '.$numtax : '');
783 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $labelvataccount);
784
785 $bookkeeping->montant = $mt;
786 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
787 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
788 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
789 $bookkeeping->code_journal = $journal;
790 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
791 $bookkeeping->fk_user_author = $user->id;
792 $bookkeeping->entity = $conf->entity;
793
794 $totaldebit += $bookkeeping->debit;
795 $totalcredit += $bookkeeping->credit;
796
797 $result = $bookkeeping->create($user);
798 if ($result < 0) {
799 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
800 $error++;
801 $errorforline++;
802 $errorforinvoice[$key] = 'alreadyjournalized';
803 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
804 } else {
805 $error++;
806 $errorforline++;
807 $errorforinvoice[$key] = 'other';
808 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
809 }
810 }
811 }
812 }
813 }
814 }
815
816 // Revenue stamp
817 if (!$errorforline) {
818 if (isset($tabrevenuestamp[$key]) && is_array($tabrevenuestamp[$key])) {
819 foreach ($tabrevenuestamp[$key] as $k => $mt) {
820 if ($mt) {
821 if (empty($conf->cache['accountingaccountincurrententity_rs'][$k])) {
822 $accountingaccount = new AccountingAccount($db);
823 $accountingaccount->fetch(0, $k, true);
824 $conf->cache['accountingaccountincurrententity_rs'][$k] = $accountingaccount;
825 } else {
826 $accountingaccount = $conf->cache['accountingaccountincurrententity_rs'][$k];
827 }
828
829 $label_account = $accountingaccount->label;
830
831 $bookkeeping = new BookKeeping($db);
832 $bookkeeping->doc_date = $val["date"];
833 $bookkeeping->date_lim_reglement = $val["datereg"];
834 $bookkeeping->doc_ref = $val["ref"];
835 $bookkeeping->date_creation = $now;
836 $bookkeeping->doc_type = 'customer_invoice';
837 $bookkeeping->fk_doc = (int) $key;
838 $bookkeeping->fk_docdet = 0; // Useless, can be several lines that are source of this record to add
839 $bookkeeping->thirdparty_code = $companystatic->code_client;
840
841 $bookkeeping->subledger_account = '';
842 $bookkeeping->subledger_label = '';
843
844 $bookkeeping->numero_compte = $k;
845 $bookkeeping->label_compte = $label_account;
846
847 $bookkeeping->label_operation = $bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RevenueStamp"));
848 $bookkeeping->montant = $mt;
849 $bookkeeping->sens = ($mt < 0) ? 'D' : 'C';
850 $bookkeeping->debit = ($mt < 0) ? -$mt : 0;
851 $bookkeeping->credit = ($mt >= 0) ? $mt : 0;
852 $bookkeeping->code_journal = $journal;
853 $bookkeeping->journal_label = $langs->transnoentities($journal_label);
854 $bookkeeping->fk_user_author = $user->id;
855 $bookkeeping->entity = $conf->entity;
856
857 $totaldebit += $bookkeeping->debit;
858 $totalcredit += $bookkeeping->credit;
859
860 $result = $bookkeeping->create($user);
861 if ($result < 0) {
862 if ($bookkeeping->error == 'BookkeepingRecordAlreadyExists') { // Already exists
863 $error++;
864 $errorforline++;
865 $errorforinvoice[$key] = 'alreadyjournalized';
866 //setEventMessages('Transaction for ('.$bookkeeping->doc_type.', '.$bookkeeping->fk_doc.', '.$bookkeeping->fk_docdet.') were already recorded', null, 'warnings');
867 } else {
868 $error++;
869 $errorforline++;
870 $errorforinvoice[$key] = 'other';
871 setEventMessages($bookkeeping->error, $bookkeeping->errors, 'errors');
872 }
873 }
874 }
875 }
876 }
877 }
878
879 // Protection against a bug on lines before
880 if (!$errorforline && (price2num($totaldebit, 'MT') != price2num($totalcredit, 'MT'))) {
881 $error++;
882 $errorforline++;
883 $errorforinvoice[$key] = 'amountsnotbalanced';
884 setEventMessages('We Tried to insert a non balanced transaction in book for '.$invoicestatic->ref.'. Canceled. Surely a bug.', null, 'errors');
885 }
886
887 if (!$errorforline) {
888 $db->commit();
889 } else {
890 $db->rollback();
891
892 if ($error >= 10) {
893 setEventMessages($langs->trans("ErrorTooManyErrorsProcessStopped"), null, 'errors');
894 break; // Break in the foreach
895 }
896 }
897 }
898
899 $tabpay = $tabfac;
900
901 if (empty($error) && count($tabpay) > 0) {
902 setEventMessages($langs->trans("GeneralLedgerIsWritten"), null, 'mesgs');
903 } elseif (count($tabpay) == $error) {
904 setEventMessages($langs->trans("NoNewRecordSaved"), null, 'warnings');
905 } else {
906 setEventMessages($langs->trans("GeneralLedgerSomeRecordWasNotRecorded"), null, 'warnings');
907 }
908
909 $action = '';
910
911 // Must reload data, so we make a redirect
912 if (count($tabpay) != $error) {
913 $param = 'id_journal='.$id_journal;
914 $param .= '&date_startday='.$date_startday;
915 $param .= '&date_startmonth='.$date_startmonth;
916 $param .= '&date_startyear='.$date_startyear;
917 $param .= '&date_endday='.$date_endday;
918 $param .= '&date_endmonth='.$date_endmonth;
919 $param .= '&date_endyear='.$date_endyear;
920 $param .= '&in_bookkeeping='.$in_bookkeeping;
921 header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
922 exit;
923 }
924}
925
926
927
928/*
929 * View
930 */
931
932$form = new Form($db);
933
934// Export
935if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 !
936 // Note that to have the button to get this feature enabled, you must enable ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL
937 $sep = getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV');
938
939 $filename = 'journal';
940 $type_export = 'journal';
941 include DOL_DOCUMENT_ROOT.'/accountancy/tpl/export_journal.tpl.php';
942
943 $companystatic = new Client($db);
944 $invoicestatic = new Facture($db);
945 $bookkeepingstatic = new BookKeeping($db);
946
947 foreach ($tabfac as $key => $val) {
948 $companystatic->id = $tabcompany[$key]['id'];
949 $companystatic->name = $tabcompany[$key]['name'];
950 $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;
951 $companystatic->code_compta = $tabcompany[$key]['code_compta']; // deprecated
952 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
953 $companystatic->code_client = $tabcompany[$key]['code_client'];
954 $companystatic->client = 3;
955
956 $invoicestatic->id = (int) $key;
957 $invoicestatic->ref = (string) $val["ref"];
958 $invoicestatic->type = $val["type"];
959 $invoicestatic->close_code = $val["close_code"];
960
961 $date = dol_print_date($val["date"], 'day');
962
963 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
964 $replacedinvoice = 0;
965 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
966 $replacedinvoice = 1;
967 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
968 if ($alreadydispatched) {
969 $replacedinvoice = 2;
970 }
971 }
972
973 // 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)
974 if ($replacedinvoice == 1) {
975 continue;
976 }
977
978 // Warranty
979 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && isset($tabwarranty[$key])) {
980 foreach ($tabwarranty[$key] as $k => $mt) {
981 //if ($mt) {
982 print '"'.$key.'"'.$sep;
983 print '"'.$date.'"'.$sep;
984 print '"'.$val["ref"].'"'.$sep;
985 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
986 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
987 print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY')).'"'.$sep;
988 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
989 print '"'.$langs->trans("ThirdParty").'"'.$sep;
990 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RetainedWarranty"))).'"'.$sep;
991 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
992 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
993 print '"'.$journal.'"';
994 print "\n";
995 //}
996 }
997 }
998
999 // Third party
1000 foreach ($tabttc[$key] as $k => $mt) {
1001 //if ($mt) {
1002 print '"'.$key.'"'.$sep;
1003 print '"'.$date.'"'.$sep;
1004 print '"'.$val["ref"].'"'.$sep;
1005 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1006 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1007 print '"'.length_accountg($companystatic->accountancy_code_customer_general).'"'.$sep;
1008 print '"'.length_accounta(html_entity_decode($k)).'"'.$sep;
1009 print '"'.$langs->trans("ThirdParty").'"'.$sep;
1010 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("ThirdParty"))).'"'.$sep;
1011 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1012 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1013 print '"'.$journal.'"';
1014 print "\n";
1015 //}
1016 }
1017
1018 // Product / Service
1019 foreach ($tabht[$key] as $k => $mt) {
1020 $accountingaccount = new AccountingAccount($db);
1021 $accountingaccount->fetch(0, $k, true);
1022 //if ($mt) {
1023 print '"'.$key.'"'.$sep;
1024 print '"'.$date.'"'.$sep;
1025 print '"'.$val["ref"].'"'.$sep;
1026 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1027 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1028 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1029 print '""'.$sep;
1030 print '"'.csvClean(dol_trunc($accountingaccount->label, 32)).'"'.$sep;
1031 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $accountingaccount->label)).'"'.$sep;
1032 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1033 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1034 print '"'.$journal.'"';
1035 print "\n";
1036 //}
1037 }
1038
1039 // VAT
1040 $listoftax = array(0, 1, 2);
1041 foreach ($listoftax as $numtax) {
1042 $arrayofvat = $tabtva;
1043 if ($numtax == 1) {
1044 $arrayofvat = $tablocaltax1;
1045 }
1046 if ($numtax == 2) {
1047 $arrayofvat = $tablocaltax2;
1048 }
1049
1050 foreach ($arrayofvat[$key] as $k => $mt) {
1051 if ($mt) {
1052 print '"'.$key.'"'.$sep;
1053 print '"'.$date.'"'.$sep;
1054 print '"'.$val["ref"].'"'.$sep;
1055 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1056 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1057 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1058 print '""'.$sep;
1059 print '"'.$langs->trans("VAT").' - '.implode(', ', $def_tva[$key][$k]).' %"'.$sep;
1060 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("VAT").implode($def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : ''))).'"'.$sep;
1061 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1062 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1063 print '"'.$journal.'"';
1064 print "\n";
1065 }
1066 }
1067 }
1068
1069 // Revenue stamp
1070 if (isset($tabrevenuestamp[$key])) {
1071 foreach ($tabrevenuestamp[$key] as $k => $mt) {
1072 //if ($mt) {
1073 print '"'.$key.'"'.$sep;
1074 print '"'.$date.'"'.$sep;
1075 print '"'.$val["ref"].'"'.$sep;
1076 print '"'.csvClean(dol_trunc($companystatic->name, 32)).'"'.$sep;
1077 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1078 print '"'.length_accountg(html_entity_decode($k)).'"'.$sep;
1079 print '""'.$sep;
1080 print '"'.$langs->trans("RevenueStamp").'"'.$sep;
1081 print '"'.csvClean($bookkeepingstatic->accountingLabelForOperation($companystatic->name, $invoicestatic->ref, $langs->trans("RevenueStamp"))).'"'.$sep;
1082 print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep;
1083 print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep;
1084 print '"'.$journal.'"';
1085 print "\n";
1086 //}
1087 }
1088 }
1089 }
1090}
1091
1092
1093
1094if (empty($action) || $action == 'view') {
1095 $title = $langs->trans("GenerationOfAccountingEntries").' - '.$accountingjournalstatic->getNomUrl(0, 2, 1, '', 1);
1096 $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;';
1097 llxHeader('', dol_string_nohtmltag($title), $help_url, '', 0, 0, '', '', '', 'mod-accountancy accountancy-generation page-sellsjournal');
1098
1099 $nom = $title;
1100 $nomlink = '';
1101 $periodlink = '';
1102 $exportlink = '';
1103 $builddate = dol_now();
1104 $description = $langs->trans("DescJournalOnlyBindedVisible").'<br>';
1105 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
1106 $description .= $langs->trans("DepositsAreNotIncluded");
1107 } else {
1108 $description .= $langs->trans("DepositsAreIncluded");
1109 }
1110
1111 $listofchoices = array('notyet' => $langs->trans("NotYetInGeneralLedger"), 'already' => $langs->trans("AlreadyInGeneralLedger"));
1112 $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);
1113 $period .= ' - '.$langs->trans("JournalizationInLedgerStatus").' '.$form->selectarray('in_bookkeeping', $listofchoices, $in_bookkeeping, 1);
1114
1115 $varlink = 'id_journal='.$id_journal;
1116
1117 journalHead($nom, $nomlink, $period, $periodlink, $description, $builddate, $exportlink, array('action' => ''), '', $varlink);
1118
1119 if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') != 'blockedonclosed') {
1120 // Test that setup is complete (we are in accounting, so test on entity is always on $conf->entity only, no sharing allowed)
1121 // Fiscal period test
1122 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_fiscalyear WHERE entity = ".((int) $conf->entity);
1123 $resql = $db->query($sql);
1124 if ($resql) {
1125 $obj = $db->fetch_object($resql);
1126 if ($obj->nb == 0) {
1127 print '<br><div class="warning">'.img_warning().' '.$langs->trans("TheFiscalPeriodIsNotDefined");
1128 $desc = ' : '.$langs->trans("AccountancyAreaDescFiscalPeriod", 4, '{link}');
1129 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("FiscalPeriod").'</strong>', $desc);
1130 print $desc;
1131 print '</div>';
1132 }
1133 } else {
1135 }
1136 }
1137
1138 // Button to write into Ledger
1139 $acctCustomerNotConfigured = in_array(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER'), ['','-1']);
1140 if ($acctCustomerNotConfigured) {
1141 print '<br><div class="warning">'.img_warning().' '.$langs->trans("SomeMandatoryStepsOfSetupWereNotDone");
1142 $desc = ' : '.$langs->trans("AccountancyAreaDescMisc", 4, '{link}');
1143 $desc = str_replace('{link}', '<strong>'.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("MenuDefaultAccounts").'</strong>', $desc);
1144 print $desc;
1145 print '</div>';
1146 }
1147 print '<br><div class="tabsAction tabsActionNoBottom centerimp">';
1148 if (getDolGlobalString('ACCOUNTING_ENABLE_EXPORT_DRAFT_JOURNAL') && $in_bookkeeping == 'notyet') {
1149 print '<input type="button" class="butAction" name="exportcsv" value="'.$langs->trans("ExportDraftJournal").'" onclick="launch_export();" />';
1150 }
1151 if ($acctCustomerNotConfigured) {
1152 print '<input type="button" class="butActionRefused classfortooltip" title="'.dol_escape_htmltag($langs->trans("SomeMandatoryStepsOfSetupWereNotDone")).'" value="'.$langs->trans("WriteBookKeeping").'" />';
1153 } else {
1154 if ($in_bookkeeping == 'notyet') {
1155 print '<input type="button" class="butAction" name="writebookkeeping" value="'.$langs->trans("WriteBookKeeping").'" onclick="writebookkeeping();" />';
1156 } else {
1157 print '<a href="#" class="butActionRefused classfortooltip" name="writebookkeeping">'.$langs->trans("WriteBookKeeping").'</a>';
1158 }
1159 }
1160 print '</div>';
1161
1162 // TODO Avoid using js. We can use a direct link with $param
1163 print '
1164 <script type="text/javascript">
1165 function launch_export() {
1166 $("div.fiche form input[name=\"action\"]").val("exportcsv");
1167 $("div.fiche form input[type=\"submit\"]").click();
1168 $("div.fiche form input[name=\"action\"]").val("");
1169 }
1170 function writebookkeeping() {
1171 console.log("click on writebookkeeping");
1172 $("div.fiche form input[name=\"action\"]").val("writebookkeeping");
1173 $("div.fiche form input[type=\"submit\"]").click();
1174 $("div.fiche form input[name=\"action\"]").val("");
1175 }
1176 </script>';
1177
1178 /*
1179 * Show result array
1180 */
1181 print '<br>';
1182
1183 print '<div class="div-table-responsive">';
1184 print "<table class=\"noborder\" width=\"100%\">";
1185 print "<tr class=\"liste_titre\">";
1186 print "<td>".$langs->trans("Date")."</td>";
1187 print "<td>".$langs->trans("Piece").' ('.$langs->trans("InvoiceRef").")</td>";
1188 print "<td>".$langs->trans("AccountAccounting")."</td>";
1189 print "<td>".$langs->trans("SubledgerAccount")."</td>";
1190 print "<td>".$langs->trans("LabelOperation")."</td>";
1191 print '<td class="center">'.$langs->trans("AccountingDebit")."</td>";
1192 print '<td class="center">'.$langs->trans("AccountingCredit")."</td>";
1193 print "</tr>\n";
1194
1195 $i = 0;
1196
1197 $companystatic = new Client($db);
1198 $invoicestatic = new Facture($db);
1199 $bookkeepingstatic = new BookKeeping($db);
1200
1201 foreach ($tabfac as $key => $val) {
1202 $companystatic->id = $tabcompany[$key]['id'];
1203 $companystatic->name = $tabcompany[$key]['name'];
1204 $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;
1205 $companystatic->code_compta = $tabcompany[$key]['code_compta'];
1206 $companystatic->code_compta_client = $tabcompany[$key]['code_compta'];
1207 $companystatic->code_client = $tabcompany[$key]['code_client'];
1208 $companystatic->client = 3;
1209
1210 $invoicestatic->id = (int) $key;
1211 $invoicestatic->ref = (string) $val["ref"];
1212 $invoicestatic->type = $val["type"];
1213 $invoicestatic->close_code = $val["close_code"];
1214
1215 $date = dol_print_date($val["date"], 'day');
1216
1217 // Is it a replaced invoice? 0=not a replaced invoice, 1=replaced invoice not yet dispatched, 2=replaced invoice dispatched
1218 $replacedinvoice = 0;
1219 if ($invoicestatic->close_code == Facture::CLOSECODE_REPLACED) {
1220 $replacedinvoice = 1;
1221 $alreadydispatched = $invoicestatic->getVentilExportCompta(); // Test if replaced invoice already into bookkeeping.
1222 if ($alreadydispatched) {
1223 $replacedinvoice = 2;
1224 }
1225 }
1226
1227 // If not already into bookkeeping, we won't add it, if yes, add the counterpart ???.
1228 if ($replacedinvoice == 1) {
1229 print '<tr class="oddeven">';
1230 print "<!-- Replaced invoice -->";
1231 print "<td>".$date."</td>";
1232 print "<td><strike>".$invoicestatic->getNomUrl(1)."</strike></td>";
1233 // Account
1234 print "<td>";
1235 print $langs->trans("Replaced");
1236 print '</td>';
1237 // Subledger account
1238 print "<td>";
1239 print '</td>';
1240 print "<td>";
1241 print "</td>";
1242 print '<td class="right"></td>';
1243 print '<td class="right"></td>';
1244 print "</tr>";
1245
1246 $i++;
1247 continue;
1248 }
1249 if (isset($errorforinvoice[$key]) && $errorforinvoice[$key] == 'somelinesarenotbound') {
1250 print '<tr class="oddeven">';
1251 print "<!-- Some lines are not bound -->";
1252 print "<td>".$date."</td>";
1253 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1254 // Account
1255 print "<td>";
1256 print '<span class="error">'.$langs->trans('ErrorInvoiceContainsLinesNotYetBoundedShort', $val['ref']).'</span>';
1257 print '</td>';
1258 // Subledger account
1259 print "<td>";
1260 print '</td>';
1261 print "<td>";
1262 print "</td>";
1263 print '<td class="right"></td>';
1264 print '<td class="right"></td>';
1265 print "</tr>";
1266
1267 $i++;
1268 }
1269
1270 // Warranty
1271 if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY') && isset($tabwarranty[$key]) && is_array($tabwarranty[$key])) {
1272 foreach ($tabwarranty[$key] as $k => $mt) {
1273 print '<tr class="oddeven">';
1274 print "<!-- Thirdparty warranty -->";
1275 print "<td>" . $date . "</td>";
1276 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1277 // Account
1278 print "<td>";
1279 $accountoshow = length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY'));
1280 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1281 print '<span class="error">' . $langs->trans("MainAccountForRetainedWarrantyNotDefined") . '</span>';
1282 } else {
1283 print $accountoshow;
1284 }
1285 print '</td>';
1286 // Subledger account
1287 print "<td>";
1288 $accountoshow = length_accounta($k);
1289 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1290 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1291 } else {
1292 print $accountoshow;
1293 }
1294 print '</td>';
1295 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0), $invoicestatic->ref, $langs->trans("RetainedWarranty"), 1) . "</td>";
1296 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1297 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1298 print "</tr>";
1299 }
1300 }
1301
1302 // Third party
1303 foreach ($tabttc[$key] as $k => $mt) {
1304 print '<tr class="oddeven">';
1305 print "<!-- Thirdparty -->";
1306 print "<td>".$date."</td>";
1307 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1308 // Account
1309 print "<td>";
1310 $accountoshow = length_accountg($companystatic->accountancy_code_customer_general);
1311 if (($accountoshow == "") || $accountoshow == "-1" || $accountoshow == 'NotDefined') {
1312 print '<span class="error">'.$langs->trans("MainAccountForCustomersNotDefined").'</span>';
1313 } else {
1314 print $accountoshow;
1315 }
1316 print '</td>';
1317 // Subledger account
1318 print "<td>";
1319 $accountoshow = length_accounta($k);
1320 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1321 print '<span class="error">'.$langs->trans("ThirdpartyAccountNotDefined").'</span>';
1322 } else {
1323 print $accountoshow;
1324 }
1325 print '</td>';
1326 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $langs->trans("SubledgerAccount"), 1) . "</td>";
1327 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1328 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1329 print "</tr>";
1330
1331 $i++;
1332 }
1333
1334 // Product / Service
1335 foreach ($tabht[$key] as $k => $mt) {
1336 if (empty($conf->cache['accountingaccountincurrententity'][$k])) {
1337 $accountingaccount = new AccountingAccount($db);
1338 $accountingaccount->fetch(0, $k, true);
1339 $conf->cache['accountingaccountincurrententity'][$k] = $accountingaccount;
1340 } else {
1341 $accountingaccount = $conf->cache['accountingaccountincurrententity'][$k];
1342 }
1343
1344 print '<tr class="oddeven">';
1345 print "<!-- Product -->";
1346 print "<td>".$date."</td>";
1347 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1348 // Account
1349 print "<td>";
1350 $accountoshow = length_accountg($k);
1351 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1352 print '<span class="error">'.$langs->trans("ProductNotDefined").'</span>';
1353 } else {
1354 print $accountoshow;
1355 }
1356 print "</td>";
1357 // Subledger account
1358 print "<td>";
1359 if (getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_USE_AUXILIARY_ON_DEPOSIT')) {
1360 if ($k == getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_DEPOSIT')) {
1361 print length_accounta($tabcompany[$key]['code_compta']);
1362 }
1363 } elseif (($accountoshow == "") || $accountoshow == 'NotDefined') {
1364 print '<span class="error">' . $langs->trans("ThirdpartyAccountNotDefined") . '</span>';
1365 }
1366 print '</td>';
1367 $companystatic->id = $tabcompany[$key]['id'];
1368 $companystatic->name = $tabcompany[$key]['name'];
1369 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $accountingaccount->label, 1) . "</td>";
1370 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1371 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1372 print "</tr>";
1373
1374 $i++;
1375 }
1376
1377 // VAT
1378 $listoftax = array(0, 1, 2);
1379 foreach ($listoftax as $numtax) {
1380 $arrayofvat = $tabtva;
1381 if ($numtax == 1) {
1382 $arrayofvat = $tablocaltax1;
1383 }
1384 if ($numtax == 2) {
1385 $arrayofvat = $tablocaltax2;
1386 }
1387
1388 // $key is id of invoice
1389 foreach ($arrayofvat[$key] as $k => $mt) {
1390 if ($mt) {
1391 print '<tr class="oddeven">';
1392 print "<!-- VAT -->";
1393 print "<td>".$date."</td>";
1394 print "<td>".$invoicestatic->getNomUrl(1)."</td>";
1395 // Account
1396 print "<td>";
1397 $accountoshow = length_accountg($k);
1398 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1399 print '<span class="error">'.$langs->trans("VATAccountNotDefined").' ('.$langs->trans("AccountingJournalType6").')</span>';
1400 } else {
1401 print $accountoshow;
1402 }
1403 print "</td>";
1404 // Subledger account
1405 print "<td>";
1406 print '</td>';
1407 // $def_tva is array[invoiceid][accountancy_code_sell_of_vat_rate_found][vatrate]=vatrate
1408 //var_dump($arrayofvat[$key]); //var_dump($key); //var_dump($k);
1409 $tmpvatrate = (empty($def_tva[$key][$k]) ? (empty($arrayofvat[$key][$k]) ? '' : $arrayofvat[$key][$k]) : implode(', ', $def_tva[$key][$k]));
1410 $labelvatrate = $langs->trans("Taxes").' '.$tmpvatrate.' %';
1411 $labelvatrate .= ($numtax ? ' - Localtax '.$numtax : '');
1412 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $labelvatrate, 1) . "</td>";
1413 print '<td class="right nowraponall amount">'.($mt < 0 ? price(-$mt) : '')."</td>";
1414 print '<td class="right nowraponall amount">'.($mt >= 0 ? price($mt) : '')."</td>";
1415 print "</tr>";
1416
1417 $i++;
1418 }
1419 }
1420 }
1421
1422 // Revenue stamp
1423 if (isset($tabrevenuestamp[$key]) && is_array($tabrevenuestamp[$key])) {
1424 foreach ($tabrevenuestamp[$key] as $k => $mt) {
1425 print '<tr class="oddeven">';
1426 print "<!-- Thirdparty revenuestamp -->";
1427 print "<td>" . $date . "</td>";
1428 print "<td>" . $invoicestatic->getNomUrl(1) . "</td>";
1429 // Account
1430 print "<td>";
1431 $accountoshow = length_accountg($k);
1432 if (($accountoshow == "") || $accountoshow == 'NotDefined') {
1433 print '<span class="error">' . $langs->trans("MainAccountForRevenueStampSaleNotDefined") . '</span>';
1434 } else {
1435 print $accountoshow;
1436 }
1437 print '</td>';
1438 // Subledger account
1439 print "<td>";
1440 print '</td>';
1441 print "<td>" . $bookkeepingstatic->accountingLabelForOperation($companystatic->getNomUrl(0, 'customer'), $invoicestatic->ref, $langs->trans("RevenueStamp"), 1) . "</td>";
1442 print '<td class="right nowraponall amount">' . ($mt < 0 ? price(-$mt) : '') . "</td>";
1443 print '<td class="right nowraponall amount">' . ($mt >= 0 ? price($mt) : '') . "</td>";
1444 print "</tr>";
1445 }
1446 }
1447 }
1448
1449 if (!$i) {
1450 print '<tr class="oddeven"><td colspan="7"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
1451 }
1452
1453 print "</table>";
1454 print '</div>';
1455
1456 // End of page
1457 llxFooter();
1458}
1459
1460$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 invoices.
const TYPE_REPLACEMENT
Replacement 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:604
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:623
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:
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.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
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)
Return value of a param into GET or POST supervariable.
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.
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.