dolibarr 23.0.3
index.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2013 Olivier Geffroy <jeff@jeffinfo.com>
3 * Copyright (C) 2013-2014 Florian Henry <florian.henry@open-concept.pro>
4 * Copyright (C) 2013-2022 Alexandre Spangaro <aspangaro@open-dsi.fr>
5 * Copyright (C) 2014 Juanjo Menent <jmenent@2byte.es>
6 * Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
7 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
30// Load Dolibarr environment
31require '../../main.inc.php';
32require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
34require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
35require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
36require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
37
47// Load translation files required by the page
48$langs->loadLangs(array("compta", "bills", "other", "accountancy"));
49
50$validatemonth = GETPOSTINT('validatemonth');
51$validateyear = GETPOSTINT('validateyear');
52
53$accountingAccount = new AccountingAccount($db);
54
55$month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1);
56if (GETPOSTINT("year")) {
57 $year_start = GETPOSTINT("year");
58} else {
59 $year_start = dol_print_date(dol_now(), '%Y');
60 if (dol_print_date(dol_now(), '%m') < $month_start) {
61 $year_start--; // If current month is lower that starting fiscal month, we start last year
62 }
63}
64$year_end = $year_start + 1;
65$month_end = $month_start - 1;
66if ($month_end < 1) {
67 $month_end = 12;
68 $year_end--;
69}
70$search_date_start = dol_mktime(0, 0, 0, $month_start, 1, $year_start);
71$search_date_end = dol_get_last_day($year_end, $month_end);
72$year_current = $year_start;
73
74// Validate History
75$action = GETPOST('action', 'aZ09');
76
77$chartaccountcode = dol_getIdFromCode($db, getDolGlobalString('CHARTOFACCOUNTS'), 'accounting_system', 'rowid', 'pcg_version');
78
79// Security check
80if (!isModEnabled('accounting')) {
82}
83if ($user->socid > 0) {
85}
86if (!$user->hasRight('accounting', 'bind', 'write')) {
88}
89
90
91/*
92 * Actions
93 */
94
95if (($action == 'clean' || $action == 'validatehistory') && $user->hasRight('accounting', 'bind', 'write')) {
96 $error = 0;
97 // Clean database by removing binding done on non existing or no more existing accounts
98 $db->begin();
99 $sql1 = "UPDATE ".$db->prefix()."facturedet as fd";
100 $sql1 .= " SET fk_code_ventilation = 0";
101 $sql1 .= ' WHERE fd.fk_code_ventilation NOT IN';
102 $sql1 .= ' (SELECT accnt.rowid ';
103 $sql1 .= ' FROM '.$db->prefix().'accounting_account as accnt';
104 $sql1 .= ' INNER JOIN '.$db->prefix().'accounting_system as syst';
105 $sql1 .= " ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid = ".((int) getDolGlobalInt('CHARTOFACCOUNTS'))." AND accnt.entity = ".((int) $conf->entity).")";
106 $sql1 .= " AND fd.fk_facture IN (SELECT rowid FROM ".$db->prefix()."facture WHERE entity = ".((int) $conf->entity).")";
107 $sql1 .= " AND fk_code_ventilation <> 0";
108
109 dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG);
110 $resql1 = $db->query($sql1);
111 if (!$resql1) {
112 $error++;
113 $db->rollback();
114 setEventMessages($db->lasterror(), null, 'errors');
115 } else {
116 $db->commit();
117 }
118 // End clean database
119}
120
121if ($action == 'validatehistory' && $user->hasRight('accounting', 'bind', 'write')) {
122 $error = 0;
123 $nbbinddone = 0;
124 $nbbindfailed = 0;
125 $notpossible = 0;
126
127 $db->begin();
128
129 // Now make the binding. Bind automatically only for product with a dedicated account that exists into chart of account, others need a manual bind
130 // Customer Invoice lines (must be same request than into page list.php for manual binding)
131 $sql = "SELECT f.rowid as facid, f.ref as ref, f.datef, f.type as ftype, f.situation_cycle_ref, f.fk_facture_source,";
132 $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.situation_percent, l.tva_tx as tva_tx_line, l.vat_src_code,";
133 $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,";
134 if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
135 $sql .= " ppe.accountancy_code_sell as code_sell, ppe.accountancy_code_sell_intra as code_sell_intra, ppe.accountancy_code_sell_export as code_sell_export,";
136 } else {
137 $sql .= " p.accountancy_code_sell as code_sell, p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,";
138 }
139 $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export, aa4.rowid as aarowid_thirdparty,";
140 $sql .= " co.code as country_code, co.label as country_label,";
141 $sql .= " s.tva_intra,";
142 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
143 $sql .= " spe.accountancy_code_sell as company_code_sell"; // accounting code for product but stored on thirdparty
144 } else {
145 $sql .= " s.accountancy_code_sell as company_code_sell"; // accounting code for product but stored on thirdparty
146 }
147 $sql .= " FROM ".$db->prefix()."facture as f";
148 $sql .= " INNER JOIN ".$db->prefix()."societe as s ON s.rowid = f.fk_soc";
149 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
150 $sql .= " LEFT JOIN " . $db->prefix() . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
151 }
152 $sql .= " LEFT JOIN ".$db->prefix()."c_country as co ON co.rowid = s.fk_pays ";
153 $sql .= " INNER JOIN ".$db->prefix()."facturedet as l ON f.rowid = l.fk_facture"; // the main table
154 $sql .= " LEFT JOIN ".$db->prefix()."product as p ON p.rowid = l.fk_product";
155 if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
156 $sql .= " LEFT JOIN " . $db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
157 }
158 $alias_societe_perentity = !getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED') ? "s" : "spe";
159 $alias_product_perentity = !getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED') ? "p" : "ppe";
160 $sql .= " LEFT JOIN ".$db->prefix()."accounting_account as aa ON ".$db->sanitize($alias_product_perentity).".accountancy_code_sell = aa.account_number AND aa.active = 1 AND aa.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa.entity = ".$conf->entity;
161 $sql .= " LEFT JOIN ".$db->prefix()."accounting_account as aa2 ON ".$db->sanitize($alias_product_perentity).".accountancy_code_sell_intra = aa2.account_number AND aa2.active = 1 AND aa2.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa2.entity = ".$conf->entity;
162 $sql .= " LEFT JOIN ".$db->prefix()."accounting_account as aa3 ON ".$db->sanitize($alias_product_perentity).".accountancy_code_sell_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa3.entity = ".$conf->entity;
163 $sql .= " LEFT JOIN ".$db->prefix()."accounting_account as aa4 ON ".$db->sanitize($alias_societe_perentity).".accountancy_code_sell = aa4.account_number AND aa4.active = 1 AND aa4.fk_pcg_version = '".$db->escape($chartaccountcode)."' AND aa4.entity = ".$conf->entity;
164 $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0";
165 $sql .= " AND l.product_type <= 2";
166 $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
167 if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
168 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
169 }
170 if ($validatemonth && $validateyear) {
171 $sql .= dolSqlDateFilter('f.datef', 0, $validatemonth, $validateyear);
172 }
173
174 dol_syslog('htdocs/accountancy/customer/index.php');
175
176 $result = $db->query($sql);
177 if (!$result) {
178 $error++;
179 setEventMessages($db->lasterror(), null, 'errors');
180 } else {
181 $num_lines = $db->num_rows($result);
182
183 $thirdpartystatic = new Societe($db);
184 $facture_static = new Facture($db);
185 $facture_static_det = new FactureLigne($db);
186 $product_static = new Product($db);
187
188 $i = 0;
189 while ($i < min($num_lines, 10000)) { // No more than 10000 at once
190 $objp = $db->fetch_object($result);
191
192 $thirdpartystatic->id = !empty($objp->socid) ? $objp->socid : 0;
193 $thirdpartystatic->name = !empty($objp->name) ? $objp->name : "";
194 $thirdpartystatic->client = !empty($objp->client) ? $objp->client : "";
195 $thirdpartystatic->fournisseur = !empty($objp->fournisseur) ? $objp->fournisseur : "";
196 $thirdpartystatic->code_client = !empty($objp->code_client) ? $objp->code_client : "";
197 $thirdpartystatic->code_compta_client = !empty($objp->code_compta_client) ? $objp->code_compta_client : "";
198 $thirdpartystatic->code_fournisseur = !empty($objp->code_fournisseur) ? $objp->code_fournisseur : "";
199 $thirdpartystatic->code_compta_fournisseur = !empty($objp->code_compta_fournisseur) ? $objp->code_compta_fournisseur : "";
200 $thirdpartystatic->email = !empty($objp->email) ? $objp->email : "";
201 $thirdpartystatic->country_code = !empty($objp->country_code) ? $objp->country_code : "";
202 $thirdpartystatic->tva_intra = !empty($objp->tva_intra) ? $objp->tva_intra : "";
203 $thirdpartystatic->code_compta_product = !empty($objp->company_code_sell) ? $objp->company_code_sell : ""; // The accounting account for product stored on thirdparty object (for level3 suggestion)
204
205 $product_static->ref = $objp->product_ref;
206 $product_static->id = $objp->product_id;
207 $product_static->type = $objp->type;
208 $product_static->label = $objp->product_label;
209 $product_static->status = !empty($objp->status) ? $objp->status : 0;
210 $product_static->status_buy = !empty($objp->status_buy) ? $objp->status_buy : 0;
211 $product_static->accountancy_code_sell = $objp->code_sell;
212 $product_static->accountancy_code_sell_intra = $objp->code_sell_intra;
213 $product_static->accountancy_code_sell_export = $objp->code_sell_export;
214 $product_static->accountancy_code_buy = !empty($objp->code_buy) ? $objp->code_buy : "";
215 $product_static->accountancy_code_buy_intra = !empty($objp->code_buy_intra) ? $objp->code_buy_intra : "";
216 $product_static->accountancy_code_buy_export = !empty($objp->code_buy_export) ? $objp->code_buy_export : "";
217 $product_static->tva_tx = $objp->tva_tx_prod;
218
219 $facture_static->ref = $objp->ref;
220 $facture_static->id = $objp->facid;
221 $facture_static->type = $objp->ftype;
222 $facture_static->date = $db->jdate($objp->datef);
223 $facture_static->fk_facture_source = $objp->fk_facture_source;
224
225 $facture_static_det->id = $objp->rowid;
226 $facture_static_det->total_ht = $objp->total_ht;
227 $facture_static_det->tva_tx = $objp->tva_tx_line;
228 $facture_static_det->vat_src_code = $objp->vat_src_code;
229 $facture_static_det->product_type = $objp->type_l;
230 $facture_static_det->desc = $objp->description;
231
232 $accountingAccountArray = array(
233 'dom' => $objp->aarowid,
234 'intra' => $objp->aarowid_intra,
235 'export' => $objp->aarowid_export,
236 'thirdparty' => $objp->aarowid_thirdparty);
237
238 $suggestedid = 0;
239
240 $return = $accountingAccount->getAccountingCodeToBind($thirdpartystatic, $mysoc, $product_static, $facture_static, $facture_static_det, $accountingAccountArray, 'customer');
241 if (!is_array($return) && $return < 0) {
242 setEventMessage($accountingAccount->error, 'errors');
243 } else {
244 $suggestedid = $return['suggestedid'];
245 $suggestedaccountingaccountfor = $return['suggestedaccountingaccountfor'];
246
247 if (!empty($suggestedid) && $suggestedaccountingaccountfor != '' && $suggestedaccountingaccountfor != 'eecwithoutvatnumber') {
248 $suggestedid = $return['suggestedid'];
249 } else {
250 $suggestedid = 0;
251 }
252 }
253
254 if ($suggestedid > 0) {
255 $sqlupdate = "UPDATE ".$db->prefix()."facturedet";
256 $sqlupdate .= " SET fk_code_ventilation = ".((int) $suggestedid);
257 $sqlupdate .= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = ".((int) $facture_static_det->id);
258
259 $resqlupdate = $db->query($sqlupdate);
260 if (!$resqlupdate) {
261 $error++;
262 setEventMessages($db->lasterror(), null, 'errors');
263 $nbbindfailed++;
264 break;
265 } else {
266 $nbbinddone++;
267 }
268 } else {
269 $notpossible++;
270 $nbbindfailed++;
271 }
272
273 $i++;
274 }
275 if ($num_lines > 10000) {
276 $notpossible += ($num_lines - 10000);
277 }
278 }
279
280 if ($error) {
281 $db->rollback();
282 } else {
283 $db->commit();
284 setEventMessages($langs->trans('AutomaticBindingDone', $nbbinddone, $notpossible), null, ($notpossible ? 'warnings' : 'mesgs'));
285 if ($nbbindfailed) {
286 setEventMessages($langs->trans('DoManualBindingForFailedRecord', $nbbindfailed), null, 'warnings');
287 }
288 }
289}
290
291
292/*
293 * View
294 */
295$help_url = 'EN:Module_Double_Entry_Accounting|FR:Module_Comptabilit&eacute;_en_Partie_Double#Liaisons_comptables';
296
297llxHeader('', $langs->trans("CustomersVentilation"), $help_url, '', 0, 0, '', '', '', 'mod-accountancy accountancy-customer page-index');
298
299$textprevyear = '<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_current - 1).'">'.img_previous().'</a>';
300$textnextyear = '&nbsp;<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_current + 1).'">'.img_next().'</a>';
301
302
303print load_fiche_titre($langs->trans("CustomersVentilation")." ".$textprevyear." ".$langs->trans("Year")." ".$year_start." ".$textnextyear, '', 'title_accountancy');
304
305print '<span class="opacitymedium">'.$langs->trans("DescVentilCustomer").'</span><br>';
306print '<span class="opacitymedium hideonsmartphone">'.$langs->trans("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToBind")).'<br>';
307print '</span><br>';
308
309if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
310 print info_admin($langs->trans("SorryThisModuleIsNotCompatibleWithTheExperimentalFeatureOfSituationInvoices"));
311 print "<br>";
312}
313
314$y = $year_current;
315
316$buttonbind = '<a class="button small" href="'.$_SERVER['PHP_SELF'].'?action=validatehistory&token='.newToken().'&year='.$year_current.'">'.img_picto($langs->trans("ValidateHistory"), 'link', 'class="pictofixedwidth fa-color-unset"').$langs->trans("ValidateHistory").'</a>';
317
318print_barre_liste(img_picto('', 'unlink', 'class="paddingright fa-color-unset"').$langs->trans("OverviewOfAmountOfLinesNotBound"), 0, '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1, 0, $buttonbind);
319//print load_fiche_titre($langs->trans("OverviewOfAmountOfLinesNotBound"), $buttonbind, '');
320
321print '<div class="div-table-responsive-no-min">';
322print '<table class="noborder centpercent">';
323print '<tr class="liste_titre"><td class="minwidth100">'.$langs->trans("Account").'</td>';
324for ($i = 1; $i <= 12; $i++) {
325 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
326 if ($j > 12) {
327 $j -= 12;
328 }
329 $cursormonth = $j;
330 if ($cursormonth > 12) {
331 $cursormonth -= 12;
332 }
333 $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
334 $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
335
336 print '<td width="60" class="right">';
337 if (!empty($tmp['mday'])) {
338 $param = 'search_date_startday=1&search_date_startmonth='.$cursormonth.'&search_date_startyear='.$cursoryear;
339 $param .= '&search_date_endday='.$tmp['mday'].'&search_date_endmonth='.$tmp['mon'].'&search_date_endyear='.$tmp['year'];
340 print '<a href="'.DOL_URL_ROOT.'/accountancy/customer/list.php?'.$param.'">';
341 }
342 print $langs->trans('MonthShort'.str_pad((string) $j, 2, '0', STR_PAD_LEFT));
343 if (!empty($tmp['mday'])) {
344 print '</a>';
345 }
346 print '</td>';
347}
348print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
349
350$sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,";
351$sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
352for ($i = 1; $i <= 12; $i++) {
353 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
354 if ($j > 12) {
355 $j -= 12;
356 }
357 $sql .= " SUM(".$db->ifsql("MONTH(f.datef) = ".((string) $j), "fd.total_ht", "0").") AS month".str_pad((string) $j, 2, "0", STR_PAD_LEFT).",";
358 $sql .= " SUM(".$db->ifsql("MONTH(f.datef) = ".((string) $j), "1", "0").") AS nbmonth".str_pad((string) $j, 2, "0", STR_PAD_LEFT).",";
359}
360$sql .= " SUM(fd.total_ht) as total, COUNT(fd.rowid) as nb";
361$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
362$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
363$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
364$sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'";
365$sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
366// Define begin binding date
367if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
368 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
369}
370$sql .= " AND f.fk_statut > 0";
371$sql .= " AND fd.product_type <= 2";
372$sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
373$sql .= " AND aa.account_number IS NULL";
374if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
375 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
376} else {
377 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
378}
379$sql .= " GROUP BY fd.fk_code_ventilation,aa.account_number,aa.label";
380
381dol_syslog('htdocs/accountancy/customer/index.php', LOG_DEBUG);
382$resql = $db->query($sql);
383if ($resql) {
384 $num = $db->num_rows($resql);
385
386 while ($row = $db->fetch_row($resql)) {
387 // TODO When INVOICE_USE_SITUATION = 1, values here are wrong. There is no compensation on bad stored amounts
388 //$situation_ratio = 1;
389 //if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
390 //}
391
392 print '<tr class="oddeven">';
393 print '<td>';
394 if ($row[0] == 'tobind') {
395 //print '<span class="opacitymedium">'.$langs->trans("Unknown").'</span>';
396 } else {
397 print length_accountg($row[0]).' - ';
398 }
399 //print '</td>';
400 //print '<td>';
401 if ($row[0] == 'tobind') {
402 $startmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1);
403 if ($startmonth > 12) {
404 $startmonth -= 12;
405 }
406 $startyear = ($startmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
407 $endmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + 11;
408 if ($endmonth > 12) {
409 $endmonth -= 12;
410 }
411 $endyear = ($endmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
412 print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/customer/list.php?search_date_startday=1&search_date_startmonth='.((int) $startmonth).'&search_date_startyear='.((int) $startyear).'&search_date_endday=&search_date_endmonth='.((int) $endmonth).'&search_date_endyear='.((int) $endyear), $langs->transnoentitiesnoconv("ToBind"));
413 } else {
414 print $row[1];
415 }
416 print '</td>';
417
418 for ($i = 2; $i <= 13; $i++) {
419 $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2);
420 if ($cursormonth > 12) {
421 $cursormonth -= 12;
422 }
423 $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
424 $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
425
426 print '<td class="right nowraponall amount" title="'.price($row[2 * $i - 2]).' - '.$row[2 * $i - 1].' lines">';
427 print price($row[2 * $i - 2]);
428 // Add link to make binding
429 if (!empty(price2num($row[2 * $i - 2])) || !empty($row[2 * $i - 1])) {
430 print '<a href="'.$_SERVER['PHP_SELF'].'?action=validatehistory&year='.$y.'&validatemonth='.((int) $cursormonth).'&validateyear='.((int) $cursoryear).'&token='.newToken().'">';
431 print img_picto($langs->trans("ValidateHistory").' ('.$langs->trans('Month'.str_pad((string) $cursormonth, 2, '0', STR_PAD_LEFT)).' '.$cursoryear.')', 'link', 'class="marginleft2"');
432 print '</a>';
433 }
434 print '</td>';
435 }
436
437 print '<td class="right nowraponall amount"><b>'.price($row[26]).'</b></td>';
438
439 print '</tr>';
440 }
441 $db->free($resql);
442
443 if ($num == 0) {
444 print '<tr class="oddeven"><td colspan="15">';
445 print '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
446 print '</td></tr>';
447 }
448} else {
449 print $db->lasterror(); // Show last sql error
450}
451print "</table>\n";
452print '</div>';
453
454
455print '<br>';
456
457
458print_barre_liste(img_picto('', 'link', 'class="paddingright fa-color-unset"').$langs->trans("OverviewOfAmountOfLinesBound"), 0, '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1);
459//print load_fiche_titre($langs->trans("OverviewOfAmountOfLinesBound"), '', '');
460
461print '<div class="div-table-responsive-no-min">';
462print '<table class="noborder centpercent">';
463print '<tr class="liste_titre"><td class="minwidth100">'.$langs->trans("Account").'</td>';
464for ($i = 1; $i <= 12; $i++) {
465 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
466 if ($j > 12) {
467 $j -= 12;
468 }
469 $cursormonth = $j;
470 if ($cursormonth > 12) {
471 $cursormonth -= 12;
472 }
473 $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
474 $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
475
476 print '<td width="60" class="right">';
477 if (!empty($tmp['mday'])) {
478 $param = 'search_date_startday=1&search_date_startmonth='.$cursormonth.'&search_date_startyear='.$cursoryear;
479 $param .= '&search_date_endday='.$tmp['mday'].'&search_date_endmonth='.$tmp['mon'].'&search_date_endyear='.$tmp['year'];
480 print '<a href="'.DOL_URL_ROOT.'/accountancy/customer/lines.php?'.$param.'">';
481 }
482 print $langs->trans('MonthShort'.str_pad((string) $j, 2, '0', STR_PAD_LEFT));
483 if (!empty($tmp['mday'])) {
484 print '</a>';
485 }
486 print '</td>';
487}
488print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
489
490$sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,";
491$sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
492for ($i = 1; $i <= 12; $i++) {
493 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
494 if ($j > 12) {
495 $j -= 12;
496 }
497 $sql .= " SUM(".$db->ifsql("MONTH(f.datef) = ".((int) $j), "fd.total_ht", "0").") AS month".str_pad((string) $j, 2, "0", STR_PAD_LEFT).",";
498}
499$sql .= " SUM(fd.total_ht) as total";
500$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
501$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
502$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
503$sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'";
504$sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
505// Define begin binding date
506if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
507 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
508}
509$sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
510$sql .= " AND f.fk_statut > 0";
511$sql .= " AND fd.product_type <= 2";
512if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
513 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_SITUATION.")";
514} else {
515 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_DEPOSIT.", ".Facture::TYPE_SITUATION.")";
516}
517$sql .= " AND aa.account_number IS NOT NULL";
518$sql .= " GROUP BY fd.fk_code_ventilation,aa.account_number,aa.label";
519$sql .= ' ORDER BY aa.account_number';
520
521dol_syslog('htdocs/accountancy/customer/index.php');
522$resql = $db->query($sql);
523if ($resql) {
524 $num = $db->num_rows($resql);
525
526 while ($row = $db->fetch_row($resql)) {
527 // TODO When INVOICE_USE_SITUATION = 1, values here are wrong. There is no compensation on bad stored amounts
528 //$situation_ratio = 1;
529 //if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
530 //}
531
532 print '<tr class="oddeven">';
533 print '<td class="tdoverflowmax300"'.(empty($row[1]) ? '' : ' title="'.dol_escape_htmltag($row[1]).'"').'>';
534 if ($row[0] == 'tobind') {
535 //print $langs->trans("Unknown");
536 } else {
537 print length_accountg($row[0]).' - ';
538 }
539 if ($row[0] == 'tobind') {
540 print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/customer/list.php?search_year='.((int) $y), $langs->transnoentitiesnoconv("ToBind"));
541 } else {
542 print $row[1];
543 }
544 print '</td>';
545
546 for ($i = 2; $i <= 13; $i++) {
547 $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2);
548 if ($cursormonth > 12) {
549 $cursormonth -= 12;
550 }
551 $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
552 $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
553
554 print '<td class="right nowraponall amount">';
555 print price($row[$i]);
556 print '</td>';
557 }
558 print '<td class="right nowraponall amount"><b>'.price($row[14]).'</b></td>';
559 print '</tr>';
560 }
561 $db->free($resql);
562
563 if ($num == 0) {
564 print '<tr class="oddeven"><td colspan="15">';
565 print '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
566 print '</td></tr>';
567 }
568} else {
569 print $db->lasterror(); // Show last sql error
570}
571print "</table>\n";
572print '</div>';
573
574
575if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This part of code looks strange. Why showing a report that should rely on result of this step ?
576 print '<br>';
577 print '<br>';
578
579 print_barre_liste($langs->trans("OtherInfo"), 0, '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1);
580 //print load_fiche_titre($langs->trans("OtherInfo"), '', '');
581
582 print '<div class="div-table-responsive-no-min">';
583 print '<table class="noborder centpercent">';
584 print '<tr class="liste_titre"><td class="left">'.$langs->trans("TotalVente").'</td>';
585 for ($i = 1; $i <= 12; $i++) {
586 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
587 if ($j > 12) {
588 $j -= 12;
589 }
590 print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad((string) $j, 2, '0', STR_PAD_LEFT)).'</td>';
591 }
592 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
593
594 $sql = "SELECT '".$db->escape($langs->trans("TotalVente"))."' AS total,";
595 for ($i = 1; $i <= 12; $i++) {
596 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
597 if ($j > 12) {
598 $j -= 12;
599 }
600 $sql .= " SUM(".$db->ifsql("MONTH(f.datef) = ".((int) $j), "fd.total_ht", "0").") AS month".str_pad((string) $j, 2, "0", STR_PAD_LEFT).",";
601 }
602 $sql .= " SUM(fd.total_ht) as total";
603 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
604 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
605 $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'";
606 $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
607 // Define begin binding date
608 if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
609 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
610 }
611 $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
612 $sql .= " AND f.fk_statut > 0";
613 $sql .= " AND fd.product_type <= 2";
614 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
615 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_SITUATION.")";
616 } else {
617 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_DEPOSIT.", ".Facture::TYPE_SITUATION.")";
618 }
619
620 dol_syslog('htdocs/accountancy/customer/index.php');
621 $resql = $db->query($sql);
622 if ($resql) {
623 $num = $db->num_rows($resql);
624
625 while ($row = $db->fetch_row($resql)) {
626 print '<tr><td>'.$row[0].'</td>';
627 for ($i = 1; $i <= 12; $i++) {
628 print '<td class="right nowraponall amount">'.price($row[$i]).'</td>';
629 }
630 print '<td class="right nowraponall amount"><b>'.price($row[13]).'</b></td>';
631 print '</tr>';
632 }
633 $db->free($resql);
634 } else {
635 print $db->lasterror(); // Show last sql error
636 }
637 print "</table>\n";
638 print '</div>';
639
640 if (isModEnabled('margin')) {
641 print "<br>\n";
642 print '<div class="div-table-responsive-no-min">';
643 print '<table class="noborder centpercent">';
644 print '<tr class="liste_titre"><td>'.$langs->trans("TotalMarge").'</td>';
645 for ($i = 1; $i <= 12; $i++) {
646 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
647 if ($j > 12) {
648 $j -= 12;
649 }
650 print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad((string) $j, 2, '0', STR_PAD_LEFT)).'</td>';
651 }
652 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
653
654 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
655 // With old situation invoice setup
656 $sql = "SELECT '".$db->escape($langs->trans("Vide"))."' AS marge,";
657 for ($i = 1; $i <= 12; $i++) {
658 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
659 if ($j > 12) {
660 $j -= 12;
661 }
662 $sql .= " SUM(".$db->ifsql(
663 "MONTH(f.datef) = ".((int) $j),
664 " (".$db->ifsql(
665 "fd.total_ht < 0",
666 " (-1 * (abs(fd.total_ht) - (fd.buy_price_ht * fd.qty * (fd.situation_percent / 100))))", // TODO This is bugged, we must use the percent for the invoice and fd.situation_percent is cumulated percent !
667 " (fd.total_ht - (fd.buy_price_ht * fd.qty * (fd.situation_percent / 100)))"
668 ).")",
669 '0'
670 ).") AS month".str_pad((string) $j, 2, '0', STR_PAD_LEFT).",";
671 }
672 $sql .= " SUM(".$db->ifsql(
673 "fd.total_ht < 0",
674 " (-1 * (abs(fd.total_ht) - (fd.buy_price_ht * fd.qty * (fd.situation_percent / 100))))", // TODO This is bugged, we must use the percent for the invoice and fd.situation_percent is cumulated percent !
675 " (fd.total_ht - (fd.buy_price_ht * fd.qty * (fd.situation_percent / 100)))"
676 ).") as total";
677 } else {
678 $sql = "SELECT '".$db->escape($langs->trans("Vide"))."' AS marge,";
679 for ($i = 1; $i <= 12; $i++) {
680 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
681 if ($j > 12) {
682 $j -= 12;
683 }
684 $sql .= " SUM(".$db->ifsql(
685 "MONTH(f.datef) = ".((int) $j),
686 " (".$db->ifsql(
687 "fd.total_ht < 0",
688 " (-1 * (abs(fd.total_ht) - (fd.buy_price_ht * fd.qty)))",
689 " (fd.total_ht - (fd.buy_price_ht * fd.qty))"
690 ).")",
691 '0'
692 ).") AS month".str_pad((string) $j, 2, '0', STR_PAD_LEFT).",";
693 }
694 $sql .= " SUM(".$db->ifsql(
695 "fd.total_ht < 0",
696 " (-1 * (abs(fd.total_ht) - (fd.buy_price_ht * fd.qty)))",
697 " (fd.total_ht - (fd.buy_price_ht * fd.qty))"
698 ).") as total";
699 }
700 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
701 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
702 $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'";
703 $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
704 // Define begin binding date
705 if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
706 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
707 }
708 $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
709 $sql .= " AND f.fk_statut > 0";
710 $sql .= " AND fd.product_type <= 2";
711 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
712 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_SITUATION.")";
713 } else {
714 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_DEPOSIT.", ".Facture::TYPE_SITUATION.")";
715 }
716 dol_syslog('htdocs/accountancy/customer/index.php');
717 $resql = $db->query($sql);
718 if ($resql) {
719 $num = $db->num_rows($resql);
720
721 while ($row = $db->fetch_row($resql)) {
722 print '<tr><td>'.$row[0].'</td>';
723 for ($i = 1; $i <= 12; $i++) {
724 print '<td class="right nowraponall amount">'.price(price2num($row[$i])).'</td>';
725 }
726 print '<td class="right nowraponall amount"><b>'.price(price2num($row[13])).'</b></td>';
727 print '</tr>';
728 }
729 $db->free($resql);
730 } else {
731 print $db->lasterror(); // Show last sql error
732 }
733 print "</table>\n";
734 print '</div>';
735 }
736}
737
738// End of page
739llxFooter();
740$db->close();
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
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 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 products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
global $mysoc
dolSqlDateFilter($datefield, $day_date, $month_date, $year_date, $excludefirstand=0, $gm=false)
Generate a SQL string to make a filter into a range (for second of date until last second of date).
Definition date.lib.php:385
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:622
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...
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
print_barre_liste($title, $page, $file, $options='', $sortfield='', $sortorder='', $morehtmlcenter='', $num=-1, $totalnboflines='', $picto='generic', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limit=-1, $selectlimitsuffix=0, $hidenavigation=0, $pagenavastextinput=0, $morehtmlrightbeforearrow='')
Print a title with navigation controls for pagination.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
setEventMessage($mesgs, $style='mesgs', $noduplicate=0, $attop=0)
Set event message in dol_events session object.
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.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
img_previous($titlealt='default', $moreatt='')
Show previous logo.
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).
img_next($titlealt='default', $moreatt='')
Show next logo.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='')
Show information in HTML for admin users or standard users.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.