dolibarr 25.0.0-alpha
fiscalyear_card.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2014-2026 Alexandre Spangaro <alexandre@inovea-conseil.com>
3 * Copyright (C) 2018-2026 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26// Load Dolibarr environment
27require '../../main.inc.php';
36require_once DOL_DOCUMENT_ROOT.'/core/lib/fiscalyear.lib.php';
37require_once DOL_DOCUMENT_ROOT.'/core/class/fiscalyear.class.php';
38
39// Load translation files required by the page
40$langs->loadLangs(array("admin", "compta"));
41
42// Get parameters
43$id = GETPOSTINT('id');
44$ref = GETPOST('ref', 'alpha') ? GETPOST('ref', 'alpha') : GETPOST('label', 'alpha');
45
46$action = GETPOST('action', 'aZ09');
47$confirm = GETPOST('confirm', 'alpha');
48$cancel = GETPOST('cancel', 'alpha');
49$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)).basename(__FILE__, '.php')); // To manage different context of search
50$backtopage = GETPOST('backtopage', 'alpha'); // if not set, a default page will be used
51$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); // if not set, $backtopage will be used
52$dol_openinpopup = GETPOST('dol_openinpopup', 'aZ09');
53
54$error = 0;
55
56// Initialize a technical objects
57$object = new Fiscalyear($db);
58
59// Load object
60include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be 'include', not 'include_once'.
61
62$date_start = dol_mktime(0, 0, 0, GETPOSTINT('fiscalyearmonth'), GETPOSTINT('fiscalyearday'), GETPOSTINT('fiscalyearyear'));
63$date_end = dol_mktime(0, 0, 0, GETPOSTINT('fiscalyearendmonth'), GETPOSTINT('fiscalyearendday'), GETPOSTINT('fiscalyearendyear'));
64
65$permissiontoadd = $user->hasRight('accounting', 'fiscalyear', 'write');
66$permissiontodelete = $user->hasRight('accounting', 'fiscalyear', 'write');
67
68// Security check
69if ($user->socid > 0) {
71}
72if (!$permissiontoadd) { // after this test $permissiontoadd is always true
74}
75
76
77/*
78 * Actions
79 */
80
81$parameters = array();
82$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
83if ($reshook < 0) {
84 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
85}
86
87if ($reshook == 0) {
88 if ($action == 'confirm_delete' && $confirm == "yes") { // @phpstan-ignore-line $permissiontoadd always true
89 $result = $object->fetch($id);
90 $object->oldcopy = dol_clone($object, 2); // @phan-suppress-current-line PhanTypeMismatchProperty
91 $result = $object->delete($user);
92 if ($result >= 0) {
93 header("Location: fiscalyear.php");
94 exit();
95 } else {
96 setEventMessages($object->error, $object->errors, 'errors');
97 }
98 } elseif ($action == 'add') { // @phpstan-ignore-line $permissiontoadd always true
99 if (!GETPOST('cancel', 'alpha')) {
100 $error = 0;
101
102 $object->date_start = $date_start;
103 $object->date_end = $date_end;
104 $object->label = GETPOST('label', 'alpha');
105 $object->status = 0; // A new fiscal year is always open
106 $object->datec = dol_now();
107
108 if (empty($object->date_start) || empty($object->date_end)) {
109 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors');
110 $error++;
111 }
112 if (empty($object->label)) {
113 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
114 $error++;
115 }
116
117 if (!$error) {
118 $db->begin();
119
120 $id = $object->create($user);
121
122 if ($id > 0) {
123 $db->commit();
124
125 header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
126 exit;
127 } else {
128 $db->rollback();
129
130 // Handle overlap error
131 if ($id == -5 && !empty($object->errors[0])) {
132 setEventMessages($langs->trans($object->error, $object->errors[0]), null, 'errors');
133 } else {
134 setEventMessages($object->error, $object->errors, 'errors');
135 }
136 $action = 'create';
137 }
138 } else {
139 $action = 'create';
140 }
141 } else {
142 header("Location: ".DOL_URL_ROOT.'/accountancy/admin/fiscalyear.php');
143 exit();
144 }
145 } elseif ($action == 'update') { // @phpstan-ignore-line $permissiontoadd always true
146 // Update record
147 if (!GETPOST('cancel', 'alpha')) {
148 $result = $object->fetch($id);
149
150 $object->date_start = GETPOST('fiscalyear') ? $date_start : '';
151 $object->date_end = GETPOST('fiscalyearend') ? $date_end : '';
152 $object->label = GETPOST('label', 'alpha');
153 $object->status = GETPOSTINT('status');
154
155 $result = $object->update($user);
156
157 if ($result > 0) {
158 header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
159 exit;
160 } else {
161 // Handle overlap error
162 if ($result == -5 && !empty($object->errors[0])) {
163 setEventMessages($langs->trans($object->error, $object->errors[0]), null, 'errors');
164 } else {
165 setEventMessages($object->error, $object->errors, 'errors');
166 }
167 }
168 } else {
169 header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
170 exit;
171 }
172 } elseif ($action == 'reopen') { // @phpstan-ignore-line $permissiontoadd always true
173 if (getDolGlobalString('ACCOUNTING_CAN_REOPEN_CLOSED_PERIOD')) {
174 $result = $object->fetch($id);
175
176 $object->status = GETPOSTINT('status');
177
178 $result = $object->update($user);
179
180 if ($result > 0) {
181 header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id);
182 exit;
183 } else {
184 setEventMessages($object->error, $object->errors, 'errors');
185 }
186 }
187 }
188}
189
190
191/*
192 * View
193 */
194
195$form = new Form($db);
196
197$title = $langs->trans("Fiscalyear")." - ".$langs->trans("Card");
198if ($action == 'create') {
199 $title = $langs->trans("NewFiscalYear");
200}
201
202$help_url = 'EN:Module_Double_Entry_Accounting#Setup|FR:Module_Comptabilit&eacute;_en_Partie_Double#Configuration';
203
204llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-accountancy page-fiscalyear_card');
205
206// Default values for a new fiscal year
207$defaultstart = '';
208$defaultend = '';
209$defaultlabel = '';
210if ($action == 'create' && empty($date_start)) {
211 $lastend = 0;
212 $sql = "SELECT MAX(date_end) as date_end FROM ".MAIN_DB_PREFIX."accounting_fiscalyear";
213 $sql .= " WHERE entity = ".((int) $conf->entity);
214 $resql = $db->query($sql);
215 if ($resql) {
216 $obj = $db->fetch_object($resql);
217 if ($obj && !empty($obj->date_end)) {
218 $lastend = $db->jdate($obj->date_end);
219 }
220 }
221
222 if ($lastend) {
223 // Day after the end of the previous fiscal year
224 $p = dol_getdate($lastend);
225 $defaultstart = dol_time_plus_duree(dol_mktime(12, 0, 0, $p['mon'], $p['mday'], $p['year']), 1, 'd');
226 } else {
227 // No fiscal year yet: use SOCIETE_FISCAL_MONTH_START (1 = January)
228 $startmonth = max(1, min(12, getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)));
229 $now = dol_getdate(dol_now());
230 $startyear = ($startmonth > $now['mon']) ? $now['year'] - 1 : $now['year'];
231 $defaultstart = dol_mktime(12, 0, 0, $startmonth, 1, $startyear);
232 }
233
234 // End = start + 12 months - 1 day
235 $defaultend = dol_time_plus_duree(dol_time_plus_duree($defaultstart, 12, 'm'), -1, 'd');
236
237 // Label: "2026" if same calendar year, otherwise "2026-2027"
238 $ys = (int) dol_print_date($defaultstart, '%Y');
239 $ye = (int) dol_print_date($defaultend, '%Y');
240 $defaultlabel = ($ys == $ye) ? (string) $ys : $ys.'-'.$ye;
241}
242
243if ($action == 'create') {
244 print load_fiche_titre($title, '', 'object_'.$object->picto);
245
246 print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
247 print '<input type="hidden" name="token" value="'.newToken().'">';
248 print '<input type="hidden" name="action" value="add">';
249
250 print dol_get_fiche_head(array(), '');
251
252 print '<table class="border centpercent tableforfieldcreate">';
253
254 // Label
255 print '<tr><td class="titlefieldcreate fieldrequired">'.$langs->trans("Label").'</td><td>';
256 print '<input name="label" id="label" size="32" value="'.dol_escape_htmltag(GETPOST('label', 'alpha') ? GETPOST('label', 'alpha') : $defaultlabel).'">';
257 print '</td></tr>';
258
259 // Date start
260 print '<tr><td class="fieldrequired">'.$langs->trans("DateStart").'</td><td>';
261 print $form->selectDate($date_start ? $date_start : ($defaultstart ? $defaultstart : -1), 'fiscalyear');
262 print '</td></tr>';
263
264 // Date end
265 print '<tr><td class="fieldrequired">'.$langs->trans("DateEnd").'</td><td>';
266 print $form->selectDate($date_end ? $date_end : ($defaultend ? $defaultend : -1), 'fiscalyearend');
267 print '</td></tr>';
268
269 /*
270 // Status
271 print '<tr>';
272 print '<td class="fieldrequired">' . $langs->trans("Status") . '</td>';
273 print '<td class="valeur">';
274 print $form->selectarray('status', $status2label, GETPOST('status', 'int'));
275 print '</td></tr>';
276 */
277
278 print '</table>'."\n";
279
280 print dol_get_fiche_end();
281
282 $labelposted = GETPOST('label', 'alpha') ? 1 : 0;
283 print '<script>
284 jQuery(document).ready(function() {
285 // The label is "touched" only if the user typed it (or it was posted back after an error)
286 var labelTouched = '.((int) $labelposted).';
287 jQuery("#label").on("input", function() { labelTouched = true; });
288
289 function readDate(prefix) {
290 var d = parseInt(jQuery("#" + prefix + "day").val());
291 var m = parseInt(jQuery("#" + prefix + "month").val());
292 var y = parseInt(jQuery("#" + prefix + "year").val());
293 if (!d || !m || !y) return null;
294 return new Date(y, m - 1, d);
295 }
296
297 function updateLabel() {
298 if (labelTouched) return;
299 var start = readDate("fiscalyear");
300 var end = readDate("fiscalyearend");
301 if (!start || !end) return;
302 var ys = start.getFullYear(), ye = end.getFullYear();
303 jQuery("#label").val(ys === ye ? ys : ys + "-" + ye);
304 }
305
306 function updateEndFromStart() {
307 var start = readDate("fiscalyear");
308 if (!start) return;
309 var end = new Date(start.getFullYear() + 1, start.getMonth(), start.getDate() - 1);
310 jQuery("#fiscalyearendday").val(end.getDate());
311 jQuery("#fiscalyearendmonth").val(end.getMonth() + 1);
312 jQuery("#fiscalyearendyear").val(end.getFullYear());
313 jQuery("#fiscalyearend").datepicker("setDate", end);
314 updateLabel();
315 }
316
317 jQuery("#fiscalyear").on("change", function() { setTimeout(updateEndFromStart, 100); });
318 jQuery("#fiscalyearend").on("change", function() { setTimeout(updateLabel, 100); });
319 });
320 </script>';
321
322 print $form->buttonsSaveCancel("Create");
323
324 print '</form>';
325
326 dol_set_focus('input[name="label"]');
327}
328
329// Part to edit record
330if (($id || $ref) && $action == 'edit') {
331 print load_fiche_titre($langs->trans("Fiscalyear"), '', 'object_'.$object->picto);
332
333 print '<form method="POST" name="update" action="'.$_SERVER["PHP_SELF"].'">'."\n";
334 print '<input type="hidden" name="token" value="'.newToken().'">';
335 print '<input type="hidden" name="action" value="update">';
336 print '<input type="hidden" name="status" value="' . $object->status . '">';
337 print '<input type="hidden" name="id" value="'.$object->id.'">';
338 if ($backtopage) {
339 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
340 }
341 if ($backtopageforcancel) {
342 print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">';
343 }
344
345 print dol_get_fiche_head();
346
347 print '<table class="border centpercent tableforfieldedit">'."\n";
348
349 // Ref
350 print "<tr>";
351 print '<td class="titlefieldcreate titlefield">'.$langs->trans("Ref").'</td><td>';
352 print $object->ref;
353 print '</td></tr>';
354
355 // Label
356 print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td>';
357 print '<input name="label" class="flat" size="32" value="'.dolPrintHTMLForAttribute($object->label).'">';
358 print '</td></tr>';
359
360 // Date start
361 print '<tr><td class="fieldrequired">'.$langs->trans("DateStart").'</td><td>';
362 print $form->selectDate($object->date_start ? $object->date_start : -1, 'fiscalyear');
363 print '</td></tr>';
364
365 // Date end
366 print '<tr><td class="fieldrequired">'.$langs->trans("DateEnd").'</td><td>';
367 print $form->selectDate($object->date_end ? $object->date_end : -1, 'fiscalyearend');
368 print '</td></tr>';
369
370 // Status
371 print '<tr><td>'.$langs->trans("Status").'</td><td>';
372 print $object->getLibStatut(4);
373 print '</td></tr>';
374
375 print '</table>';
376
377 print dol_get_fiche_end();
378
379 print $form->buttonsSaveCancel();
380
381 print '</form>';
382}
383
384// Part to show record
385if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
386 $head = fiscalyear_prepare_head($object);
387
388 print dol_get_fiche_head($head, 'card', $langs->trans("Fiscalyear"), -1, $object->picto);
389
390 $morehtmlref = '<div class="refidno">';
391 $morehtmlref .= '</div>';
392
393 $formconfirm = '';
394
395 // Confirmation to delete
396 if ($action == 'delete') {
397 $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("DeleteFiscalYear"), $langs->trans("ConfirmDeleteFiscalYear"), "confirm_delete", '', 0, 1);
398 }
399
400 // Print form confirm
401 print $formconfirm;
402
403 // Object card
404 // ------------------------------------------------------------
405 $linkback = '<a href="'.DOL_URL_ROOT.'/accountancy/admin/fiscalyear.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
406
407 dol_banner_tab($object, 'label', $linkback, 1, 'label', 'label', $morehtmlref);
408
409 print '<div class="fichecenter">';
410 print '<div class="fichehalfleft">';
411 print '<div class="underbanner clearboth"></div>';
412 print '<table class="border centpercent tableforfield">'."\n";
413
414 // Id
415 print "<tr>";
416 print '<td class="titlefield">'.$langs->trans("Id").'</td><td>';
417 print $object->id;
418 print '</td></tr>';
419
420 // Label
421 print '<tr><td class="tdtop">';
422 print $form->editfieldkey("Label", 'label', $object->label, $object, 0, 'alpha:32');
423 print '</td><td>';
424 print $form->editfieldval("Label", 'label', $object->label, $object, 0, 'alpha:32');
425 print '</td></tr>';
426
427 // Date start
428 print '<tr><td>';
429 print $form->editfieldkey("DateStart", 'date_start', (string) $object->date_start, $object, 0, 'datepicker');
430 print '</td><td>';
431 print $form->editfieldval("DateStart", 'date_start', $object->date_start, $object, 0, 'datepicker');
432 print '</td></tr>';
433
434 // Date end
435 print '<tr><td>';
436 print $form->editfieldkey("DateEnd", 'date_end', (string) $object->date_end, $object, 0, 'datepicker');
437 print '</td><td>';
438 print $form->editfieldval("DateEnd", 'date_end', $object->date_end, $object, 0, 'datepicker');
439 print '</td></tr>';
440
441 print '</table>';
442
443 print '</div>';
444 print '</div>';
445
446 print '<div class="clearboth"></div>';
447
448 print dol_get_fiche_end();
449
450
451 /*
452 * Action bar
453 */
454 if ($user->hasRight('accounting', 'fiscalyear', 'write')) {
455 print '<div class="tabsAction">';
456
457 if (getDolGlobalString('ACCOUNTING_CAN_REOPEN_CLOSED_PERIOD') && $object->status == $object::STATUS_CLOSED) {
458 print dolGetButtonAction($langs->trans("ReOpen"), '', 'reopen', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen&token='.newToken(), 'reopen', (int) $permissiontoadd);
459 }
460
461 print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?action=edit&token='.newToken().'&id='.$id.'">'.$langs->trans('Modify').'</a>';
462
463 print dolGetButtonAction($langs->trans('Delete'), $langs->trans('Delete'), 'delete', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken(), 'delete', (int) $permissiontodelete);
464
465 print '</div>';
466 }
467}
468
469// End of page
470llxFooter();
471$db->close();
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage fiscal year.
Class to manage generation of HTML components Only common components must be here.
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
fiscalyear_prepare_head(Fiscalyear $object)
Prepare array with list of tabs.
$date_start
Variables from include:
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
dol_set_focus($selector, $nooutput=0)
Set focus onto field with selector (similar behaviour of 'autofocus' HTML5 tag)
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.