dolibarr 24.0.0-beta
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';
40require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
41require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
42require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
43require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
44require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php';
45
46// Load translation files required by the page
47$langs->loadLangs(array("compta", "bills", "other", "accountancy"));
48
49$validatemonth = GETPOSTINT('validatemonth');
50$validateyear = GETPOSTINT('validateyear');
51
52$accountingAccount = new AccountingAccount($db);
53
54$month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1);
55if (GETPOSTINT("year")) {
56 $year_start = GETPOSTINT("year");
57} else {
58 $year_start = dol_print_date(dol_now(), '%Y');
59 if (dol_print_date(dol_now(), '%m') < $month_start) {
60 $year_start--; // If current month is lower that starting fiscal month, we start last year
61 }
62}
63$year_end = $year_start + 1;
64$month_end = $month_start - 1;
65if ($month_end < 1) {
66 $month_end = 12;
67 $year_end--;
68}
69$search_date_start = dol_mktime(0, 0, 0, $month_start, 1, $year_start);
70$search_date_end = dol_get_last_day($year_end, $month_end);
71$year_current = $year_start;
72
73// Validate History
74$action = GETPOST('action', 'aZ09');
75
76$chartaccountcode = dol_getIdFromCode($db, getDolGlobalString('CHARTOFACCOUNTS'), 'accounting_system', 'rowid', 'pcg_version');
77
78// Security check
79if (!isModEnabled('accounting')) {
81}
82if ($user->socid > 0) {
84}
85if (!$user->hasRight('accounting', 'bind', 'write')) {
87}
88
89
90/*
91 * Actions
92 */
93
94if (($action == 'clean' || $action == 'validatehistory') && $user->hasRight('accounting', 'bind', 'write')) {
95 $error = 0;
96 // Clean database by removing binding done on non existing or no more existing accounts
97 $db->begin();
98 $sql1 = "UPDATE ".$db->prefix()."facturedet as fd";
99 $sql1 .= " SET fk_code_ventilation = 0";
100 $sql1 .= ' WHERE fd.fk_code_ventilation NOT IN';
101 $sql1 .= ' (SELECT accnt.rowid ';
102 $sql1 .= ' FROM '.$db->prefix().'accounting_account as accnt';
103 $sql1 .= ' INNER JOIN '.$db->prefix().'accounting_system as syst';
104 $sql1 .= " ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid = ".((int) getDolGlobalInt('CHARTOFACCOUNTS'))." AND accnt.entity = ".((int) $conf->entity).")";
105 $sql1 .= " AND fd.fk_facture IN (SELECT rowid FROM ".$db->prefix()."facture WHERE entity = ".((int) $conf->entity).")";
106 $sql1 .= " AND fk_code_ventilation <> 0";
107
108 dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG);
109 $resql1 = $db->query($sql1);
110 if (!$resql1) {
111 $error++;
112 $db->rollback();
113 setEventMessages($db->lasterror(), null, 'errors');
114 } else {
115 $db->commit();
116 }
117 // End clean database
118}
119
120if ($action == 'validatehistory' && $user->hasRight('accounting', 'bind', 'write')) {
121 $error = 0;
122 $nbbinddone = 0;
123 $nbbindfailed = 0;
124 $notpossible = 0;
125
126 $db->begin();
127
128 // Now make the binding. Bind automatically only for product with a dedicated account that exists into chart of account, others need a manual bind
129 // Customer Invoice lines (must be same request than into page list.php for manual binding)
130 $sql = "SELECT f.rowid as facid, f.ref as ref, f.datef, f.type as ftype, f.situation_cycle_ref, f.fk_facture_source,";
131 $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,";
132 $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,";
133 if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
134 $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,";
135 } else {
136 $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,";
137 }
138 $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export, aa4.rowid as aarowid_thirdparty,";
139 $sql .= " co.code as country_code, co.label as country_label,";
140 $sql .= " s.tva_intra,";
141 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
142 $sql .= " spe.accountancy_code_sell as company_code_sell"; // accounting code for product but stored on thirdparty
143 } else {
144 $sql .= " s.accountancy_code_sell as company_code_sell"; // accounting code for product but stored on thirdparty
145 }
146 $sql .= " FROM ".$db->prefix()."facture as f";
147 $sql .= " INNER JOIN ".$db->prefix()."societe as s ON s.rowid = f.fk_soc";
148 if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
149 $sql .= " LEFT JOIN " . $db->prefix() . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
150 }
151 $sql .= " LEFT JOIN ".$db->prefix()."c_country as co ON co.rowid = s.fk_pays ";
152 $sql .= " INNER JOIN ".$db->prefix()."facturedet as l ON f.rowid = l.fk_facture"; // the main table
153 $sql .= " LEFT JOIN ".$db->prefix()."product as p ON p.rowid = l.fk_product";
154 if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
155 $sql .= " LEFT JOIN " . $db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
156 }
157 $alias_societe_perentity = !getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED') ? "s" : "spe";
158 $alias_product_perentity = !getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED') ? "p" : "ppe";
159 $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;
160 $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;
161 $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;
162 $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;
163 $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0";
164 $sql .= " AND l.product_type <= 2";
165 $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
166 if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
167 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
168 }
169 if ($validatemonth && $validateyear) {
170 $sql .= dolSqlDateFilter('f.datef', 0, $validatemonth, $validateyear);
171 }
172
173 dol_syslog('htdocs/accountancy/customer/index.php');
174
175 $result = $db->query($sql);
176 if (!$result) {
177 $error++;
178 setEventMessages($db->lasterror(), null, 'errors');
179 } else {
180 $num_lines = $db->num_rows($result);
181
182 $thirdpartystatic = new Societe($db);
183 $facture_static = new Facture($db);
184 $facture_static_det = new FactureLigne($db);
185 $product_static = new Product($db);
186
187 $i = 0;
188 while ($i < min($num_lines, 10000)) { // No more than 10000 at once
189 $objp = $db->fetch_object($result);
190
191 $thirdpartystatic->id = !empty($objp->socid) ? $objp->socid : 0;
192 $thirdpartystatic->name = !empty($objp->name) ? $objp->name : "";
193 $thirdpartystatic->client = !empty($objp->client) ? $objp->client : "";
194 $thirdpartystatic->fournisseur = !empty($objp->fournisseur) ? $objp->fournisseur : "";
195 $thirdpartystatic->code_client = !empty($objp->code_client) ? $objp->code_client : "";
196 $thirdpartystatic->code_compta_client = !empty($objp->code_compta_client) ? $objp->code_compta_client : "";
197 $thirdpartystatic->code_fournisseur = !empty($objp->code_fournisseur) ? $objp->code_fournisseur : "";
198 $thirdpartystatic->code_compta_fournisseur = !empty($objp->code_compta_fournisseur) ? $objp->code_compta_fournisseur : "";
199 $thirdpartystatic->email = !empty($objp->email) ? $objp->email : "";
200 $thirdpartystatic->country_code = !empty($objp->country_code) ? $objp->country_code : "";
201 $thirdpartystatic->tva_intra = !empty($objp->tva_intra) ? $objp->tva_intra : "";
202 $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)
203
204 $product_static->ref = $objp->product_ref;
205 $product_static->id = $objp->product_id;
206 $product_static->type = $objp->type;
207 $product_static->label = $objp->product_label;
208 $product_static->status = !empty($objp->status) ? $objp->status : 0;
209 $product_static->status_buy = !empty($objp->status_buy) ? $objp->status_buy : 0;
210 $product_static->accountancy_code_sell = $objp->code_sell;
211 $product_static->accountancy_code_sell_intra = $objp->code_sell_intra;
212 $product_static->accountancy_code_sell_export = $objp->code_sell_export;
213 $product_static->accountancy_code_buy = !empty($objp->code_buy) ? $objp->code_buy : "";
214 $product_static->accountancy_code_buy_intra = !empty($objp->code_buy_intra) ? $objp->code_buy_intra : "";
215 $product_static->accountancy_code_buy_export = !empty($objp->code_buy_export) ? $objp->code_buy_export : "";
216 $product_static->tva_tx = $objp->tva_tx_prod;
217
218 $facture_static->ref = $objp->ref;
219 $facture_static->id = $objp->facid;
220 $facture_static->type = $objp->ftype;
221 $facture_static->date = $db->jdate($objp->datef);
222 $facture_static->fk_facture_source = $objp->fk_facture_source;
223
224 $facture_static_det->id = $objp->rowid;
225 $facture_static_det->total_ht = $objp->total_ht;
226 $facture_static_det->tva_tx = $objp->tva_tx_line;
227 $facture_static_det->vat_src_code = $objp->vat_src_code;
228 $facture_static_det->product_type = $objp->type_l;
229 $facture_static_det->desc = $objp->description;
230
231 $accountingAccountArray = array(
232 'dom' => $objp->aarowid,
233 'intra' => $objp->aarowid_intra,
234 'export' => $objp->aarowid_export,
235 'thirdparty' => $objp->aarowid_thirdparty);
236
237 $suggestedid = 0;
238
239 $return = $accountingAccount->getAccountingCodeToBind($thirdpartystatic, $mysoc, $product_static, $facture_static, $facture_static_det, $accountingAccountArray, 'customer');
240 if (!is_array($return) && $return < 0) {
241 setEventMessage($accountingAccount->error, 'errors');
242 } else {
243 $suggestedid = $return['suggestedid'];
244 $suggestedaccountingaccountfor = $return['suggestedaccountingaccountfor'];
245
246 if (!empty($suggestedid) && $suggestedaccountingaccountfor != '' && $suggestedaccountingaccountfor != 'eecwithoutvatnumber') {
247 $suggestedid = $return['suggestedid'];
248 } else {
249 $suggestedid = 0;
250 }
251 }
252
253 if ($suggestedid > 0) {
254 $sqlupdate = "UPDATE ".$db->prefix()."facturedet";
255 $sqlupdate .= " SET fk_code_ventilation = ".((int) $suggestedid);
256 $sqlupdate .= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = ".((int) $facture_static_det->id);
257
258 $resqlupdate = $db->query($sqlupdate);
259 if (!$resqlupdate) {
260 $error++;
261 setEventMessages($db->lasterror(), null, 'errors');
262 $nbbindfailed++;
263 break;
264 } else {
265 $nbbinddone++;
266 }
267 } else {
268 $notpossible++;
269 $nbbindfailed++;
270 }
271
272 $i++;
273 }
274 if ($num_lines > 10000) {
275 $notpossible += ($num_lines - 10000);
276 }
277 }
278
279 if ($error) {
280 $db->rollback();
281 } else {
282 $db->commit();
283 setEventMessages($langs->trans('AutomaticBindingDone', $nbbinddone, $notpossible), null, ($notpossible ? 'warnings' : 'mesgs'));
284 if ($nbbindfailed) {
285 setEventMessages($langs->trans('DoManualBindingForFailedRecord', $nbbindfailed), null, 'warnings');
286 }
287 }
288}
289
290
291/*
292 * View
293 */
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 '<div class="info">';
306print '<span class="">'.$langs->trans("DescVentilCustomer").'</span><br>';
307print '<span class="hideonsmartphone">'.$langs->trans("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToBind")).'<br>';
308print '</span>';
309print '</div>';
310
311if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
312 print info_admin($langs->trans("SorryThisModuleIsNotCompatibleWithTheExperimentalFeatureOfSituationInvoices"), 0, 0, 'warning');
313 print "<br>";
314}
315
316$y = $year_current;
317
318$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>';
319
320print_barre_liste(img_picto('', 'unlink', 'class="paddingright fa-color-unset"').$langs->trans("OverviewOfAmountOfLinesNotBound"), 0, '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1, 0, $buttonbind);
321//print load_fiche_titre($langs->trans("OverviewOfAmountOfLinesNotBound"), $buttonbind, '');
322
323print '<div class="div-table-responsive-no-min">';
324print '<table class="noborder centpercent">';
325print '<tr class="liste_titre"><td class="minwidth100">'.$langs->trans("Account").'</td>';
326for ($i = 1; $i <= 12; $i++) {
327 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
328 if ($j > 12) {
329 $j -= 12;
330 }
331 $cursormonth = $j;
332 if ($cursormonth > 12) {
333 $cursormonth -= 12;
334 }
335 $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
336 $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
337
338 print '<td width="60" class="right">';
339 if (!empty($tmp['mday'])) {
340 $param = 'search_date_startday=1&search_date_startmonth='.$cursormonth.'&search_date_startyear='.$cursoryear;
341 $param .= '&search_date_endday='.$tmp['mday'].'&search_date_endmonth='.$tmp['mon'].'&search_date_endyear='.$tmp['year'];
342 print '<a href="'.DOL_URL_ROOT.'/accountancy/customer/list.php?'.$param.'">';
343 }
344 print $langs->trans('MonthShort'.str_pad((string) $j, 2, '0', STR_PAD_LEFT));
345 if (!empty($tmp['mday'])) {
346 print '</a>';
347 }
348 print '</td>';
349}
350print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
351
352$sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,";
353$sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
354for ($i = 1; $i <= 12; $i++) {
355 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
356 if ($j > 12) {
357 $j -= 12;
358 }
359 $sql .= " SUM(".$db->ifsql("MONTH(f.datef) = ".((string) $j), "fd.total_ht", "0").") AS month".str_pad((string) $j, 2, "0", STR_PAD_LEFT).",";
360 $sql .= " SUM(".$db->ifsql("MONTH(f.datef) = ".((string) $j), "1", "0").") AS nbmonth".str_pad((string) $j, 2, "0", STR_PAD_LEFT).",";
361}
362$sql .= " SUM(fd.total_ht) as total, COUNT(fd.rowid) as nb";
363$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
364$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
365$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
366$sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'";
367$sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
368// Define begin binding date
369if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
370 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
371}
372$sql .= " AND f.fk_statut > 0";
373$sql .= " AND fd.product_type <= 2";
374$sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
375$sql .= " AND aa.account_number IS NULL";
376if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
377 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_SITUATION.")";
378} else {
379 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.",".Facture::TYPE_REPLACEMENT.",".Facture::TYPE_CREDIT_NOTE.",".Facture::TYPE_DEPOSIT.",".Facture::TYPE_SITUATION.")";
380}
381$sql .= " GROUP BY fd.fk_code_ventilation,aa.account_number,aa.label";
382
383dol_syslog('htdocs/accountancy/customer/index.php', LOG_DEBUG);
384$resql = $db->query($sql);
385if ($resql) {
386 $num = $db->num_rows($resql);
387
388 while ($row = $db->fetch_row($resql)) {
389 // TODO When INVOICE_USE_SITUATION = 1, values here are wrong. There is no compensation on bad stored amounts
390 //$situation_ratio = 1;
391 //if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
392 //}
393
394 print '<tr class="oddeven">';
395 print '<td>';
396 if ($row[0] == 'tobind') {
397 //print '<span class="opacitymedium">'.$langs->trans("Unknown").'</span>';
398 } else {
399 print length_accountg($row[0]).' - ';
400 }
401 //print '</td>';
402 //print '<td>';
403 if ($row[0] == 'tobind') {
404 $startmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1);
405 if ($startmonth > 12) {
406 $startmonth -= 12;
407 }
408 $startyear = ($startmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
409 $endmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + 11;
410 if ($endmonth > 12) {
411 $endmonth -= 12;
412 }
413 $endyear = ($endmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
414 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"));
415 } else {
416 print $row[1];
417 }
418 print '</td>';
419
420 for ($i = 2; $i <= 13; $i++) {
421 $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2);
422 if ($cursormonth > 12) {
423 $cursormonth -= 12;
424 }
425 $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
426 $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
427
428 print '<td class="right nowraponall amount" title="'.price($row[2 * $i - 2]).' - '.$row[2 * $i - 1].' lines">';
429 print price($row[2 * $i - 2]);
430 // Add link to make binding
431 if (!empty(price2num($row[2 * $i - 2])) || !empty($row[2 * $i - 1])) {
432 print '<a href="'.$_SERVER['PHP_SELF'].'?action=validatehistory&year='.$y.'&validatemonth='.((int) $cursormonth).'&validateyear='.((int) $cursoryear).'&token='.newToken().'">';
433 print img_picto($langs->trans("ValidateHistory").' ('.$langs->trans('Month'.str_pad((string) $cursormonth, 2, '0', STR_PAD_LEFT)).' '.$cursoryear.')', 'link', 'class="marginleft2"');
434 print '</a>';
435 }
436 print '</td>';
437 }
438
439 print '<td class="right nowraponall amount"><b>'.price($row[26]).'</b></td>';
440
441 print '</tr>';
442 }
443 $db->free($resql);
444
445 if ($num == 0) {
446 print '<tr class="oddeven"><td colspan="15">';
447 print '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
448 print '</td></tr>';
449 }
450} else {
451 print $db->lasterror(); // Show last sql error
452}
453print "</table>\n";
454print '</div>';
455
456
457print '<br>';
458
459
460print_barre_liste(img_picto('', 'link', 'class="paddingright fa-color-unset"').$langs->trans("OverviewOfAmountOfLinesBound"), 0, '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1);
461//print load_fiche_titre($langs->trans("OverviewOfAmountOfLinesBound"), '', '');
462
463print '<div class="div-table-responsive-no-min">';
464print '<table class="noborder centpercent">';
465print '<tr class="liste_titre"><td class="minwidth100">'.$langs->trans("Account").'</td>';
466for ($i = 1; $i <= 12; $i++) {
467 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
468 if ($j > 12) {
469 $j -= 12;
470 }
471 $cursormonth = $j;
472 if ($cursormonth > 12) {
473 $cursormonth -= 12;
474 }
475 $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
476 $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
477
478 print '<td width="60" class="right">';
479 if (!empty($tmp['mday'])) {
480 $param = 'search_date_startday=1&search_date_startmonth='.$cursormonth.'&search_date_startyear='.$cursoryear;
481 $param .= '&search_date_endday='.$tmp['mday'].'&search_date_endmonth='.$tmp['mon'].'&search_date_endyear='.$tmp['year'];
482 print '<a href="'.DOL_URL_ROOT.'/accountancy/customer/lines.php?'.$param.'">';
483 }
484 print $langs->trans('MonthShort'.str_pad((string) $j, 2, '0', STR_PAD_LEFT));
485 if (!empty($tmp['mday'])) {
486 print '</a>';
487 }
488 print '</td>';
489}
490print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
491
492$sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,";
493$sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,";
494for ($i = 1; $i <= 12; $i++) {
495 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
496 if ($j > 12) {
497 $j -= 12;
498 }
499 $sql .= " SUM(".$db->ifsql("MONTH(f.datef) = ".((int) $j), "fd.total_ht", "0").") AS month".str_pad((string) $j, 2, "0", STR_PAD_LEFT).",";
500}
501$sql .= " SUM(fd.total_ht) as total";
502$sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
503$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
504$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."accounting_account as aa ON aa.rowid = fd.fk_code_ventilation";
505$sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'";
506$sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
507// Define begin binding date
508if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
509 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
510}
511$sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
512$sql .= " AND f.fk_statut > 0";
513$sql .= " AND fd.product_type <= 2";
514if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
515 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_SITUATION.")";
516} else {
517 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_DEPOSIT.", ".Facture::TYPE_SITUATION.")";
518}
519$sql .= " AND aa.account_number IS NOT NULL";
520$sql .= " GROUP BY fd.fk_code_ventilation,aa.account_number,aa.label";
521$sql .= ' ORDER BY aa.account_number';
522
523dol_syslog('htdocs/accountancy/customer/index.php');
524$resql = $db->query($sql);
525if ($resql) {
526 $num = $db->num_rows($resql);
527
528 while ($row = $db->fetch_row($resql)) {
529 // TODO When INVOICE_USE_SITUATION = 1, values here are wrong. There is no compensation on bad stored amounts
530 //$situation_ratio = 1;
531 //if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
532 //}
533
534 print '<tr class="oddeven">';
535 print '<td class="tdoverflowmax300"'.(empty($row[1]) ? '' : ' title="'.dol_escape_htmltag($row[1]).'"').'>';
536 if ($row[0] == 'tobind') {
537 //print $langs->trans("Unknown");
538 } else {
539 print length_accountg($row[0]).' - ';
540 }
541 if ($row[0] == 'tobind') {
542 print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/customer/list.php?search_year='.((int) $y), $langs->transnoentitiesnoconv("ToBind"));
543 } else {
544 print $row[1];
545 }
546 print '</td>';
547
548 for ($i = 2; $i <= 13; $i++) {
549 $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2);
550 if ($cursormonth > 12) {
551 $cursormonth -= 12;
552 }
553 $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
554 $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
555
556 print '<td class="right nowraponall amount">';
557 print price($row[$i]);
558 print '</td>';
559 }
560 print '<td class="right nowraponall amount"><b>'.price($row[14]).'</b></td>';
561 print '</tr>';
562 }
563 $db->free($resql);
564
565 if ($num == 0) {
566 print '<tr class="oddeven"><td colspan="15">';
567 print '<span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span>';
568 print '</td></tr>';
569 }
570} else {
571 print $db->lasterror(); // Show last sql error
572}
573print "</table>\n";
574print '</div>';
575
576
577if (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 ?
578 print '<br>';
579 print '<br>';
580
581 print_barre_liste($langs->trans("OtherInfo"), 0, '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1);
582 //print load_fiche_titre($langs->trans("OtherInfo"), '', '');
583
584 print '<div class="div-table-responsive-no-min">';
585 print '<table class="noborder centpercent">';
586 print '<tr class="liste_titre"><td class="left">'.$langs->trans("TotalVente").'</td>';
587 for ($i = 1; $i <= 12; $i++) {
588 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
589 if ($j > 12) {
590 $j -= 12;
591 }
592 print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad((string) $j, 2, '0', STR_PAD_LEFT)).'</td>';
593 }
594 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
595
596 $sql = "SELECT '".$db->escape($langs->trans("TotalVente"))."' AS total,";
597 for ($i = 1; $i <= 12; $i++) {
598 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
599 if ($j > 12) {
600 $j -= 12;
601 }
602 $sql .= " SUM(".$db->ifsql("MONTH(f.datef) = ".((int) $j), "fd.total_ht", "0").") AS month".str_pad((string) $j, 2, "0", STR_PAD_LEFT).",";
603 }
604 $sql .= " SUM(fd.total_ht) as total";
605 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
606 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
607 $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'";
608 $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
609 // Define begin binding date
610 if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
611 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
612 }
613 $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
614 $sql .= " AND f.fk_statut > 0";
615 $sql .= " AND fd.product_type <= 2";
616 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
617 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_SITUATION.")";
618 } else {
619 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_DEPOSIT.", ".Facture::TYPE_SITUATION.")";
620 }
621
622 dol_syslog('htdocs/accountancy/customer/index.php');
623 $resql = $db->query($sql);
624 if ($resql) {
625 $num = $db->num_rows($resql);
626
627 while ($row = $db->fetch_row($resql)) {
628 print '<tr><td>'.$row[0].'</td>';
629 for ($i = 1; $i <= 12; $i++) {
630 print '<td class="right nowraponall amount">'.price($row[$i]).'</td>';
631 }
632 print '<td class="right nowraponall amount"><b>'.price($row[13]).'</b></td>';
633 print '</tr>';
634 }
635 $db->free($resql);
636 } else {
637 print $db->lasterror(); // Show last sql error
638 }
639 print "</table>\n";
640 print '</div>';
641
642 if (isModEnabled('margin')) {
643 print "<br>\n";
644 print '<div class="div-table-responsive-no-min">';
645 print '<table class="noborder centpercent">';
646 print '<tr class="liste_titre"><td>'.$langs->trans("TotalMarge").'</td>';
647 for ($i = 1; $i <= 12; $i++) {
648 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
649 if ($j > 12) {
650 $j -= 12;
651 }
652 print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad((string) $j, 2, '0', STR_PAD_LEFT)).'</td>';
653 }
654 print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
655
656 if (getDolGlobalInt('INVOICE_USE_SITUATION') == 1) {
657 // With old situation invoice setup
658 $sql = "SELECT '".$db->escape($langs->trans("Vide"))."' AS marge,";
659 for ($i = 1; $i <= 12; $i++) {
660 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
661 if ($j > 12) {
662 $j -= 12;
663 }
664 $sql .= " SUM(".$db->ifsql(
665 "MONTH(f.datef) = ".((int) $j),
666 " (".$db->ifsql(
667 "fd.total_ht < 0",
668 " (-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 !
669 " (fd.total_ht - (fd.buy_price_ht * fd.qty * (fd.situation_percent / 100)))"
670 ).")",
671 '0'
672 ).") AS month".str_pad((string) $j, 2, '0', STR_PAD_LEFT).",";
673 }
674 $sql .= " SUM(".$db->ifsql(
675 "fd.total_ht < 0",
676 " (-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 !
677 " (fd.total_ht - (fd.buy_price_ht * fd.qty * (fd.situation_percent / 100)))"
678 ).") as total";
679 } else {
680 $sql = "SELECT '".$db->escape($langs->trans("Vide"))."' AS marge,";
681 for ($i = 1; $i <= 12; $i++) {
682 $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
683 if ($j > 12) {
684 $j -= 12;
685 }
686 $sql .= " SUM(".$db->ifsql(
687 "MONTH(f.datef) = ".((int) $j),
688 " (".$db->ifsql(
689 "fd.total_ht < 0",
690 " (-1 * (abs(fd.total_ht) - (fd.buy_price_ht * fd.qty)))",
691 " (fd.total_ht - (fd.buy_price_ht * fd.qty))"
692 ).")",
693 '0'
694 ).") AS month".str_pad((string) $j, 2, '0', STR_PAD_LEFT).",";
695 }
696 $sql .= " SUM(".$db->ifsql(
697 "fd.total_ht < 0",
698 " (-1 * (abs(fd.total_ht) - (fd.buy_price_ht * fd.qty)))",
699 " (fd.total_ht - (fd.buy_price_ht * fd.qty))"
700 ).") as total";
701 }
702 $sql .= " FROM ".MAIN_DB_PREFIX."facturedet as fd";
703 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON f.rowid = fd.fk_facture";
704 $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'";
705 $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'";
706 // Define begin binding date
707 if (getDolGlobalInt('ACCOUNTING_DATE_START_BINDING')) {
708 $sql .= " AND f.datef >= '".$db->idate(getDolGlobalInt('ACCOUNTING_DATE_START_BINDING'))."'";
709 }
710 $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy
711 $sql .= " AND f.fk_statut > 0";
712 $sql .= " AND fd.product_type <= 2";
713 if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) {
714 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_SITUATION.")";
715 } else {
716 $sql .= " AND f.type IN (".Facture::TYPE_STANDARD.", ".Facture::TYPE_REPLACEMENT.", ".Facture::TYPE_CREDIT_NOTE.", ".Facture::TYPE_DEPOSIT.", ".Facture::TYPE_SITUATION.")";
717 }
718 dol_syslog('htdocs/accountancy/customer/index.php');
719 $resql = $db->query($sql);
720 if ($resql) {
721 $num = $db->num_rows($resql);
722
723 while ($row = $db->fetch_row($resql)) {
724 print '<tr><td>'.$row[0].'</td>';
725 for ($i = 1; $i <= 12; $i++) {
726 print '<td class="right nowraponall amount">'.price(price2num($row[$i])).'</td>';
727 }
728 print '<td class="right nowraponall amount"><b>'.price(price2num($row[13])).'</b></td>';
729 print '</tr>';
730 }
731 $db->free($resql);
732 } else {
733 print $db->lasterror(); // Show last sql error
734 }
735 print "</table>\n";
736 print '</div>';
737 }
738}
739
740// End of page
741llxFooter();
742$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:386
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:623
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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)
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='')
Show information in HTML for admin users or standard users.
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.
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.
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.