Compare commits
25 Commits
Author | SHA1 | Date | |
---|---|---|---|
465d958d9b | |||
d8ece979a8 | |||
2defdd4657 | |||
078f87687f | |||
49723831e9 | |||
025ea0dd4e | |||
97467c7a52 | |||
7842d6f45d | |||
b77089f7ad | |||
24f4459318 | |||
751182df52 | |||
33e136a810 | |||
362732c22a | |||
8e1c670ffd | |||
e5a9b9aa50 | |||
c9b2d5bd8d
|
|||
0d20b543b0
|
|||
f7b69f7704
|
|||
1ccfdc321a
|
|||
25a58c2732
|
|||
270d9f7296
|
|||
2939b4a515
|
|||
d029fda896 | |||
9dead362c1 | |||
d81dba727b |
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
src/web/static/*
|
||||||
|
.venv
|
||||||
|
.githooks
|
||||||
|
.vscode
|
||||||
|
node_modules
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -4,4 +4,5 @@ __pycache__
|
|||||||
.venv
|
.venv
|
||||||
node_modules
|
node_modules
|
||||||
package-lock.json
|
package-lock.json
|
||||||
db.sqlite3
|
db.sqlite3
|
||||||
|
src/web/static
|
24
CHANGELOG.md
24
CHANGELOG.md
@ -1,3 +1,25 @@
|
|||||||
|
## 0.2.1 / 2023-01-13 16:53+01:00
|
||||||
|
|
||||||
|
* List number of sessions when filtering on session list
|
||||||
|
* Start sessions of last purchase from list (https://git.kucharczyk.xyz/lukas/timetracker/issues/19)
|
||||||
|
|
||||||
|
## 0.2.0 / 2023-01-09 22:42+01:00
|
||||||
|
|
||||||
|
* Show playtime total on session list (https://git.kucharczyk.xyz/lukas/timetracker/issues/6)
|
||||||
|
* Make formatting durations more robust, change default duration display to "X hours" (https://git.kucharczyk.xyz/lukas/timetracker/issues/26)
|
||||||
|
|
||||||
|
## 0.1.4 / 2023-01-08 15:45+01:00
|
||||||
|
|
||||||
|
* Fix collectstaticfiles causing error when restarting container (https://git.kucharczyk.xyz/lukas/timetracker/issues/23)
|
||||||
|
|
||||||
|
## 0.1.3 / 2023-01-08 15:23+01:00
|
||||||
|
|
||||||
|
* Fix CSRF error (https://git.kucharczyk.xyz/lukas/timetracker/pulls/22)
|
||||||
|
|
||||||
|
## 0.1.2 / 2023-01-07 22:05+01:00
|
||||||
|
|
||||||
|
* Switch to Uvicorn/Gunicorn + Caddy (https://git.kucharczyk.xyz/lukas/timetracker/pulls/4)
|
||||||
|
|
||||||
## 0.1.1 / 2023-01-05 23:26+01:00
|
## 0.1.1 / 2023-01-05 23:26+01:00
|
||||||
* Order by timestamp_start by default
|
* Order by timestamp_start by default
|
||||||
* Add pre-commit hook to update version
|
* Add pre-commit hook to update version
|
||||||
@ -19,4 +41,4 @@
|
|||||||
* Make it possible to add a new platform
|
* Make it possible to add a new platform
|
||||||
* Save calculated duration to database if both timestamps are set
|
* Save calculated duration to database if both timestamps are set
|
||||||
* Improve session listing
|
* Improve session listing
|
||||||
* Set version in the footer to fixed, fix main container height
|
* Set version in the footer to fixed, fix main container height
|
||||||
|
14
Caddyfile
Normal file
14
Caddyfile
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
auto_https off
|
||||||
|
admin off
|
||||||
|
}
|
||||||
|
|
||||||
|
:8000 {
|
||||||
|
handle_path /static/* {
|
||||||
|
root * src/web/static/
|
||||||
|
file_server
|
||||||
|
}
|
||||||
|
handle {
|
||||||
|
reverse_proxy :8001
|
||||||
|
}
|
||||||
|
}
|
11
Dockerfile
11
Dockerfile
@ -4,12 +4,17 @@ COPY . /app
|
|||||||
RUN npm install && \
|
RUN npm install && \
|
||||||
npx tailwindcss -i ./src/input.css -o ./src/web/tracker/static/base.css --minify
|
npx tailwindcss -i ./src/input.css -o ./src/web/tracker/static/base.css --minify
|
||||||
|
|
||||||
FROM python:3.10-slim-bullseye
|
FROM python:3.10.9-alpine
|
||||||
|
|
||||||
ENV VERSION_NUMBER 0.1.0-48-gdb5de81
|
ENV VERSION_NUMBER 0.2.0-2-gd8ece97
|
||||||
ENV PROD 1
|
ENV PROD 1
|
||||||
|
|
||||||
RUN useradd --create-home --uid 1000 timetracker
|
RUN apk add \
|
||||||
|
bash \
|
||||||
|
vim \
|
||||||
|
curl \
|
||||||
|
caddy
|
||||||
|
RUN adduser -D -u 1000 timetracker
|
||||||
WORKDIR /home/timetracker/app
|
WORKDIR /home/timetracker/app
|
||||||
COPY . /home/timetracker/app/
|
COPY . /home/timetracker/app/
|
||||||
RUN chown -R timetracker:timetracker /home/timetracker/app
|
RUN chown -R timetracker:timetracker /home/timetracker/app
|
||||||
|
22
Makefile
22
Makefile
@ -1,5 +1,3 @@
|
|||||||
.PHONY: createsuperuser shell
|
|
||||||
|
|
||||||
all: css migrate
|
all: css migrate
|
||||||
|
|
||||||
initialize: npm css migrate sethookdir loadplatforms
|
initialize: npm css migrate sethookdir loadplatforms
|
||||||
@ -22,7 +20,13 @@ migrate: makemigrations
|
|||||||
poetry run python src/web/manage.py migrate
|
poetry run python src/web/manage.py migrate
|
||||||
|
|
||||||
dev: migrate sethookdir
|
dev: migrate sethookdir
|
||||||
poetry run python src/web/manage.py runserver_plus
|
poetry run python src/web/manage.py runserver
|
||||||
|
|
||||||
|
caddy:
|
||||||
|
caddy run --watch
|
||||||
|
|
||||||
|
dev-prod: migrate collectstatic sethookdir
|
||||||
|
cd src/web/; PROD=1 poetry run python -m gunicorn --bind 0.0.0.0:8001 web.asgi:application -k uvicorn.workers.UvicornWorker
|
||||||
|
|
||||||
dumptracker:
|
dumptracker:
|
||||||
poetry run python src/web/manage.py dumpdata --format yaml tracker --output tracker_fixture.yaml
|
poetry run python src/web/manage.py dumpdata --format yaml tracker --output tracker_fixture.yaml
|
||||||
@ -39,6 +43,9 @@ createsuperuser:
|
|||||||
shell:
|
shell:
|
||||||
poetry run python src/web/manage.py shell
|
poetry run python src/web/manage.py shell
|
||||||
|
|
||||||
|
collectstatic:
|
||||||
|
poetry run python src/web/manage.py collectstatic --clear --no-input
|
||||||
|
|
||||||
poetry.lock: pyproject.toml
|
poetry.lock: pyproject.toml
|
||||||
poetry install
|
poetry install
|
||||||
|
|
||||||
@ -48,5 +55,10 @@ test: poetry.lock
|
|||||||
sethookdir:
|
sethookdir:
|
||||||
git config core.hooksPath .githooks
|
git config core.hooksPath .githooks
|
||||||
|
|
||||||
make date:
|
date:
|
||||||
python3 -c 'import datetime; from zoneinfo import ZoneInfo; print(datetime.datetime.isoformat(datetime.datetime.now(ZoneInfo("Europe/Prague")), timespec="minutes", sep=" "))'
|
poetry run python -c 'import datetime; from zoneinfo import ZoneInfo; print(datetime.datetime.isoformat(datetime.datetime.now(ZoneInfo("Europe/Prague")), timespec="minutes", sep=" "))'
|
||||||
|
|
||||||
|
cleanstatic:
|
||||||
|
rm -r src/web/static/*
|
||||||
|
|
||||||
|
clean: cleanstatic
|
||||||
|
17
docker-compose.yml
Normal file
17
docker-compose.yml
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
---
|
||||||
|
services:
|
||||||
|
timetracker:
|
||||||
|
image: registry.kucharczyk.xyz/timetracker
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: timetracker
|
||||||
|
environment:
|
||||||
|
- TZ=Europe/Prague
|
||||||
|
- CSRF_TRUSTED_ORIGINS="https://tracker.kucharczyk.xyz"
|
||||||
|
user: "1000"
|
||||||
|
# volumes:
|
||||||
|
# - "db:/home/timetracker/app/src/web/db.sqlite3"
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
restart: unless-stopped
|
@ -1,8 +1,13 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# Apply database migrations
|
# Apply database migrations
|
||||||
|
set -euo pipefail
|
||||||
echo "Apply database migrations"
|
echo "Apply database migrations"
|
||||||
poetry run python src/web/manage.py migrate
|
poetry run python src/web/manage.py migrate
|
||||||
|
|
||||||
# Start server
|
echo "Collect static files"
|
||||||
|
poetry run python src/web/manage.py collectstatic --clear --no-input
|
||||||
|
|
||||||
echo "Starting server"
|
echo "Starting server"
|
||||||
poetry run python src/web/manage.py runserver 0.0.0.0:8000
|
caddy start
|
||||||
|
cd src/web || exit
|
||||||
|
poetry run python -m gunicorn --bind 0.0.0.0:8001 web.asgi:application -k uvicorn.workers.UvicornWorker --access-logfile - --error-logfile -
|
||||||
|
75
poetry.lock
generated
75
poetry.lock
generated
@ -73,7 +73,7 @@ uvloop = ["uvloop (>=0.15.2)"]
|
|||||||
name = "click"
|
name = "click"
|
||||||
version = "8.1.3"
|
version = "8.1.3"
|
||||||
description = "Composable command line interface toolkit"
|
description = "Composable command line interface toolkit"
|
||||||
category = "dev"
|
category = "main"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.7"
|
python-versions = ">=3.7"
|
||||||
files = [
|
files = [
|
||||||
@ -88,7 +88,7 @@ colorama = {version = "*", markers = "platform_system == \"Windows\""}
|
|||||||
name = "colorama"
|
name = "colorama"
|
||||||
version = "0.4.6"
|
version = "0.4.6"
|
||||||
description = "Cross-platform colored terminal text."
|
description = "Cross-platform colored terminal text."
|
||||||
category = "dev"
|
category = "main"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
|
python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
|
||||||
files = [
|
files = [
|
||||||
@ -215,6 +215,39 @@ files = [
|
|||||||
[package.extras]
|
[package.extras]
|
||||||
test = ["pytest (>=6)"]
|
test = ["pytest (>=6)"]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "gunicorn"
|
||||||
|
version = "20.1.0"
|
||||||
|
description = "WSGI HTTP Server for UNIX"
|
||||||
|
category = "main"
|
||||||
|
optional = false
|
||||||
|
python-versions = ">=3.5"
|
||||||
|
files = [
|
||||||
|
{file = "gunicorn-20.1.0-py3-none-any.whl", hash = "sha256:9dcc4547dbb1cb284accfb15ab5667a0e5d1881cc443e0677b4882a4067a807e"},
|
||||||
|
{file = "gunicorn-20.1.0.tar.gz", hash = "sha256:e0a968b5ba15f8a328fdfd7ab1fcb5af4470c28aaf7e55df02a99bc13138e6e8"},
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.dependencies]
|
||||||
|
setuptools = ">=3.0"
|
||||||
|
|
||||||
|
[package.extras]
|
||||||
|
eventlet = ["eventlet (>=0.24.1)"]
|
||||||
|
gevent = ["gevent (>=1.4.0)"]
|
||||||
|
setproctitle = ["setproctitle"]
|
||||||
|
tornado = ["tornado (>=0.2)"]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "h11"
|
||||||
|
version = "0.14.0"
|
||||||
|
description = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1"
|
||||||
|
category = "main"
|
||||||
|
optional = false
|
||||||
|
python-versions = ">=3.7"
|
||||||
|
files = [
|
||||||
|
{file = "h11-0.14.0-py3-none-any.whl", hash = "sha256:e3fe4ac4b851c468cc8363d500db52c2ead036020723024a109d37346efaa761"},
|
||||||
|
{file = "h11-0.14.0.tar.gz", hash = "sha256:8f19fbbe99e72420ff35c00b27a34cb9937e902a8b810e2c88300c6f0a3b699d"},
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "html-tag-names"
|
name = "html-tag-names"
|
||||||
version = "0.1.2"
|
version = "0.1.2"
|
||||||
@ -627,6 +660,23 @@ files = [
|
|||||||
{file = "regex-2022.10.31.tar.gz", hash = "sha256:a3a98921da9a1bf8457aeee6a551948a83601689e5ecdd736894ea9bbec77e83"},
|
{file = "regex-2022.10.31.tar.gz", hash = "sha256:a3a98921da9a1bf8457aeee6a551948a83601689e5ecdd736894ea9bbec77e83"},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "setuptools"
|
||||||
|
version = "65.6.3"
|
||||||
|
description = "Easily download, build, install, upgrade, and uninstall Python packages"
|
||||||
|
category = "main"
|
||||||
|
optional = false
|
||||||
|
python-versions = ">=3.7"
|
||||||
|
files = [
|
||||||
|
{file = "setuptools-65.6.3-py3-none-any.whl", hash = "sha256:57f6f22bde4e042978bcd50176fdb381d7c21a9efa4041202288d3737a0c6a54"},
|
||||||
|
{file = "setuptools-65.6.3.tar.gz", hash = "sha256:a7620757bf984b58deaf32fc8a4577a9bbc0850cf92c20e1ce41c38c19e5fb75"},
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.extras]
|
||||||
|
docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-hoverxref (<2)", "sphinx-inline-tabs", "sphinx-notfound-page (==0.8.3)", "sphinx-reredirects", "sphinxcontrib-towncrier"]
|
||||||
|
testing = ["build[virtualenv]", "filelock (>=3.4.0)", "flake8 (<5)", "flake8-2020", "ini2toml[lite] (>=0.9)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pip (>=19.1)", "pip-run (>=8.8)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)", "pytest-perf", "pytest-timeout", "pytest-xdist", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"]
|
||||||
|
testing-integration = ["build[virtualenv]", "filelock (>=3.4.0)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pytest", "pytest-enabler", "pytest-xdist", "tomli", "virtualenv (>=13.0.0)", "wheel"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "six"
|
name = "six"
|
||||||
version = "1.16.0"
|
version = "1.16.0"
|
||||||
@ -708,6 +758,25 @@ files = [
|
|||||||
{file = "tzdata-2022.7.tar.gz", hash = "sha256:fe5f866eddd8b96e9fcba978f8e503c909b19ea7efda11e52e39494bad3a7bfa"},
|
{file = "tzdata-2022.7.tar.gz", hash = "sha256:fe5f866eddd8b96e9fcba978f8e503c909b19ea7efda11e52e39494bad3a7bfa"},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "uvicorn"
|
||||||
|
version = "0.20.0"
|
||||||
|
description = "The lightning-fast ASGI server."
|
||||||
|
category = "main"
|
||||||
|
optional = false
|
||||||
|
python-versions = ">=3.7"
|
||||||
|
files = [
|
||||||
|
{file = "uvicorn-0.20.0-py3-none-any.whl", hash = "sha256:c3ed1598a5668208723f2bb49336f4509424ad198d6ab2615b7783db58d919fd"},
|
||||||
|
{file = "uvicorn-0.20.0.tar.gz", hash = "sha256:a4e12017b940247f836bc90b72e725d7dfd0c8ed1c51eb365f5ba30d9f5127d8"},
|
||||||
|
]
|
||||||
|
|
||||||
|
[package.dependencies]
|
||||||
|
click = ">=7.0"
|
||||||
|
h11 = ">=0.8"
|
||||||
|
|
||||||
|
[package.extras]
|
||||||
|
standard = ["colorama (>=0.4)", "httptools (>=0.5.0)", "python-dotenv (>=0.13)", "pyyaml (>=5.1)", "uvloop (>=0.14.0,!=0.15.0,!=0.15.1)", "watchfiles (>=0.13)", "websockets (>=10.4)"]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "werkzeug"
|
name = "werkzeug"
|
||||||
version = "2.2.2"
|
version = "2.2.2"
|
||||||
@ -745,4 +814,4 @@ testing = ["flake8 (<5)", "func-timeout", "jaraco.functools", "jaraco.itertools"
|
|||||||
[metadata]
|
[metadata]
|
||||||
lock-version = "2.0"
|
lock-version = "2.0"
|
||||||
python-versions = "^3.10"
|
python-versions = "^3.10"
|
||||||
content-hash = "4e2d507e5549e97f894ebcaf0781c1fa54acf3444583510c36d3807e6c4761d9"
|
content-hash = "fd85e51c8fb99824a433b451c9712b7418c13688b9eb0e8ca6c51768f544e48f"
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[tool.poetry]
|
[tool.poetry]
|
||||||
name = "timetracker"
|
name = "timetracker"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
description = "A simple time tracker."
|
description = "A simple time tracker."
|
||||||
authors = ["Lukáš Kucharczyk <lukas@kucharczyk.xyz>"]
|
authors = ["Lukáš Kucharczyk <lukas@kucharczyk.xyz>"]
|
||||||
license = "GPL"
|
license = "GPL"
|
||||||
@ -9,6 +9,8 @@ readme = "README.md"
|
|||||||
[tool.poetry.dependencies]
|
[tool.poetry.dependencies]
|
||||||
python = "^3.10"
|
python = "^3.10"
|
||||||
django = "^4.1.4"
|
django = "^4.1.4"
|
||||||
|
gunicorn = "^20.1.0"
|
||||||
|
uvicorn = "^0.20.0"
|
||||||
|
|
||||||
[tool.poetry.group.dev.dependencies]
|
[tool.poetry.group.dev.dependencies]
|
||||||
black = "^22.12.0"
|
black = "^22.12.0"
|
||||||
|
@ -8,8 +8,17 @@ def now() -> datetime:
|
|||||||
return datetime.now(ZoneInfo(settings.TIME_ZONE))
|
return datetime.now(ZoneInfo(settings.TIME_ZONE))
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_timedelta(duration: timedelta | int | None):
|
||||||
|
if duration == None:
|
||||||
|
return timedelta(0)
|
||||||
|
elif isinstance(duration, int):
|
||||||
|
return timedelta(seconds=duration)
|
||||||
|
elif isinstance(duration, timedelta):
|
||||||
|
return duration
|
||||||
|
|
||||||
|
|
||||||
def format_duration(
|
def format_duration(
|
||||||
duration: timedelta, format_string: str = "%H hours %m minutes"
|
duration: timedelta | int | None, format_string: str = "%H hours"
|
||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""
|
||||||
Format timedelta into the specified format_string.
|
Format timedelta into the specified format_string.
|
||||||
@ -18,19 +27,28 @@ def format_duration(
|
|||||||
- %m minutes
|
- %m minutes
|
||||||
- %s seconds
|
- %s seconds
|
||||||
- %r total seconds
|
- %r total seconds
|
||||||
|
Values don't change into higher units if those units are missing
|
||||||
|
from the formatting string. For example:
|
||||||
|
- 61 seconds as "%s" = 61 seconds
|
||||||
|
- 61 seconds as "%m %s" = 1 minutes 1 seconds"
|
||||||
"""
|
"""
|
||||||
minute_seconds = 60
|
minute_seconds = 60
|
||||||
hour_seconds = 60 * minute_seconds
|
hour_seconds = 60 * minute_seconds
|
||||||
day_seconds = 24 * hour_seconds
|
day_seconds = 24 * hour_seconds
|
||||||
if not isinstance(duration, timedelta):
|
duration = _safe_timedelta(duration)
|
||||||
duration = timedelta(seconds=duration)
|
# we don't need float
|
||||||
seconds_total = int(duration.total_seconds())
|
seconds_total = int(duration.total_seconds())
|
||||||
# timestamps where end is before start
|
# timestamps where end is before start
|
||||||
if seconds_total < 0:
|
if seconds_total < 0:
|
||||||
seconds_total = 0
|
seconds_total = 0
|
||||||
days, remainder = divmod(seconds_total, day_seconds)
|
days = hours = minutes = seconds = 0
|
||||||
hours, remainder = divmod(remainder, hour_seconds)
|
remainder = seconds = seconds_total
|
||||||
minutes, seconds = divmod(remainder, minute_seconds)
|
if "%d" in format_string:
|
||||||
|
days, remainder = divmod(seconds_total, day_seconds)
|
||||||
|
if "%H" in format_string:
|
||||||
|
hours, remainder = divmod(remainder, hour_seconds)
|
||||||
|
if "%m" in format_string:
|
||||||
|
minutes, seconds = divmod(remainder, minute_seconds)
|
||||||
literals = {
|
literals = {
|
||||||
"%d": str(days),
|
"%d": str(days),
|
||||||
"%H": str(hours),
|
"%H": str(hours),
|
||||||
|
@ -0,0 +1,21 @@
|
|||||||
|
# Generated by Django 4.1.5 on 2023-01-09 14:49
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("tracker", "0003_alter_session_duration_manual_and_more"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="session",
|
||||||
|
name="duration_manual",
|
||||||
|
field=models.DurationField(
|
||||||
|
blank=True, default=datetime.timedelta(0), null=True
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
34
src/web/tracker/migrations/0005_auto_20230109_1843.py
Normal file
34
src/web/tracker/migrations/0005_auto_20230109_1843.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
# Generated by Django 4.1.5 on 2023-01-09 17:43
|
||||||
|
|
||||||
|
from django.db import migrations
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
|
||||||
|
def set_duration_calculated_none_to_zero(apps, schema_editor):
|
||||||
|
Session = apps.get_model("tracker", "Session")
|
||||||
|
for session in Session.objects.all():
|
||||||
|
if session.duration_calculated == None:
|
||||||
|
session.duration_calculated = timedelta(0)
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
|
||||||
|
def revert_set_duration_calculated_none_to_zero(apps, schema_editor):
|
||||||
|
Session = apps.get_model("tracker", "Session")
|
||||||
|
for session in Session.objects.all():
|
||||||
|
if session.duration_calculated == timedelta(0):
|
||||||
|
session.duration_calculated = None
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("tracker", "0004_alter_session_duration_manual"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(
|
||||||
|
set_duration_calculated_none_to_zero,
|
||||||
|
revert_set_duration_calculated_none_to_zero,
|
||||||
|
)
|
||||||
|
]
|
34
src/web/tracker/migrations/0006_auto_20230109_1904.py
Normal file
34
src/web/tracker/migrations/0006_auto_20230109_1904.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
# Generated by Django 4.1.5 on 2023-01-09 18:04
|
||||||
|
|
||||||
|
from django.db import migrations
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
|
||||||
|
def set_duration_manual_none_to_zero(apps, schema_editor):
|
||||||
|
Session = apps.get_model("tracker", "Session")
|
||||||
|
for session in Session.objects.all():
|
||||||
|
if session.duration_manual == None:
|
||||||
|
session.duration_manual = timedelta(0)
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
|
||||||
|
def revert_set_duration_manual_none_to_zero(apps, schema_editor):
|
||||||
|
Session = apps.get_model("tracker", "Session")
|
||||||
|
for session in Session.objects.all():
|
||||||
|
if session.duration_manual == timedelta(0):
|
||||||
|
session.duration_manual = None
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("tracker", "0005_auto_20230109_1843"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(
|
||||||
|
set_duration_manual_none_to_zero,
|
||||||
|
revert_set_duration_manual_none_to_zero,
|
||||||
|
)
|
||||||
|
]
|
@ -3,7 +3,9 @@ from datetime import datetime, timedelta
|
|||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
from common.util.time import format_duration
|
from common.util.time import format_duration
|
||||||
from django.db.models import Sum
|
from django.db.models import Sum, F
|
||||||
|
from django.db.models import Manager
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
class Game(models.Model):
|
class Game(models.Model):
|
||||||
@ -32,69 +34,58 @@ class Platform(models.Model):
|
|||||||
return self.name
|
return self.name
|
||||||
|
|
||||||
|
|
||||||
|
class SessionQuerySet(models.QuerySet):
|
||||||
|
def total_duration(self):
|
||||||
|
result = self.aggregate(
|
||||||
|
duration=Sum(F("duration_calculated") + F("duration_manual"))
|
||||||
|
)
|
||||||
|
return format_duration(result["duration"])
|
||||||
|
|
||||||
|
|
||||||
class Session(models.Model):
|
class Session(models.Model):
|
||||||
purchase = models.ForeignKey("Purchase", on_delete=models.CASCADE)
|
purchase = models.ForeignKey("Purchase", on_delete=models.CASCADE)
|
||||||
timestamp_start = models.DateTimeField()
|
timestamp_start = models.DateTimeField()
|
||||||
timestamp_end = models.DateTimeField(blank=True, null=True)
|
timestamp_end = models.DateTimeField(blank=True, null=True)
|
||||||
duration_manual = models.DurationField(blank=True, null=True)
|
duration_manual = models.DurationField(blank=True, null=True, default=timedelta(0))
|
||||||
duration_calculated = models.DurationField(blank=True, null=True)
|
duration_calculated = models.DurationField(blank=True, null=True)
|
||||||
note = models.TextField(blank=True, null=True)
|
note = models.TextField(blank=True, null=True)
|
||||||
|
|
||||||
|
objects = SessionQuerySet.as_manager()
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
mark = ", manual" if self.duration_manual != None else ""
|
mark = ", manual" if self.duration_manual != None else ""
|
||||||
return f"{str(self.purchase)} {str(self.timestamp_start.date())} ({self.duration_any()}{mark})"
|
return f"{str(self.purchase)} {str(self.timestamp_start.date())} ({self.duration_formatted()}{mark})"
|
||||||
|
|
||||||
def finish_now(self):
|
def finish_now(self):
|
||||||
self.timestamp_end = datetime.now(ZoneInfo(settings.TIME_ZONE))
|
self.timestamp_end = datetime.now(ZoneInfo(settings.TIME_ZONE))
|
||||||
|
|
||||||
|
def start_now():
|
||||||
|
self.timestamp_start = datetime.now(ZoneInfo(settings.TIME_ZONE))
|
||||||
|
|
||||||
def duration_seconds(self) -> timedelta:
|
def duration_seconds(self) -> timedelta:
|
||||||
if self.duration_manual == None:
|
manual = timedelta(0)
|
||||||
if self.timestamp_end == None or self.timestamp_start == None:
|
calculated = timedelta(0)
|
||||||
return timedelta(0)
|
if not self.duration_manual in (None, 0, timedelta(0)):
|
||||||
else:
|
manual = self.duration_manual
|
||||||
value = self.timestamp_end - self.timestamp_start
|
if self.timestamp_end != None and self.timestamp_start != None:
|
||||||
else:
|
calculated = self.timestamp_end - self.timestamp_start
|
||||||
value = self.duration_manual
|
return timedelta(seconds=(manual + calculated).total_seconds())
|
||||||
return timedelta(seconds=value.total_seconds())
|
|
||||||
|
|
||||||
def duration_formatted(self) -> str:
|
def duration_formatted(self) -> str:
|
||||||
result = format_duration(self.duration_seconds(), "%H:%m")
|
result = format_duration(self.duration_seconds(), "%H:%m")
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def duration_any(self):
|
@property
|
||||||
return (
|
def duration_sum(self) -> str:
|
||||||
self.duration_formatted()
|
return Session.objects.all().total_duration()
|
||||||
if self.duration_manual == None
|
|
||||||
else self.duration_manual
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
@property
|
||||||
def calculated_sum() -> timedelta:
|
def last(self) -> Manager[Any]:
|
||||||
calculated_sum_query = Session.objects.all().aggregate(
|
return Session.objects.all().order_by("timestamp_start")[:-1]
|
||||||
Sum("duration_calculated")
|
|
||||||
)
|
|
||||||
calculated_sum = (
|
|
||||||
timedelta(0)
|
|
||||||
if calculated_sum_query["duration_calculated__sum"] == None
|
|
||||||
else calculated_sum_query["duration_calculated__sum"]
|
|
||||||
)
|
|
||||||
return calculated_sum
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def manual_sum() -> timedelta:
|
|
||||||
manual_sum_query = Session.objects.all().aggregate(Sum("duration_manual"))
|
|
||||||
manual_sum = (
|
|
||||||
timedelta(0)
|
|
||||||
if manual_sum_query["duration_manual__sum"] == None
|
|
||||||
else manual_sum_query["duration_manual__sum"]
|
|
||||||
)
|
|
||||||
return manual_sum
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def total_sum() -> timedelta:
|
|
||||||
return Session.manual_sum() + Session.calculated_sum()
|
|
||||||
|
|
||||||
def save(self, *args, **kwargs):
|
def save(self, *args, **kwargs):
|
||||||
if self.timestamp_start != None and self.timestamp_end != None:
|
if self.timestamp_start != None and self.timestamp_end != None:
|
||||||
self.duration_calculated = self.timestamp_end - self.timestamp_start
|
self.duration_calculated = self.timestamp_end - self.timestamp_start
|
||||||
|
else:
|
||||||
|
self.duration_calculated = timedelta(0)
|
||||||
super(Session, self).save(*args, **kwargs)
|
super(Session, self).save(*args, **kwargs)
|
||||||
|
@ -3,12 +3,18 @@
|
|||||||
{% block title %}Sessions{% endblock title %}
|
{% block title %}Sessions{% endblock title %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
{% if purchase %}
|
|
||||||
<div class="text-center text-xl mb-4 dark:text-slate-400">
|
<div class="text-center text-xl mb-4 dark:text-slate-400">
|
||||||
|
<a href="{% url 'start_session' dataset.last.purchase.id %}">
|
||||||
|
<button type="button" title="Track last tracked" class="py-1 px-2 bg-green-600 hover:bg-green-700 focus:ring-green-500 focus:ring-offset-blue-200 text-white transition ease-in duration-200 text-center text-base font-semibold shadow-md focus:outline-none focus:ring-2 focus:ring-offset-2 w-12 h-6 rounded-lg ">
|
||||||
|
New session of {{ dataset.last.purchase }}
|
||||||
|
</button>
|
||||||
|
</a>
|
||||||
|
{% if purchase %}
|
||||||
<h1>Listing sessions only for purchase "{{ purchase }}"</h1>
|
<h1>Listing sessions only for purchase "{{ purchase }}"</h1>
|
||||||
|
<h2>Total playtime: {{ total_duration }} over {{ dataset.count }} sessions.</h2>
|
||||||
<a class="dark:text-white hover:underline" href="{% url 'list_sessions' %}">View all sessions</a>
|
<a class="dark:text-white hover:underline" href="{% url 'list_sessions' %}">View all sessions</a>
|
||||||
|
{% endif %}
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
|
||||||
<div id="session-table" class="gap-4 shadow rounded-xl max-w-screen-lg mx-auto dark:bg-slate-700 p-2 justify-center">
|
<div id="session-table" class="gap-4 shadow rounded-xl max-w-screen-lg mx-auto dark:bg-slate-700 p-2 justify-center">
|
||||||
<div class="dark:border-white dark:text-slate-300 text-lg">Name</div>
|
<div class="dark:border-white dark:text-slate-300 text-lg">Name</div>
|
||||||
<div class="dark:border-white dark:text-slate-300 text-lg text-center">Start</div>
|
<div class="dark:border-white dark:text-slate-300 text-lg text-center">Start</div>
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
from django import template
|
from django import template
|
||||||
|
from django.conf import settings
|
||||||
import time
|
import time
|
||||||
import os
|
import os
|
||||||
|
|
||||||
@ -9,7 +10,11 @@ register = template.Library()
|
|||||||
def version_date():
|
def version_date():
|
||||||
return time.strftime(
|
return time.strftime(
|
||||||
"%d-%b-%Y %H:%m",
|
"%d-%b-%Y %H:%m",
|
||||||
time.gmtime(os.path.getmtime(os.path.abspath(os.path.join(".git")))),
|
time.gmtime(
|
||||||
|
os.path.getmtime(
|
||||||
|
os.path.abspath(os.path.join(settings.BASE_DIR, "..", "..", ".git"))
|
||||||
|
)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@ -12,6 +12,11 @@ urlpatterns = [
|
|||||||
views.update_session,
|
views.update_session,
|
||||||
name="update_session",
|
name="update_session",
|
||||||
),
|
),
|
||||||
|
path(
|
||||||
|
"start-session/<int:purchase_id>",
|
||||||
|
views.start_session,
|
||||||
|
name="start_session",
|
||||||
|
),
|
||||||
path(
|
path(
|
||||||
"delete_session/by-id/<int:session_id>",
|
"delete_session/by-id/<int:session_id>",
|
||||||
views.delete_session,
|
views.delete_session,
|
||||||
|
@ -40,6 +40,12 @@ def update_session(request, session_id=None):
|
|||||||
return redirect("list_sessions")
|
return redirect("list_sessions")
|
||||||
|
|
||||||
|
|
||||||
|
def start_session(request, purchase_id=None):
|
||||||
|
session = SessionForm({"purchase": purchase_id, "timestamp_start": now_with_tz()})
|
||||||
|
session.save()
|
||||||
|
return redirect("list_sessions")
|
||||||
|
|
||||||
|
|
||||||
def delete_session(request, session_id=None):
|
def delete_session(request, session_id=None):
|
||||||
session = Session.objects.get(id=session_id)
|
session = Session.objects.get(id=session_id)
|
||||||
session.delete()
|
session.delete()
|
||||||
@ -56,10 +62,11 @@ def list_sessions(request, purchase_id=None):
|
|||||||
dataset = Session.objects.all().order_by("timestamp_start")
|
dataset = Session.objects.all().order_by("timestamp_start")
|
||||||
|
|
||||||
for session in dataset:
|
for session in dataset:
|
||||||
if session.timestamp_end == None and session.duration_manual == None:
|
if session.timestamp_end == None and session.duration_manual.seconds == 0:
|
||||||
session.timestamp_end = datetime.now(ZoneInfo(settings.TIME_ZONE))
|
session.timestamp_end = datetime.now(ZoneInfo(settings.TIME_ZONE))
|
||||||
session.unfinished = True
|
session.unfinished = True
|
||||||
|
|
||||||
|
context["total_duration"] = dataset.total_duration()
|
||||||
context["dataset"] = dataset
|
context["dataset"] = dataset
|
||||||
|
|
||||||
return render(request, "list_sessions.html", context)
|
return render(request, "list_sessions.html", context)
|
||||||
@ -105,12 +112,6 @@ def add_platform(request):
|
|||||||
|
|
||||||
def index(request):
|
def index(request):
|
||||||
context = {}
|
context = {}
|
||||||
if Session.objects.count() == 0:
|
context["total_duration"] = Session().duration_sum
|
||||||
duration: str = ""
|
|
||||||
else:
|
|
||||||
context["total_duration"] = format_duration(
|
|
||||||
Session.total_sum(),
|
|
||||||
"%H hours %m minutes",
|
|
||||||
)
|
|
||||||
context["title"] = "Index"
|
context["title"] = "Index"
|
||||||
return render(request, "index.html", context)
|
return render(request, "index.html", context)
|
||||||
|
@ -34,7 +34,6 @@ ALLOWED_HOSTS = ["*"]
|
|||||||
|
|
||||||
INSTALLED_APPS = [
|
INSTALLED_APPS = [
|
||||||
"tracker.apps.TrackerConfig",
|
"tracker.apps.TrackerConfig",
|
||||||
"django.contrib.admin",
|
|
||||||
"django.contrib.auth",
|
"django.contrib.auth",
|
||||||
"django.contrib.contenttypes",
|
"django.contrib.contenttypes",
|
||||||
"django.contrib.sessions",
|
"django.contrib.sessions",
|
||||||
@ -44,6 +43,7 @@ INSTALLED_APPS = [
|
|||||||
|
|
||||||
if DEBUG:
|
if DEBUG:
|
||||||
INSTALLED_APPS.append("django_extensions")
|
INSTALLED_APPS.append("django_extensions")
|
||||||
|
INSTALLED_APPS.append("django.contrib.admin")
|
||||||
|
|
||||||
MIDDLEWARE = [
|
MIDDLEWARE = [
|
||||||
"django.middleware.security.SecurityMiddleware",
|
"django.middleware.security.SecurityMiddleware",
|
||||||
@ -123,6 +123,7 @@ USE_TZ = True
|
|||||||
# https://docs.djangoproject.com/en/4.1/howto/static-files/
|
# https://docs.djangoproject.com/en/4.1/howto/static-files/
|
||||||
|
|
||||||
STATIC_URL = "static/"
|
STATIC_URL = "static/"
|
||||||
|
STATIC_ROOT = BASE_DIR / "static"
|
||||||
|
|
||||||
# Default primary key field type
|
# Default primary key field type
|
||||||
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
|
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
|
||||||
@ -144,7 +145,8 @@ LOGGING = {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
CSRF_TRUSTED_ORIGINS = []
|
_csrf_trusted_origins = os.environ.get("CSRF_TRUSTED_ORIGINS")
|
||||||
|
if _csrf_trusted_origins:
|
||||||
if os.environ.get("PROD"):
|
CSRF_TRUSTED_ORIGINS = _csrf_trusted_origins.split(",")
|
||||||
CSRF_TRUSTED_ORIGINS.append(os.environ.get("CSRF_TRUSTED_ORIGINS"))
|
else:
|
||||||
|
CSRF_TRUSTED_ORIGINS = []
|
||||||
|
@ -16,10 +16,13 @@ Including another URLconf
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
from django.urls import include, path
|
from django.urls import include, path
|
||||||
from django.views.generic import RedirectView
|
from django.views.generic import RedirectView
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path("admin/", admin.site.urls),
|
|
||||||
path("", RedirectView.as_view(url="/tracker/list-sessions")),
|
path("", RedirectView.as_view(url="/tracker/list-sessions")),
|
||||||
path("tracker/", include("tracker.urls")),
|
path("tracker/", include("tracker.urls")),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
if settings.DEBUG:
|
||||||
|
urlpatterns.append(path("admin/", admin.site.urls))
|
||||||
|
@ -18,15 +18,40 @@ class FormatDurationTest(unittest.TestCase):
|
|||||||
result = format_duration(delta, "%H hours")
|
result = format_duration(delta, "%H hours")
|
||||||
self.assertEqual(result, "1 hours")
|
self.assertEqual(result, "1 hours")
|
||||||
|
|
||||||
|
def test_overflow_hours(self):
|
||||||
|
delta = timedelta(hours=25)
|
||||||
|
result = format_duration(delta, "%H hours")
|
||||||
|
self.assertEqual(result, "25 hours")
|
||||||
|
|
||||||
|
def test_overflow_hours_into_days(self):
|
||||||
|
delta = timedelta(hours=25)
|
||||||
|
result = format_duration(delta, "%d days, %H hours")
|
||||||
|
self.assertEqual(result, "1 days, 1 hours")
|
||||||
|
|
||||||
def test_only_minutes(self):
|
def test_only_minutes(self):
|
||||||
delta = timedelta(minutes=34)
|
delta = timedelta(minutes=34)
|
||||||
result = format_duration(delta, "%m minutes")
|
result = format_duration(delta, "%m minutes")
|
||||||
self.assertEqual(result, "34 minutes")
|
self.assertEqual(result, "34 minutes")
|
||||||
|
|
||||||
|
def test_only_overflow_minutes(self):
|
||||||
|
delta = timedelta(minutes=61)
|
||||||
|
result = format_duration(delta, "%m minutes")
|
||||||
|
self.assertEqual(result, "61 minutes")
|
||||||
|
|
||||||
|
def test_overflow_minutes_into_hours(self):
|
||||||
|
delta = timedelta(minutes=61)
|
||||||
|
result = format_duration(delta, "%H hours, %m minutes")
|
||||||
|
self.assertEqual(result, "1 hours, 1 minutes")
|
||||||
|
|
||||||
def test_only_overflow_seconds(self):
|
def test_only_overflow_seconds(self):
|
||||||
delta = timedelta(seconds=61)
|
delta = timedelta(seconds=61)
|
||||||
result = format_duration(delta, "%s seconds")
|
result = format_duration(delta, "%s seconds")
|
||||||
self.assertEqual(result, "1 seconds")
|
self.assertEqual(result, "61 seconds")
|
||||||
|
|
||||||
|
def test_overflow_seconds_into_minutes(self):
|
||||||
|
delta = timedelta(seconds=61)
|
||||||
|
result = format_duration(delta, "%m minutes, %s seconds")
|
||||||
|
self.assertEqual(result, "1 minutes, 1 seconds")
|
||||||
|
|
||||||
def test_only_rawseconds(self):
|
def test_only_rawseconds(self):
|
||||||
delta = timedelta(seconds=5690)
|
delta = timedelta(seconds=5690)
|
||||||
@ -56,3 +81,12 @@ class FormatDurationTest(unittest.TestCase):
|
|||||||
delta = timedelta(hours=-2)
|
delta = timedelta(hours=-2)
|
||||||
result = format_duration(delta, "%H hours")
|
result = format_duration(delta, "%H hours")
|
||||||
self.assertEqual(result, "0 hours")
|
self.assertEqual(result, "0 hours")
|
||||||
|
|
||||||
|
def test_none(self):
|
||||||
|
try:
|
||||||
|
format_duration(None)
|
||||||
|
except TypeError as exc:
|
||||||
|
assert False, f"format_duration(None) raised an exception {exc}"
|
||||||
|
|
||||||
|
def test_number(self):
|
||||||
|
self.assertEqual(format_duration(3600, "%H hour"), "1 hour")
|
||||||
|
Reference in New Issue
Block a user