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