1<?php
2/* Copyright (C) 2019       Open-DSI    	    <support@open-dsi.fr>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19/**
20 * \file 	    htdocs/accountancy/closure/index.php
21 * \ingroup     Accountancy
22 * \brief 	    Home closure page
23 */
24
25require '../../main.inc.php';
26require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
27require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
28require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php';
29require_once DOL_DOCUMENT_ROOT.'/accountancy/class/bookkeeping.class.php';
30
31// Load translation files required by the page
32$langs->loadLangs(array("compta", "bills", "other", "main", "accountancy"));
33
34$socid = GETPOST('socid', 'int');
35
36$action = GETPOST('action', 'aZ09');
37
38// Security check
39if (empty($conf->accounting->enabled)) {
40	accessforbidden();
41}
42if ($user->socid > 0)
43	accessforbidden();
44if (!$user->rights->accounting->fiscalyear->write)
45	accessforbidden();
46
47$object = new BookKeeping($db);
48
49$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1);
50if (GETPOST("year", 'int')) $year_start = GETPOST("year", 'int');
51else {
52	$year_start = dol_print_date(dol_now(), '%Y');
53	if (dol_print_date(dol_now(), '%m') < $month_start) $year_start--; // If current month is lower that starting fiscal month, we start last year
54}
55$year_end = $year_start + 1;
56$month_end = $month_start - 1;
57if ($month_end < 1)
58{
59	$month_end = 12;
60	$year_end--;
61}
62$search_date_start = dol_mktime(0, 0, 0, $month_start, 1, $year_start);
63$search_date_end = dol_get_last_day($year_end, $month_end);
64$year_current = $year_start;
65
66/*
67 * Actions
68 */
69if ($action == 'validate_movements_confirm' && $user->rights->accounting->fiscalyear->write) {
70	$result = $object->fetchAll();
71
72	if ($result < 0)
73	{
74		setEventMessages($object->error, $object->errors, 'errors');
75	} else {
76		// Specify as export : update field date_validated on selected month/year
77		$error = 0;
78		$db->begin();
79
80		$date_start = dol_mktime(0, 0, 0, GETPOST('date_startmonth', 'int'), GETPOST('date_startday', 'int'), GETPOST('date_startyear', 'int'));
81		$date_end = dol_mktime(23, 59, 59, GETPOST('date_endmonth', 'int'), GETPOST('date_endday', 'int'), GETPOST('date_endyear', 'int'));
82
83		if (is_array($object->lines))
84		{
85			foreach ($object->lines as $movement)
86			{
87				$now = dol_now();
88
89				$sql = " UPDATE ".MAIN_DB_PREFIX."accounting_bookkeeping";
90				$sql .= " SET date_validated = '".$db->idate($now)."'";
91				$sql .= " WHERE rowid = ".$movement->id;
92				$sql .= " AND doc_date >= '" . dol_print_date($date_start, 'dayrfc') . "'";
93                $sql .= " AND doc_date <= '" . dol_print_date($date_end, 'dayrfc') . "'";
94
95				dol_syslog("/accountancy/closure/index.php :: Function validate_movement_confirm Specify movements as validated sql=".$sql, LOG_DEBUG);
96				$result = $db->query($sql);
97				if (!$result)
98				{
99					$error++;
100					break;
101				}
102			}
103		}
104
105		if (!$error)
106		{
107			$db->commit();
108			setEventMessages($langs->trans("AllMovementsWereRecordedAsValidated"), null, 'mesgs');
109		} else {
110			$error++;
111			$db->rollback();
112			setEventMessages($langs->trans("NotAllMovementsCouldBeRecordedAsValidated"), null, 'errors');
113		}
114		header("Location: ".$_SERVER['PHP_SELF']."?year=".$year_start);
115		exit;
116	}
117}
118
119/*
120 * View
121 */
122
123$form = new Form($db);
124$formaccounting = new FormAccounting($db);
125
126llxHeader('', $langs->trans("Closure"));
127
128if ($action == 'validate_movements') {
129	$form_question = array();
130
131	$month = isset($conf->global->SOCIETE_FISCAL_MONTH_START) ? intval($conf->global->SOCIETE_FISCAL_MONTH_START) : 1;
132	$date_start = new DateTime(sprintf('%04d-%02d-%02d', $year_start, $month, 1));
133	$date_end = new DateTime(sprintf('%04d-%02d-%02d', $year_start, $month, 1));
134	$date_end->add(new DateInterval('P1Y'));
135	$date_end->sub(new DateInterval('P1D'));
136
137	$form_question['date_start'] = array(
138		'name' => 'date_start',
139		'type' => 'date',
140		'label' => $langs->trans('DateStart'),
141		'value' => $date_start->format('Y-m-d')
142	);
143	$form_question['date_end'] = array(
144		'name' => 'date_end',
145		'type' => 'date',
146		'label' => $langs->trans('DateEnd'),
147		'value' => $date_end->format('Y-m-d')
148	);
149
150	$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?year='.$year_start, $langs->trans('ValidateMovements'), $langs->trans('DescValidateMovements', $langs->transnoentitiesnoconv("RegistrationInAccounting")), 'validate_movements_confirm', $form_question, '', 1, 300);
151	print $formconfirm;
152}
153
154$textprevyear = '<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_current - 1).'">'.img_previous().'</a>';
155$textnextyear = '&nbsp;<a href="'.$_SERVER["PHP_SELF"].'?year='.($year_current + 1).'">'.img_next().'</a>';
156
157
158print load_fiche_titre($langs->trans("Closure")." ".$textprevyear." ".$langs->trans("Year")." ".$year_start." ".$textnextyear, '', 'title_accountancy');
159
160print '<span class="opacitymedium">'.$langs->trans("DescClosure").'</span><br>';
161print '<br>';
162
163
164$y = $year_current;
165
166$buttonvalidate = '<a class="butAction" name="button_validate_movements" href="'.$_SERVER["PHP_SELF"].'?action=validate_movements&year='.$year_start.'">'.$langs->trans("ValidateMovements").'</a>';
167
168print_barre_liste($langs->trans("OverviewOfMovementsNotValidated"), '', '', '', '', '', '', -1, '', '', 0, $buttonvalidate, '', 0, 1, 1);
169
170print '<div class="div-table-responsive-no-min">';
171print '<table class="noborder centpercent">';
172for ($i = 1; $i <= 12; $i++) {
173	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
174	if ($j > 12) $j -= 12;
175	print '<td width="60" class="right">'.$langs->trans('MonthShort'.str_pad($j, 2, '0', STR_PAD_LEFT)).'</td>';
176}
177print '<td width="60" class="right"><b>'.$langs->trans("Total").'</b></td></tr>';
178
179$sql = "SELECT COUNT(b.rowid) as detail,";
180for ($i = 1; $i <= 12; $i++) {
181	$j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1;
182	if ($j > 12) $j -= 12;
183	$sql .= "  SUM(".$db->ifsql('MONTH(b.doc_date)='.$j, '1', '0').") AS month".str_pad($j, 2, '0', STR_PAD_LEFT).",";
184}
185$sql .= " COUNT(b.rowid) as total";
186$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as b";
187$sql .= " WHERE b.doc_date >= '".$db->idate($search_date_start)."'";
188$sql .= " AND b.doc_date <= '".$db->idate($search_date_end)."'";
189$sql .= " AND b.entity IN (".getEntity('bookkeeping', 0).")"; // We don't share object for accountancy
190$sql .= " AND date_validated IS NULL";
191
192dol_syslog('htdocs/accountancy/closure/index.php sql='.$sql, LOG_DEBUG);
193$resql = $db->query($sql);
194if ($resql) {
195	$num = $db->num_rows($resql);
196
197	while ($row = $db->fetch_row($resql)) {
198		print '<tr class="oddeven">';
199		for ($i = 1; $i <= 12; $i++) {
200			print '<td class="right">'.$row[$i].'</td>';
201		}
202		print '<td class="right"><b>'.$row[13].'</b></td>';
203		print '</tr>';
204	}
205
206	$db->free($resql);
207} else {
208	print $db->lasterror(); // Show last sql error
209}
210print "</table>\n";
211print '</div>';
212
213// End of page
214llxFooter();
215$db->close();
216