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