time tracking and display of elapsed time no working

This commit is contained in:
2025-08-27 13:43:02 +02:00
parent 72375b82cf
commit f1d0d69455
11 changed files with 140 additions and 34 deletions

View File

@@ -15,6 +15,8 @@ public class Paths {
public static final String SERVICE = "service";
public static final String SETTINGS = "settings";
public static final String STATES = "states";
public static final String STARTED = "started";
public static final String STOP = "stop";
public static final String SUBMIT = "submit";
public static final String TOKEN = "token";
public static final String VIEW = "view";

View File

@@ -7,7 +7,6 @@ import static de.srsoftware.umbrella.core.Constants.NAME;
import de.srsoftware.tools.Mappable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

View File

@@ -10,12 +10,11 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
public class Time implements Mappable{
private final Collection<Long> taskIds;
private final HashSet<Long> taskIds = new HashSet<>();
private LocalDateTime end;
private final LocalDateTime start;
private long id;
@@ -61,7 +60,7 @@ public class Time implements Mappable{
this.start = start;
this.end = end;
this.state = state;
this.taskIds = taskIds;
if (taskIds != null) this.taskIds.addAll(taskIds);
}
public String description(){
return description;
@@ -122,7 +121,7 @@ public class Time implements Mappable{
}
public Time stop(LocalDateTime endTime) {
end = endTime;
end = endTime.withNano(0);
state = State.Open;
return this;
}

View File

@@ -11,7 +11,6 @@
let services = $state([]);
function doLogin(ev){
ev.preventDefault();
tryLogin(credentials);
@@ -21,7 +20,7 @@
element.focus();
}
onMount(async () => {
async function load(){
await checkUser();
const url = api('user/oidc/buttons');
const resp = await fetch(url,{credentials:'include'});
@@ -29,7 +28,8 @@
const json = await resp.json();
for (let service of json) services.push(service);
}
});
}
async function redirectTo(service){
const url = api(`user/oidc/redirect/${service}`);
@@ -49,7 +49,12 @@
router.navigate('/user/reset/pw');
}
if (router.fullPath.endsWith('/openid_login') && router.query.service) redirectTo(router.query.service);
if (router.fullPath.endsWith('/openid_login') && router.query.service) {
redirectTo(router.query.service);
} else {
onMount(load);
}
</script>
<style>

View File

@@ -1,9 +1,11 @@
<script>
import { onMount } from 'svelte';
import { onDestroy, onMount } from 'svelte';
import { useTinyRouter } from 'svelte-tiny-router';
import { api } from '../urls.svelte.js';
import { logout, user } from '../user.svelte.js';
import { t } from '../translations.svelte.js';
import { timetrack } from '../user.svelte.js';
let key = $state(null);
const router = useTinyRouter();
@@ -28,13 +30,61 @@ function go(path){
return false;
}
function msToTime(ms) {
const days = Math.floor(ms / (24 * 60 * 60 * 1000));
ms %= 24 * 60 * 60 * 1000;
const hours = Math.floor(ms / (60 * 60 * 1000));
ms %= 60 * 60 * 1000;
const minutes = Math.floor(ms / (60 * 1000));
ms %= 60 * 1000;
const seconds = Math.floor(ms / 1000);
let daysStr = days > 0 ? padTo2Digits(days) + ':' : '';
return `${daysStr}${padTo2Digits(hours)}:${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`;
}
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
async function search(e){
e.preventDefault();
router.navigate(`/search?key=${key}`);
return false;
}
async function stopTrack(){
if (timetrack.running.id){
const url = api(`time/${timetrack.running.id}/stop`);
const res = await fetch(url,{credentials:'include'});
if (res.ok){
timetrack.running = null;
timetrack.elapsed = null;
timetrack.start = null;
router.navigate('/time');
}
}
}
let interval = null;
$effect(() => {
if (timetrack.running) {
console.log('effect!');
timetrack.start = Date.parse(timetrack.running.start_time);
interval = setInterval(() => { timetrack.elapsed = msToTime(Date.now() - timetrack.start); },1000);
} else {
clearInterval(interval);
timetrack.elapsed = null;
interval = null;
}
});
onMount(fetchModules);
onDestroy(() => {
if (interval) clearInterval(interval);
});
</script>
<style>
@@ -63,4 +113,9 @@ onMount(fetchModules);
{#if user.name }
<a onclick={logout}>{t('logout')}</a>
{/if}
{#if timetrack.running}
<span class="timetracking">{timetrack.elapsed} {timetrack.running.subject}
<button onclick={stopTrack} title={t('stop')} class="symbol"></button>
</span>
{/if}
</nav>

View File

@@ -5,6 +5,7 @@
import { dragged } from './dragndrop.svelte.js';
import { api } from '../../urls.svelte.js';
import { t } from '../../translations.svelte.js';
import { timetrack } from '../../user.svelte.js';
import TaskList from './TaskList.svelte';
import LineEditor from '../../Components/LineEditor.svelte';
@@ -31,6 +32,7 @@
const resp = await fetch(url,{credentials:'include'}); // create new time or return time with assigned tasks
if (resp.ok) {
const track = await resp.json();
timetrack.running = track;
console.log(track);
} else {
error = await resp.text();

View File

@@ -3,14 +3,22 @@ export const user = $state({
theme : 'default'
})
export const timetrack = $state({running:null});
export async function checkUser(){
const url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/whoami`;
const response = await fetch(url,{
credentials: 'include'
});
if (response.ok){
const json = await response.json();
let url = `${location.protocol}//${location.host.replace('5173','8080')}/api/user/whoami`;
let resp = await fetch(url,{credentials: 'include'});
if (resp.ok){
const json = await resp.json();
for (let key of Object.keys(json)) user[key] = json[key];
url = `${location.protocol}//${location.host.replace('5173','8080')}/api/time/started`;
resp = await fetch(url,{credentials: 'include'});
}
if (resp.ok){
const track = await resp.json();
timetrack.running = track;
}
}

View File

@@ -5,9 +5,7 @@ import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import de.srsoftware.umbrella.core.model.Permission;
import de.srsoftware.umbrella.core.model.Project;
import de.srsoftware.umbrella.core.model.Status;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public interface ProjectDb {

View File

@@ -5,19 +5,16 @@ import static de.srsoftware.tools.jdbc.Condition.*;
import static de.srsoftware.tools.jdbc.Query.*;
import static de.srsoftware.tools.jdbc.Query.SelectQuery.ALL;
import static de.srsoftware.umbrella.core.Constants.*;
import static de.srsoftware.umbrella.core.model.Status.OPEN;
import static de.srsoftware.umbrella.core.model.Time.State.Complete;
import static de.srsoftware.umbrella.time.Constants.*;
import static java.lang.System.Logger.Level.ERROR;
import static java.text.MessageFormat.format;
import static java.time.ZoneOffset.UTC;
import de.srsoftware.umbrella.core.BaseDb;
import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import de.srsoftware.umbrella.core.model.Time;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.ZoneOffset;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
@@ -132,7 +129,25 @@ CREATE TABLE IF NOT EXISTS {0} (
}
}
@Override
@Override
public Time load(long timeId) {
try {
var query = select(ALL).from(TABLE_TIMES).where(ID,equal(timeId));
var rs = query.exec(db);
Time time = null;
if (rs.next()) time = Time.of(rs);
rs.close();
rs = select(ALL).from(TABLE_TASK_TIMES).where(TIME_ID,equal(timeId)).exec(db);
while (rs.next()) time.taskIds().add(rs.getLong(TASK_ID));
rs.close();
if (time == null) throw UmbrellaException.notFound("No time found with id = {0}",timeId);
return time;
} catch (SQLException e) {
throw new UmbrellaException("Failed to load times for task list");
}
}
@Override
public Time save(Time track) throws UmbrellaException {
try {
if (track.id() == 0) { // create new

View File

@@ -3,8 +3,6 @@ package de.srsoftware.umbrella.time;
import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import de.srsoftware.umbrella.core.model.Time;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
@@ -13,5 +11,7 @@ public interface TimeDb {
HashMap<Long,Time> listUserTimes(long userId, boolean showClosed);
Time load(long timeId);
Time save(Time track) throws UmbrellaException;
}

View File

@@ -3,7 +3,7 @@ package de.srsoftware.umbrella.time;
import static de.srsoftware.umbrella.core.ConnectionProvider.connect;
import static de.srsoftware.umbrella.core.Constants.*;
import static de.srsoftware.umbrella.core.Paths.LIST;
import static de.srsoftware.umbrella.core.Paths.*;
import static de.srsoftware.umbrella.core.exceptions.UmbrellaException.*;
import static de.srsoftware.umbrella.core.model.Time.State.Started;
import static de.srsoftware.umbrella.time.Constants.*;
@@ -21,9 +21,7 @@ import de.srsoftware.umbrella.core.exceptions.UmbrellaException;
import de.srsoftware.umbrella.core.model.*;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;
public class TimeModule extends BaseHandler implements TimeService {
@@ -58,14 +56,27 @@ public class TimeModule extends BaseHandler implements TimeService {
var head = path.pop();
return switch (head) {
case TRACK_TASK -> trackTask(user.get(),path,ex);
case null -> getUserTimes(user.get(),ex);
default -> super.doGet(path,ex);
case STARTED -> getStartedTime(user.get(),ex);
case null -> getUserTimes(user.get(),ex);
default -> {
try {
long timeId = Long.parseLong(head);
if (STOP.equals(path.pop())) yield getStoppedTask(user.get(),timeId,ex);
} catch (Exception ignored) {}
yield super.doGet(path,ex);
}
};
} catch (UmbrellaException e){
return send(ex,e);
}
}
private boolean getStoppedTask(UmbrellaUser user, long timeId, HttpExchange ex) throws IOException {
var time = timeDb.load(timeId);
timeDb.save(time.stop(LocalDateTime.now()));
return sendContent(ex,time);
}
@Override
public boolean doPost(Path path, HttpExchange ex) throws IOException {
addCors(ex);
@@ -83,6 +94,13 @@ public class TimeModule extends BaseHandler implements TimeService {
}
}
private Optional<Time> getStartedTime(UmbrellaUser user){
return timeDb.listUserTimes(user.id(), false).values()
.stream()
.filter(time -> time.state() == Started)
.max(Comparator.comparing(Time::start));
}
private boolean trackTask(UmbrellaUser user, Path path, HttpExchange ex) throws IOException {
if (path.empty()) throw missingFieldException(TASK_ID);
Task task;
@@ -93,12 +111,9 @@ public class TimeModule extends BaseHandler implements TimeService {
} catch (NumberFormatException e) {
throw invalidFieldException(TASK_ID,"long value");
}
var now = LocalDateTime.now().withSecond(0).withNano(0);
var now = LocalDateTime.now().withNano(0);
var opt = timeDb.listUserTimes(user.id(), false).values()
.stream()
.filter(time -> time.state() == Started)
.max(Comparator.comparing(Time::start));
var opt = getStartedTime(user);
if (opt.isPresent()){
var startedTime = opt.get();
@@ -114,6 +129,14 @@ public class TimeModule extends BaseHandler implements TimeService {
return sendContent(ex,track);
}
private boolean getStartedTime(UmbrellaUser user, HttpExchange ex) throws IOException {
var startedTime = getStartedTime(user);
if (startedTime.isPresent()){
return sendContent(ex,startedTime.get());
}
return send(ex,UmbrellaException.notFound("no started time"));
}
private boolean getUserTimes(UmbrellaUser user, HttpExchange ex) throws IOException {
Set<Long> taskIds = new HashSet<>();
Map<Long, Project> projects = projectService().listUserProjects(user.id(), true);