dolibarr 25.0.0-alpha
time.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2006-2023 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2010-2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
6 * Copyright (C) 2018 Ferran Marcet <fmarcet@2byte.es>
7 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2019-2021 Christophe Battarel <christophe@altairis.fr>
9 * Copyright (C) 2023 Gauthier VERDOL <gauthier.verdol@atm-consulting.fr>
10 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
11 * Copyright (C) 2024 Vincent de Grandpré <vincent@de-grandpre.quebec>
12 * Copyright (C) 2024 Solution Libre SAS <contact@solution-libre.fr>
13 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
14 *
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * You should have received a copy of the GNU General Public License
26 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27 */
28
35// Load Dolibarr environment
36require '../../main.inc.php';
45'
46@phan-var-force ?string $uploaddir
47';
48require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
49require_once DOL_DOCUMENT_ROOT . '/projet/class/task.class.php';
50require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
51require_once DOL_DOCUMENT_ROOT . '/core/lib/project.lib.php';
52require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
53require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
54require_once DOL_DOCUMENT_ROOT . '/core/class/html.formprojet.class.php';
55require_once DOL_DOCUMENT_ROOT . '/core/class/html.formintervention.class.php';
56require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
57
58// Load translation files required by the page
59$langsLoad = array('projects', 'bills', 'orders', 'companies');
60if (isModEnabled('eventorganization')) {
61 $langsLoad[] = 'eventorganization';
62}
63
64$langs->loadLangs($langsLoad);
65
66$action = GETPOST('action', 'aZ09');
67$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
68$confirm = GETPOST('confirm', 'alpha');
69$cancel = GETPOST('cancel', 'alpha');
70$toselect = GETPOST('toselect', 'array:int'); // Array of ids of elements selected into a list
71$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'timespentlist'; // To manage different context of search
72$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
73$optioncss = GETPOST('optioncss', 'alpha');
74$mode = GETPOST('mode', 'alpha');
75
76$id = GETPOSTINT('id'); // Id of task
77$ref = GETPOST('ref', 'alpha'); // Ref of task
78$projectid = GETPOSTINT('projectid'); // Id of project
79$lineid = GETPOSTINT('lineid'); // Id of time spent line
80$withproject = GETPOSTINT('withproject');
81$project_ref = GETPOST('project_ref', 'alpha');
82$tab = GETPOST('tab', 'aZ09');
83
84$search_day = GETPOSTINT('search_day');
85$search_month = GETPOSTINT('search_month');
86$search_year = GETPOSTINT('search_year');
87$search_date_startday = GETPOSTINT('search_date_startday');
88$search_date_startmonth = GETPOSTINT('search_date_startmonth');
89$search_date_startyear = GETPOSTINT('search_date_startyear');
90$search_date_endday = GETPOSTINT('search_date_endday');
91$search_date_endmonth = GETPOSTINT('search_date_endmonth');
92$search_date_endyear = GETPOSTINT('search_date_endyear');
93$search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear); // Use tzserver
94$search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_endday, $search_date_endyear);
95$search_note = GETPOST('search_note', 'alpha');
96$search_duration = GETPOST('search_duration', 'alpha');
97$search_task_ref = GETPOST('search_task_ref', 'alpha');
98$search_task_label = GETPOST('search_task_label', 'alpha');
99$search_user = GETPOST('search_user', 'intcomma');
100$search_valuebilled = GETPOST('search_valuebilled', 'intcomma');
101$search_product_ref = GETPOST('search_product_ref', 'alpha');
102$search_company = GETPOST('$search_company', 'alpha');
103$search_company_alias = GETPOST('$search_company_alias', 'alpha');
104$search_project_ref = GETPOST('$search_project_ref', 'alpha');
105$search_project_label = GETPOST('$search_project_label', 'alpha');
106$search_timespent_starthour = GETPOSTINT("search_timespent_duration_starthour");
107$search_timespent_startmin = GETPOSTINT("search_timespent_duration_startmin");
108$search_timespent_endhour = GETPOSTINT("search_timespent_duration_endhour");
109$search_timespent_endmin = GETPOSTINT("search_timespent_duration_endmin");
110
111$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
112$sortfield = GETPOST('sortfield', 'aZ09comma');
113$sortorder = GETPOST('sortorder', 'aZ09comma');
114$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
115if (empty($page) || $page == -1) {
116 $page = 0;
117} // If $page is not defined, or '' or -1
118$offset = $limit * $page;
119$pageprev = $page - 1;
120$pagenext = $page + 1;
121if (!$sortfield) {
122 $sortfield = 't.element_date,t.element_datehour,t.rowid';
123}
124if (!$sortorder) {
125 $sortorder = 'DESC,DESC,DESC';
126}
127
128$childids = $user->getAllChildIds(1);
129
130// Initialize a technical object to manage hooks of page. Note that conf->hooks_modules contains an array of hook context
131//$object = new TaskTime($db);
132$hookmanager->initHooks(array('projecttasktime', 'globalcard'));
133
134$object = new Task($db);
135$extrafields = new ExtraFields($db);
136$projectstatic = new Project($db);
137
138// fetch optionals attributes and labels
139$extrafields->fetch_name_optionals_label($projectstatic->table_element);
140$extrafields->fetch_name_optionals_label($object->table_element);
141
142$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
143
144// Load task
145if ($id > 0 || $ref) {
146 $object->fetch($id, $ref);
147 $id = $object->id; // So when doing a search from ref, id is also set correctly.
148}
149
150
151// Security check
152$socid = 0;
153//if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignment.
154if (!$user->hasRight('projet', 'lire')) {
156}
157
158if ($object->fk_project > 0) {
159 restrictedArea($user, 'projet', $object->fk_project, 'projet&project');
160} else {
161 restrictedArea($user, 'projet', 0, 'projet&project');
162 // We check user has permission to see all tasks of all users
163 if (empty($projectid) && !$user->hasRight('projet', 'all', 'lire')) {
164 $search_user = $user->id;
165 }
166}
167
168
169/*
170 * Actions
171 */
172
173$error = 0;
174
175if (GETPOST('cancel', 'alpha')) {
176 $action = '';
177}
178if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_generateinvoice' && $massaction != 'confirm_generateinter') {
179 $massaction = '';
180}
181
182$parameters = array('socid' => $socid, 'projectid' => $projectid);
183$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
184if ($reshook < 0) {
185 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
186}
187
188include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
189
190// Purge search criteria
191if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
192 $search_day = '';
193 $search_month = '';
194 $search_year = '';
195 $search_note = '';
196 $search_duration = '';
197 $search_date_startday = '';
198 $search_date_startmonth = '';
199 $search_date_startyear = '';
200 $search_date_endday = '';
201 $search_date_endmonth = '';
202 $search_date_endyear = '';
203 $search_date_start = '';
204 $search_date_end = '';
205 $search_task_ref = '';
206 $search_company = '';
207 $search_company_alias = '';
208 $search_project_ref = '';
209 $search_project_label = '';
210 $search_task_label = '';
211 $search_user = -1;
212 $search_valuebilled = '';
213 $search_product_ref = '';
214 $toselect = array();
215 $search_array_options = array();
216 $search_timespent_starthour = '';
217 $search_timespent_startmin = '';
218 $search_timespent_endhour = '';
219 $search_timespent_endmin = '';
220 $action = '';
221}
222
223if ($action == 'addtimespent' && GETPOST('button_search_x', 'alpha')) { // Test on permission not required
224 $action = '';
225}
226
227if ($action == 'addtimespent' && $user->hasRight('projet', 'time')) {
228 $timespent_durationhour = GETPOSTINT('timespent_durationhour');
229 $timespent_durationmin = GETPOSTINT('timespent_durationmin');
230 if (empty($timespent_durationhour) && empty($timespent_durationmin)) {
231 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Duration")), null, 'errors');
232 $error++;
233 }
234 if (!GETPOSTINT("userid")) {
235 $langs->load("errors");
236 setEventMessages($langs->trans('ErrorUserNotAssignedToTask'), null, 'errors');
237 $error++;
238 }
239
240 if (!$error) {
241 if ($id || $ref) {
242 $object->fetch($id, $ref);
243 } else {
244 if (!GETPOSTINT('taskid') || GETPOSTINT('taskid') < 0) {
245 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Task")), null, 'errors');
246 $action = 'createtime';
247 $error++;
248 } else {
249 $object->fetch(GETPOSTINT('taskid'));
250 }
251 }
252
253 if (!$error) {
254 $object->fetchProject();
255
256 if (empty($object->project->status)) {
257 setEventMessages($langs->trans("ProjectMustBeValidatedFirst"), null, 'errors');
258 $action = 'createtime';
259 $error++;
260 } else {
261 $object->timespent_note = GETPOST("timespent_note", 'alpha');
262 if (GETPOSTINT('progress') > 0) {
263 $object->progress = GETPOSTINT('progress'); // If progress is -1 (not defined), we do not change value
264 }
265 $object->timespent_duration = GETPOSTINT("timespent_durationhour") * 60 * 60; // We store duration in seconds
266 $object->timespent_duration += (GETPOSTINT('timespent_durationmin') ? GETPOSTINT('timespent_durationmin') : 0) * 60; // We store duration in seconds
267 if (GETPOST("timehour") != '' && GETPOST("timehour") >= 0) { // If hour was entered
268 $object->timespent_date = dol_mktime(GETPOSTINT("timehour"), GETPOSTINT("timemin"), 0, GETPOSTINT("timemonth"), GETPOSTINT("timeday"), GETPOSTINT("timeyear"));
269 $object->timespent_withhour = 1;
270 } else {
271 $object->timespent_date = dol_mktime(12, 0, 0, GETPOSTINT("timemonth"), GETPOSTINT("timeday"), GETPOSTINT("timeyear"));
272 $object->timespent_withhour = 0;
273 }
274 $object->timespent_fk_user = GETPOSTINT("userid");
275 $object->timespent_fk_product = GETPOSTINT("fk_product");
276
277 $result = $object->addTimeSpent($user);
278
279 if ($result >= 0) {
280 setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
281 } else {
282 setEventMessages($langs->trans($object->error), null, 'errors');
283 $error++;
284 }
285 }
286 }
287 } else {
288 $action = 'createtime';
289 }
290}
291
292if (($action == 'updateline' || $action == 'updatesplitline') && !$cancel && $user->hasRight('projet', 'lire')) {
293 if (!GETPOST("new_durationhour") && !GETPOST("new_durationmin")) {
294 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Duration")), null, 'errors');
295 $error++;
296 }
297
298 //If timespent date is not provided in POST (for eg, because in list the column date is hidden) we keep the actual date
299 $timespent_date = dol_mktime(12, 0, 0, GETPOSTINT("timelinemonth"), GETPOSTINT("timelineday"), GETPOSTINT("timelineyear"));
300
301 if (!$error) {
302 if ($id && GETPOSTINT('taskid') != $id) { // GETPOSTINT('taskid') is the id of new task
303 $id_temp = GETPOSTINT('taskid'); // should not overwrite $id
304
305 $object->fetchTimeSpent($lineid);
306 $timespentoldowner = $object->timespent_fk_user; // Owner of the line, before the value of the form is set
307
308 $result = 0;
309
310 $object->fetch($id_temp, $ref);
311
312 $object->timespent_note = GETPOST("timespent_note_line", "alphanohtml");
313 $object->timespent_old_duration = GETPOSTINT("old_duration");
314 $object->timespent_duration = GETPOSTINT("new_durationhour") * 60 * 60; // We store duration in seconds
315 $object->timespent_duration += (GETPOSTINT("new_durationmin") ? GETPOSTINT('new_durationmin') : 0) * 60; // We store duration in seconds
316 if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0 && !empty($timespent_date)) { // If hour was entered
317 $object->timespent_date = dol_mktime(GETPOSTINT("timelinehour"), GETPOSTINT("timelinemin"), 0, GETPOSTINT("timelinemonth"), GETPOSTINT("timelineday"), GETPOSTINT("timelineyear"));
318 $object->timespent_withhour = 1;
319 } elseif (!empty($timespent_date)) {
320 $object->timespent_date = $timespent_date;
321 $object->timespent_withhour = 0;
322 }
323 // If column "by" is hidden, no userid_line is posted; keep the existing fk_user instead of resetting it to 0.
324 if (GETPOSTISSET("userid_line")) {
325 $object->timespent_fk_user = GETPOSTINT("userid_line");
326 }
327 $object->timespent_fk_product = GETPOSTINT("fk_product");
328 $object->timespent_invoiceid = GETPOSTINT("invoiceid");
329 $object->timespent_invoicelineid = GETPOSTINT("invoicelineid");
330
331 $result = 0;
332 if ((in_array($timespentoldowner, $childids) || $user->hasRight('projet', 'all', 'creer')) && (in_array($object->timespent_fk_user, $childids) || $user->hasRight('projet', 'all', 'creer'))) {
333 $result = $object->updateTimeSpent($user);
334 if ($result >= 0) {
335 setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
336 } else {
337 setEventMessages($langs->trans($object->error), null, 'errors');
338 $error++;
339 }
340 }
341 } else {
342 $object->fetch($id, $ref); // $object is Task
343
344 $object->fetchTimeSpent(GETPOSTINT('lineid'));
345 $timespentoldowner = $object->timespent_fk_user; // Owner of the line, before the value of the form is set
346
347 $object->timespent_note = GETPOST("timespent_note_line", "alphanohtml");
348 $object->timespent_old_duration = GETPOSTINT("old_duration");
349 $object->timespent_duration = GETPOSTINT("new_durationhour") * 60 * 60; // We store duration in seconds
350 $object->timespent_duration += (GETPOSTINT("new_durationmin") ? GETPOSTINT('new_durationmin') : 0) * 60; // We store duration in seconds
351
352 if (GETPOST("timelinehour") != '' && GETPOST("timelinehour") >= 0) { // If hour was entered
353 $object->timespent_date = dol_mktime(12, 0, 0, GETPOSTINT("timelinemonth"), GETPOSTINT("timelineday"), GETPOSTINT("timelineyear"));
354 $object->timespent_datehour = dol_mktime(GETPOSTINT("timelinehour"), GETPOSTINT("timelinemin"), 0, GETPOSTINT("timelinemonth"), GETPOSTINT("timelineday"), GETPOSTINT("timelineyear"));
355 $object->timespent_withhour = 1;
356 } elseif (!empty($timespent_date)) {
357 $object->timespent_date = $timespent_date;
358 $object->timespent_datehour = $timespent_date;
359 $object->timespent_withhour = 0;
360 }
361
362 // If column "by" is hidden, no userid_line is posted; keep the existing fk_user instead of resetting it to 0.
363 if (GETPOSTISSET("userid_line")) {
364 $object->timespent_fk_user = GETPOSTINT("userid_line");
365 }
366 $object->timespent_fk_product = GETPOSTINT("fk_product");
367 $object->timespent_invoiceid = GETPOSTINT("invoiceid");
368 $object->timespent_invoicelineid = GETPOSTINT("invoicelineid");
369
370 $result = 0;
371
372 if ((in_array($timespentoldowner, $childids) || $user->hasRight('projet', 'all', 'creer')) && (in_array($object->timespent_fk_user, $childids) || $user->hasRight('projet', 'all', 'creer'))) {
373 $result = $object->updateTimeSpent($user);
374
375 if ($result >= 0) {
376 setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
377 } else {
378 setEventMessages($langs->trans($object->error), null, 'errors');
379 $error++;
380 }
381 }
382 }
383 } else {
384 $action = '';
385 }
386}
387
388if ($action == 'confirm_deleteline' && $confirm == "yes" && ($user->hasRight('projet', 'time') || $user->hasRight('projet', 'all', 'creer'))) {
389 $object->fetchTimeSpent(GETPOSTINT('lineid')); // load properties like $object->timespent_xxx
390
391 if (in_array($object->timespent_fk_user, $childids) || $user->hasRight('projet', 'all', 'creer')) {
392 $result = $object->delTimeSpent($user); // delete line with $object->timespent_id
393
394 if ($result < 0) {
395 $langs->load("errors");
396 setEventMessages($langs->trans($object->error), null, 'errors');
397 $error++;
398 $action = '';
399 } else {
400 setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs');
401 }
402 }
403}
404
405// Retrieve First Task ID of Project if withproject is on to allow project prev next to work
406if (!empty($project_ref) && !empty($withproject)) {
407 if ($projectstatic->fetch(0, $project_ref) > 0) {
408 $tasksarray = $object->getTasksArray(null, null, $projectstatic->id, $socid, 0);
409 if (count($tasksarray) > 0) {
410 $id = $tasksarray[0]->id;
411 } else {
412 header("Location: " . DOL_URL_ROOT . '/projet/tasks.php?id=' . $projectstatic->id . ($withproject ? '&withproject=1' : '') . (empty($mode) ? '' : '&mode=' . $mode));
413 exit;
414 }
415 }
416}
417
418// To show all time lines for project
419$projectidforalltimes = 0;
420if (GETPOSTINT('projectid') > 0) {
421 $projectidforalltimes = GETPOSTINT('projectid');
422
423 $result = $projectstatic->fetch($projectidforalltimes);
424 if (!empty($projectstatic->socid)) {
425 $projectstatic->fetch_thirdparty();
426 }
427 $res = $projectstatic->fetch_optionals();
428
429 // Quick edit for project extrafields (pencil shown on the project summary of this page)
430 if ($action == 'update_extras' && $projectstatic->id > 0) { // Test on permission already done
431 $permissiontoeditextra = $user->hasRight('projet', 'creer');
432 if (GETPOST('attribute', 'aZ09') && isset($extrafields->attributes[$projectstatic->table_element]['perms'][GETPOST('attribute', 'aZ09')])) {
433 $permissiontoeditextra = dol_eval((string) $extrafields->attributes[$projectstatic->table_element]['perms'][GETPOST('attribute', 'aZ09')]);
434 }
435
436 if ($permissiontoeditextra) {
437 $projectstatic->oldcopy = dol_clone($projectstatic, 2);
438
439 $attribute_name = GETPOST('attribute', 'aZ09');
440
441 // Fill array 'array_options' with data from update form
442 $ret = $extrafields->setOptionalsFromPost(null, $projectstatic, $attribute_name);
443 if ($ret < 0) {
444 $error++;
445 }
446
447 if (!$error) {
448 $result = $projectstatic->updateExtraField($attribute_name, 'PROJECT_MODIFY');
449 if ($result < 0) {
450 setEventMessages($projectstatic->error, $projectstatic->errors, 'errors');
451 $error++;
452 }
453 }
454 }
455
456 if ($error) {
457 $action = 'edit_extras';
458 }
459 }
460} elseif (GETPOST('project_ref', 'alpha')) {
461 $projectstatic->fetch(0, GETPOST('project_ref', 'alpha'));
462 $projectidforalltimes = $projectstatic->id;
463 $withproject = 1;
464} elseif ($id > 0) {
465 $object->fetch($id);
466 $result = $projectstatic->fetch($object->fk_project);
467}
468// If not task selected and no project selected
469$allprojectforuser = 0;
470
471if ($id <= 0 && $projectidforalltimes == 0) {
472 $allprojectforuser = $user->id;
473}
474
475// Export selected time spent lines into a CSV file
476if ($massaction == 'exportlines' && !empty($toselect)) {
477 $sql = "SELECT t.rowid, t.element_date, t.element_datehour, t.element_date_withhour, t.element_duration, t.note, t.thm,";
478 $sql .= " s.nom as thirdparty_name, p.ref as project_ref, p.title as project_label, pt.ref as task_ref, pt.label as task_label,";
479 $sql .= " u.lastname, u.firstname, u.login, prod.ref as product_ref, inv.ref as invoice_ref";
480 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as t";
481 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facturedet as il ON il.rowid = t.invoice_line_id";
482 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as inv ON inv.rowid = il.fk_facture";
483 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as prod ON prod.rowid = t.fk_product";
484 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."projet_task as pt ON pt.rowid = t.fk_element";
485 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = pt.fk_projet";
486 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON t.fk_user = u.rowid";
487 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc";
488 $sql .= " WHERE t.elementtype = 'task'";
489 $sql .= " AND t.rowid IN (".$db->sanitize(implode(',', $toselect)).")";
490 $sql .= " AND p.entity IN (".getEntity('project').")";
491 if (!$user->hasRight('projet', 'all', 'lire')) {
492 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $user->socid > 0 ? $user->socid : 0);
493 $sql .= " AND p.rowid IN (".$db->sanitize($projectsListId).")";
494 }
495 if (empty($projectidforalltimes) && empty($allprojectforuser)) {
496 $sql .= " AND t.fk_element = ".((int) $object->id);
497 } elseif (!empty($projectidforalltimes)) {
498 $sql .= " AND pt.fk_projet = ".((int) $projectidforalltimes);
499 }
500 $sql .= $db->order('t.element_date,t.element_datehour,t.rowid', 'ASC,ASC,ASC');
501
502 $resql = $db->query($sql);
503 if ($resql) {
504 require_once DOL_DOCUMENT_ROOT.'/core/modules/export/export_csvutf8.modules.php';
505 $langs->load("salaries");
506
507 $array_fields = array(
508 'date' => 'Date',
509 'thirdparty_name' => 'ThirdParty',
510 'project_ref' => 'RefProject',
511 'project_label' => 'ProjectLabel',
512 'task_ref' => 'RefTask',
513 'task_label' => 'LabelTask',
514 'user' => 'By',
515 'note' => 'Note',
516 'duration' => 'Duration',
517 'duration_hours' => 'DurationInHours',
518 'product_ref' => 'Product',
519 );
520 if (isModEnabled('salaries')) {
521 $array_fields['value'] = 'Value';
522 }
523 $array_fields['invoice_ref'] = 'Invoice';
524 $array_selected = array_fill_keys(array_keys($array_fields), '1');
525
526 $exportcsv = new ExportCsvUtf8($db);
527 $filename = 'timespent_'.dol_print_date(dol_now(), 'dayhourlog').'.csv';
528
529 top_httphead('text/csv');
530 header('Content-Disposition: attachment; filename="'.$filename.'"');
531
532 $exportcsv->open_file('php://output', $langs);
533 $exportcsv->write_header($langs); // @phpstan-ignore-line
534 $exportcsv->write_title($array_fields, $array_selected, $langs, array());
535 while ($obj = $db->fetch_object($resql)) {
536 $record = new stdClass();
537 $record->date = dol_print_date($db->jdate($obj->element_date_withhour ? $obj->element_datehour : $obj->element_date), ($obj->element_date_withhour ? 'dayhour' : 'day'), 'tzuserrel');
538 $record->thirdparty_name = $obj->thirdparty_name;
539 $record->project_ref = $obj->project_ref;
540 $record->project_label = $obj->project_label;
541 $record->task_ref = $obj->task_ref;
542 $record->task_label = $obj->task_label;
543 $record->user = dolGetFirstLastname($obj->firstname, $obj->lastname);
544 $record->note = $obj->note;
545 $record->duration = convertSecondToTime($obj->element_duration, 'allhourmin');
546 $record->duration_hours = price2num($obj->element_duration / 3600, 'MS');
547 $record->product_ref = $obj->product_ref;
548 $record->value = price2num($obj->thm * $obj->element_duration / 3600, 'MT', 1);
549 $record->invoice_ref = $obj->invoice_ref;
550 $exportcsv->write_record($array_selected, $record, $langs, array());
551 }
552 $exportcsv->write_footer($langs); // @phpstan-ignore-line
553 $exportcsv->close_file();
554
555 $db->free($resql);
556 $db->close();
557 exit;
558 } else {
559 setEventMessages($db->lasterror(), null, 'errors');
560 }
561}
562
563if ($action == 'confirm_generateinvoice' && $user->hasRight('facture', 'creer')) {
564 if (!empty($projectstatic->socid)) {
565 $projectstatic->fetch_thirdparty();
566 }
567
568 if (!($projectstatic->thirdparty->id > 0)) {
569 setEventMessages($langs->trans("ThirdPartyRequiredToGenerateInvoice"), null, 'errors');
570 } else {
571 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
572 include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
573 include_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
574
575 $tmpinvoice = new Facture($db);
576 $tmptimespent = new Task($db);
577 $tmpproduct = new Product($db);
578 $fuser = new User($db);
579 $remiseproject = price2num(GETPOST('remiseprojet', 'alphanohtml'));
580 $condidproject = GETPOSTINT('condidproject');
581
582 $db->begin();
583
584 $idprod = GETPOSTINT('productid');
585 $generateinvoicemode = GETPOST('generateinvoicemode', 'alphanohtml');
586 $invoiceToUse = GETPOSTINT('invoiceid');
587
588 $prodDurationHoursBase = 1.0;
589 $product_data_cache = array();
590 if ($idprod > 0) {
591 $result = $tmpproduct->fetch($idprod);
592 if ($result < 0) {
593 $error++;
594 setEventMessages($tmpproduct->error, $tmpproduct->errors, 'errors');
595 }
596
597 $prodDurationHoursBase = $tmpproduct->getProductDurationHours();
598 if ($prodDurationHoursBase < 0) {
599 $error++;
600 $langs->load("errors");
601 setEventMessages(null, $tmpproduct->errors, 'errors');
602 }
603
604 $dataforprice = $tmpproduct->getSellPrice($mysoc, $projectstatic->thirdparty, 0);
605
606 $pu_ht = empty($dataforprice['pu_ht']) ? 0 : $dataforprice['pu_ht'];
607 $txtva = $dataforprice['tva_tx'];
608 $localtax1 = get_localtax($txtva, 1, $projectstatic->thirdparty);
609 $localtax2 = get_localtax($txtva, 2, $projectstatic->thirdparty);
610 } else {
611 $prodDurationHoursBase = 1;
612
613 $pu_ht = 0;
614 $txtva = get_default_tva($mysoc, $projectstatic->thirdparty);
615 $localtax1 = get_default_localtax($mysoc, $projectstatic->thirdparty, 1);
616 $localtax2 = get_default_localtax($mysoc, $projectstatic->thirdparty, 2);
617 }
618
619 $tmpinvoice->socid = $projectstatic->thirdparty->id;
620 $tmpinvoice->date = dol_mktime(GETPOSTINT('rehour'), GETPOSTINT('remin'), GETPOSTINT('resec'), GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
621 $tmpinvoice->fk_project = $projectstatic->id;
622 $tmpinvoice->cond_reglement_id = $condidproject;
623 $tmpinvoice->mode_reglement_id = $projectstatic->thirdparty->mode_reglement_id;
624 $tmpinvoice->fk_account = $projectstatic->thirdparty->fk_account;
625
626 if ($invoiceToUse) {
627 $tmpinvoice->fetch($invoiceToUse);
628 } else {
629 $result = $tmpinvoice->create($user);
630 if ($result <= 0) {
631 $error++;
632 setEventMessages($tmpinvoice->error, $tmpinvoice->errors, 'errors');
633 }
634 }
635
636 if (!$error) {
637 if ($generateinvoicemode == 'onelineperuser') { // 1 line per user (and per product)
638 $arrayoftasks = array();
639 foreach ($toselect as $key => $value) {
640 // Get userid, timepent
641 $object->fetchTimeSpent($value); // $value is ID of 1 line in timespent table
642 if (!array_key_exists($object->timespent_fk_user, $arrayoftasks)) {
643 $arrayoftasks[$object->timespent_fk_user] = [
644 (int) $object->timespent_fk_product => ['timespent' => 0, 'totalvaluetodivideby3600' => 0]
645 ];
646 }
647 $arrayoftasks[$object->timespent_fk_user][(int) $object->timespent_fk_product]['timespent'] += $object->timespent_duration;
648 $arrayoftasks[$object->timespent_fk_user][(int) $object->timespent_fk_product]['totalvaluetodivideby3600'] += ($object->timespent_duration * $object->timespent_thm);
649 }
650
651 foreach ($arrayoftasks as $userid => $data) { // @phan-suppress-current-line PhanEmptyForeach
652 $fuser->fetch($userid);
653 $username = $fuser->getFullName($langs);
654
655 foreach ($data as $fk_product => $timespent_data) {
656 // Define qty per hour
657 $qtyhour = $timespent_data['timespent'] / 3600;
658 $qtyhourtext = convertSecondToTime($timespent_data['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY);
659
660 // Set the unit price we want to sell the time, for this user
661 if (getDolGlobalInt('PROJECT_USE_REAL_COST_FOR_TIME_INVOICING')) {
662 // We set unit price to 0 to force the use of the rate saved during recording
663 $pu_ht = 0;
664 } elseif ($idprod <= 0) {
665 // We want to sell all the time spent with the last hourly rate of user
666 // -> but what about choice user selected ? add idprod test
667 $pu_ht = $fuser->thm;
668 }
669
670 // If no unit price known for user, we use the price recorded when recording timespent.
671 if (empty($pu_ht)) {
672 if ($timespent_data['timespent']) {
673 $pu_ht = price2num(($timespent_data['totalvaluetodivideby3600'] / $timespent_data['timespent']), 'MU');
674 }
675 }
676
677 // Add lines
678 $prodDurationHours = $prodDurationHoursBase;
679 $idprodline = $idprod;
680 $pu_htline = $pu_ht;
681 $txtvaline = $txtva;
682 $localtax1line = $localtax1;
683 $localtax2line = $localtax2;
684
685 // If a particular product/service was defined for the task
686 if (!empty($fk_product) && ($fk_product > 0) && ($fk_product !== $idprod)) {
687 if (!array_key_exists($fk_product, $product_data_cache)) {
688 $result = $tmpproduct->fetch($fk_product);
689 if ($result < 0) {
690 $error++;
691 setEventMessages($tmpproduct->error, $tmpproduct->errors, 'errors');
692 }
693 $prodDurationHours = $tmpproduct->getProductDurationHours();
694 if ($prodDurationHours < 0) {
695 $error++;
696 $langs->load("errors");
697 setEventMessages(null, $tmpproduct->errors, 'errors');
698 // Skip this entry: without it the loop reaches addline() and divides by the duration (#40805).
699 continue;
700 }
701
702 $dataforprice = $tmpproduct->getSellPrice($mysoc, $projectstatic->thirdparty, 0);
703
704 $pu_htline = empty($dataforprice['pu_ht']) ? 0 : $dataforprice['pu_ht'];
705 $txtvaline = $dataforprice['tva_tx'];
706 $localtax1line = $dataforprice['localtax1'];
707 $localtax2line = $dataforprice['localtax2'];
708
709 $product_data_cache[$fk_product] = array('duration' => $prodDurationHours, 'dataforprice' => $dataforprice);
710 } else {
711 $prodDurationHours = $product_data_cache[$fk_product]['duration'];
712 $pu_htline = empty($product_data_cache[$fk_product]['dataforprice']['pu_ht']) ? 0 : $product_data_cache[$fk_product]['dataforprice']['pu_ht'];
713 $txtvaline = $product_data_cache[$fk_product]['dataforprice']['tva_tx'];
714 $localtax1line = $product_data_cache[$fk_product]['dataforprice']['localtax1'];
715 $localtax2line = $product_data_cache[$fk_product]['dataforprice']['localtax2'];
716 }
717 $idprodline = $fk_product;
718 }
719
720 // Add lines. Pass type=1 (service) explicitly so the invoice line is tagged
721 // as a service even when no product is bound to the time entry. Otherwise
722 // the default $type=0 leaks through and the PDF labels the operation as
723 // "Delivery of goods" instead of "Provision of services" (issue #34571).
724 $lineid = $tmpinvoice->addline($langs->trans("TimeSpentForInvoice").' - '.$username . ' : ' . $qtyhourtext, $pu_htline, round($qtyhour / $prodDurationHours, 2), $txtvaline, $localtax1line, $localtax2line, ($idprodline > 0 ? $idprodline : 0), (float) $remiseproject, '', '', 0, 0, 0, 'HT', 0, Product::TYPE_SERVICE);
725 if ($lineid < 0) {
726 $error++;
727 setEventMessages(null, $tmpinvoice->errors, 'errors');
728 }
729
730 // Update lineid into line of timespent
731 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time SET invoice_line_id = '.((int) $lineid).', invoice_id = '.((int) $tmpinvoice->id);
732 $sql .= ' WHERE rowid IN ('.$db->sanitize(implode(',', $toselect)).') AND fk_user = '.((int) $userid);
733 $result = $db->query($sql);
734 if (!$result) {
735 $error++;
736 setEventMessages($db->lasterror(), null, 'errors');
737 break;
738 }
739 }
740 }
741 } elseif ($generateinvoicemode == 'onelineperperiod') { // One line for each time spent line
742 $arrayoftasks = array();
743
744 $withdetail = GETPOST('detail_time_duration', 'alpha');
745 foreach ($toselect as $key => $value) {
746 // Get userid, timepent
747 $object->fetchTimeSpent($value);
748 // $object->id is the task id
749 $ftask = new Task($db);
750 $ftask->fetch($object->id);
751
752 $fuser->fetch($object->timespent_fk_user);
753 $username = $fuser->getFullName($langs);
754
755 $arrayoftasks[$object->timespent_id]['timespent'] = $object->timespent_duration;
756 $arrayoftasks[$object->timespent_id]['totalvaluetodivideby3600'] = $object->timespent_duration * $object->timespent_thm;
757 $arrayoftasks[$object->timespent_id]['note'] = $ftask->ref . ' - ' . $ftask->label . ' - ' . $username;
758 $arrayoftasks[$object->timespent_id]['note'] = dol_concatdesc($arrayoftasks[$object->timespent_id]['note'], $object->timespent_note);
759
760 if (!empty($withdetail)) {
761 if (!empty($object->timespent_withhour)) {
762 $arrayoftasks[$object->timespent_id]['note'] = dol_concatdesc($arrayoftasks[$object->timespent_id]['note'], $langs->trans("Date") . ': ' . dol_print_date($object->timespent_datehour));
763 } else {
764 $arrayoftasks[$object->timespent_id]['note'] = dol_concatdesc($arrayoftasks[$object->timespent_id]['note'], $langs->trans("Date") . ': ' . dol_print_date($object->timespent_date));
765 }
766 $arrayoftasks[$object->timespent_id]['note'] = dol_concatdesc($arrayoftasks[$object->timespent_id]['note'], $langs->trans("Duration") . ': ' . convertSecondToTime($object->timespent_duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY));
767 }
768 $arrayoftasks[$object->timespent_id]['user'] = $object->timespent_fk_user;
769 $arrayoftasks[$object->timespent_id]['fk_product'] = $object->timespent_fk_product;
770 }
771
772 $pu_ht_saved = $pu_ht; // Save the base unit price (price of the selected product/service if any, 0 otherwise)
773 foreach ($arrayoftasks as $timespent_id => $value) {
774 $pu_ht = $pu_ht_saved; // Reset for each line, so a line does not inherit the unit price computed for the previous one
775 $userid = $value['user'];
776 //$pu_ht = $value['timespent'] * $fuser->thm;
777
778 // Define qty per hour
779 $qtyhour = $value['timespent'] / 3600;
780
781 // If no unit price known
782 if (empty($pu_ht)) {
783 if ($value['timespent']) {
784 $pu_ht = price2num(($value['totalvaluetodivideby3600'] / $value['timespent']), 'MU');
785 }
786 }
787
788 // Add lines
789 $prodDurationHours = $prodDurationHoursBase;
790 $idprodline = $idprod;
791 $pu_htline = $pu_ht;
792 $txtvaline = $txtva;
793 $localtax1line = $localtax1;
794 $localtax2line = $localtax2;
795
796 if (!empty($value['fk_product']) && $value['fk_product'] !== $idprod) {
797 if (!array_key_exists($value['fk_product'], $product_data_cache)) {
798 $result = $tmpproduct->fetch($value['fk_product']);
799 if ($result < 0) {
800 $error++;
801 setEventMessages($tmpproduct->error, $tmpproduct->errors, 'errors');
802 }
803 $prodDurationHours = $tmpproduct->getProductDurationHours();
804 if ($prodDurationHours < 0) {
805 $error++;
806 $langs->load("errors");
807 setEventMessages(null, $tmpproduct->errors, 'errors');
808 // Skip this entry: without it the loop reaches addline() and divides by the duration (#40805).
809 continue;
810 }
811
812 $dataforprice = $tmpproduct->getSellPrice($mysoc, $projectstatic->thirdparty, 0);
813
814 $pu_htline = empty($dataforprice['pu_ht']) ? 0 : $dataforprice['pu_ht'];
815 $txtvaline = $dataforprice['tva_tx'];
816 $localtax1line = $dataforprice['localtax1'];
817 $localtax2line = $dataforprice['localtax2'];
818
819 $product_data_cache[$value['fk_product']] = array('duration' => $prodDurationHours, 'dataforprice' => $dataforprice);
820 } else {
821 $prodDurationHours = $product_data_cache[$value['fk_product']]['duration'];
822 $pu_htline = empty($product_data_cache[$value['fk_product']]['dataforprice']['pu_ht']) ? 0 : $product_data_cache[$value['fk_product']]['dataforprice']['pu_ht'];
823 $txtvaline = $product_data_cache[$value['fk_product']]['dataforprice']['tva_tx'];
824 $localtax1line = $product_data_cache[$value['fk_product']]['dataforprice']['localtax1'];
825 $localtax2line = $product_data_cache[$value['fk_product']]['dataforprice']['localtax2'];
826 }
827 $idprodline = $value['fk_product'];
828 }
829 // Pass type=1 (service) explicitly so the invoice line is tagged as a service
830 // even when no product is bound to the time entry. Otherwise the default
831 // $type=0 leaks through and the PDF labels the operation as
832 // "Delivery of goods" instead of "Provision of services" (issue #34571).
833 $lineid = $tmpinvoice->addline($value['note'], $pu_htline, round($qtyhour / $prodDurationHours, 2), $txtvaline, $localtax1line, $localtax2line, ($idprodline > 0 ? $idprodline : 0), (float) $remiseproject, '', '', 0, 0, 0, 'HT', 0, Product::TYPE_SERVICE);
834 if ($lineid < 0) {
835 $error++;
836 setEventMessages(null, $tmpinvoice->errors, 'errors');
837 }
838 //var_dump($lineid);exit;
839
840 // Update lineid into line of timespent
841 $sql = 'UPDATE '.MAIN_DB_PREFIX.'element_time SET invoice_line_id = '.((int) $lineid).', invoice_id = '.((int) $tmpinvoice->id);
842 $sql .= ' WHERE rowid = '.((int) $timespent_id).' AND fk_user = '.((int) $userid);
843 $result = $db->query($sql);
844 if (!$result) {
845 $error++;
846 setEventMessages($db->lasterror(), null, 'errors');
847 break;
848 }
849 }
850 } elseif ($generateinvoicemode == 'onelinepertask') { // One line for each different task
851 $arrayoftasks = array();
852 foreach ($toselect as $key => $value) {
853 // Get userid, timepent
854 $object->fetchTimeSpent($value); // Call method to get list of timespent for a timespent line id (We use the utility method found into Task object)
855 // $object->id is now the task id
856 if (!isset($arrayoftasks[$object->id][(int) $object->timespent_fk_product])) {
857 $arrayoftasks[$object->id][(int) $object->timespent_fk_product] = array('timespent' => 0, 'totalvaluetodivideby3600' => 0, 'ids' => array());
858 }
859 $arrayoftasks[$object->id][(int) $object->timespent_fk_product]['timespent'] += $object->timespent_duration;
860 $arrayoftasks[$object->id][(int) $object->timespent_fk_product]['totalvaluetodivideby3600'] += ($object->timespent_duration * $object->timespent_thm);
861 // Keep the time spent lines that feed this invoice line, so the back link below
862 // points each of them at its own line and not at the last one created.
863 $arrayoftasks[$object->id][(int) $object->timespent_fk_product]['ids'][] = (int) $value;
864 }
865
866 foreach ($arrayoftasks as $task_id => $data) { // @phan-suppress-current-line PhanEmptyForeach
867 $ftask = new Task($db);
868 $ftask->fetch($task_id);
869
870 foreach ($data as $fk_product => $timespent_data) {
871 $qtyhour = $timespent_data['timespent'] / 3600;
872 $qtyhourtext = convertSecondToTime($timespent_data['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY);
873
874 // Add lines
875 $prodDurationHours = $prodDurationHoursBase;
876 $idprodline = $idprod;
877 $pu_htline = $pu_ht;
878 $txtvaline = $txtva;
879 $localtax1line = $localtax1;
880 $localtax2line = $localtax2;
881
882 if (!empty($fk_product) && $fk_product !== $idprod) {
883 if (!array_key_exists($fk_product, $product_data_cache)) {
884 $result = $tmpproduct->fetch($fk_product);
885 if ($result < 0) {
886 $error++;
887 setEventMessages($tmpproduct->error, $tmpproduct->errors, 'errors');
888 }
889 $prodDurationHours = $tmpproduct->getProductDurationHours();
890 if ($prodDurationHours < 0) {
891 $error++;
892 $langs->load("errors");
893 setEventMessages(null, $tmpproduct->errors, 'errors');
894 // Skip this entry: without it the loop reaches addline() and divides by the duration (#40805).
895 continue;
896 }
897
898 $dataforprice = $tmpproduct->getSellPrice($mysoc, $projectstatic->thirdparty, 0);
899
900 $pu_htline = empty($dataforprice['pu_ht']) ? 0 : $dataforprice['pu_ht'];
901 $txtvaline = $dataforprice['tva_tx'];
902 $localtax1line = $dataforprice['localtax1'];
903 $localtax2line = $dataforprice['localtax2'];
904
905 $product_data_cache[$fk_product] = array('duration' => $prodDurationHours, 'dataforprice' => $dataforprice);
906 } else {
907 $prodDurationHours = $product_data_cache[$fk_product]['duration'];
908 $pu_htline = empty($product_data_cache[$fk_product]['dataforprice']['pu_ht']) ? 0 : $product_data_cache[$fk_product]['dataforprice']['pu_ht'];
909 $txtvaline = $product_data_cache[$fk_product]['dataforprice']['tva_tx'];
910 $localtax1line = $product_data_cache[$fk_product]['dataforprice']['localtax1'];
911 $localtax2line = $product_data_cache[$fk_product]['dataforprice']['localtax2'];
912 }
913 $idprodline = $fk_product;
914 }
915
916
917 if ($idprodline > 0) {
918 // If a product is defined, we msut use the $prodDurationHours and $pu_ht of product (already set previously).
919 $pu_ht_for_task = $pu_htline;
920 // If we want to reuse the value of timespent (so use same price than cost price)
921 if (getDolGlobalString('PROJECT_TIME_SPENT_INTO_INVOICE_USE_VALUE')) {
922 $pu_ht_for_task = (float) price2num($timespent_data['totalvaluetodivideby3600'] / $timespent_data['timespent'], 'MU') * $prodDurationHours;
923 }
924 $pa_ht = (float) price2num($timespent_data['totalvaluetodivideby3600'] / $timespent_data['timespent'], 'MU') * $prodDurationHours;
925 } else {
926 // If not product used, we use the hour unit for duration and unit price.
927 $pu_ht_for_task = 0;
928 // If we want to reuse the value of timespent (so use same price than cost price)
929 if (getDolGlobalString('PROJECT_TIME_SPENT_INTO_INVOICE_USE_VALUE')) {
930 $pu_ht_for_task = price2num($timespent_data['totalvaluetodivideby3600'] / $timespent_data['timespent'], 'MU');
931 }
932 $pa_ht = price2num($timespent_data['totalvaluetodivideby3600'] / $timespent_data['timespent'], 'MU');
933 }
934
935 // Add lines
936 $date_start = '';
937 $date_end = '';
938 $lineName = $ftask->ref . ' - ' . $ftask->label;
939 $lineid = $tmpinvoice->addline($lineName, (float) $pu_ht_for_task, (float) price2num($qtyhour / $prodDurationHours, 'MS'), $txtvaline, $localtax1line, $localtax2line, ($idprodline > 0 ? $idprodline : 0), (float) $remiseproject, $date_start, $date_end, 0, 0, 0, 'HT', 0, 1, -1, 0, '', 0, 0, 0, $pa_ht);
940 if ($lineid < 0) {
941 $error++;
942 setEventMessages($tmpinvoice->error, $tmpinvoice->errors, 'errors');
943 break;
944 }
945
946 if (!$error) {
947 // Update lineid into line of timespent
948 $sql = 'UPDATE ' . MAIN_DB_PREFIX . 'element_time SET invoice_line_id = ' . ((int) $lineid) . ', invoice_id = ' . ((int) $tmpinvoice->id);
949 $sql .= ' WHERE rowid IN (' . $db->sanitize(implode(',', $timespent_data['ids'])) . ')';
950 $result = $db->query($sql);
951 if (!$result) {
952 $error++;
953 setEventMessages($db->lasterror(), null, 'errors');
954 break;
955 }
956 }
957 }
958 }
959 }
960 }
961
962 if (!$error) {
963 $urltoinvoice = $tmpinvoice->getNomUrl(0);
964 $mesg = $langs->trans("InvoiceGeneratedFromTimeSpent", '{s1}');
965 $mesg = str_replace('{s1}', $urltoinvoice, $mesg);
966 setEventMessages($mesg, null, 'mesgs');
967
968 $db->commit();
969 } else {
970 $db->rollback();
971 }
972 }
973}
974
975if ($action == 'confirm_generateinter' && $user->hasRight('fichinter', 'creer')) {
976 $langs->load('interventions');
977
978 if (!empty($projectstatic->socid)) {
979 $projectstatic->fetch_thirdparty();
980 }
981
982 if (!($projectstatic->thirdparty->id > 0)) {
983 setEventMessages($langs->trans("ThirdPartyRequiredToGenerateIntervention"), null, 'errors');
984 } else {
985 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
986 include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
987 include_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
988
989
990 require_once DOL_DOCUMENT_ROOT . '/fichinter/class/fichinter.class.php';
991 $tmpinter = new Fichinter($db);
992 $tmptimespent = new Task($db);
993 $fuser = new User($db);
994
995 $db->begin();
996 $interToUse = GETPOSTINT('interid');
997
998
999 $tmpinter->socid = $projectstatic->thirdparty->id;
1000 $tmpinter->date = dol_mktime(GETPOSTINT('rehour'), GETPOSTINT('remin'), GETPOSTINT('resec'), GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
1001 $tmpinter->fk_project = $projectstatic->id;
1002 $tmpinter->description = $projectstatic->title . (!empty($projectstatic->description) ? '-' . $projectstatic->description : '');
1003
1004 if ($interToUse) {
1005 $tmpinter->fetch($interToUse);
1006 } else {
1007 $result = $tmpinter->create($user);
1008 if ($result <= 0) {
1009 $error++;
1010 setEventMessages($tmpinter->error, $tmpinter->errors, 'errors');
1011 }
1012 }
1013
1014 if (!$error) {
1015 $arrayoftasks = array();
1016 foreach ($toselect as $key => $value) {
1017 // Get userid, timespent
1018 $object->fetchTimeSpent($value);
1019 // $object->id is the task id
1020 $arrayoftasks[$object->timespent_id]['id'] = $object->id;
1021 $arrayoftasks[$object->timespent_id]['timespent'] = $object->timespent_duration;
1022 $arrayoftasks[$object->timespent_id]['totalvaluetodivideby3600'] = $object->timespent_duration * $object->timespent_thm;
1023 $arrayoftasks[$object->timespent_id]['note'] = $object->timespent_note;
1024 $arrayoftasks[$object->timespent_id]['date'] = $object->timespent_datehour;
1025 }
1026
1027 foreach ($arrayoftasks as $timespent_id => $value) {
1028 $ftask = new Task($db);
1029 $ftask->fetch($value['id']);
1030 // Define qty per hour
1031 $qtyhour = $value['timespent'] / 3600;
1032 $qtyhourtext = convertSecondToTime($value['timespent'], 'all', $conf->global->MAIN_DURATION_OF_WORKDAY);
1033
1034 // Add lines
1035 $lineid = $tmpinter->addline($user, $tmpinter->id, $ftask->label . (!empty($value['note']) ? ' - ' . $value['note'] : ''), (int) $value['date'], $value['timespent']);
1036
1037 if ($lineid > 0) {
1038 // Link timespent to intervention
1039 $timespent = new TimeSpent($db);
1040 $timespent->fetch($timespent_id);
1041 $timespent->intervention_id = $tmpinter->id;
1042 $timespent->intervention_line_id = $lineid;
1043 $result = $timespent->update($user);
1044 if ($result < 0) {
1045 $error++;
1046 setEventMessages($timespent->error, $timespent->errors, 'errors');
1047 }
1048 }
1049 }
1050 }
1051
1052 if (!$error) {
1053 $urltointer = $tmpinter->getNomUrl(0);
1054 $mesg = $langs->trans("InterventionGeneratedFromTimeSpent", '{s1}');
1055 $mesg = str_replace('{s1}', $urltointer, $mesg);
1056 setEventMessages($mesg, null, 'mesgs');
1057
1058 //var_dump($tmpinvoice);
1059
1060 $db->commit();
1061 } else {
1062 $db->rollback();
1063 }
1064 }
1065}
1066
1067
1068/*
1069 * View
1070 */
1071
1072$form = new Form($db);
1073$formother = new FormOther($db);
1074$formproject = new FormProjets($db);
1075$userstatic = new User($db);
1076//$result = $projectstatic->fetch($object->fk_project);
1077$arrayofselected = is_array($toselect) ? $toselect : array();
1078
1079$title = $object->ref . ' - ' . $langs->trans("TimeSpent");
1080if (!empty($withproject)) {
1081 $title .= ' | ' . $langs->trans("Project") . (!empty($projectstatic->ref) ? ': ' . $projectstatic->ref : '');
1082}
1083$help_url = '';
1084
1085llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-project project-tasks page-task_time');
1086
1087
1088$param = ((!empty($mode) && $mode == 'mine') ? '&mode=mine' : '');
1089if ($search_user) {
1090 $param .= '&search_user=' . ((int) $search_user);
1091}
1092if ($search_month) {
1093 $param .= '&search_month=' . ((int) $search_month);
1094}
1095if ($search_year) {
1096 $param .= '&search_year=' . ((int) $search_year);
1097}
1098
1099
1100if (($id > 0 || !empty($ref)) || $projectidforalltimes > 0 || $allprojectforuser > 0) {
1101 // Project car in view mode
1102 if ($projectidforalltimes > 0) {
1103 $result = $projectstatic->fetch($projectidforalltimes);
1104 if (!empty($projectstatic->socid)) {
1105 $projectstatic->fetch_thirdparty();
1106 }
1107 $res = $projectstatic->fetch_optionals();
1108 } elseif ($object->fetch($id, $ref) > 0) {
1109 if (getDolGlobalString('PROJECT_ALLOW_COMMENT_ON_TASK') && empty($object->comments)) {
1110 $object->fetchComments();
1111 }
1112 $result = $projectstatic->fetch($object->fk_project);
1113 if (getDolGlobalString('PROJECT_ALLOW_COMMENT_ON_PROJECT') && method_exists($projectstatic, 'fetchComments') && empty($projectstatic->comments)) {
1114 $projectstatic->fetchComments();
1115 }
1116 if (!empty($projectstatic->socid)) {
1117 $projectstatic->fetch_thirdparty();
1118 }
1119 $res = $projectstatic->fetch_optionals();
1120
1121 $object->project = clone $projectstatic;
1122 }
1123
1124 $userRead = $projectstatic->restrictedProjectArea($user, 'read');
1125 $linktocreatetime = '';
1126
1127 if ($projectstatic->id > 0) {
1128 if ($withproject) {
1129 // Tabs for project
1130 if (empty($id) || $tab == 'timespent') {
1131 $tab = 'timespent';
1132 } else {
1133 $tab = 'tasks';
1134 }
1135
1136 $head = project_prepare_head($projectstatic);
1137 print dol_get_fiche_head($head, $tab, $langs->trans("Project"), -1, ($projectstatic->public ? 'projectpub' : 'project'));
1138
1139 // Project card
1140
1141 $linkback = '<a href="'.DOL_URL_ROOT.'/projet/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
1142
1143 $morehtmlref = '<div class="refidno">';
1144 // Title
1145 $morehtmlref .= $projectstatic->title;
1146 // Thirdparty
1147 if (!empty($projectstatic->thirdparty->id) && $projectstatic->thirdparty->id > 0) {
1148 $morehtmlref .= '<br>' . $projectstatic->thirdparty->getNomUrl(1, 'project');
1149 }
1150 $morehtmlref .= '</div>';
1151
1152 // Define a complementary filter for search of next/prev ref.
1153 if (!$user->hasRight('projet', 'all', 'lire')) {
1154 $objectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 0);
1155 $projectstatic->next_prev_filter = "rowid:IN:" . $db->sanitize(count($objectsListId) ? implode(',', array_keys($objectsListId)) : '0');
1156 }
1157
1158 dol_banner_tab($projectstatic, 'project_ref', $linkback, 1, 'ref', 'ref', $morehtmlref, $param);
1159
1160 print '<div class="fichecenter">';
1161 print '<div class="fichehalfleft">';
1162 print '<div class="underbanner clearboth"></div>';
1163
1164 print '<table class="border tableforfield centpercent">';
1165
1166 // Usage
1167 if (getDolGlobalString('PROJECT_USE_OPPORTUNITIES') || !getDolGlobalString('PROJECT_HIDE_TASKS') || isModEnabled('eventorganization')) {
1168 print '<tr><td class="tdtop">';
1169 print $langs->trans("Usage");
1170 print '</td>';
1171 print '<td>';
1172 if (getDolGlobalString('PROJECT_USE_OPPORTUNITIES')) {
1173 print '<input type="checkbox" disabled name="usage_opportunity"' . (GETPOSTISSET('usage_opportunity') ? (GETPOST('usage_opportunity', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_opportunity ? ' checked="checked"' : '')) . '"> ';
1174 $htmltext = $langs->trans("ProjectFollowOpportunity");
1175 print $form->textwithpicto($langs->trans("ProjectFollowOpportunity"), $htmltext);
1176 print '<br>';
1177 }
1178 if (!getDolGlobalString('PROJECT_HIDE_TASKS')) {
1179 print '<input type="checkbox" disabled name="usage_task"' . (GETPOSTISSET('usage_task') ? (GETPOST('usage_task', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_task ? ' checked="checked"' : '')) . '"> ';
1180 $htmltext = $langs->trans("ProjectFollowTasks");
1181 print $form->textwithpicto($langs->trans("ProjectFollowTasks"), $htmltext);
1182 print '<br>';
1183 }
1184 if (!getDolGlobalString('PROJECT_HIDE_TASKS') && getDolGlobalString('PROJECT_BILL_TIME_SPENT')) {
1185 print '<input type="checkbox" disabled name="usage_bill_time"' . (GETPOSTISSET('usage_bill_time') ? (GETPOST('usage_bill_time', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_bill_time ? ' checked="checked"' : '')) . '"> ';
1186 $htmltext = $langs->trans("ProjectBillTimeDescription");
1187 print $form->textwithpicto($langs->trans("BillTime"), $htmltext);
1188 print '<br>';
1189 }
1190 if (isModEnabled('eventorganization')) {
1191 print '<input type="checkbox" disabled name="usage_organize_event"' . (GETPOSTISSET('usage_organize_event') ? (GETPOST('usage_organize_event', 'alpha') != '' ? ' checked="checked"' : '') : ($projectstatic->usage_organize_event ? ' checked="checked"' : '')) . '"> ';
1192 $htmltext = $langs->trans("EventOrganizationDescriptionLong");
1193 print $form->textwithpicto($langs->trans("ManageOrganizeEvent"), $htmltext);
1194 }
1195 print '</td></tr>';
1196 }
1197
1198 // Budget
1199 print '<tr><td>' . $langs->trans("Budget") . '</td><td>';
1200 if (!is_null($projectstatic->budget_amount) && strcmp($projectstatic->budget_amount, '')) {
1201 print '<span class="amount">' . price($projectstatic->budget_amount, 0, $langs, 1, 0, 0, $conf->currency) . '</span>';
1202 }
1203 print '</td></tr>';
1204
1205 // Date start - end project
1206 print '<tr><td>' . $langs->trans("Dates") . '</td><td>';
1207 $start = dol_print_date($projectstatic->date_start, 'day');
1208 print($start ? $start : '?');
1209 $end = dol_print_date($projectstatic->date_end, 'day');
1210 print ' - ';
1211 print($end ? $end : '?');
1212 if ($projectstatic->hasDelay()) {
1213 print img_warning("Late");
1214 }
1215 print '</td></tr>';
1216
1217 // Visibility
1218 print '<tr><td class="titlefield">' . $langs->trans("Visibility") . '</td><td>';
1219 if ($projectstatic->public) {
1220 print img_picto($langs->trans('SharedProject'), 'world', 'class="paddingrightonly"');
1221 print $langs->trans('SharedProject');
1222 } else {
1223 print img_picto($langs->trans('PrivateProject'), 'private', 'class="paddingrightonly"');
1224 print $langs->trans('PrivateProject');
1225 }
1226 print '</td></tr>';
1227
1228 // Other attributes
1229 $cols = 2;
1230 $savobject = $object;
1231 $object = $projectstatic;
1232 // On this page, the 'id' GET parameter is the task id, not the project id, so force the
1233 // edit link/form of the project extrafields to use 'projectid' instead, and keep 'withproject'
1234 // so the project summary (this whole block) stays visible after the edit link is followed.
1235 $forcefieldid = 'projectid';
1236 $moreparam = '&withproject=1';
1237 include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
1238 unset($forcefieldid, $moreparam);
1239 $object = $savobject;
1240
1241 print '</table>';
1242
1243 print '</div>';
1244 print '<div class="fichehalfright">';
1245 print '<div class="underbanner clearboth"></div>';
1246
1247 print '<table class="border tableforfield centpercent">';
1248
1249 // Categories
1250 if (isModEnabled('category')) {
1251 print '<tr><td class="valignmiddle">' . $langs->trans("Categories") . '</td><td>';
1252 print $form->showCategories($projectstatic->id, 'project', 1);
1253 print "</td></tr>";
1254 }
1255
1256 // Description
1257 print '<tr><td class="titlefield'.($projectstatic->description ? ' noborderbottom' : '').'" colspan="2">'.$langs->trans("Description").'</td></tr>';
1258 if ($projectstatic->description) {
1259 print '<tr><td class="nottitleforfield" colspan="2">';
1260 print '<div class="longmessagecut">';
1261 print dolPrintHTML($projectstatic->description);
1262 print '</div>';
1263 print '</td></tr>';
1264 }
1265
1266 print '</table>';
1267
1268 print '</div>';
1269 print '</div>';
1270
1271 print '<div class="clearboth"></div>';
1272
1273 print dol_get_fiche_end();
1274
1275 print '<br>';
1276 }
1277
1278 // Link to create time
1279 $linktocreatetimeBtnStatus = 0;
1280 $linktocreatetimeUrl = '';
1281 $linktocreatetimeHelpText = '';
1282 if ($user->hasRight('projet', 'time')) {
1283 if ($projectstatic->public || $userRead > 0) {
1284 $linktocreatetimeBtnStatus = 1;
1285
1286 if (!empty($projectidforalltimes)) {
1287 // We are on tab 'Time Spent' of project
1288 $backtourl = $_SERVER['PHP_SELF'] . '?projectid=' . $projectstatic->id . ($withproject ? '&withproject=1' : '');
1289 $linktocreatetimeUrl = $_SERVER['PHP_SELF'] . '?' . ($withproject ? 'withproject=1' : '') . '&projectid=' . $projectstatic->id . '&action=createtime&token=' . newToken() . $param . '&backtopage=' . urlencode($backtourl);
1290 } else {
1291 // We are on tab 'Time Spent' of task
1292 $backtourl = $_SERVER['PHP_SELF'] . '?id=' . $object->id . ($withproject ? '&withproject=1' : '');
1293 $linktocreatetimeUrl = $_SERVER['PHP_SELF'] . '?' . ($withproject ? 'withproject=1' : '') . ($object->id > 0 ? '&id=' . $object->id : '&projectid=' . $projectstatic->id) . '&action=createtime&token=' . newToken() . $param . '&backtopage=' . urlencode($backtourl);
1294 }
1295 } else {
1296 $linktocreatetimeBtnStatus = -2;
1297 $linktocreatetimeHelpText = $langs->trans("NotOwnerOfProject");
1298 }
1299 } else {
1300 $linktocreatetimeBtnStatus = -2;
1301 $linktocreatetimeHelpText = $langs->trans("NotEnoughPermissions");
1302 }
1303
1304 $paramsbutton = array('morecss' => 'reposition');
1305 $linktocreatetime = dolGetButtonTitle($langs->trans('AddTimeSpent'), $linktocreatetimeHelpText, 'fa fa-plus-circle', $linktocreatetimeUrl, '', $linktocreatetimeBtnStatus, $paramsbutton);
1306 }
1307
1308 $massactionbutton = '';
1309 $arrayofmassactions = array();
1310
1311 if ($projectstatic->id > 0) {
1312 // If we are on a given project.
1313 if ($projectstatic->usage_bill_time) {
1314 $arrayofmassactions = array(
1315 'generateinvoice' => img_picto('', 'bill', 'class="pictofixedwidth"').$langs->trans("GenerateBill"),
1316 //'builddoc'=>$langs->trans("PDFMerge"),
1317 );
1318 }
1319 if (isModEnabled('intervention') && $user->hasRight('ficheinter', 'creer')) {
1320 $langs->load("interventions");
1321 $arrayofmassactions['generateinter'] = img_picto('', 'intervention', 'class="pictofixedwidth"').$langs->trans("GenerateInter");
1322 }
1323 }
1324 $arrayofmassactions['exportlines'] = img_picto('', 'download', 'class="pictofixedwidth"').$langs->trans("ExportLinesToFile");
1325 if (in_array($massaction, array('presend', 'predelete', 'generateinvoice', 'generateinter'))) {
1326 $arrayofmassactions = array();
1327 }
1328 $massactionbutton = $form->selectMassAction('', $arrayofmassactions);
1329
1330 $formconfirm = '';
1331
1332 // Task
1333
1334 // Show section with information of task. If id of task is not defined and project id defined, then $projectidforalltimes is not empty.
1335 if (empty($projectidforalltimes) && empty($allprojectforuser)) {
1336 $head = task_prepare_head($object);
1337 print dol_get_fiche_head($head, 'task_time', $langs->trans("Task"), -1, 'projecttask', 0, '', 'reposition');
1338
1339 $param = (GETPOST('withproject') ? '&withproject=1' : '');
1340 $linkback = GETPOST('withproject') ? '<a href="'.DOL_URL_ROOT.'/projet/tasks.php?id='.$projectstatic->id.'">'.$langs->trans("BackToList").'</a>' : '';
1341
1342 if ($action == 'deleteline') {
1343 $urlafterconfirm = $_SERVER["PHP_SELF"] . "?" . ($object->id > 0 ? "id=" . $object->id : 'projectid=' . $projectstatic->id) . '&lineid=' . GETPOSTINT("lineid") . $param;
1344 $formconfirm .= $form->formconfirm($urlafterconfirm, $langs->trans("DeleteATimeSpent"), $langs->trans("ConfirmDeleteATimeSpent"), "confirm_deleteline", '', '', 1);
1345 }
1346
1347 if (!GETPOST('withproject') || empty($projectstatic->id)) {
1348 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
1349 $object->next_prev_filter = "fk_projet:IN:" . $db->sanitize($projectsListId);
1350 } else {
1351 $object->next_prev_filter = "fk_projet:=:" . ((int) $projectstatic->id);
1352 }
1353
1354 $morehtmlref = '';
1355
1356 // Project
1357 if (empty($withproject)) {
1358 $morehtmlref .= '<div class="refidno">';
1359 $morehtmlref .= $langs->trans("Project") . ': ';
1360 $morehtmlref .= $projectstatic->getNomUrl(1);
1361 $morehtmlref .= '<br>';
1362
1363 // Third party
1364 $morehtmlref .= $langs->trans("ThirdParty") . ': ';
1365 if (!empty($projectstatic->thirdparty) && is_object($projectstatic->thirdparty)) {
1366 $morehtmlref .= $projectstatic->thirdparty->getNomUrl(1);
1367 }
1368 $morehtmlref .= '</div>';
1369 }
1370
1371 dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, $param);
1372
1373 print '<div class="fichecenter">';
1374 print '<div class="fichehalfleft">';
1375
1376 print '<div class="underbanner clearboth"></div>';
1377 print '<table class="border centpercent tableforfield">';
1378
1379 // Task parent
1380 print '<tr><td>' . $langs->trans("ParentTask") . '</td><td>';
1381 if ($object->fk_task_parent > 0) {
1382 $tasktmp = new Task($db);
1383 $tasktmp->fetch($object->fk_task_parent);
1384 print $tasktmp->getNomUrl(1);
1385 }
1386 print '</td></tr>';
1387
1388 // Date start - Date end task
1389 print '<tr><td class="titlefield">' . $langs->trans("DateStart") . ' - ' . $langs->trans("Deadline") . '</td><td>';
1390 $start = dol_print_date($object->date_start, 'dayhour');
1391 print($start ? $start : '?');
1392 $end = dol_print_date($object->date_end, 'dayhour');
1393 print ' - ';
1394 print($end ? $end : '?');
1395 if ($object->hasDelay()) {
1396 print img_warning("Late");
1397 }
1398 print '</td></tr>';
1399
1400 // Planned workload
1401 print '<tr><td>' . $langs->trans("PlannedWorkload") . '</td><td>';
1402 if ($object->planned_workload) {
1403 print convertSecondToTime($object->planned_workload, 'allhourmin');
1404 }
1405 print '</td></tr>';
1406
1407 print '</table>';
1408 print '</div>';
1409
1410 print '<div class="fichehalfright">';
1411
1412 print '<div class="underbanner clearboth"></div>';
1413 print '<table class="border tableforfield centpercent">';
1414
1415 // Progress declared
1416 print '<tr><td class="titlefield">' . $langs->trans("ProgressDeclared") . '</td><td>';
1417 print $object->progress != '' ? $object->progress . ' %' : '';
1418 print '</td></tr>';
1419
1420 // Progress calculated
1421 print '<tr><td>' . $langs->trans("ProgressCalculated") . '</td><td>';
1422 if ($object->planned_workload) {
1423 $tmparray = $object->getSummaryOfTimeSpent();
1424 if ($tmparray['total_duration'] > 0) {
1425 print round($tmparray['total_duration'] / $object->planned_workload * 100, 2) . ' %';
1426 } else {
1427 print '0 %';
1428 }
1429 } else {
1430 print '<span class="opacitymedium">' . $langs->trans("WorkloadNotDefined") . '</span>';
1431 }
1432 print '</td>';
1433
1434 print '</tr>';
1435
1436 print '</table>';
1437
1438 print '</div>';
1439
1440 print '</div>';
1441 print '<div class="clearboth"></div>';
1442
1443 print dol_get_fiche_end();
1444 } else {
1445 if ($action == 'deleteline') {
1446 $urlafterconfirm = $_SERVER["PHP_SELF"] . "?" . ($projectstatic->id > 0 ? 'projectid=' . $projectstatic->id : ($object->id > 0 ? "id=" . $object->id : '')) . '&lineid=' . GETPOSTINT("lineid") . ($withproject ? '&withproject=1' : ''). "&contextpage=" . urlencode($contextpage).$param;
1447 $formconfirm .= $form->formconfirm($urlafterconfirm, $langs->trans("DeleteATimeSpent"), $langs->trans("ConfirmDeleteATimeSpent"), "confirm_deleteline", '', '', 1);
1448 }
1449 }
1450
1451 // Call Hook formConfirm
1452 $parameters = array('formConfirm' => $formconfirm, "projectstatic" => $projectstatic, "withproject" => $withproject);
1453 $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1454 if (empty($reshook)) {
1455 $formconfirm .= $hookmanager->resPrint;
1456 } elseif ($reshook > 0) {
1457 $formconfirm = $hookmanager->resPrint;
1458 }
1459
1460
1461 if ($projectstatic->id > 0 || $allprojectforuser > 0) {
1462 // Initialize a technical object to manage hooks. Note that conf->hooks_modules contains array
1463 $hookmanager->initHooks(array('tasktimelist'));
1464
1465 // Print form confirm
1466 print $formconfirm;
1467
1468 // Definition of fields for list
1469 $arrayfields = array();
1470 $arrayfields['t.element_date'] = array('label' => $langs->trans("Date"), 'checked' => '1');
1471 $arrayfields['p.fk_soc'] = array('label' => $langs->trans("ThirdParty"), 'type' => 'integer:Societe:/societe/class/societe.class.php:1','checked' => '1');
1472 $arrayfields['s.name_alias'] = array('label' => $langs->trans("AliasNameShort"), 'type' => 'integer:Societe:/societe/class/societe.class.php:1');
1473 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
1474 if (! empty($allprojectforuser)) {
1475 $arrayfields['p.project_ref'] = ['label' => $langs->trans('RefProject'), 'checked' => '1'];
1476 $arrayfields['p.project_label'] = ['label' => $langs->trans('ProjectLabel'), 'checked' => '1'];
1477 }
1478 $arrayfields['t.element_ref'] = array('label' => $langs->trans("RefTask"), 'checked' => '1');
1479 $arrayfields['t.element_label'] = array('label' => $langs->trans("LabelTask"), 'checked' => '1');
1480 }
1481 $arrayfields['author'] = array('label' => $langs->trans("By"), 'checked' => '1');
1482 $arrayfields['t.note'] = array('label' => $langs->trans("Note"), 'checked' => '1');
1483 $arrayfields['t.tms'] = array('label' => $langs->trans("DateModification"), 'checked' => '0');
1484 if (isModEnabled('service') && !empty($projectstatic->thirdparty) && $projectstatic->thirdparty->id > 0 && $projectstatic->usage_bill_time) {
1485 $arrayfields['t.fk_product'] = array('label' => $langs->trans("Product"), 'checked' => '1');
1486 }
1487 $arrayfields['t.element_duration'] = array('label' => $langs->trans("Duration"), 'checked' => '1');
1488 $arrayfields['t.fk_product'] = array('label' => $langs->trans("Product"), 'checked' => '0', 'enabled' => (string) (int) (((getDolGlobalInt('PROJECT_HIDE_TASKS') || !getDolGlobalInt('PROJECT_BILL_TIME_SPENT')) ? 0 : 1) && $projectstatic->usage_bill_time));
1489 $arrayfields['value'] = array('label' => $langs->trans("Value"), 'checked' => '1', 'enabled' => (string) (int) isModEnabled("salaries"));
1490 $arrayfields['valuebilled'] = array('label' => $langs->trans("Billed"), 'checked' => '1', 'enabled' => (string) (int) (((getDolGlobalInt('PROJECT_HIDE_TASKS') || !getDolGlobalInt('PROJECT_BILL_TIME_SPENT')) ? 0 : 1) && $projectstatic->usage_bill_time));
1491 // Extra fields
1492 include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
1493
1494 $arrayfields = dol_sort_array($arrayfields, 'position');
1495
1496 $param = '';
1497 if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
1498 $param .= '&contextpage=' . urlencode($contextpage);
1499 }
1500 if ($limit > 0 && $limit != $conf->liste_limit) {
1501 $param .= '&limit='.((int) $limit);
1502 }
1503 if ($id > 0) {
1504 $param .= '&id='.((int) $id);
1505 }
1506 if ($search_month > 0) {
1507 $param .= '&search_month=' . urlencode((string) ($search_month));
1508 }
1509 if ($search_year > 0) {
1510 $param .= '&search_year=' . urlencode((string) ($search_year));
1511 }
1512 if (!empty($search_user)) { // We keep param if -1 because default value is forced to user id if not set
1513 $param .= '&search_user='.urlencode($search_user);
1514 }
1515 if ($search_task_ref != '') {
1516 $param .= '&search_task_ref=' . urlencode($search_task_ref);
1517 }
1518 if ($search_company != '') {
1519 $param .= '&search_company=' . urlencode($search_company);
1520 }
1521 if ($search_company_alias != '') {
1522 $param .= '&search_company_alias=' . urlencode($search_company_alias);
1523 }
1524 if ($search_project_ref != '') {
1525 $param .= '&search_project_ref=' . urlencode($search_project_ref);
1526 }
1527 if ($search_project_label != '') {
1528 $param .= '&search_project_label=' . urlencode($search_project_label);
1529 }
1530 if ($search_task_label != '') {
1531 $param .= '&search_task_label=' . urlencode($search_task_label);
1532 }
1533 if ($search_note != '') {
1534 $param .= '&search_note=' . urlencode($search_note);
1535 }
1536 if ($search_duration != '') {
1537 $param .= '&search_field2=' . urlencode((string) ($search_duration));
1538 }
1539 if ($optioncss != '') {
1540 $param .= '&optioncss=' . urlencode($optioncss);
1541 }
1542 if ($search_date_startday) {
1543 $param .= '&search_date_startday=' . urlencode((string) ($search_date_startday));
1544 }
1545 if ($search_date_startmonth) {
1546 $param .= '&search_date_startmonth=' . urlencode((string) ($search_date_startmonth));
1547 }
1548 if ($search_date_startyear) {
1549 $param .= '&search_date_startyear=' . urlencode((string) ($search_date_startyear));
1550 }
1551 if ($search_date_endday) {
1552 $param .= '&search_date_endday=' . urlencode((string) ($search_date_endday));
1553 }
1554 if ($search_date_endmonth) {
1555 $param .= '&search_date_endmonth=' . urlencode((string) ($search_date_endmonth));
1556 }
1557 if ($search_date_endyear) {
1558 $param .= '&search_date_endyear=' . urlencode((string) ($search_date_endyear));
1559 }
1560 if ($search_timespent_starthour) {
1561 $param .= '&search_timespent_duration_starthour=' . urlencode((string) ($search_timespent_starthour));
1562 }
1563 if ($search_timespent_startmin) {
1564 $param .= '&search_timespent_duration_startmin=' . urlencode((string) ($search_timespent_startmin));
1565 }
1566 if ($search_timespent_endhour) {
1567 $param .= '&search_timespent_duration_endhour=' . urlencode((string) ($search_timespent_endhour));
1568 }
1569 if ($search_timespent_endmin) {
1570 $param .= '&search_timespent_duration_endmin=' . urlencode((string) ($search_timespent_endmin));
1571 }
1572 // Add $param from extra fields
1573 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
1574 if ($id) {
1575 $param .= '&id=' . urlencode((string) ($id));
1576 }
1577 if ($projectid) {
1578 $param .= '&projectid=' . urlencode((string) ($projectid));
1579 }
1580 if ($withproject) {
1581 $param .= '&withproject=' . urlencode((string) ($withproject));
1582 }
1583 // Add $param from hooks
1584 $parameters = array('param' => &$param);
1585 $reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1586 $param .= $hookmanager->resPrint;
1587
1588 print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
1589 if ($optioncss != '') {
1590 print '<input type="hidden" name="optioncss" value="' . $optioncss . '">';
1591 }
1592 print '<input type="hidden" name="token" value="' . newToken() . '">';
1593 print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
1594 if ($action == 'editline') {
1595 print '<input type="hidden" name="action" value="updateline">';
1596 } elseif ($action == 'splitline') {
1597 print '<input type="hidden" name="action" value="updatesplitline">';
1598 } elseif ($action == 'createtime' && $user->hasRight('projet', 'time')) {
1599 print '<input type="hidden" name="action" value="addtimespent">';
1600 } elseif ($massaction == 'generateinvoice' && $user->hasRight('facture', 'creer')) {
1601 print '<input type="hidden" name="action" value="confirm_generateinvoice">';
1602 } elseif ($massaction == 'generateinter' && $user->hasRight('ficheinter', 'creer')) {
1603 print '<input type="hidden" name="action" value="confirm_generateinter">';
1604 } else {
1605 print '<input type="hidden" name="action" value="list">';
1606 }
1607 print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
1608 print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
1609
1610 // Carry the task id through the filter submit so that the timespent list
1611 // stays scoped to the current task instead of falling back to the global view.
1612 print '<input type="hidden" name="id" value="' . ((int) $id) . '">';
1613 print '<input type="hidden" name="projectid" value="' . $projectidforalltimes . '">';
1614 print '<input type="hidden" name="withproject" value="' . $withproject . '">';
1615 print '<input type="hidden" name="tab" value="' . $tab . '">';
1616 print '<input type="hidden" name="page_y" value="">';
1617
1618 // Form to convert time spent into invoice
1619 if ($massaction == 'generateinvoice') {
1620 if (!empty($projectstatic->thirdparty) && $projectstatic->thirdparty->id > 0) {
1621 print '<table class="noborder centerpercent">';
1622 print '<tr>';
1623 print '<td class="titlefield">';
1624 print $langs->trans('DateInvoice');
1625 print '</td>';
1626 print '<td>';
1627 print $form->selectDate('', '', 0, 0, 0, '', 1, 1);
1628 print '</td>';
1629 print '</tr>';
1630
1631 print '<tr>';
1632 print '<td>';
1633 print $langs->trans('Mode');
1634 print '</td>';
1635 print '<td>';
1636 $tmparray = array(
1637 'onelineperuser' => 'OneLinePerUser',
1638 'onelinepertask' => 'OneLinePerTask',
1639 'onelineperperiod' => 'OneLinePerTimeSpentLine',
1640 );
1641 print $form->selectarray('generateinvoicemode', $tmparray, 'onelineperuser', 0, 0, 0, '', 1);
1642 print "\n" . '<script type="text/javascript">';
1643 print '
1644 $(document).ready(function () {
1645 setDetailVisibility();
1646 $("#generateinvoicemode").change(function() {
1647 setDetailVisibility();
1648 });
1649 function setDetailVisibility() {
1650 generateinvoicemode = $("#generateinvoicemode option:selected").val();
1651 if (generateinvoicemode=="onelineperperiod") {
1652 $("#detail_time_duration").show();
1653 } else {
1654 $("#detail_time_duration").hide();
1655 }
1656 }
1657 });
1658 ';
1659 print '</script>' . "\n";
1660 print '<span style="display:none" id="detail_time_duration"><input type="checkbox" value="detail" name="detail_time_duration"/>' . $langs->trans('AddDetailDateAndDuration') . '</span>';
1661 print '</td>';
1662 print '</tr>';
1663
1664 if (isModEnabled("service")) {
1665 print '<tr>';
1666 print '<td>';
1667 print $langs->trans('ServiceToUseOnLines');
1668 print '</td>';
1669 print '<td>';
1670 $form->select_produits(0, 'productid', 1, 0, $projectstatic->thirdparty->price_level, 1, 2, '', 0, array(), $projectstatic->thirdparty->id, 'None', 0, 'maxwidth500');
1671 print '</td>';
1672 print '</tr>';
1673 }
1674 print '<tr>';
1675 print '<td class="titlefield">';
1676 print $langs->trans('InvoiceToUse');
1677 print '</td>';
1678 print '<td>';
1679 print $form->selectInvoiceForTimeProject($projectstatic->thirdparty->id, '', 'invoiceid', 24, 0, $langs->trans('NewInvoice'), 1, 0, 0, 'maxwidth500', '', 'all');
1680 print '</td>';
1681 print '</tr>';
1682 print '<tr>';
1683 print '<td class="titlefield">';
1684 print $langs->trans("CustomerRelativeDiscount");
1685 print '</td>';
1686 print '<td>';
1687 print '<input type="text" size="5" name="remiseproject" value="'.$projectstatic->thirdparty->remise_percent.'">%';
1688 print '</td>';
1689 print '</tr>';
1690 print '<tr class="newinvoicedetail">';
1691 print '<td class="titlefield">';
1692 print $langs->trans("PaymentConditions");
1693 print '</td>';
1694 print '<td>';
1695 print $form->getSelectConditionsPaiements((int) $projectstatic->thirdparty->cond_reglement_id, 'condidproject');
1696 print '</td>';
1697 print '</tr>';
1698 /*print '<tr>';
1699 print '<td>';
1700 print $langs->trans('ValidateInvoices');
1701 print '</td>';
1702 print '<td>';
1703 print $form->selectyesno('validate_invoices', 0, 1);
1704 print '</td>';
1705 print '</tr>';*/
1706 print '</table>';
1707
1708 print '<br>';
1709 print '<div class="center">';
1710 print '<input type="submit" class="button" id="createbills" name="createbills" value="' . $langs->trans('GenerateBill') . '"> ';
1711 print '<input type="submit" class="button button-cancel" id="cancel" name="cancel" value="' . $langs->trans("Cancel") . '">';
1712 print '</div>';
1713 print '<br>';
1714 } else {
1715 print '<div class="warning">' . $langs->trans("ThirdPartyRequiredToGenerateInvoice") . '</div>';
1716 print '<div class="center">';
1717 print '<input type="submit" class="button button-cancel" id="cancel" name="cancel" value="' . $langs->trans("Cancel") . '">';
1718 print '</div>';
1719 $massaction = '';
1720 }
1721 } elseif ($massaction == 'generateinter') {
1722 // Form to convert time spent into invoice
1723 print '<input type="hidden" name="massaction" value="confirm_createinter">';
1724
1725 if (!empty($projectstatic->thirdparty) && $projectstatic->thirdparty->id > 0) {
1726 print '<br>';
1727 print '<table class="noborder centpercent">';
1728 print '<tr>';
1729 print '<td class="titlefield">';
1730 print img_picto('', 'intervention', 'class="pictofixedwidth"') . $langs->trans('InterToUse');
1731 print '</td>';
1732 print '<td>';
1733 $forminter = new FormIntervention($db);
1734 print $forminter->select_interventions($projectstatic->thirdparty->id, 0, 'interid', 24, $langs->trans('NewInter'), true);
1735 print '</td>';
1736 print '</tr>';
1737 print '</table>';
1738
1739 print '<div class="center">';
1740 print '<input type="submit" class="button" id="createinter" name="createinter" value="' . $langs->trans('GenerateInter') . '"> ';
1741 print '<input type="submit" class="button" id="cancel" name="cancel" value="' . $langs->trans('Cancel') . '">';
1742 print '</div>';
1743 print '<br>';
1744 } else {
1745 print '<div class="warning">' . $langs->trans("ThirdPartyRequiredToGenerateIntervention") . '</div>';
1746 print '<div class="center">';
1747 print '<input type="submit" class="button" id="cancel" name="cancel" value="' . $langs->trans('Cancel') . '">';
1748 print '</div>';
1749 $massaction = '';
1750 }
1751 }
1752
1753 // Allow Pre-Mass-Action hook (eg for confirmation dialog)
1754 $parameters = array(
1755 'toselect' => $toselect,
1756 'uploaddir' => isset($uploaddir) ? $uploaddir : null
1757 );
1758
1759 $reshook = $hookmanager->executeHooks('doPreMassActions', $parameters, $object, $action);
1760 if ($reshook < 0) {
1761 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1762 } else {
1763 print $hookmanager->resPrint;
1764 }
1765
1766 /*
1767 * List of time spent
1768 */
1769 $tasks = array();
1770
1771 $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
1772 $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, $conf->main_checkbox_left_column); // This also change content of $arrayfields
1773
1774 // If project has usage "Bill time", we force visibility of field "billed"
1775 if ($projectstatic->usage_bill_time) {
1776 $arrayfields['valuebilled']['checked'] = 1;
1777 }
1778
1779 $sql = "SELECT t.rowid, t.fk_element, t.element_date, t.element_datehour, t.element_date_withhour, t.element_duration, t.fk_user, t.note, t.thm,";
1780 $sql .= " t.fk_product, t.invoice_line_id, t.import_key, t.datec, t.tms,";
1781 $sql .= " pt.rowid as taskid, pt.ref, pt.label, pt.fk_projet, pt.billable,";
1782 $sql .= " u.lastname, u.firstname, u.login, u.photo, u.gender, u.statut as user_status,";
1783 $sql .= " il.fk_facture as invoice_id, inv.fk_statut,";
1784 $sql .= " p.fk_soc, s.name_alias";
1785 if (!empty($extrafields->attributes['projet_task']['label'])) {
1786 foreach ($extrafields->attributes['projet_task']['label'] as $key => $val) {
1787 $sql .= ($extrafields->attributes['projet_task']['type'][$key] != 'separate' ? ",efpt.".$key." as options_".$key : '');
1788 }
1789 }
1790 // Add fields from hooks
1791 $parameters = array();
1792 $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1793 $sql .= $hookmanager->resPrint;
1794 $sql = preg_replace('/,\s*$/', '', $sql);
1795
1796 $sqlfields = $sql; // $sql fields to remove for count total
1797
1798 $sql .= " FROM ".MAIN_DB_PREFIX."element_time as t";
1799 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facturedet as il ON il.rowid = t.invoice_line_id";
1800 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture as inv ON inv.rowid = il.fk_facture";
1801 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as prod ON prod.rowid = t.fk_product";
1802 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."projet_task as pt ON pt.rowid = t.fk_element";
1803 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet_task_extrafields as efpt ON pt.rowid = efpt.fk_object";
1804 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = pt.fk_projet";
1805 $sql .= " INNER JOIN ".MAIN_DB_PREFIX."user as u ON t.fk_user = u.rowid";
1806 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc";
1807
1808 // Add table from hooks
1809 $parameters = array();
1810 $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1811 $sql .= $hookmanager->resPrint;
1812 $sql .= " WHERE elementtype = 'task'";
1813 $sql .= " AND p.entity IN (".getEntity('project').")";
1814 if (!$user->hasRight('projet', 'all', 'lire')) {
1815 // Get list of project id allowed to user (in a string list separated by comma)
1816 // TODO This may generate performance trouble when list of project is very large. Solution can be to complete $filterproj with filters on project.
1817 $filterproj = '';
1818 $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $user->socid > 0 ? $user->socid : 0, $filterproj);
1819 $sql .= " AND p.rowid IN (".$db->sanitize($projectsListId).")"; // public and assigned to, or restricted to company for external users
1820 }
1821 if (empty($projectidforalltimes) && empty($allprojectforuser)) {
1822 // Limit on one task
1823 $sql .= " AND t.fk_element =".((int) $object->id);
1824 } elseif (!empty($projectidforalltimes)) {
1825 // Limit on one project
1826 $sql .= " AND pt.fk_projet IN (" . $db->sanitize((string) $projectidforalltimes) . ")";
1827 } elseif (!empty($allprojectforuser)) {
1828 // Limit on on user
1829 if (empty($search_user) && !empty($arrayfields['author']['checked'])) {
1830 $search_user = $user->id;
1831 }
1832 if ($search_user > 0) {
1833 $sql .= " AND t.fk_user = " . ((int) $search_user);
1834 }
1835 }
1836
1837 if ($search_note) {
1838 $sql .= natural_search('t.note', $search_note);
1839 }
1840 if ($search_task_ref) {
1841 $sql .= natural_search('pt.ref', $search_task_ref);
1842 }
1843 if (empty($arrayfields['s.name_alias']['checked']) && $search_company) {
1844 $sql .= natural_search(array("s.nom", "s.name_alias"), $search_company);
1845 } else {
1846 if ($search_company) {
1847 $sql .= natural_search('s.nom', $search_company);
1848 }
1849 if ($search_company_alias) {
1850 $sql .= natural_search('s.name_alias', $search_company_alias);
1851 }
1852 }
1853 if ($search_project_ref) {
1854 $sql .= natural_search('p.ref', $search_project_ref);
1855 }
1856 if ($search_project_label) {
1857 $sql .= natural_search('p.title', $search_project_label);
1858 }
1859 if ($search_task_label) {
1860 $sql .= natural_search('pt.label', $search_task_label);
1861 }
1862 if ($search_user > 0) {
1863 $sql .= natural_search('t.fk_user', $search_user, 2);
1864 }
1865 if (!empty($search_product_ref)) {
1866 $sql .= natural_search('prod.ref', $search_product_ref);
1867 }
1868 if ($search_valuebilled == '1') {
1869 $sql .= ' AND t.invoice_id > 0';
1870 }
1871 if ($search_valuebilled == '0') {
1872 $sql .= ' AND (t.invoice_id = 0 OR t.invoice_id IS NULL)';
1873 }
1874
1875 if ($search_date_start) {
1876 $sql .= " AND t.element_date >= '".$db->idate($search_date_start)."'";
1877 }
1878 if ($search_date_end) {
1879 $sql .= " AND t.element_date <= '".$db->idate($search_date_end)."'";
1880 }
1881
1882 if (!empty($arrayfields['t.element_duration']['checked'])) {
1883 if ($search_timespent_starthour || $search_timespent_startmin) {
1884 $timespent_duration_start = $search_timespent_starthour * 60 * 60; // We store duration in seconds
1885 $timespent_duration_start += ($search_timespent_startmin ? $search_timespent_startmin : 0) * 60; // We store duration in seconds
1886 $sql .= " AND t.element_duration >= " . ((int) $timespent_duration_start);
1887 }
1888
1889 if ($search_timespent_endhour || $search_timespent_endmin) {
1890 $timespent_duration_end = $search_timespent_endhour * 60 * 60; // We store duration in seconds
1891 $timespent_duration_end += ($search_timespent_endmin ? $search_timespent_endmin : 0) * 60; // We store duration in seconds
1892 $sql .= " AND t.element_duration <= " . ((int) $timespent_duration_end);
1893 }
1894 }
1895
1896 $sql .= dolSqlDateFilter('t.element_datehour', $search_day, $search_month, $search_year);
1897
1898 // Add where from extra fields
1899 $extrafieldsobjectkey = 'projet_task';
1900 $extrafieldsobjectprefix = 'efpt.';
1901 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
1902
1903 // Add where from hooks
1904 $parameters = array();
1905 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1906 $sql .= $hookmanager->resPrint;
1907
1908 // Count total nb of records
1909 $nbtotalofrecords = '';
1910 if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
1911 /* The fast and low memory method to get and count full list converts the sql into a sql count */
1912 $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql);
1913 $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount);
1914 $resql = $db->query($sqlforcount);
1915 if ($resql) {
1916 $objforcount = $db->fetch_object($resql);
1917 $nbtotalofrecords = $objforcount->nbtotalofrecords;
1918 } else {
1919 dol_print_error($db);
1920 }
1921
1922 if (($page * $limit) > (int) $nbtotalofrecords) { // if total resultset is smaller than the paging size (filtering), goto and load page 0
1923 $page = 0;
1924 $offset = 0;
1925 }
1926 $db->free($resql);
1927 }
1928
1929 // Complete request and execute it with limit
1930 $sql .= $db->order($sortfield, $sortorder);
1931 if ($limit) {
1932 $sql .= $db->plimit($limit + 1, $offset);
1933 }
1934
1935 $resql = $db->query($sql);
1936 if (!$resql) {
1937 dol_print_error($db);
1938 exit;
1939 }
1940
1941 $num = $db->num_rows($resql);
1942
1943 if ($num >= 0) {
1944 if (!empty($projectidforalltimes)) {
1945 print '<!-- List of time spent for project -->' . "\n";
1946
1947 $title = $langs->trans("ListTaskTimeUserProject");
1948
1949 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'clock', 0, $linktocreatetime, '', $limit, 0, 0, 1);
1950 } else {
1951 print '<!-- List of time spent -->' . "\n";
1952
1953 $title = $langs->trans("ListTaskTimeForTask");
1954
1955 print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'clock', 0, $linktocreatetime, '', $limit, 0, 0, 1);
1956 }
1957
1958 $i = 0;
1959 while ($i < $num) {
1960 $obj = $db->fetch_object($resql);
1961
1962 $tasks[$i] = $obj;
1963
1964 $i++;
1965 }
1966 $db->free($resql);
1967 } else {
1968 dol_print_error($db);
1969 }
1970
1971 /*
1972 * Form to add a new line of time spent
1973 */
1974 if ($action == 'createtime' && $user->hasRight('projet', 'time')) {
1975 print '<!-- table to add time spent -->' . "\n";
1976 if (!empty($id)) {
1977 print '<input type="hidden" name="taskid" value="' . $id . '">';
1978 }
1979
1980 print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you don't need reserved height for your table
1981 print '<table class="noborder nohover centpercent">';
1982
1983 print '<tr class="liste_titre">';
1984 print '<td>' . $langs->trans("Date") . '</td>';
1985 if (!empty($allprojectforuser)) {
1986 print '<td>' . $langs->trans("Project") . '</td>';
1987 }
1988 if (empty($id)) {
1989 print '<td>' . $langs->trans("Task") . '</td>';
1990 }
1991 print '<td>' . $langs->trans("By") . '</td>';
1992 print '<td>' . $langs->trans("Note") . '</td>';
1993 print '<td>' . $langs->trans("NewTimeSpent") . '</td>';
1994 print '<td>' . $langs->trans("ProgressDeclared") . '</td>';
1995 if (!getDolGlobalString('PROJECT_HIDE_TASKS') && getDolGlobalString('PROJECT_BILL_TIME_SPENT')) {
1996 print '<td></td>';
1997
1998 if (isModEnabled("service") && !empty($projectstatic->thirdparty) && $projectstatic->thirdparty->id > 0 && $projectstatic->usage_bill_time) {
1999 print '<td>'.$langs->trans("Product").'</td>';
2000 }
2001 }
2002 // Hook fields
2003 $parameters = array('mode' => 'create');
2004 $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2005 print $hookmanager->resPrint;
2006 print '<td></td>';
2007 print "</tr>\n";
2008
2009 print '<tr class="oddeven nohover">';
2010
2011 // Date
2012 print '<td class="maxwidthonsmartphone">';
2013 $newdate = '';
2014 print $form->selectDate($newdate, 'time', ($conf->browser->layout == 'phone' ? 2 : 1), 1, 2, "timespent_date", 1, 0);
2015 print '</td>';
2016
2017 if (!empty($allprojectforuser)) {
2018 print '<td>';
2019 // Add project selector
2020 print '</td>';
2021 }
2022
2023 // Task
2024 $nboftasks = 0;
2025 if (empty($id)) {
2026 print '<td class="maxwidthonsmartphone">';
2027 $nboftasks = $formproject->selectTasks(-1, GETPOSTINT('taskid'), 'taskid', 0, 0, '1', 1, 0, 0, 'maxwidth300', (string) $projectstatic->id, 'progress');
2028 print '</td>';
2029 }
2030
2031 // Contributor
2032 print '<td class="maxwidthonsmartphone nowraponall">';
2033 $contactsofproject = $projectstatic->getListContactId('internal');
2034 if (count($contactsofproject) > 0) {
2035 print img_object('', 'user', 'class="hideonsmartphone"');
2036 if (in_array($user->id, $contactsofproject)) {
2037 $userid = $user->id;
2038 } else {
2039 $userid = $contactsofproject[0];
2040 }
2041
2042 if ($projectstatic->public) {
2043 $contactsofproject = array();
2044 }
2045 print $form->select_dolusers((GETPOSTINT('userid') ? GETPOSTINT('userid') : $userid), 'userid', 0, null, 0, '', $contactsofproject, '0', 0, 0, '', 0, $langs->trans("ResourceNotAssignedToProject"), 'minwidth150imp maxwidth200');
2046 } else {
2047 if ($nboftasks) {
2048 print img_error($langs->trans('FirstAddRessourceToAllocateTime')) . ' ' . $langs->trans('FirstAddRessourceToAllocateTime');
2049 }
2050 }
2051 print '</td>';
2052
2053 // Note
2054 print '<td>';
2055 print '<textarea name="timespent_note" class="maxwidth100onsmartphone" rows="' . ROWS_2 . '">' . (GETPOST('timespent_note') ? GETPOST('timespent_note') : '') . '</textarea>';
2056 print '</td>';
2057
2058 // Duration - Time spent
2059 print '<td class="nowraponall">';
2060 $durationtouse = (GETPOST('timespent_duration') ? GETPOST('timespent_duration') : '');
2061 if (GETPOSTISSET('timespent_durationhour') || GETPOSTISSET('timespent_durationmin')) {
2062 $durationtouse = ((int) GETPOST('timespent_durationhour') * 3600 + (int) GETPOST('timespent_durationmin') * 60);
2063 }
2064 print $form->select_duration('timespent_duration', $durationtouse, 0, 'text');
2065 print '</td>';
2066
2067 // Progress declared
2068 print '<td class="nowrap">';
2069 print $formother->select_percent(GETPOST('progress') ? GETPOST('progress') : $object->progress, 'progress', 0, 5, 0, 100, 1);
2070 print '</td>';
2071
2072 // Billed
2073 if (!getDolGlobalString('PROJECT_HIDE_TASKS') && getDolGlobalString('PROJECT_BILL_TIME_SPENT')) {
2074 print '<td>';
2075 print '</td>';
2076
2077 if (isModEnabled("service") && !empty($projectstatic->thirdparty) && $projectstatic->thirdparty->id > 0 && $projectstatic->usage_bill_time) {
2078 print '<td class="nowraponall">';
2079 print img_picto('', 'service');
2080 print $form->select_produits((GETPOSTISSET('fk_product') ? GETPOSTINT("fk_product") : ''), 'fk_product', 1, 0, $projectstatic->thirdparty->price_level, 1, 2, '', 1, array(), $projectstatic->thirdparty->id, 'None', 0, 'maxwidth150', ($user->hasRight('produit', 'lire') ? 0 : 1), '', null, 1);
2081 print '</td>';
2082 }
2083 }
2084
2085 // Fields from hook
2086 $parameters = array('mode' => 'create');
2087 $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2088 print $hookmanager->resPrint;
2089
2090 print '<td class="center">';
2091 $form->buttonsSaveCancel();
2092 print '<input type="submit" name="save" class="button buttongen smallpaddingimp marginleftonly margintoponlyshort marginbottomonlyshort button-add reposition" value="'.$langs->trans("Add").'">';
2093 print '<input type="submit" name="cancel" class="button buttongen smallpaddingimp marginleftonly margintoponlyshort marginbottomonlyshort button-cancel" value="'.$langs->trans("Cancel").'">';
2094 print '</td></tr>';
2095
2096 print '</table>';
2097 print '</div>';
2098
2099 print '<br>';
2100 }
2101
2102 $moreforfilter = '';
2103
2104 $parameters = array();
2105 $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2106 if (empty($reshook)) {
2107 $moreforfilter .= $hookmanager->resPrint;
2108 } else {
2109 $moreforfilter = $hookmanager->resPrint;
2110 }
2111
2112 if (!empty($moreforfilter)) {
2113 print '<div class="liste_titre liste_titre_bydiv centpercent">';
2114 print $moreforfilter;
2115 print '</div>';
2116 }
2117
2118 $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
2119 $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, $conf->main_checkbox_left_column); // This also change content of $arrayfields
2120 $selectedfields .= (is_array($arrayofmassactions) && count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
2121
2122 // If project has usage "Bill time", we force visibility of field "billed"
2123 if ($projectstatic->usage_bill_time) {
2124 $arrayfields['valuebilled']['checked'] = 1;
2125 }
2126
2127 print '<!-- Liste of time spent -->'."\n";
2128 print '<div class="div-table-responsive">';
2129 print '<table class="tagtable nobottomiftotal liste' . ($moreforfilter ? " listwithfilterbefore" : "") . '">' . "\n";
2130
2131 // Fields title search
2132 // --------------------------------------------------------------------
2133 print '<tr class="liste_titre_filter">';
2134 // Action column
2135 if ($conf->main_checkbox_left_column) {
2136 print '<td class="liste_titre center">';
2137 $searchpicto = $form->showFilterButtons('left');
2138 print $searchpicto;
2139 print '</td>';
2140 }
2141 // Date
2142 if (!empty($arrayfields['t.element_date']['checked'])) {
2143 print '<td class="liste_titre left">';
2144 print '<div class="nowrapfordate paddingright">';
2145 print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
2146 print '</div>';
2147 print '<div class="nowrapfordate">';
2148 print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
2149 print '</div>';
2150 print '</td>';
2151 }
2152 // Thirdparty
2153 if (!empty($arrayfields['p.fk_soc']['checked'])) {
2154 print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="$search_company" value="' . dol_escape_htmltag($search_company) . '"></td>';
2155 }
2156
2157 // Thirdparty alias
2158 if (!empty($arrayfields['s.name_alias']['checked'])) {
2159 print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="$search_company_alias" value="' . dol_escape_htmltag($search_company_alias) . '"></td>';
2160 }
2161
2162 if (!empty($allprojectforuser)) {
2163 if (!empty($arrayfields['p.project_ref']['checked'])) {
2164 print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="$search_project_ref" value="' . dol_escape_htmltag($search_project_ref) . '"></td>';
2165 }
2166 if (!empty($arrayfields['p.project_label']['checked'])) {
2167 print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="$search_project_label" value="' . dol_escape_htmltag($search_project_label) . '"></td>';
2168 }
2169 }
2170 // Task
2171 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
2172 if (!empty($arrayfields['t.element_ref']['checked'])) {
2173 print '<td class="liste_titre"><input type="text" class="flat maxwidth75" name="search_task_ref" value="'.dol_escape_htmltag($search_task_ref).'"></td>';
2174 }
2175 if (!empty($arrayfields['t.element_label']['checked'])) {
2176 print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_task_label" value="'.dol_escape_htmltag($search_task_label).'"></td>';
2177 }
2178 }
2179 // Author
2180 if (!empty($arrayfields['author']['checked'])) {
2181 print '<td class="liste_titre">'.$form->select_dolusers(($search_user > 0 ? $search_user : -1), 'search_user', 1, null, 0, '', '', '0', 0, 0, '', 0, '', 'maxwidth125').'</td>';
2182 }
2183 // Note
2184 if (!empty($arrayfields['t.note']['checked'])) {
2185 print '<td class="liste_titre"><input type="text" class="flat maxwidth75" name="search_note" value="' . dol_escape_htmltag($search_note) . '"></td>';
2186 }
2187 // Last modification
2188 if (!empty($arrayfields['t.tms']['checked'])) {
2189 print '<td class="liste_titre"></td>';
2190 }
2191 // Duration
2192 if (!empty($arrayfields['t.element_duration']['checked'])) {
2193 // Duration - Time spent
2194 print '<td class="liste_titre right">';
2195
2196 $durationtouse_start = '';
2197 if ($search_timespent_starthour || $search_timespent_startmin) {
2198 $durationtouse_start = ($search_timespent_starthour * 3600 + $search_timespent_startmin * 60);
2199 }
2200 print '<div class="nowraponall"><span class="opacitymedium">' . $langs->trans('fromhour') . '</span> ';
2201 print $form->select_duration('search_timespent_duration_start', $durationtouse_start, 0, 'text', 0, 1);
2202 print '</div>';
2203
2204 $durationtouse_end = '';
2205 if ($search_timespent_endhour || $search_timespent_endmin) {
2206 $durationtouse_end = ($search_timespent_endhour * 3600 + $search_timespent_endmin * 60);
2207 }
2208 print '<div class="nowraponall"><span class="opacitymedium">' . $langs->trans('tohour') . '</span> ';
2209 print $form->select_duration('search_timespent_duration_end', $durationtouse_end, 0, 'text', 0, 1);
2210 print '</div>';
2211
2212 print '</td>';
2213 }
2214 // Product
2215 if (!empty($arrayfields['t.fk_product']['checked'])) {
2216 print '<td class="liste_titre"></td>';
2217 }
2218 // Value in main currency
2219 if (!empty($arrayfields['value']['checked'])) {
2220 print '<td class="liste_titre"></td>';
2221 }
2222 // Value billed
2223 if (!empty($arrayfields['valuebilled']['checked'])) {
2224 print '<td class="liste_titre center">' . $form->selectyesno('search_valuebilled', $search_valuebilled, 1, false, 1) . '</td>';
2225 }
2226
2227 // Extra fields
2228 $extrafieldsobjectkey = 'projet_task';
2229 $extrafieldsobjectprefix = 'ef.';
2230 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
2231 // Fields from hook
2232 $parameters = array('arrayfields' => $arrayfields);
2233 $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2234 print $hookmanager->resPrint;
2235 // Action column
2236 if (!$conf->main_checkbox_left_column) {
2237 print '<td class="liste_titre center">';
2238 $searchpicto = $form->showFilterButtons();
2239 print $searchpicto;
2240 print '</td>';
2241 }
2242 print '</tr>' . "\n";
2243
2244 print '<script type="text/javascript">
2245 $(document).on("keydown", "tr.liste_titre_filter input", function (e) {
2246 if (e.which === 13) {
2247 e.preventDefault();
2248 $(this).closest("form").find("button[name=\"button_search_x\"]").first().trigger("click");
2249 }
2250 });
2251 </script>';
2252
2253
2254 $totalarray = array();
2255 $totalarray['nbfield'] = 0;
2256
2257 // Fields title label
2258 // --------------------------------------------------------------------
2259 print '<tr class="liste_titre">';
2260 if ($conf->main_checkbox_left_column) {
2261 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center maxwidthsearch ');
2262 $totalarray['nbfield']++;
2263 }
2264 if (!empty($arrayfields['t.element_date']['checked'])) {
2265 print_liste_field_titre($arrayfields['t.element_date']['label'], $_SERVER['PHP_SELF'], 't.element_date,t.element_datehour,t.rowid', '', $param, '', $sortfield, $sortorder);
2266 $totalarray['nbfield']++;
2267 }
2268 if (!empty($arrayfields['p.fk_soc']['checked'])) {
2269 print_liste_field_titre($arrayfields['p.fk_soc']['label'], $_SERVER['PHP_SELF'], 't.element_date,t.element_datehour,t.rowid', '', $param, '', $sortfield, $sortorder);
2270 $totalarray['nbfield']++;
2271 }
2272 if (!empty($arrayfields['s.name_alias']['checked'])) {
2273 // @phan-suppress-next-line PhanTypeInvalidDimOffset
2274 print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER['PHP_SELF'], 's.name_alias', '', $param, '', $sortfield, $sortorder);
2275 $totalarray['nbfield']++;
2276 }
2277 if (!empty($allprojectforuser)) {
2278 if (!empty($arrayfields['p.project_ref']['checked'])) {
2279 print_liste_field_titre($arrayfields['p.project_ref']['label'], $_SERVER['PHP_SELF'], 'p.ref', '', $param, '', $sortfield, $sortorder);
2280 $totalarray['nbfield']++;
2281 }
2282 if (!empty($arrayfields['p.project_label']['checked'])) {
2283 print_liste_field_titre($arrayfields['p.project_label']['label'], $_SERVER['PHP_SELF'], 'p.title', '', $param, '', $sortfield, $sortorder);
2284 $totalarray['nbfield']++;
2285 }
2286 }
2287 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
2288 if (!empty($arrayfields['t.element_ref']['checked'])) {
2289 print_liste_field_titre($arrayfields['t.element_ref']['label'], $_SERVER['PHP_SELF'], 'pt.ref', '', $param, '', $sortfield, $sortorder);
2290 $totalarray['nbfield']++;
2291 }
2292 if (!empty($arrayfields['t.element_label']['checked'])) {
2293 print_liste_field_titre($arrayfields['t.element_label']['label'], $_SERVER['PHP_SELF'], 'pt.label', '', $param, '', $sortfield, $sortorder);
2294 $totalarray['nbfield']++;
2295 }
2296 }
2297 if (!empty($arrayfields['author']['checked'])) {
2298 print_liste_field_titre($arrayfields['author']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder);
2299 $totalarray['nbfield']++;
2300 }
2301 if (!empty($arrayfields['t.note']['checked'])) {
2302 print_liste_field_titre($arrayfields['t.note']['label'], $_SERVER['PHP_SELF'], 't.note', '', $param, '', $sortfield, $sortorder);
2303 $totalarray['nbfield']++;
2304 }
2305 if (!empty($arrayfields['t.tms']['checked'])) {
2306 print_liste_field_titre($arrayfields['t.tms']['label'], $_SERVER['PHP_SELF'], 't.tms', '', $param, '', $sortfield, $sortorder);
2307 $totalarray['nbfield']++;
2308 }
2309 if (!empty($arrayfields['t.element_duration']['checked'])) {
2310 print_liste_field_titre($arrayfields['t.element_duration']['label'], $_SERVER['PHP_SELF'], 't.element_duration', '', $param, '', $sortfield, $sortorder, 'right ');
2311 $totalarray['nbfield']++;
2312 }
2313 if (!empty($arrayfields['t.fk_product']['checked'])) {
2314 print_liste_field_titre($arrayfields['t.fk_product']['label'], $_SERVER['PHP_SELF'], 't.fk_product', '', $param, '', $sortfield, $sortorder);
2315 $totalarray['nbfield']++;
2316 }
2317
2318 if (!empty($arrayfields['value']['checked'])) {
2319 print_liste_field_titre($arrayfields['value']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right ');
2320 $totalarray['nbfield']++;
2321 }
2322 if (!empty($arrayfields['valuebilled']['checked'])) {
2323 print_liste_field_titre($arrayfields['valuebilled']['label'], $_SERVER['PHP_SELF'], 'il.total_ht', '', $param, '', $sortfield, $sortorder, 'center ', $langs->trans("SelectLinesOfTimeSpentToInvoice"));
2324 $totalarray['nbfield']++;
2325 }
2326 // Extra fields
2327 $extrafieldsobjectkey = 'projet_task';
2328 $extrafieldsobjectprefix = 'ef.';
2329 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
2330 // Hook fields
2331 $parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder);
2332 $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2333 print $hookmanager->resPrint;
2334 if (!$conf->main_checkbox_left_column) {
2335 print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder, 'center maxwidthsearch ');
2336 $totalarray['nbfield']++;
2337 }
2338 print "</tr>\n";
2339
2340 $tasktmp = new Task($db);
2341 $tmpinvoice = new Facture($db);
2342
2343 if ($page) {
2344 $param .= '&page='.((int) $page);
2345 }
2346 $param .= '&sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder);
2347
2348 $i = 0;
2349
2350 $savnbfield = $totalarray['nbfield'];
2351 $totalarray = array();
2352 $totalarray['nbfield'] = 0;
2353 //$imaxinloop = ($limit ? min($num, $limit) : $num);
2354 foreach ($tasks as $task_time) {
2355 if ($i >= $limit) {
2356 break;
2357 }
2358
2359 // Line is invoiced if it has an invoice_id
2360 $invoiced = $task_time->invoice_id ? true : false;
2361
2362 $date1 = $db->jdate($task_time->element_date);
2363 $date2 = $db->jdate($task_time->element_datehour);
2364
2365 // Show here line of result
2366 $j = 0;
2367 print '<tr data-rowid="'.$task_time->rowid.'" class="oddeven">';
2368
2369 // Action column
2370 if ($conf->main_checkbox_left_column) {
2371 print '<td class="center nowraponall">';
2372 if (($action == 'editline' || $action == 'splitline') && GETPOSTINT('lineid') == $task_time->rowid) {
2373 print '<input type="hidden" name="lineid" value="' . GETPOSTINT('lineid') . '">';
2374 if ($id) {
2375 print '<input type="hidden" name="id" value="' . $id . '">'; // If you enable this, the edit will go beack to task view
2376 }
2377 print '<input type="submit" class="button buttongen reposition smallpaddingimp margintoponlyshort marginbottomonlyshort button-save" name="save" value="'.$langs->trans("Save").'">';
2378 print '<br>';
2379 print '<input type="submit" class="button buttongen reposition smallpaddingimp margintoponlyshort marginbottomonlyshort button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2380 } elseif ($user->hasRight('projet', 'time') || $user->hasRight('projet', 'all', 'creer')) { // Read project and enter time consumed on assigned tasks
2381 if (in_array($task_time->fk_user, $childids) || $user->hasRight('projet', 'all', 'creer')) {
2382 print '<a class="reposition editfielda" href="'.$_SERVER["PHP_SELF"].'?'.($withproject ? 'id='.$task_time->fk_element : '').'&action=editline&token='.newToken().'&lineid='.$task_time->rowid.$param.((empty($id) || $tab == 'timespent') ? '&tab=timespent' : '').'">';
2383 print img_edit('default', 0, 'class="pictofixedwidth paddingleft"');
2384 print '</a>';
2385
2386 if (getDolGlobalString('PROJECT_ALLOW_SPLIT_TIMESPENT')) {
2387 print '<a class="reposition editfielda paddingleft" href="' . $_SERVER["PHP_SELF"] . '?action=splitline&token=' . newToken() . '&lineid=' . $task_time->rowid . $param . ((empty($id) || $tab == 'timespent') ? '&tab=timespent' : '') . '">';
2388 print img_split('', 'class="pictofixedwidth paddingleft"');
2389 print '</a>';
2390 }
2391
2392 print '<a class="reposition paddingleft" href="'.$_SERVER["PHP_SELF"].'?'.($withproject ? 'id='.$task_time->fk_element : '').'&action=deleteline&token='.newToken().'&lineid='.$task_time->rowid.$param.((empty($id) || $tab == 'timespent') ? '&tab=timespent' : '').'">';
2393 print img_delete('default', 'class="pictodelete paddingleft"');
2394 print '</a>';
2395
2396 if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
2397 $selected = 0;
2398 if (in_array($task_time->rowid, $arrayofselected)) {
2399 $selected = 1;
2400 }
2401 print '&nbsp;';
2402
2403 // Disable select if task not billable or already invoiced (only when a mass action to generate invoice or intervention is available)
2404 $disabled = ((isset($arrayofmassactions['generateinvoice']) || isset($arrayofmassactions['generateinter'])) && (intval($task_time->billable) != 1 || $invoiced));
2405 $ctrl = '<input '.($disabled ? 'disabled' : '').' id="cb' . $task_time->rowid . '" class="flat checkforselect marginleftonly" type="checkbox" name="toselect[]" value="' . $task_time->rowid . '"' . ($selected ? ' checked="checked"' : '') . '>';
2406 if ($disabled) {
2407 // If disabled, a dbl-click very close outside the control
2408 // will re-enable it, so that user is not blocked if needed.
2409 print '<span id="cbsp'. $task_time->rowid . '">'.$ctrl.'</span>';
2410 print '<script>$("#cbsp' . $task_time->rowid . '").dblclick(()=>{ $("#cb' . $task_time->rowid . '").removeAttr("disabled") })</script>';
2411 } else {
2412 print $ctrl;
2413 }
2414 }
2415 }
2416 }
2417 print '</td>';
2418 if (!$i) {
2419 $totalarray['nbfield']++;
2420 }
2421 }
2422
2423 // Date
2424 if (!empty($arrayfields['t.element_date']['checked'])) {
2425 print '<td class="nowrap">';
2426 if ($action == 'editline' && GETPOSTINT('lineid') == $task_time->rowid) {
2427 if (empty($task_time->element_date_withhour)) {
2428 print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 4, 3, 2, "timespent_date", 1, 0);
2429 } else {
2430 print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 2, 1, 2, "timespent_date", 1, 0);
2431 }
2432 } else {
2433 print dol_print_date(($date2 ? $date2 : $date1), ($task_time->element_date_withhour ? 'dayhour' : 'day'));
2434 }
2435 print '</td>';
2436 if (!$i) {
2437 $totalarray['nbfield']++;
2438 }
2439 }
2440
2441 // Thirdparty
2442 if (!empty($arrayfields['p.fk_soc']['checked'])) {
2443 print '<td class="tdoverflowmax125">';
2444 if ($task_time->fk_soc > 0) {
2445 if (empty($conf->cache['thirdparty'][$task_time->fk_soc])) {
2446 $tmpsociete = new Societe($db);
2447 $tmpsociete->fetch($task_time->fk_soc);
2448 $conf->cache['thirdparty'][$task_time->fk_soc] = $tmpsociete;
2449 } else {
2450 $tmpsociete = $conf->cache['thirdparty'][$task_time->fk_soc];
2451 }
2452 print $tmpsociete->getNomUrl(1, '', 100, 0, 1, empty($arrayfields['s.name_alias']['checked']) ? 0 : 1);
2453 }
2454 print '</td>';
2455 if (!$i) {
2456 $totalarray['nbfield']++;
2457 }
2458 }
2459
2460 // Thirdparty alias
2461 if (!empty($arrayfields['s.name_alias']['checked'])) {
2462 $valtoshow = '';
2463 if ($task_time->fk_soc > 0) {
2464 if (empty($conf->cache['thirdparty'][$task_time->fk_soc])) {
2465 $tmpsociete = new Societe($db);
2466 $tmpsociete->fetch($task_time->fk_soc);
2467 $conf->cache['thirdparty'][$task_time->fk_soc] = $tmpsociete;
2468 } else {
2469 $tmpsociete = $conf->cache['thirdparty'][$task_time->fk_soc];
2470 }
2471 $valtoshow = $tmpsociete->name_alias;
2472 }
2473 print '<td class="nowrap tdoverflowmax150" title="'.dol_escape_htmltag($valtoshow).'">';
2474 print $valtoshow;
2475 print '</td>';
2476 if (!$i) {
2477 $totalarray['nbfield']++;
2478 }
2479 }
2480
2481 if (!empty($allprojectforuser)) {
2482 // Project ref
2483 if (!empty($arrayfields['p.project_ref']['checked'])) {
2484 if (empty($conf->cache['project'][$task_time->fk_projet])) {
2485 $tmpproject = new Project($db);
2486 $tmpproject->fetch($task_time->fk_projet);
2487 $conf->cache['project'][$task_time->fk_projet] = $tmpproject;
2488 } else {
2489 $tmpproject = $conf->cache['project'][$task_time->fk_projet];
2490 }
2491 print '<td class="nowraponall">';
2492 print $tmpproject->getNomUrl(1);
2493 print '</td>';
2494 if (!$i) {
2495 $totalarray['nbfield']++;
2496 }
2497 }
2498 // Project label
2499 if (!empty($arrayfields['p.project_label']['checked'])) {
2500 if (empty($conf->cache['project'][$task_time->fk_projet])) {
2501 $tmpproject = new Project($db);
2502 $tmpproject->fetch($task_time->fk_projet);
2503 $conf->cache['project'][$task_time->fk_projet] = $tmpproject;
2504 } else {
2505 $tmpproject = $conf->cache['project'][$task_time->fk_projet];
2506 }
2507 print '<td class="tdoverflowmax250" title="'.dolPrintHTMLForAttribute($tmpproject->title).'">';
2508 if (!empty($arrayfields['p.project_ref']['checked'])) {
2509 print dolPrintHTML($tmpproject->title);
2510 } else {
2511 print $tmpproject->getNomUrl(1, '', -1);
2512 }
2513 print '</td>';
2514 if (!$i) {
2515 $totalarray['nbfield']++;
2516 }
2517 }
2518 }
2519
2520 // Task ref
2521 if (!empty($arrayfields['t.element_ref']['checked'])) {
2522 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
2523 print '<td class="nowrap">';
2524 if ($action == 'editline' && GETPOSTINT('lineid') == $task_time->rowid) {
2525 $formproject->selectTasks(-1, GETPOSTINT('taskid') ? GETPOSTINT('taskid') : $task_time->fk_element, 'taskid', 0, 0, '1', 1, 0, 0, 'maxwidth250', (string) $projectstatic->id, '');
2526 } else {
2527 $tasktmp->id = $task_time->fk_element;
2528 $tasktmp->ref = $task_time->ref;
2529 $tasktmp->label = $task_time->label;
2530 print $tasktmp->getNomUrl(1, 'withproject', 'time');
2531 }
2532 print '</td>';
2533 if (!$i) {
2534 $totalarray['nbfield']++;
2535 }
2536 }
2537 } elseif ($action !== 'createtime') {
2538 print '<input type="hidden" name="taskid" value="' . $id . '">';
2539 }
2540
2541 // Task label
2542 if (!empty($arrayfields['t.element_label']['checked'])) {
2543 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
2544 print '<td class="tdoverflowmax250" title="'.dolPrintHTMLForAttribute($task_time->label).'">';
2545 if (!empty($arrayfields['t.element_ref']['checked'])) {
2546 print '<span class="spantitle">'.dolPrintHTML($task_time->label).'</span>';
2547 } else {
2548 $tasktmp->id = $task_time->fk_element;
2549 $tasktmp->ref = $task_time->ref;
2550 $tasktmp->label = $task_time->label;
2551 print $tasktmp->getNomUrl(1, 'withproject', 'time', -1);
2552 }
2553 print '</td>';
2554 if (!$i) {
2555 $totalarray['nbfield']++;
2556 }
2557 }
2558 }
2559
2560 // User
2561 if (!empty($arrayfields['author']['checked'])) {
2562 print '<td class="tdoverflowmax125">';
2563 if ($action == 'editline' && GETPOSTINT('lineid') == $task_time->rowid) {
2564 // Here $object is task. TODO Add a cache
2565 if (empty($object->id)) {
2566 $object->fetch($task_time->fk_element);
2567 }
2568 $contactsoftask = $object->getListContactId('internal');
2569 if (!in_array($task_time->fk_user, $contactsoftask)) {
2570 $contactsoftask[] = $task_time->fk_user;
2571 }
2572 if (count($contactsoftask) > 0) {
2573 print img_object('', 'user', 'class="pictofixedwidth hideonsmartphone"');
2574 print $form->select_dolusers($task_time->fk_user, 'userid_line', 0, null, 0, '', $contactsoftask, '0', 0, 0, '', 0, '', 'minwidth100 maxwidth100'); // maxwidth must be lowed than minwidth of the td
2575 } else {
2576 print img_error($langs->trans('FirstAddRessourceToAllocateTime')) . $langs->trans('FirstAddRessourceToAllocateTime');
2577 }
2578 } else {
2579 $userstatic->id = $task_time->fk_user;
2580 $userstatic->lastname = $task_time->lastname;
2581 $userstatic->firstname = $task_time->firstname;
2582 $userstatic->photo = $task_time->photo;
2583 $userstatic->gender = $task_time->gender;
2584 $userstatic->status = $task_time->user_status;
2585
2586 print $userstatic->getNomUrl(-1);
2587 }
2588 print '</td>';
2589 if (!$i) {
2590 $totalarray['nbfield']++;
2591 }
2592 }
2593
2594 // Note
2595 if (!empty($arrayfields['t.note']['checked'])) {
2596 if ($action == 'editline' && GETPOSTINT('lineid') == $task_time->rowid) {
2597 print '<td class="small">';
2598 print '<textarea name="timespent_note_line" class="centpercentimp" rows="' . ROWS_2 . '">' . dol_escape_htmltag($task_time->note, 0, 1) . '</textarea>';
2599 print '</td>';
2600 } else {
2601 print '<td class="small tdoverflowmax150 classfortooltip" title="'.dol_string_onlythesehtmltags(dol_htmlentitiesbr($task_time->note)).'">';
2602 print dolGetFirstLineOfText($task_time->note);
2603 print '</td>';
2604 }
2605 if (!$i) {
2606 $totalarray['nbfield']++;
2607 }
2608 } elseif ($action == 'editline' && GETPOSTINT('lineid') == $task_time->rowid) {
2609 print '<input type="hidden" name="timespent_note_line" value="' . dol_escape_htmltag($task_time->note, 0, 1) . '">';
2610 }
2611
2612 // Last modification
2613 if (!empty($arrayfields['t.tms']['checked'])) {
2614 print '<td class="nowraponall">';
2615 print dol_print_date($task_time->tms, 'dayhour');
2616 print '</td>';
2617 if (!$i) {
2618 $totalarray['nbfield']++;
2619 }
2620 }
2621
2622 // Time spent - Duration
2623 if (!empty($arrayfields['t.element_duration']['checked'])) {
2624 print '<td class="right nowraponall">';
2625 if ($action == 'editline' && GETPOSTINT('lineid') == $task_time->rowid) {
2626 print '<input type="hidden" name="old_duration" value="'.$task_time->element_duration.'">';
2627 print $form->select_duration('new_duration', $task_time->element_duration, 0, 'text');
2628 } else {
2629 print convertSecondToTime($task_time->element_duration, 'allhourmin');
2630 }
2631 print '</td>';
2632 if (!$i) {
2633 $totalarray['nbfield']++;
2634 }
2635 if (!$i) {
2636 $totalarray['pos'][$totalarray['nbfield']] = 't.element_duration';
2637 }
2638 if (empty($totalarray['val']['t.element_duration'])) {
2639 $totalarray['val']['t.element_duration'] = $task_time->element_duration;
2640 } else {
2641 $totalarray['val']['t.element_duration'] += $task_time->element_duration;
2642 }
2643 if (!$i) {
2644 $totalarray['totaldurationfield'] = $totalarray['nbfield'];
2645 }
2646 if (empty($totalarray['totalduration'])) {
2647 $totalarray['totalduration'] = $task_time->element_duration;
2648 } else {
2649 $totalarray['totalduration'] += $task_time->element_duration;
2650 }
2651 }
2652
2653 // Product
2654 if (!empty($arrayfields['t.fk_product']['checked'])) {
2655 print '<td class="nowraponall">';
2656 if ($action == 'editline' && GETPOSTINT('lineid') == $task_time->rowid) {
2657 print img_picto('', 'service');
2658 print $form->select_produits($task_time->fk_product, 'fk_product', 1, 0, $projectstatic->thirdparty->price_level, 1, 2, '', 1, array(), $projectstatic->thirdparty->id, 'None', 0, 'maxwidth500', ($user->hasRight('produit', 'lire') ? 0 : 1), '', null, 1);
2659 } elseif (!empty($task_time->fk_product)) {
2660 $product = new Product($db);
2661 $resultFetch = $product->fetch($task_time->fk_product);
2662 if ($resultFetch < 0) {
2663 setEventMessages($product->error, $product->errors, 'errors');
2664 } else {
2665 print $product->getNomUrl(1);
2666 }
2667 }
2668 print '</td>';
2669 if (!$i) {
2670 $totalarray['nbfield']++;
2671 }
2672 }
2673
2674 // Value spent
2675 if (!empty($arrayfields['value']['checked'])) {
2676 $langs->load("salaries");
2677 $value = price2num($task_time->thm * $task_time->element_duration / 3600, 'MT', 1);
2678
2679 print '<td class="nowraponall right">';
2680 print '<span class="amount" title="' . $langs->trans("THM") . ': ' . price($task_time->thm) . '">';
2681 print price($value, 1, $langs, 1, -1, -1, $conf->currency);
2682 print '</span>';
2683 print '</td>';
2684 if (!$i) {
2685 $totalarray['nbfield']++;
2686 }
2687 if (!$i) {
2688 $totalarray['pos'][$totalarray['nbfield']] = 'value';
2689 }
2690 if (empty($totalarray['val']['value'])) {
2691 $totalarray['val']['value'] = $value;
2692 } else {
2693 $totalarray['val']['value'] += $value;
2694 }
2695 if (!$i) {
2696 $totalarray['totalvaluefield'] = $totalarray['nbfield'];
2697 }
2698 if (empty($totalarray['totalvalue'])) {
2699 $totalarray['totalvalue'] = $value;
2700 } else {
2701 $totalarray['totalvalue'] += $value;
2702 }
2703 }
2704
2705 // Value billed
2706 if (!empty($arrayfields['valuebilled']['checked'])) {
2707 print '<td class="center">'; // invoice_id and invoice_line_id
2708 if (!getDolGlobalString('PROJECT_HIDE_TASKS') && getDolGlobalString('PROJECT_BILL_TIME_SPENT')) {
2709 if ($projectstatic->usage_bill_time) {
2710 if ($task_time->invoice_id) {
2711 $result = $tmpinvoice->fetch($task_time->invoice_id);
2712 if ($result > 0) {
2713 if ($user->hasRight('facture', 'lire')) {
2714 if ($action == 'editline' && GETPOSTINT('lineid') == $task_time->rowid) {
2715 print $formproject->selectInvoiceAndLine($task_time->invoice_id, $task_time->invoice_line_id, 'invoiceid', 'invoicelineid', 'maxwidth500', array('p.rowid' => $projectstatic->id));
2716 } else {
2717 print $tmpinvoice->getNomUrl(1);
2718 if (!empty($task_time->invoice_line_id)) {
2719 $invoiceLine = new FactureLigne($db);
2720 $invoiceLine->fetch($task_time->invoice_line_id);
2721 if (!empty($invoiceLine->id)) {
2722 print '<br><span class="small opacitymedium">'.$langs->trans('Qty').':'.$invoiceLine->qty;
2723 print ' '.$langs->trans('TotalHT').':'.price($invoiceLine->total_ht);
2724 print '</span>';
2725 }
2726 }
2727 }
2728 } else {
2729 print $langs->trans("Yes");
2730 }
2731 }
2732 $invoiced = true;
2733 } else {
2734 if (intval($task_time->billable) == 1) {
2735 print $langs->trans("No");
2736 } else {
2737 print $langs->trans("Disabled");
2738 }
2739 }
2740 } else {
2741 print '<span class="opacitymedium">' . $langs->trans("NA") . '</span>';
2742 }
2743 }
2744 print '</td>';
2745 if (!$i) {
2746 $totalarray['nbfield']++;
2747 }
2748 }
2749
2750 // Extra fields
2751 $obj = $task_time;
2752 $extrafieldsobjectkey = 'projet_task';
2753 $extrafieldsobjectprefix = 'ef.';
2754 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
2755
2756 // Fields from hook
2757 $parameters = array('arrayfields' => $arrayfields, 'obj' => $task_time, 'i' => $i, 'totalarray' => &$totalarray);
2758 $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2759 print $hookmanager->resPrint;
2760
2761 // Action column
2762 if (!$conf->main_checkbox_left_column) {
2763 print '<td class="center nowraponall">';
2764 if (($action == 'editline' || $action == 'splitline') && GETPOSTINT('lineid') == $task_time->rowid) {
2765 print '<input type="hidden" name="lineid" value="'.GETPOSTINT('lineid').'">';
2766 print '<input type="submit" class="button buttongen smallpaddingimp margintoponlyshort marginbottomonlyshort button-save" name="save" value="'.$langs->trans("Save").'">';
2767 print '<br>';
2768 print '<input type="submit" class="button buttongen smallpaddingimp margintoponlyshort marginbottomonlyshort button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
2769 } elseif ($user->hasRight('projet', 'time') || $user->hasRight('projet', 'all', 'creer')) { // Read project and enter time consumed on assigned tasks
2770 if (in_array($task_time->fk_user, $childids) || $user->hasRight('projet', 'all', 'creer')) {
2771 print '<a class="reposition editfielda" href="'.$_SERVER["PHP_SELF"].'?'.($withproject ? 'id='.$task_time->fk_element : '').'&action=editline&token='.newToken().'&lineid='.$task_time->rowid.$param.((empty($id) || $tab == 'timespent') ? '&tab=timespent' : '').'">';
2772 print img_edit('default', 0, 'class="pictofixedwidth paddingleft"');
2773 print '</a>';
2774
2775 if (getDolGlobalString('PROJECT_ALLOW_SPLIT_TIMESPENT')) {
2776 print '<a class="reposition editfielda paddingleft" href="' . $_SERVER["PHP_SELF"] . '?action=splitline&token=' . newToken() . '&lineid=' . $task_time->rowid . $param . ((empty($id) || $tab == 'timespent') ? '&tab=timespent' : '') . '">';
2777 print img_split('', 'class="pictofixedwidth paddingleft"');
2778 print '</a>';
2779 }
2780
2781 print '<a class="reposition paddingleft" href="'.$_SERVER["PHP_SELF"].'?'.($withproject ? 'id='.$task_time->fk_element : '').'&action=deleteline&token='.newToken().'&lineid='.$task_time->rowid.$param.((empty($id) || $tab == 'timespent') ? '&tab=timespent' : '').'">';
2782 print img_delete('default', 'class="pictodelete paddingleft"');
2783 print '</a>';
2784
2785 if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
2786 $selected = 0;
2787 if (in_array($task_time->rowid, $arrayofselected)) {
2788 $selected = 1;
2789 }
2790 print '&nbsp;';
2791
2792 // Disable select if task not billable or already invoiced (only when a mass action to generate invoice or intervention is available)
2793 $disabled = ((isset($arrayofmassactions['generateinvoice']) || isset($arrayofmassactions['generateinter'])) && (intval($task_time->billable) != 1 || $invoiced));
2794 $ctrl = '<input '.($disabled ? 'disabled' : '').' id="cb' . $task_time->rowid . '" class="flat checkforselect marginleftonly" type="checkbox" name="toselect[]" value="' . $task_time->rowid . '"' . ($selected ? ' checked="checked"' : '') . '>';
2795 if ($disabled) {
2796 // If disabled, a dbl-click very close outside the control
2797 // will re-enable it, so that user is not blocked if needed.
2798 print '<span id="cbsp'. $task_time->rowid . '">'.$ctrl.'</span>';
2799 print '<script>$("#cbsp' . $task_time->rowid . '").dblclick(()=>{ $("#cb' . $task_time->rowid . '").removeAttr("disabled") })</script>';
2800 } else {
2801 print $ctrl;
2802 }
2803 }
2804 }
2805 }
2806 print '</td>';
2807 if (!$i) {
2808 $totalarray['nbfield']++;
2809 }
2810 }
2811
2812 print "</tr>\n";
2813
2814
2815 // Add the lines for the split feature
2816
2817 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
2818 print '<!-- first line -->';
2819 print '<tr class="oddeven">';
2820
2821 // Action column
2822 if ($conf->main_checkbox_left_column) {
2823 print '<td></td>';
2824 }
2825
2826 // Date
2827 if (!empty($arrayfields['t.element_date']['checked'])) {
2828 print '<td class="nowrap">';
2829 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
2830 if (empty($task_time->element_date_withhour)) {
2831 print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 3, 3, 2, "timespent_date", 1, 0);
2832 } else {
2833 print $form->selectDate(($date2 ? $date2 : $date1), 'timeline', 1, 1, 2, "timespent_date", 1, 0);
2834 }
2835 } else {
2836 print dol_print_date(($date2 ? $date2 : $date1), ($task_time->element_date_withhour ? 'dayhour' : 'day'));
2837 }
2838 print '</td>';
2839 }
2840
2841 // Thirdparty
2842 if (!empty($arrayfields['p.fk_soc']['checked'])) {
2843 print '<td class="nowrap">';
2844 print '</td>';
2845 }
2846
2847 // Thirdparty alias
2848 if (!empty($arrayfields['s.name_alias']['checked'])) {
2849 print '<td class="nowrap">';
2850 print '</td>';
2851 }
2852
2853 // Project ref
2854 if (!empty($allprojectforuser)) {
2855 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
2856 print '<td class="nowrap">';
2857 print '</td>';
2858 }
2859 }
2860
2861 // Task ref
2862 if (!empty($arrayfields['t.element_ref']['checked'])) {
2863 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
2864 print '<td class="nowrap">';
2865 $tasktmp->id = $task_time->fk_element;
2866 $tasktmp->ref = $task_time->ref;
2867 $tasktmp->label = $task_time->label;
2868 print $tasktmp->getNomUrl(1, 'withproject', 'time');
2869 print '</td>';
2870 }
2871 }
2872
2873 // Task label
2874 if (!empty($arrayfields['t.element_label']['checked'])) {
2875 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
2876 print '<td class="tdoverflowmax300" title="'.dol_escape_htmltag($task_time->label).'">';
2877 print '<span class="spantitle">'.dol_escape_htmltag($task_time->label).'</span>';
2878 print '</td>';
2879 }
2880 }
2881
2882 // User
2883 if (!empty($arrayfields['author']['checked'])) {
2884 print '<td class="nowraponall">';
2885 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
2886 if (empty($object->id)) {
2887 $idTask = (!empty($id)) ? $id : $task_time->fk_element;
2888 $object->fetch($idTask);
2889 }
2890 $contactsoftask = $object->getListContactId('internal');
2891 if (!in_array($task_time->fk_user, $contactsoftask)) {
2892 $contactsoftask[] = $task_time->fk_user;
2893 }
2894 if (count($contactsoftask) > 0) {
2895 print img_object('', 'user', 'class="hideonsmartphone"');
2896 print $form->select_dolusers($task_time->fk_user, 'userid_line', 0, null, 0, '', $contactsoftask);
2897 } else {
2898 print img_error($langs->trans('FirstAddRessourceToAllocateTime')) . $langs->trans('FirstAddRessourceToAllocateTime');
2899 }
2900 } else {
2901 $userstatic->id = $task_time->fk_user;
2902 $userstatic->lastname = $task_time->lastname;
2903 $userstatic->firstname = $task_time->firstname;
2904 $userstatic->photo = $task_time->photo;
2905 $userstatic->status = $task_time->user_status;
2906 print $userstatic->getNomUrl(-1);
2907 }
2908 print '</td>';
2909 }
2910
2911 // Note
2912 if (!empty($arrayfields['t.note']['checked'])) {
2913 print '<td class="tdoverflowmax300">';
2914 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
2915 print '<textarea name="timespent_note_line" class="centpercentimp" rows="' . ROWS_2 . '">' . dol_escape_htmltag($task_time->note, 0, 1) . '</textarea>';
2916 } else {
2917 print dol_nl2br($task_time->note);
2918 }
2919 print '</td>';
2920 } elseif ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
2921 print '<input type="hidden" name="timespent_note_line" rows="' . ROWS_2 . '" value="' . dol_escape_htmltag($task_time->note, 0, 1) . '">';
2922 }
2923
2924 // Last modification
2925 if (!empty($arrayfields['t.tms']['checked'])) {
2926 print '<td class="nowraponall">';
2927 print '</td>';
2928 }
2929
2930 // Time spent - duration
2931 if (!empty($arrayfields['t.element_duration']['checked'])) {
2932 print '<td class="right">';
2933 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
2934 print '<input type="hidden" name="old_duration" value="'.$task_time->element_duration.'">';
2935 print $form->select_duration('new_duration', $task_time->element_duration, 0, 'text');
2936 } else {
2937 print convertSecondToTime($task_time->element_duration, 'allhourmin');
2938 }
2939 print '</td>';
2940 }
2941
2942 // Product
2943 if (!empty($arrayfields['t.fk_product']['checked'])) {
2944 print '<td class="nowraponall tdoverflowmax125">';
2945 print '</td>';
2946 }
2947
2948 // Value spent
2949 if (!empty($arrayfields['value']['checked'])) {
2950 print '<td class="right">';
2951 print '<span class="amount">';
2952 $value = price2num($task_time->thm * $task_time->element_duration / 3600, 'MT', 1);
2953 print price($value, 1, $langs, 1, -1, -1, $conf->currency);
2954 print '</span>';
2955 print '</td>';
2956 }
2957
2958 // Value billed
2959 if (!empty($arrayfields['valuebilled']['checked'])) {
2960 print '<td class="right">';
2961 $valuebilled = price2num($task_time->total_ht, '', 1);
2962 if (isset($task_time->total_ht)) {
2963 print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency);
2964 }
2965 print '</td>';
2966 }
2967
2968 // Extra fields
2969 $obj = $task_time;
2970 $extrafieldsobjectkey = 'projet_task';
2971 $extrafieldsobjectprefix = 'ef.';
2972 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
2973
2974 // Fields from hook
2975 $parameters = array('arrayfields' => $arrayfields, 'obj' => $task_time, 'mode' => 'split1');
2976 $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
2977 print $hookmanager->resPrint;
2978
2979 // Action column
2980 if (!$conf->main_checkbox_left_column) {
2981 print '<td class="center nowraponall">';
2982 print '</td>';
2983 }
2984
2985 print "</tr>\n";
2986
2987
2988 // Line for second dispatching
2989
2990 print '<!-- second line --><tr class="oddeven">';
2991
2992 // Action column
2993 if ($conf->main_checkbox_left_column) {
2994 print '<td class="center nowraponall">';
2995 print '</td>';
2996 }
2997
2998 // Date
2999 if (!empty($arrayfields['t.element_date']['checked'])) {
3000 print '<td class="nowraponall">';
3001 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
3002 if (empty($task_time->element_date_withhour)) {
3003 print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 3, 3, 2, "timespent_date", 1, 0);
3004 } else {
3005 print $form->selectDate(($date2 ? $date2 : $date1), 'timeline_2', 1, 1, 2, "timespent_date", 1, 0);
3006 }
3007 } else {
3008 print dol_print_date(($date2 ? $date2 : $date1), ($task_time->element_date_withhour ? 'dayhour' : 'day'));
3009 }
3010 print '</td>';
3011 }
3012
3013 // Thirdparty
3014 if (!empty($arrayfields['p.fk_soc']['checked'])) {
3015 print '<td>';
3016 print '</td>';
3017 }
3018
3019 // Thirdparty alias
3020 if (!empty($arrayfields['s.name_alias']['checked'])) {
3021 print '<td>';
3022 print '</td>';
3023 }
3024
3025 // Project ref
3026 if (!empty($allprojectforuser)) {
3027 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
3028 print '<td>';
3029 print '</td>';
3030 }
3031 }
3032
3033 // Task ref
3034 if (!empty($arrayfields['t.element_ref']['checked'])) {
3035 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
3036 print '<td class="nowraponall">';
3037 $tasktmp->id = $task_time->fk_element;
3038 $tasktmp->ref = $task_time->ref;
3039 $tasktmp->label = $task_time->label;
3040 print $tasktmp->getNomUrl(1, 'withproject', 'time');
3041 print '</td>';
3042 }
3043 }
3044
3045 // Task label
3046 if (!empty($arrayfields['t.element_label']['checked'])) {
3047 if ((empty($id) && empty($ref)) || !empty($projectidforalltimes)) { // Not a dedicated task
3048 print '<td class="tdoverflowmax125" title="'.dol_escape_htmltag($task_time->label).'">';
3049 print '<span class="spantitle">'.dol_escape_htmltag($task_time->label).'</span>';
3050 print '</td>';
3051 }
3052 }
3053
3054 // User
3055 if (!empty($arrayfields['author']['checked'])) {
3056 print '<td class="nowraponall tdoverflowmax100">';
3057 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
3058 if (empty($object->id)) {
3059 $idTask = (!empty($id)) ? $id : $task_time->fk_element;
3060 $object->fetch($idTask);
3061 }
3062 $contactsoftask = $object->getListContactId('internal');
3063 if (!in_array($task_time->fk_user, $contactsoftask)) {
3064 $contactsoftask[] = $task_time->fk_user;
3065 }
3066 if (count($contactsoftask) > 0) {
3067 print img_object('', 'user', 'class="hideonsmartphone"');
3068 print $form->select_dolusers($task_time->fk_user, 'userid_line_2', 0, null, 0, '', $contactsoftask);
3069 } else {
3070 print img_error($langs->trans('FirstAddRessourceToAllocateTime')) . $langs->trans('FirstAddRessourceToAllocateTime');
3071 }
3072 } else {
3073 $userstatic->id = $task_time->fk_user;
3074 $userstatic->lastname = $task_time->lastname;
3075 $userstatic->firstname = $task_time->firstname;
3076 $userstatic->photo = $task_time->photo;
3077 $userstatic->status = $task_time->user_status;
3078 print $userstatic->getNomUrl(-1);
3079 }
3080 print '</td>';
3081 }
3082
3083 // Note
3084 if (!empty($arrayfields['t.note']['checked'])) {
3085 print '<td class="small tdoverflowmax300"">';
3086 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
3087 print '<textarea name="timespent_note_line_2" class="centpercentimp" rows="' . ROWS_2 . '">' . dol_escape_htmltag($task_time->note, 0, 1) . '</textarea>';
3088 } else {
3089 print dol_nl2br($task_time->note);
3090 }
3091 print '</td>';
3092 } elseif ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
3093 print '<input type="hidden" name="timespent_note_line_2" value="' . dol_escape_htmltag($task_time->note, 0, 1) . '">';
3094 }
3095
3096 // Last modification
3097 if (!empty($arrayfields['t.tms']['checked'])) {
3098 print '<td class="nowraponall">';
3099 print dol_print_date($task_time->tms, 'dayhour');
3100 print '</td>';
3101 }
3102
3103 // Time spent - duration
3104 if (!empty($arrayfields['t.element_duration']['checked'])) {
3105 print '<td class="right">';
3106 if ($action == 'splitline' && GETPOSTINT('lineid') == $task_time->rowid) {
3107 print '<input type="hidden" name="old_duration_2" value="0">';
3108 print $form->select_duration('new_duration_2', 0, 0, 'text');
3109 } else {
3110 print convertSecondToTime($task_time->element_duration, 'allhourmin');
3111 }
3112 print '</td>';
3113 }
3114
3115 // Product
3116 if (!empty($arrayfields['t.fk_product']['checked'])) {
3117 print '<td class="nowraponall tdoverflowmax125">';
3118 print '</td>';
3119 }
3120
3121 // Value spent - duration
3122 if (!empty($arrayfields['value']['checked'])) {
3123 print '<td class="right">';
3124 print '<span class="amount nowraponall">';
3125 $value = 0;
3126 print price($value, 1, $langs, 1, -1, -1, $conf->currency);
3127 // Note: On the transverse project view, we also have a warning if value is zero here
3128 print '</span>';
3129 print '</td>';
3130 }
3131
3132 // Value billed
3133 if (!empty($arrayfields['valuebilled']['checked'])) {
3134 print '<td class="right">';
3135 if (isset($task_time->total_ht)) {
3136 $valuebilled = price2num($task_time->total_ht, '', 1);
3137 print '<span class="amount nowraponall small">';
3138 print price($valuebilled, 1, $langs, 1, -1, -1, $conf->currency);
3139 print '</span>';
3140 }
3141 print '</td>';
3142 }
3143
3144 // Extra fields
3145 $obj = $task_time;
3146 $extrafieldsobjectkey = 'projet_task';
3147 $extrafieldsobjectprefix = 'ef.';
3148 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
3149
3150 // Fields from hook
3151 $parameters = array('arrayfields' => $arrayfields, 'obj' => $task_time, 'mode' => 'split2');
3152 $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3153 print $hookmanager->resPrint;
3154
3155 // Action column
3156 if (!$conf->main_checkbox_left_column) {
3157 print '<td class="center nowraponall">';
3158 print '</td>';
3159 }
3160
3161 print "</tr>\n";
3162 }
3163
3164 $i++;
3165 }
3166
3167 // Show total line
3168 //include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
3169 if (isset($totalarray['totaldurationfield']) || isset($totalarray['totalvaluefield'])) {
3170 print '<tr class="liste_total">';
3171 $i = 0;
3172 while ($i < $totalarray['nbfield']) {
3173 $i++;
3174 if ($i == 1) {
3175 if ($num < $limit && empty($offset)) {
3176 print '<td class="left">' . $langs->trans("Total") . '</td>';
3177 } else {
3178 print '<td class="left">'.$form->textwithpicto($langs->trans("Total"), $langs->trans("Totalforthispage")).'</td>';
3179 }
3180 } elseif (isset($totalarray['totaldurationfield']) && $totalarray['totaldurationfield'] == $i) {
3181 print '<td class="right">' . convertSecondToTime($totalarray['totalduration'], 'allhourmin') . '</td>';
3182 } elseif (isset($totalarray['totalvaluefield']) && $totalarray['totalvaluefield'] == $i) {
3183 print '<td class="right">' . price($totalarray['totalvalue']) . '</td>';
3184 //} elseif ($totalarray['totalvaluebilledfield'] == $i) { print '<td class="center">'.price($totalarray['totalvaluebilled']).'</td>';
3185 } else {
3186 print '<td></td>';
3187 }
3188 }
3189 print '</tr>';
3190 }
3191
3192 if (!count($tasks)) {
3193 $totalnboffields = 1;
3194 foreach ($arrayfields as $value) {
3195 if (!empty($value['checked'])) {
3196 $totalnboffields++;
3197 }
3198 }
3199 print '<tr class="oddeven"><td colspan="' . $totalnboffields . '">';
3200 print '<span class="opacitymedium">' . $langs->trans("None") . '</span>';
3201 print '</td></tr>';
3202 }
3203
3204 $parameters = array('arrayfields' => $arrayfields, 'sql' => $sql);
3205 $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
3206 print $hookmanager->resPrint;
3207
3208 print "</table>";
3209 print '</div>';
3210 print "</form>";
3211 }
3212}
3213
3214// End of page
3215llxFooter();
3216$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 build export files with format CSV utf-8.
Class to manage standard extra fields.
Class to manage invoices.
Class to manage invoice lines.
Class to manage generation of HTML components Only common components must be here.
Class to manage generation of HTML components for intervention module.
Class to help generate other html components Only common components are here.
Class to manage building of HTML components.
Class to manage products or services.
Class to manage projects.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage tasks.
Class for TimeSpent.
Class to manage Dolibarr users.
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:401
convertSecondToTime($iSecond, $format='all', $lengthOfDay=86400, $lengthOfWeek=7)
Return, in clear text, value of a number of seconds in days, hours and minutes.
Definition date.lib.php:263
$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...
get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod=0)
Function that return localtax of a product line (according to seller, buyer and product vat rate) If ...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_eval($s, $returnvalue=1, $hideerrors=1, $onlysimplestring='1')
Replace eval function to add more security.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
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.
natural_search($fields, $value, $mode=0, $nofirstand=0, $sqltoadd='')
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
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.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
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).
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
print_liste_field_titre($name, $file="", $field="", $begin="", $param="", $moreattrib="", $sortfield="", $sortorder="", $prefix="", $tooltip="", $forcenowrapcolumntitle=0)
Show title line of an array.
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
dolGetButtonTitle($label, $helpText='', $iconClass='fa fa-file', $url='', $id='', $status=1, $params=array())
Function dolGetButtonTitle : this kind of buttons are used in title in list.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
img_split($titlealt='default', $other='class="pictosplit"')
Show split logo.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
task_prepare_head($object)
Prepare array with list of tabs.
project_prepare_head(Project $project, $moreparam='')
Prepare array with list of tabs.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.