wip
Some checks failed
build / image (push) Failing after 31s

This commit is contained in:
Antoine Pelletier 2026-10-24 12:55:18 +02:00
parent 5e160ae11c
commit ce985ef784
101 changed files with 5669 additions and 548 deletions

12
.dockerignore Normal file
View file

@ -0,0 +1,12 @@
# Only what the Dockerfile copies matters: keep the context small, and the secrets out
.git
target
storage
dev-db
config.yml
config.yaml
config.auth
.env
.vscode
frontend/node_modules
frontend/dist

View file

@ -0,0 +1,54 @@
# One job on purpose. The checks (eslint, vue-tsc, cargo test) live in the
# Dockerfile stages, so this workflow needs a single job image — one that has
# docker, git and node. Splitting the checks into their own jobs would mean
# `container: rust:...`, and a JavaScript action like `actions/checkout` needs
# node inside the job container, which the rust image does not have.
#
# Deliberately no third-party actions beyond `checkout`: a self-hosted Forgejo
# runner resolves `uses:` against its own mirror, and `docker/*` is usually not
# there. Plain docker commands work everywhere.
name: build
on:
push:
branches: [main]
workflow_dispatch:
env:
IMAGE: registry.tibiscuit.ch/studium
jobs:
image:
runs-on: ubuntu-latest
env:
# Secrets are read into the environment here, not interpolated into the
# shell commands below: `${{ secrets.X }}` inside a `run:` ends up in the
# process arguments, and the `secrets` context is not usable in `if:`.
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
PORTAINER_WEBHOOK: ${{ secrets.PORTAINER_WEBHOOK }}
steps:
- uses: actions/checkout@v4
# Turns itself on as soon as the registry has authentication and the two
# secrets exist; skipped while the registry is open.
- name: Log in to the registry
if: env.REGISTRY_USERNAME != ''
run: echo "$REGISTRY_PASSWORD" | docker login registry.tibiscuit.ch -u "$REGISTRY_USERNAME" --password-stdin
- name: Build and push
run: |
set -eu
docker build \
--build-arg GIT_HASH="${{ github.sha }}" \
--tag "$IMAGE:${{ github.sha }}" \
--tag "$IMAGE:latest" \
.
docker push "$IMAGE:${{ github.sha }}"
docker push "$IMAGE:latest"
# Portainer re-pulls the image and recreates the stack. Enable
# "Re-pull image" on the webhook, otherwise :latest stays the old layer.
- name: Redeploy on Portainer
if: env.PORTAINER_WEBHOOK != ''
run: curl -fsS -X POST "$PORTAINER_WEBHOOK"

View file

@ -0,0 +1,52 @@
{
"db_name": "PostgreSQL",
"query": "SELECT s.id, s.course_id, s.tag_id, s.weekday, s.start_time, s.end_time\n FROM time_slots s JOIN courses c ON c.id = s.course_id\n WHERE c.owner = $1\n ORDER BY s.weekday, s.start_time, s.id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "course_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "tag_id",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "weekday",
"type_info": "Int2"
},
{
"ordinal": 4,
"name": "start_time",
"type_info": "Time"
},
{
"ordinal": 5,
"name": "end_time",
"type_info": "Time"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false,
false,
false,
false
]
},
"hash": "022450cd184d5ccd6f09d4b80d59315f3ee9067bfc00499f192c4c217efb2d29"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM course_files\n WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": []
},
"hash": "0270806a2f7521c299bb3f33aad94d87ffa4ea83df1841912a441ae50f396d9c"
}

View file

@ -0,0 +1,76 @@
{
"db_name": "PostgreSQL",
"query": "SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,\n t.deadline, t.done, t.time_spent,\n COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)\n FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS \"tag_ids!\"\n FROM tasks t\n JOIN courses c ON c.id = t.course_id AND c.owner = $1\n LEFT JOIN task_tags tt ON tt.task_id = t.id\n WHERE t.id IN (SELECT id FROM tasks WHERE parent_id IS NULL AND NOT done)\n OR t.parent_id IN (SELECT id FROM tasks WHERE parent_id IS NULL AND NOT done)\n GROUP BY t.id\n ORDER BY t.id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "course_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "parent_id",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "links",
"type_info": "TextArray"
},
{
"ordinal": 6,
"name": "deadline",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "done",
"type_info": "Bool"
},
{
"ordinal": 8,
"name": "time_spent",
"type_info": "Int4"
},
{
"ordinal": 9,
"name": "tag_ids!",
"type_info": "Int4Array"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
true,
false,
true,
false,
true,
false,
false,
null
]
},
"hash": "0ee076ba8e885a59e5f2b31f946401479f985c87ad4f28a2e502a05f49833889"
}

View file

@ -0,0 +1,77 @@
{
"db_name": "PostgreSQL",
"query": "SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,\n t.deadline, t.done, t.time_spent,\n COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)\n FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS \"tag_ids!\"\n FROM tasks t\n JOIN courses c ON c.id = t.course_id AND c.owner = $2\n LEFT JOIN task_tags tt ON tt.task_id = t.id\n WHERE t.id = $1\n GROUP BY t.id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "course_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "parent_id",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "links",
"type_info": "TextArray"
},
{
"ordinal": 6,
"name": "deadline",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "done",
"type_info": "Bool"
},
{
"ordinal": 8,
"name": "time_spent",
"type_info": "Int4"
},
{
"ordinal": 9,
"name": "tag_ids!",
"type_info": "Int4Array"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false,
false,
true,
false,
true,
false,
true,
false,
false,
null
]
},
"hash": "16a674344d0d30f8ad3b11a25481121a97e8eacd9848499c8104579505203a79"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM courses WHERE id = $1 AND owner = $2",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": []
},
"hash": "16d59423114e405f69eac28cbdb62197be2c57f256c331b087cac6029d285884"
}

View file

@ -0,0 +1,19 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO time_slots (course_id, tag_id, weekday, start_time, end_time)\n SELECT id, $2, $3, $4, $5 FROM courses WHERE id = $1 AND owner = $6",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Int4",
"Int2",
"Time",
"Time",
"Text"
]
},
"nullable": []
},
"hash": "253febb057681ba7cb7b644c5ecfa054b43e30b6f81586a98f12029d8b99c1b8"
}

View file

@ -0,0 +1,20 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE tasks SET name = $2, description = $3, links = $4, deadline = $5, done = $6\n WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $7)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text",
"Text",
"TextArray",
"Timestamptz",
"Bool",
"Text"
]
},
"nullable": []
},
"hash": "2925a80406e08b4d5f56bb4768e5e269a6a7ff2457f50ebe83032029d7a53105"
}

View file

@ -0,0 +1,65 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, calendar_id, title, location, description, starts_at, ends_at, all_day\n FROM events\n WHERE id = $1 AND calendar_id IN (SELECT id FROM calendars WHERE owner = $2)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "calendar_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "title",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "location",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "starts_at",
"type_info": "Timestamptz"
},
{
"ordinal": 6,
"name": "ends_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "all_day",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false,
false,
false,
true,
true,
false,
true,
false
]
},
"hash": "2dbec0bbca07f88ce2ef1b67f962ce3cb5c49943895fd459c3fbef4f8255dc00"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM calendars WHERE id = $1 AND owner = $2",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": []
},
"hash": "349db07fde24a5c20267da22f454a0ac22e1cf64de7e993a0cbc3539d979893e"
}

View file

@ -0,0 +1,25 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO course_files (course_id, name, kind, path)\n SELECT id, $2, 'note', $3 FROM courses WHERE id = $1 AND owner = $4\n RETURNING id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
}
],
"parameters": {
"Left": [
"Int4",
"Text",
"Text",
"Text"
]
},
"nullable": [
false
]
},
"hash": "36c8da4b087ac7ae55b6a691867f66d94319e023a2034870cb24cf901486274a"
}

View file

@ -0,0 +1,19 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE grades SET name = $2, score = $3, max_score = $4, weight = $5\n WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $6)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text",
"Float8",
"Float8",
"Float8",
"Text"
]
},
"nullable": []
},
"hash": "384d94fe1033d6610a80da44e200119c500dfadc9a274cfd87218e2b92829383"
}

View file

@ -0,0 +1,71 @@
{
"db_name": "PostgreSQL",
"query": "SELECT f.id, f.course_id, f.name, f.kind, f.path, f.has_pdf, f.created_at, f.updated_at,\n COALESCE(ARRAY_AGG(ft.tag_id ORDER BY ft.tag_id)\n FILTER (WHERE ft.tag_id IS NOT NULL), '{}') AS \"tag_ids!\"\n FROM course_files f\n JOIN courses c ON c.id = f.course_id AND c.owner = $2\n LEFT JOIN file_tags ft ON ft.file_id = f.id\n WHERE f.id = $1\n GROUP BY f.id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "course_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "kind",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "path",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "has_pdf",
"type_info": "Bool"
},
{
"ordinal": 6,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "updated_at",
"type_info": "Timestamptz"
},
{
"ordinal": 8,
"name": "tag_ids!",
"type_info": "Int4Array"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false,
false,
false,
false,
false,
false,
false,
false,
null
]
},
"hash": "38c3a1dc809231f075a5945a79c22749b60d4401f525029edf15312f786877ce"
}

View file

@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM time_slots\n WHERE id = $1 AND course_id = $2\n AND course_id IN (SELECT id FROM courses WHERE owner = $3)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Int4",
"Text"
]
},
"nullable": []
},
"hash": "3bed2d1e90bcb627f9d9d3de84cd6fdeb8dd5e96ff7a77786632e33d4015b36c"
}

View file

@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO calendars (owner, name, color) VALUES ($1, $2, $3)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text",
"Text"
]
},
"nullable": []
},
"hash": "3dd5b4612a55c12f6518603e11c5cd1f3f5269649882f922495d355b976e532e"
}

View file

@ -0,0 +1,71 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO events\n (calendar_id, title, location, description, starts_at, ends_at, all_day)\n SELECT id, $2, $3, $4, $5, $6, $7 FROM calendars WHERE id = $1 AND owner = $8\n RETURNING id, calendar_id, title, location, description, starts_at, ends_at,\n all_day",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "calendar_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "title",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "location",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "starts_at",
"type_info": "Timestamptz"
},
{
"ordinal": 6,
"name": "ends_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "all_day",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Int4",
"Text",
"Text",
"Text",
"Timestamptz",
"Timestamptz",
"Bool",
"Text"
]
},
"nullable": [
false,
false,
false,
true,
true,
false,
true,
false
]
},
"hash": "408662559ba3c8ac507033502066b1c5ebf442b7d2f1751a32240c6d3bd993e0"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO task_tags (task_id, tag_id)\n SELECT $1, tag_id FROM UNNEST($2::INTEGER[]) AS tag_id\n ON CONFLICT DO NOTHING",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Int4Array"
]
},
"nullable": []
},
"hash": "45e575bf790edc0158fe5211da34f165f723e159aa829b3df2dfadb169b95c11"
}

View file

@ -0,0 +1,58 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, kind, name, code, teachers, main_page_url, folder\n FROM courses WHERE owner = $1 ORDER BY name, id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "kind",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "code",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "teachers",
"type_info": "TextArray"
},
{
"ordinal": 5,
"name": "main_page_url",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "folder",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false,
true,
false,
true,
false
]
},
"hash": "4b1692df89b23fb197aa0ab6b19d45bb2382d2549db1ad475400594248abbeed"
}

View file

@ -0,0 +1,59 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, kind, name, code, teachers, main_page_url, folder\n FROM courses WHERE id = $1 AND owner = $2",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "kind",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "code",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "teachers",
"type_info": "TextArray"
},
{
"ordinal": 5,
"name": "main_page_url",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "folder",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false,
false,
false,
true,
false,
true,
false
]
},
"hash": "5c8607c6e765e5b87f24744438438b5fe951c58cc7be848b96cfb6a8f721585f"
}

View file

@ -0,0 +1,64 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO courses (owner, kind, name, code, teachers, main_page_url, folder)\n VALUES ($7, $1, $2, $3, $4, $5, $6)\n RETURNING id, kind, name, code, teachers, main_page_url, folder",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "kind",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "code",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "teachers",
"type_info": "TextArray"
},
{
"ordinal": 5,
"name": "main_page_url",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "folder",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Text",
"Text",
"Text",
"TextArray",
"Text",
"Text",
"Text"
]
},
"nullable": [
false,
false,
false,
true,
false,
true,
false
]
},
"hash": "67912ef2ee6af9f27e021328b2938d6e039dc6c4f76e878bf3b996b716c54640"
}

View file

@ -0,0 +1,77 @@
{
"db_name": "PostgreSQL",
"query": "SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,\n t.deadline, t.done, t.time_spent,\n COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)\n FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS \"tag_ids!\"\n FROM tasks t\n JOIN courses c ON c.id = t.course_id AND c.owner = $2\n LEFT JOIN task_tags tt ON tt.task_id = t.id\n WHERE t.course_id = $1\n GROUP BY t.id\n ORDER BY t.id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "course_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "parent_id",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "links",
"type_info": "TextArray"
},
{
"ordinal": 6,
"name": "deadline",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "done",
"type_info": "Bool"
},
{
"ordinal": 8,
"name": "time_spent",
"type_info": "Int4"
},
{
"ordinal": 9,
"name": "tag_ids!",
"type_info": "Int4Array"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false,
false,
true,
false,
true,
false,
true,
false,
false,
null
]
},
"hash": "688981658bd5bc4c5d061d0528f6c806cc2ce2fe6050dc9f52908d619285ed2e"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO file_tags (file_id, tag_id)\n SELECT $1, tag_id FROM UNNEST($2::INTEGER[]) AS tag_id",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Int4Array"
]
},
"nullable": []
},
"hash": "6a2d2f4b7c24bd671f0fe5c550e30a6297b7142cbc72ef69c073ad4072ad9ea0"
}

View file

@ -0,0 +1,47 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, name, score, max_score, weight FROM grades\n WHERE course_id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)\n ORDER BY id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "score",
"type_info": "Float8"
},
{
"ordinal": 3,
"name": "max_score",
"type_info": "Float8"
},
{
"ordinal": 4,
"name": "weight",
"type_info": "Float8"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false,
false,
false,
false,
false
]
},
"hash": "6f6c33a9ed3792a2dbfce200e3dd1ba4bc02fa0b93450e551584d3335475d79a"
}

View file

@ -0,0 +1,19 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO grades (course_id, name, score, max_score, weight)\n SELECT id, $2, $3, $4, $5 FROM courses WHERE id = $1 AND owner = $6",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text",
"Float8",
"Float8",
"Float8",
"Text"
]
},
"nullable": []
},
"hash": "70f85820ef9062be82f0acc0c3cc347e7e4973a4d67ef8d5f8147ffa3f5a55bc"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM tasks\n WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": []
},
"hash": "74030bb10ad36911b9fd55d19d95f811842830075e7fbf0a7127a2a3f8e7d8c8"
}

View file

@ -0,0 +1,24 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE tasks SET time_spent = time_spent + $2\n WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $3)\n RETURNING time_spent",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "time_spent",
"type_info": "Int4"
}
],
"parameters": {
"Left": [
"Int4",
"Int4",
"Text"
]
},
"nullable": [
false
]
},
"hash": "78c9ebfe2e95ec579e3b2dd96e7fac23fbba3d057d006d2ab06c7f1c7f5a103b"
}

View file

@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "SELECT course_id FROM grades\n WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "course_id",
"type_info": "Int4"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false
]
},
"hash": "795f6a1eccdabe3c344949f9c7b382ae5709b1700f36f9d4dc3e2df5a68e882c"
}

View file

@ -0,0 +1,29 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO tasks (course_id, parent_id, name, description, links, deadline, done)\n SELECT id, $2, $3, $4, $5, $6, $7 FROM courses WHERE id = $1 AND owner = $8\n RETURNING id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
}
],
"parameters": {
"Left": [
"Int4",
"Int4",
"Text",
"Text",
"TextArray",
"Timestamptz",
"Bool",
"Text"
]
},
"nullable": [
false
]
},
"hash": "7c52bfa69d62471bd84baccaf19cdb444ed02c6fea2f6b6fe00bb7e3446e1ec7"
}

View file

@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, name, color FROM calendars WHERE owner = $1 ORDER BY id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "color",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false
]
},
"hash": "920a585069249b2d0f2f0be096f231de7f96c73aa91152d11d9f6fce4f56904f"
}

View file

@ -0,0 +1,17 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE calendars SET name = $2, color = $3 WHERE id = $1 AND owner = $4",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text",
"Text",
"Text"
]
},
"nullable": []
},
"hash": "952be5e6de4c5e1db46c523e6679f3e5405fdc6073252447a706de637f628319"
}

View file

@ -0,0 +1,22 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id FROM tags WHERE slug = $1",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false
]
},
"hash": "9b165200b303773be1afd4e94cfacb4d3cff3b249e6238032a336552e94423e4"
}

View file

@ -0,0 +1,78 @@
{
"db_name": "PostgreSQL",
"query": "SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,\n t.deadline, t.done, t.time_spent,\n COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)\n FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS \"tag_ids!\"\n FROM tasks t\n JOIN courses c ON c.id = t.course_id AND c.owner = $3\n LEFT JOIN task_tags tt ON tt.task_id = t.id\n WHERE (t.deadline >= $1 AND t.deadline < $2)\n OR t.id IN (SELECT parent_id FROM tasks\n WHERE deadline >= $1 AND deadline < $2 AND parent_id IS NOT NULL)\n GROUP BY t.id\n ORDER BY t.id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "course_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "parent_id",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "links",
"type_info": "TextArray"
},
{
"ordinal": 6,
"name": "deadline",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "done",
"type_info": "Bool"
},
{
"ordinal": 8,
"name": "time_spent",
"type_info": "Int4"
},
{
"ordinal": 9,
"name": "tag_ids!",
"type_info": "Int4Array"
}
],
"parameters": {
"Left": [
"Timestamptz",
"Timestamptz",
"Text"
]
},
"nullable": [
false,
false,
true,
false,
true,
false,
true,
false,
false,
null
]
},
"hash": "9be470705776fdd73222078776b785cee496fb822c03e6a8daada1a35b1f55b8"
}

View file

@ -0,0 +1,35 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, name, color FROM calendars WHERE id = $1 AND owner = $2",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "color",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false,
false,
false
]
},
"hash": "9e20c5ab6d09706a9c3b600b1db6b88515a9160d0149db85df08a4f9233f5256"
}

View file

@ -0,0 +1,66 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, calendar_id, title, location, description, starts_at, ends_at, all_day\n FROM events\n WHERE starts_at < $2\n AND (ends_at > $1 OR (ends_at IS NULL AND starts_at >= $1))\n AND calendar_id IN (SELECT id FROM calendars WHERE owner = $3)\n ORDER BY starts_at, id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "calendar_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "title",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "location",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "starts_at",
"type_info": "Timestamptz"
},
{
"ordinal": 6,
"name": "ends_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "all_day",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Timestamptz",
"Timestamptz",
"Text"
]
},
"nullable": [
false,
false,
false,
true,
true,
false,
true,
false
]
},
"hash": "a357ad6ba20b7645245646e0bbb114484a24e2bcc10ff0a291b35606c1e277f6"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM grades\n WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": []
},
"hash": "a4b97dde542b193867ca8beb78d88b75edaa08abbfe2ca09c7f3d21b03bcfcee"
}

View file

@ -0,0 +1,18 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE course_files SET name = $2, path = $3, has_pdf = $4, updated_at = now()\n WHERE id = $1 AND kind = 'note'\n AND course_id IN (SELECT id FROM courses WHERE owner = $5)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text",
"Text",
"Bool",
"Text"
]
},
"nullable": []
},
"hash": "a71592742c8dc24bef841c890479d61aba9f6378f0006a8b22bda64e9384a369"
}

View file

@ -0,0 +1,52 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, course_id, tag_id, weekday, start_time, end_time\n FROM time_slots WHERE course_id = $1 ORDER BY weekday, start_time, id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "course_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "tag_id",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "weekday",
"type_info": "Int2"
},
{
"ordinal": 4,
"name": "start_time",
"type_info": "Time"
},
{
"ordinal": 5,
"name": "end_time",
"type_info": "Time"
}
],
"parameters": {
"Left": [
"Int4"
]
},
"nullable": [
false,
false,
false,
false,
false,
false
]
},
"hash": "ac6921146d07ec7c23da435a8c2494b15960b1fe041214b154d424f85e5b8381"
}

View file

@ -0,0 +1,72 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE events SET calendar_id = $2, title = $3, location = $4, description = $5,\n starts_at = $6, ends_at = $7, all_day = $8\n WHERE id = $1\n AND calendar_id IN (SELECT id FROM calendars WHERE owner = $9)\n AND $2 IN (SELECT id FROM calendars WHERE owner = $9)\n RETURNING id, calendar_id, title, location, description, starts_at, ends_at,\n all_day",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "calendar_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "title",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "location",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "description",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "starts_at",
"type_info": "Timestamptz"
},
{
"ordinal": 6,
"name": "ends_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "all_day",
"type_info": "Bool"
}
],
"parameters": {
"Left": [
"Int4",
"Int4",
"Text",
"Text",
"Text",
"Timestamptz",
"Timestamptz",
"Bool",
"Text"
]
},
"nullable": [
false,
false,
false,
true,
true,
false,
true,
false
]
},
"hash": "b78f7a8b18a3aa0c98841c17e496c06fb0dfde9b95082d42e5418b416d4786c8"
}

View file

@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, name, color, slug, scopes FROM tags\n WHERE $1::TEXT IS NULL OR $1 = ANY(scopes)\n ORDER BY id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Jsonb"
},
{
"ordinal": 2,
"name": "color",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "slug",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "scopes",
"type_info": "TextArray"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false,
true,
false
]
},
"hash": "cc1eef4626da357a2605bb32c64271fffddde727a7e449dfaae658051025558a"
}

View file

@ -0,0 +1,71 @@
{
"db_name": "PostgreSQL",
"query": "SELECT f.id, f.course_id, f.name, f.kind, f.path, f.has_pdf, f.created_at, f.updated_at,\n COALESCE(ARRAY_AGG(ft.tag_id ORDER BY ft.tag_id)\n FILTER (WHERE ft.tag_id IS NOT NULL), '{}') AS \"tag_ids!\"\n FROM course_files f\n JOIN courses c ON c.id = f.course_id AND c.owner = $2\n LEFT JOIN file_tags ft ON ft.file_id = f.id\n WHERE f.course_id = $1\n GROUP BY f.id\n ORDER BY f.created_at, f.id",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "course_id",
"type_info": "Int4"
},
{
"ordinal": 2,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "kind",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "path",
"type_info": "Text"
},
{
"ordinal": 5,
"name": "has_pdf",
"type_info": "Bool"
},
{
"ordinal": 6,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 7,
"name": "updated_at",
"type_info": "Timestamptz"
},
{
"ordinal": 8,
"name": "tag_ids!",
"type_info": "Int4Array"
}
],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": [
false,
false,
false,
false,
false,
false,
false,
false,
null
]
},
"hash": "d037e9597a9d4ba59c0825e8f264a757319754e5882af2d6d2ef465a98590092"
}

View file

@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM events\n WHERE id = $1 AND calendar_id IN (SELECT id FROM calendars WHERE owner = $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4",
"Text"
]
},
"nullable": []
},
"hash": "f06ef7be08ca4b56d54b0c2e230b07d918a0f6bbbf7037c15773a0cda44f1f18"
}

View file

@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "DELETE FROM task_tags WHERE task_id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int4"
]
},
"nullable": []
},
"hash": "f6a2ae2f08904b0699b90d67b5c17b5d499cfe84d5a0dd7a58ad1411b6500182"
}

View file

@ -0,0 +1,64 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE courses\n SET name = $2, code = $3, teachers = $4, main_page_url = $5, folder = $6\n WHERE id = $1 AND owner = $7\n RETURNING id, kind, name, code, teachers, main_page_url, folder",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "kind",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "name",
"type_info": "Text"
},
{
"ordinal": 3,
"name": "code",
"type_info": "Text"
},
{
"ordinal": 4,
"name": "teachers",
"type_info": "TextArray"
},
{
"ordinal": 5,
"name": "main_page_url",
"type_info": "Text"
},
{
"ordinal": 6,
"name": "folder",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Int4",
"Text",
"Text",
"TextArray",
"Text",
"Text",
"Text"
]
},
"nullable": [
false,
false,
false,
true,
false,
true,
false
]
},
"hash": "f927c26731ebd4ac640777534b7072936235d40044ff86a6234046c35948823e"
}

89
Dockerfile Normal file
View file

@ -0,0 +1,89 @@
# Frontend: built first, it is the part that changes most often
FROM node:22-slim AS frontend
WORKDIR /build
# Dependencies in their own layer, so a source-only change does not reinstall them
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend/ ./
# The checks run here rather than in a separate CI job: the build then fails on
# the runner for the same reason it would fail locally, and there is only one
# environment to keep working.
RUN npx eslint . --max-warnings=0
RUN npm run build # type-check + vite build
# Backend: compiled against the sqlx offline data (`cargo sqlx prepare`), so no
# database is needed here
FROM rust:1.97-slim AS backend
WORKDIR /build
ENV SQLX_OFFLINE=true
# Traceability: `build.rs` falls back on this when there is no git repository
ARG GIT_HASH=unknown
ENV GIT_HASH=${GIT_HASH}
# Warm the dependency layer with a dummy main, so editing src/ does not rebuild
# every crate we depend on
COPY Cargo.toml Cargo.lock build.rs ./
RUN mkdir src && echo 'fn main() {}' > src/main.rs \
&& cargo build --release \
&& rm -rf src
COPY .sqlx/ .sqlx/
COPY src/ src/
# cargo skips a rebuild when only mtime changed: force it for our own crate
RUN touch src/main.rs \
&& cargo build --release --locked \
&& cargo test --release --locked
# Runtime
FROM debian:trixie-slim
LABEL org.opencontainers.image.title="studium"
# The lecture notes are rendered by pandoc and pdflatex. latex-extra holds tcolorbox,
# sectsty and pmboxdraw, used by the template. curl serves the healthcheck, and
# fetches pandoc below.
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
curl ca-certificates \
texlive-latex-base texlive-latex-recommended texlive-latex-extra \
texlive-fonts-recommended texlive-pictures lmodern \
&& rm -rf /var/lib/apt/lists/*
# The pandoc of Debian is too old for `--syntax-highlighting` (3.8+): the release of
# pandoc itself, the same version as in development
ARG PANDOC_VERSION=3.11
RUN arch="$(dpkg --print-architecture)" \
&& curl -fsSL -o /tmp/pandoc.deb \
"https://github.com/jgm/pandoc/releases/download/${PANDOC_VERSION}/pandoc-${PANDOC_VERSION}-1-${arch}.deb" \
&& dpkg -i /tmp/pandoc.deb \
&& rm /tmp/pandoc.deb
# The migrations travel with the image, so the stack needs nothing from the
# repository: the `migrate` service runs this same image with another entrypoint.
COPY --from=ghcr.io/amacneil/dbmate:2 /usr/local/bin/dbmate /usr/local/bin/dbmate
COPY db/migrations/ /app/db/migrations/
# Not root: the app only needs to write in its storage. The folder mounted there must
# belong to this uid (`chown -R 1000:1000` on the host).
RUN useradd --uid 1000 --create-home studium \
&& mkdir -p /data/storage \
&& chown studium:studium /data/storage
WORKDIR /app
COPY --from=backend /build/target/release/studium /usr/local/bin/studium
COPY --from=frontend /build/dist/ /app/frontend/
COPY LaTeX_pdf/ /app/LaTeX_pdf/
COPY docker/config.yml /etc/studium/config.yml
USER studium
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD curl -fsS http://localhost:3000/api/version || exit 1
# No shell: signals reach the binary directly, so the graceful shutdown works
ENTRYPOINT ["/usr/local/bin/studium"]

View file

@ -15,7 +15,10 @@ shadcn-vue), on **PostgreSQL** with **dbmate** migrations.
- Tailwind 4 and the shadcn-vue components already vendored in `frontend/src/components/ui`
- A single binary in production: the backend serves the built frontend
There is **no authentication** in this template: add whatever the project needs.
Authentication is left to **Authelia**, in front of the app (forward auth of the reverse
proxy): it gives the login of the person in the `Remote-User` header, and each person has
their own courses, calendars and files. The app must only be reachable through Authelia.
Without it (development), `auth.default_user` in `config.yml` says who the requests act as.
## Getting started
@ -36,12 +39,29 @@ cargo run
cd frontend && npm install && npm run dev
```
Open http://localhost:5000. The api documentation is on http://localhost:3000/api/docs.
In development too, the app is reached through the real Authelia: the reverse proxy of the
server forwards `studium-dev.<domain>` to this machine (port 5000) through the VPN. Without
it, set `auth.default_user` in `config.yml` and open http://localhost:5000.
The api documentation is on http://localhost:3000/api/docs.
`config.yml` is gitignored: it is where the secrets go. `config.example.yml` documents every
key, keep it up to date. Every value can also come from the environment
(`APP__POSTGRES__PASSWORD=...`), which is how the app is configured in production.
## Deployment
A push on `main` builds the image (`Dockerfile`, which also runs the checks and the
tests), pushes it to `registry.tibiscuit.ch/studium` and redeploys the Portainer stack
(`.forgejo/workflows/build.yml`). The stack is `docker-compose.yml`: its header lists the
variables to set in Portainer.
- The sql queries are checked at compile time: after changing one, run
`cargo sqlx prepare` and commit `.sqlx/`, or the image does not build.
- The files go to `/mnt/nas.data/dockers/studium` on the server, which must belong to
uid 1000 (the user of the container).
- Caddy puts Authelia in front of the app, and adds the `X-Proxy-Secret` header
(`PROXY_SECRET` of the stack): the app refuses any request without it.
## Layout
```
@ -54,8 +74,8 @@ key, keep it up to date. Every value can also come from the environment
│ ├── services/ implementations of the repositories (postgres/sqlx)
│ └── utils/ configuration
├── LaTeX_pdf/ template of the lecture notes pdf (pandoc + pdflatex)
├── storage/ files of the courses and associations, one folder each,
│ stands in for the NAS (gitignored)
├── storage/ files of the courses and associations, a folder per person
│ then per course, stands in for the NAS (gitignored)
├── db/
│ ├── migrations/ dbmate migrations
│ ├── schema.sql dump regenerated by dbmate, do not edit by hand

View file

@ -8,7 +8,10 @@ fn main() {
.ok()
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|hash| hash.trim().chars().take(8).collect::<String>())
.map(|hash| hash.trim().to_owned())
// No repository in a docker build: the hash is given as a build argument
.or_else(|| std::env::var("GIT_HASH").ok())
.map(|hash| hash.chars().take(8).collect::<String>())
.unwrap_or_else(|| "unknown".to_owned());
println!("cargo:rustc-env=GIT_HASH={git_hash}");
@ -17,4 +20,5 @@ fn main() {
env!("CARGO_PKG_NAME").replace("-", "_")
);
println!("cargo:rerun-if-changed=.git/HEAD");
println!("cargo:rerun-if-env-changed=GIT_HASH");
}

0
config.auth Normal file
View file

View file

@ -15,8 +15,8 @@ postgres:
frontend_dir: frontend/dist
# Where the files of the courses and associations are stored (lecture notes and their
# pdf...), one folder each: Cours/CS-477 Advanced OS/Notes/..., Associations/...
# A local directory standing in for the NAS for now.
# pdf...): a folder per person, then one per course: jdoe/Cours/CS-477 Advanced OS/Notes/...
# A local directory, or the NAS mounted.
storage_dir: storage
# Rendering of the lecture notes to pdf (needs pandoc and pdflatex)
@ -25,15 +25,34 @@ notes:
template_dir: LaTeX_pdf
# Relative to template_dir
logo: assets/epfl.png
# Shown in the header of the pdf, both optional
student_name: Jane Doe
student_id: "123456"
# Optional: the focus sessions of the pomodoro are also counted in TimeTagger, tagged
# with the course code, the tags and the name of the task. Without it, the time is only
# counted in the app.
# The app must be behind Authelia (forward auth of the reverse proxy), which gives the
# login of the person in the Remote-User header: each person has their own courses,
# calendars and files. The app must not be reachable without going through Authelia,
# or anyone could send this header.
auth:
# Login used for the requests without Remote-User. Only for development, never in
# production: anyone reaching the app would be this person.
# default_user: jdoe
# Where the "log out" link leads: the logout page of Authelia
# logout_url: https://auth.example.com/logout
# Secret the reverse proxy sends in the X-Proxy-Secret header: the requests without it
# are refused. Set it whenever the port of the app can be reached by anything else than
# the proxy (e.g. `openssl rand -hex 32`).
# proxy_secret: ...
# Optional: the focus sessions of the pomodoro can also be counted in TimeTagger, tagged
# with the course code, the tags and the name of the task, for the people with a token.
# timetagger:
# # https://timetagger.app/api/v2 by default, or the api of your own server
# url: https://timetagger.app/api/v2
# # Api token, from the account page of TimeTagger
# token: ...
# Settings of each person, by login, all optional
# users:
# jdoe:
# # Shown in the header of the notes (the name given by Authelia by default)
# student_name: Jane Doe
# student_id: "123456"
# # Api token, from the account page of TimeTagger. Without it, the time is only
# # counted in the app.
# timetagger_token: ...

View file

@ -0,0 +1,33 @@
-- migrate:up
-- Personal calendars, apart from the courses and associations. Their events are not
-- tasks: nothing to check, only something happening at a time, maybe somewhere.
CREATE TABLE calendars (
id SERIAL PRIMARY KEY,
"name" TEXT NOT NULL,
-- Hex color of the events, e.g. `#2563eb`
color TEXT NOT NULL CHECK (color ~ '^#[0-9a-fA-F]{6}$')
);
-- An event of a personal calendar: a time range, or a single moment (a deadline, a
-- reminder) when `ends_at` is null. An all-day event goes from the midnight of its
-- first day to the midnight after its last one, in the time zone of the user.
CREATE TABLE events (
id SERIAL PRIMARY KEY,
calendar_id INTEGER NOT NULL REFERENCES calendars (id) ON DELETE CASCADE,
title TEXT NOT NULL,
"location" TEXT,
description TEXT,
starts_at TIMESTAMPTZ NOT NULL,
ends_at TIMESTAMPTZ,
all_day BOOLEAN NOT NULL DEFAULT FALSE,
CHECK (ends_at IS NULL OR ends_at > starts_at),
CHECK (NOT all_day OR ends_at IS NOT NULL)
);
CREATE INDEX events_starts_at_idx ON events (starts_at);
CREATE INDEX events_calendar_id_idx ON events (calendar_id);
-- migrate:down
DROP TABLE IF EXISTS events;
DROP TABLE IF EXISTS calendars;

View file

@ -0,0 +1,25 @@
-- migrate:up
-- Each person has their own courses, associations and calendars: they are owned by the
-- login given by Authelia (`Remote-User`). Everything else (slots, grades, tasks,
-- files, events) belongs to the owner of its course or calendar. The tags stay shared.
-- What existed before is given to the first user of the app.
ALTER TABLE courses ADD COLUMN "owner" TEXT;
UPDATE courses SET "owner" = 'appellet';
ALTER TABLE courses ALTER COLUMN "owner" SET NOT NULL;
-- The folders are in the folder of their owner in the storage: two people may have the
-- same course
ALTER TABLE courses DROP CONSTRAINT courses_folder_key;
ALTER TABLE courses ADD CONSTRAINT courses_owner_folder_key UNIQUE ("owner", folder);
ALTER TABLE calendars ADD COLUMN "owner" TEXT;
UPDATE calendars SET "owner" = 'appellet';
ALTER TABLE calendars ALTER COLUMN "owner" SET NOT NULL;
CREATE INDEX calendars_owner_idx ON calendars ("owner");
-- migrate:down
DROP INDEX IF EXISTS calendars_owner_idx;
ALTER TABLE calendars DROP COLUMN "owner";
ALTER TABLE courses DROP CONSTRAINT courses_owner_folder_key;
ALTER TABLE courses ADD CONSTRAINT courses_folder_key UNIQUE (folder);
ALTER TABLE courses DROP COLUMN "owner";

View file

@ -19,6 +19,39 @@ SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: calendars; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.calendars (
id integer NOT NULL,
name text NOT NULL,
color text NOT NULL,
owner text NOT NULL,
CONSTRAINT calendars_color_check CHECK ((color ~ '^#[0-9a-fA-F]{6}$'::text))
);
--
-- Name: calendars_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.calendars_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: calendars_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.calendars_id_seq OWNED BY public.calendars.id;
--
-- Name: course_files; Type: TABLE; Schema: public; Owner: -
--
@ -68,6 +101,7 @@ CREATE TABLE public.courses (
main_page_url text,
kind text NOT NULL,
folder text NOT NULL,
owner text NOT NULL,
CONSTRAINT courses_kind_check CHECK ((kind = ANY (ARRAY['course'::text, 'association'::text])))
);
@ -92,6 +126,44 @@ CREATE SEQUENCE public.courses_id_seq
ALTER SEQUENCE public.courses_id_seq OWNED BY public.courses.id;
--
-- Name: events; Type: TABLE; Schema: public; Owner: -
--
CREATE TABLE public.events (
id integer NOT NULL,
calendar_id integer NOT NULL,
title text NOT NULL,
location text,
description text,
starts_at timestamp with time zone NOT NULL,
ends_at timestamp with time zone,
all_day boolean DEFAULT false NOT NULL,
CONSTRAINT events_check CHECK (((ends_at IS NULL) OR (ends_at > starts_at))),
CONSTRAINT events_check1 CHECK (((NOT all_day) OR (ends_at IS NOT NULL)))
);
--
-- Name: events_id_seq; Type: SEQUENCE; Schema: public; Owner: -
--
CREATE SEQUENCE public.events_id_seq
AS integer
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
--
-- Name: events_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
--
ALTER SEQUENCE public.events_id_seq OWNED BY public.events.id;
--
-- Name: file_tags; Type: TABLE; Schema: public; Owner: -
--
@ -267,6 +339,13 @@ CREATE SEQUENCE public.time_slots_id_seq
ALTER SEQUENCE public.time_slots_id_seq OWNED BY public.time_slots.id;
--
-- Name: calendars id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.calendars ALTER COLUMN id SET DEFAULT nextval('public.calendars_id_seq'::regclass);
--
-- Name: course_files id; Type: DEFAULT; Schema: public; Owner: -
--
@ -281,6 +360,13 @@ ALTER TABLE ONLY public.course_files ALTER COLUMN id SET DEFAULT nextval('public
ALTER TABLE ONLY public.courses ALTER COLUMN id SET DEFAULT nextval('public.courses_id_seq'::regclass);
--
-- Name: events id; Type: DEFAULT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.events ALTER COLUMN id SET DEFAULT nextval('public.events_id_seq'::regclass);
--
-- Name: grades id; Type: DEFAULT; Schema: public; Owner: -
--
@ -309,6 +395,14 @@ ALTER TABLE ONLY public.tasks ALTER COLUMN id SET DEFAULT nextval('public.tasks_
ALTER TABLE ONLY public.time_slots ALTER COLUMN id SET DEFAULT nextval('public.time_slots_id_seq'::regclass);
--
-- Name: calendars calendars_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.calendars
ADD CONSTRAINT calendars_pkey PRIMARY KEY (id);
--
-- Name: course_files course_files_course_id_path_key; Type: CONSTRAINT; Schema: public; Owner: -
--
@ -326,11 +420,11 @@ ALTER TABLE ONLY public.course_files
--
-- Name: courses courses_folder_key; Type: CONSTRAINT; Schema: public; Owner: -
-- Name: courses courses_owner_folder_key; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.courses
ADD CONSTRAINT courses_folder_key UNIQUE (folder);
ADD CONSTRAINT courses_owner_folder_key UNIQUE (owner, folder);
--
@ -341,6 +435,14 @@ ALTER TABLE ONLY public.courses
ADD CONSTRAINT courses_pkey PRIMARY KEY (id);
--
-- Name: events events_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.events
ADD CONSTRAINT events_pkey PRIMARY KEY (id);
--
-- Name: file_tags file_tags_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@ -405,6 +507,13 @@ ALTER TABLE ONLY public.time_slots
ADD CONSTRAINT time_slots_pkey PRIMARY KEY (id);
--
-- Name: calendars_owner_idx; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX calendars_owner_idx ON public.calendars USING btree (owner);
--
-- Name: course_files_course_id_idx; Type: INDEX; Schema: public; Owner: -
--
@ -412,6 +521,20 @@ ALTER TABLE ONLY public.time_slots
CREATE INDEX course_files_course_id_idx ON public.course_files USING btree (course_id);
--
-- Name: events_calendar_id_idx; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX events_calendar_id_idx ON public.events USING btree (calendar_id);
--
-- Name: events_starts_at_idx; Type: INDEX; Schema: public; Owner: -
--
CREATE INDEX events_starts_at_idx ON public.events USING btree (starts_at);
--
-- Name: grades_course_id_idx; Type: INDEX; Schema: public; Owner: -
--
@ -441,6 +564,14 @@ ALTER TABLE ONLY public.course_files
ADD CONSTRAINT course_files_course_id_fkey FOREIGN KEY (course_id) REFERENCES public.courses(id) ON DELETE CASCADE;
--
-- Name: events events_calendar_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
ALTER TABLE ONLY public.events
ADD CONSTRAINT events_calendar_id_fkey FOREIGN KEY (calendar_id) REFERENCES public.calendars(id) ON DELETE CASCADE;
--
-- Name: file_tags file_tags_file_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: -
--
@ -528,4 +659,6 @@ INSERT INTO public.schema_migrations (version) VALUES
('20260928120000'),
('20260928150000'),
('20260929090000'),
('20260929180000');
('20260929180000'),
('20261022100000'),
('20261024120000');

76
docker-compose.yml Normal file
View file

@ -0,0 +1,76 @@
# Stack for Portainer. Everything it needs lives in the image, so it can be
# deployed by pasting this file — no checkout of the repository on the server.
#
# Environment variables to set in the Portainer stack:
# IMAGE registry.tibiscuit.ch/studium:latest
# POSTGRES_PASSWORD anything, it never leaves the internal network
# PROXY_SECRET shared with Caddy (`openssl rand -hex 32`): without it in the
# X-Proxy-Secret header, a request is refused
# APP_PORT host port for the reverse proxy to point at (default 3011)
# LOGOUT_URL logout page of Authelia, e.g. https://authelia.tibiscuit.ch/logout
#
# The settings of each person also come from the environment, by login (all optional):
# APP__USERS__<login>__STUDENT_NAME, APP__USERS__<login>__STUDENT_ID,
# APP__USERS__<login>__TIMETAGGER_TOKEN
services:
db:
image: postgres:18.3-alpine
restart: unless-stopped
environment:
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in the stack}
POSTGRES_DB: studium
volumes:
# Postgres 18 moved PGDATA to /var/lib/postgresql/18/docker and its declared
# VOLUME to /var/lib/postgresql. Mounting the pre-18 /var/lib/postgresql/data
# leaves the real data outside the volume, and trips the entrypoint.
- db_data:/var/lib/postgresql
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres -d studium']
interval: 5s
timeout: 5s
retries: 10
# initdb runs on the very first boot: do not count failures before it is done
start_period: 30s
networks: [internal]
# Runs once per deployment, before the app: applies any new migration, then exits
migrate:
image: ${IMAGE:?set IMAGE in the stack}
restart: 'no'
entrypoint:
['dbmate', '--migrations-dir', '/app/db/migrations', '--no-dump-schema', 'up']
environment:
DATABASE_URL: postgres://postgres:${POSTGRES_PASSWORD}@db:5432/studium?sslmode=disable
depends_on:
db:
condition: service_healthy
networks: [internal]
app:
image: ${IMAGE:?set IMAGE in the stack}
restart: unless-stopped
ports:
- '${APP_PORT:-3011}:3000'
environment:
APP__POSTGRES__PASSWORD: ${POSTGRES_PASSWORD}
# The app trusts the Remote-User header of Authelia: only the requests carrying
# this secret, added by Caddy, are accepted
APP__AUTH__PROXY_SECRET: ${PROXY_SECRET:?set PROXY_SECRET in the stack}
APP__AUTH__LOGOUT_URL: ${LOGOUT_URL:-}
volumes:
# Files of the courses: a folder per person. Must belong to uid 1000, the user
# of the container.
- /mnt/nas.data/dockers/studium:/data/storage
depends_on:
db:
condition: service_healthy
migrate:
condition: service_completed_successfully
networks: [internal]
volumes:
db_data:
networks:
internal:

View file

@ -2,7 +2,10 @@
<html lang="fr">
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="theme-color" content="#155dfc" />
<link rel="stylesheet" href="/src/styles/tailwind.css" />
<link
rel="stylesheet"

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View file

@ -0,0 +1,22 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<!-- Logo of Studium: the graduation cap of the sidebar, white on the primary blue -->
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#2b7fff" />
<stop offset="1" stop-color="#155dfc" />
</linearGradient>
</defs>
<rect width="32" height="32" rx="8" fill="url(#bg)" />
<g
transform="translate(4.5 4.75) scale(0.958)"
fill="none"
stroke="#fff"
stroke-width="2.1"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z" />
<path d="M22 10v6" />
<path d="M6 12.5V16a6 3 0 0 0 12 0v-3.5" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 793 B

View file

@ -1,5 +1,6 @@
<script setup lang="ts">
import { GraduationCap, House, Settings } from '@lucide/vue'
import { CircleUser, GraduationCap, House, LogOut, Settings } from '@lucide/vue'
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import {
@ -17,9 +18,21 @@ import {
useSidebar,
} from '@/components/ui/sidebar'
import { sections } from '@/router/navigation'
import { useMe } from '@/services/api/misc'
const route = useRoute()
const { setOpenMobile } = useSidebar()
const { data: me } = useMe()
// Back to the app after logging out: it then sends to the portal of Authelia, which
// knows where to come back after the next login (without it, Authelia sends to its
// default page)
const logoutUrl = computed(() => {
if (!me.value?.logout_url) return undefined
const url = new URL(me.value.logout_url)
url.searchParams.set('rd', window.location.origin)
return url.toString()
})
// On mobile the sidebar is a sheet over the page: close it once a page is picked
function onNavigate() {
@ -94,6 +107,23 @@ function onNavigate() {
</RouterLink>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem v-if="me">
<SidebarMenuButton
v-if="logoutUrl"
as-child
:tooltip="$t('sidebar.logout', { name: me.display_name ?? me.username })"
>
<a :href="logoutUrl">
<CircleUser />
<span class="truncate">{{ me.display_name ?? me.username }}</span>
<LogOut class="ml-auto" />
</a>
</SidebarMenuButton>
<SidebarMenuButton v-else :tooltip="me.display_name ?? me.username">
<CircleUser />
<span class="truncate">{{ me.display_name ?? me.username }}</span>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarFooter>

View file

@ -0,0 +1,159 @@
<script setup lang="ts">
/**
* Creates a personal calendar, or edits (and deletes) `calendar` when given. `saved` is
* emitted with the id of the calendar once saved.
*/
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { toast } from 'vue-sonner'
import { Check, Trash2 } from '@lucide/vue'
import ConfirmDeleteDialog from '@/components/ConfirmDeleteDialog.vue'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useCalendarMutations } from '@/services/api/calendars'
import type { Calendar } from '@/utils/types'
const props = defineProps<{ calendar?: Calendar }>()
const open = defineModel<boolean>('open', { required: true })
const emit = defineEmits<{ saved: [id: number] }>()
const { t } = useI18n()
const { save, remove } = useCalendarMutations()
/** Colors offered, the first ones being the most distinct */
const COLORS = [
'#2563eb',
'#16a34a',
'#ea580c',
'#db2777',
'#7c3aed',
'#0891b2',
'#ca8a04',
'#dc2626',
'#475569',
]
const name = ref('')
const color = ref(COLORS[0]!)
const submitted = ref(false)
const confirmDelete = ref(false)
watch(
open,
(isOpen) => {
if (!isOpen) return
name.value = props.calendar?.name ?? ''
color.value = props.calendar?.color ?? COLORS[0]!
submitted.value = false
},
{ immediate: true },
)
const nameError = computed(() => !name.value.trim())
async function submit() {
submitted.value = true
if (nameError.value) return
try {
const calendars = await save.mutateAsync({
id: props.calendar?.id,
body: { name: name.value.trim(), color: color.value },
})
toast.success(props.calendar ? t('calendars.updated') : t('calendars.created'))
// The new calendar is the last one
emit('saved', props.calendar?.id ?? calendars.at(-1)!.id)
open.value = false
} catch (err) {
toast.error(t('calendars.save-error'), {
description: err instanceof Error ? err.message : undefined,
})
}
}
async function deleteCalendar() {
if (!props.calendar) return
try {
await remove.mutateAsync(props.calendar.id)
toast.success(t('calendars.deleted'))
open.value = false
} catch {
toast.error(t('calendars.delete-error'))
}
}
</script>
<template>
<Dialog v-model:open="open">
<DialogContent class="sm:max-w-md">
<DialogHeader>
<DialogTitle>{{ calendar ? $t('calendars.edit') : $t('calendars.new') }}</DialogTitle>
<DialogDescription>{{ $t('calendars.form.description') }}</DialogDescription>
</DialogHeader>
<form id="calendar-form" class="flex flex-col gap-4" novalidate @submit.prevent="submit">
<div class="flex flex-col gap-2">
<Label for="calendar-name">{{ $t('calendars.form.name') }}</Label>
<Input
id="calendar-name"
v-model="name"
:placeholder="$t('calendars.form.name-placeholder')"
:aria-invalid="submitted && nameError"
/>
</div>
<fieldset class="flex flex-col gap-2">
<legend class="mb-2 text-sm font-medium">{{ $t('calendars.form.color') }}</legend>
<div class="flex flex-wrap gap-2">
<button
v-for="option in COLORS"
:key="option"
type="button"
class="flex size-8 items-center justify-center rounded-full text-white ring-offset-2 ring-offset-background transition-transform hover:scale-110 focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
:class="{ 'ring-2 ring-foreground/60': color === option }"
:style="{ backgroundColor: option }"
:aria-label="option"
:aria-pressed="color === option"
@click="color = option"
>
<Check v-if="color === option" class="size-4" />
</button>
</div>
</fieldset>
</form>
<DialogFooter class="gap-2">
<Button
v-if="calendar"
variant="ghost"
class="mr-auto text-destructive hover:text-destructive"
@click="confirmDelete = true"
>
<Trash2 />
{{ $t('common.delete') }}
</Button>
<Button variant="outline" @click="open = false">{{ $t('common.cancel') }}</Button>
<Button type="submit" form="calendar-form" :disabled="save.isPending.value">
{{ $t('common.save') }}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<ConfirmDeleteDialog
v-if="calendar"
v-model:open="confirmDelete"
:title="$t('calendars.delete-title', { name: calendar.name })"
:description="$t('calendars.delete-description')"
@confirm="deleteCalendar"
/>
</template>

View file

@ -0,0 +1,370 @@
<script setup lang="ts">
/**
* Creates an event in a personal calendar, or edits (and deletes) `event` when given.
* An event is a time range, a single moment when it has no end (a deadline, a reminder),
* or whole days. `defaultDay` prefills a new event on that day.
*/
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { toast } from 'vue-sonner'
import { MapPin, Plus, Trash2 } from '@lucide/vue'
import CalendarFormDialog from '@/components/calendar/CalendarFormDialog.vue'
import ConfirmDeleteDialog from '@/components/ConfirmDeleteDialog.vue'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
import { useCalendars, useEventMutations } from '@/services/api/calendars'
import { dayKey, fromDayKey, nextDay } from '@/utils/calendar'
import { fromDateTimeInput, toDateTimeInput } from '@/utils/dates'
import type { CalendarEvent, EventBody } from '@/utils/types'
const props = defineProps<{ event?: CalendarEvent; defaultDay?: Date }>()
const open = defineModel<boolean>('open', { required: true })
const { t } = useI18n()
const { data: calendars } = useCalendars()
const { save, remove } = useEventMutations()
/** Remembered between two events: often the same calendar */
const lastCalendarId = ref<number>()
const title = ref('')
const calendarId = ref<number>()
const allDay = ref(false)
/** `datetime-local` values, used when not all day */
const start = ref('')
const end = ref('')
/** `date` values, used when all day. `endDay` is the last day, included. */
const startDay = ref('')
const endDay = ref('')
const location = ref('')
const description = ref('')
const submitted = ref(false)
const confirmDelete = ref(false)
const calendarFormOpen = ref(false)
/** A new event starts at the next full hour today, at 9:00 another day, and lasts 1 hour */
function defaultStart(day: Date): Date {
const now = new Date()
if (dayKey(day) === dayKey(now)) {
const next = new Date(now)
next.setHours(now.getHours() + 1, 0, 0, 0)
return next
}
const at = new Date(day)
at.setHours(9, 0, 0, 0)
return at
}
watch(
open,
(isOpen) => {
if (!isOpen) return
submitted.value = false
const event = props.event
title.value = event?.title ?? ''
calendarId.value =
event?.calendar_id ??
(calendars.value?.some((c) => c.id === lastCalendarId.value)
? lastCalendarId.value
: calendars.value?.[0]?.id)
allDay.value = event?.all_day ?? false
location.value = event?.location ?? ''
description.value = event?.description ?? ''
if (event) {
start.value = toDateTimeInput(event.starts_at)
end.value = event.ends_at ? toDateTimeInput(event.ends_at) : ''
startDay.value = dayKey(new Date(event.starts_at))
endDay.value = event.ends_at
? dayKey(new Date(new Date(event.ends_at).getTime() - 1))
: startDay.value
} else {
const from = defaultStart(props.defaultDay ?? new Date())
start.value = toDateTimeInput(from.toISOString())
end.value = toDateTimeInput(new Date(from.getTime() + 3600_000).toISOString())
startDay.value = endDay.value = dayKey(from)
}
},
{ immediate: true },
)
// Switching between a time range and whole days keeps the days. Not watchers: opening
// the form sets the fields too.
function setAllDay(value: boolean) {
allDay.value = value
if (value) {
if (start.value) startDay.value = start.value.slice(0, 10)
endDay.value = end.value ? end.value.slice(0, 10) : startDay.value
if (endDay.value < startDay.value) endDay.value = startDay.value
} else if (startDay.value && start.value.slice(0, 10) !== startDay.value) {
start.value = `${startDay.value}T09:00`
end.value = `${startDay.value}T10:00`
}
}
/** Moving the start moves the end with it, keeping the length */
function setStart(value: string | number) {
const previous = start.value
start.value = String(value)
if (!start.value || !previous || !end.value) return
const shift = new Date(start.value).getTime() - new Date(previous).getTime()
end.value = toDateTimeInput(new Date(new Date(end.value).getTime() + shift).toISOString())
}
watch(startDay, (value) => {
if (value && endDay.value < value) endDay.value = value
})
// Same rules as the backend, checked here to point at the faulty field
const errors = computed(() => ({
title: !title.value.trim(),
calendar: calendarId.value === undefined,
start: allDay.value ? !startDay.value : !start.value,
end: allDay.value
? !endDay.value || endDay.value < startDay.value
: !!end.value && !!start.value && new Date(end.value) <= new Date(start.value),
}))
function body(): EventBody {
const common = {
calendar_id: calendarId.value!,
title: title.value.trim(),
location: location.value.trim() || null,
description: description.value.trim() || null,
}
if (allDay.value) {
return {
...common,
all_day: true,
starts_at: fromDayKey(startDay.value).toISOString(),
ends_at: nextDay(fromDayKey(endDay.value)).toISOString(),
}
}
return {
...common,
all_day: false,
starts_at: fromDateTimeInput(start.value)!,
ends_at: fromDateTimeInput(end.value),
}
}
async function submit() {
submitted.value = true
if (Object.values(errors.value).some(Boolean)) return
try {
await save.mutateAsync({ id: props.event?.id, body: body() })
lastCalendarId.value = calendarId.value
toast.success(props.event ? t('events.updated') : t('events.created'))
open.value = false
} catch (err) {
toast.error(t('events.save-error'), {
description: err instanceof Error ? err.message : undefined,
})
}
}
async function deleteEvent() {
if (!props.event) return
try {
await remove.mutateAsync(props.event.id)
toast.success(t('events.deleted'))
open.value = false
} catch {
toast.error(t('events.delete-error'))
}
}
</script>
<template>
<Dialog v-model:open="open">
<DialogContent class="max-h-[90svh] overflow-y-auto sm:max-w-lg">
<DialogHeader>
<DialogTitle>{{ event ? $t('events.edit') : $t('events.new') }}</DialogTitle>
<DialogDescription>{{ $t('events.form.description') }}</DialogDescription>
</DialogHeader>
<form id="event-form" class="flex flex-col gap-4" novalidate @submit.prevent="submit">
<div class="flex flex-col gap-2">
<Label for="event-title">{{ $t('events.form.title') }}</Label>
<Input
id="event-title"
v-model="title"
:placeholder="$t('events.form.title-placeholder')"
:aria-invalid="submitted && errors.title"
/>
</div>
<div class="flex flex-col gap-2">
<Label for="event-calendar">{{ $t('events.form.calendar') }}</Label>
<div class="flex gap-2">
<Select v-model="calendarId">
<SelectTrigger
id="event-calendar"
class="min-w-0 flex-1"
:aria-invalid="submitted && errors.calendar"
>
<SelectValue :placeholder="$t('events.form.calendar-placeholder')" />
</SelectTrigger>
<SelectContent>
<SelectItem v-for="calendar in calendars" :key="calendar.id" :value="calendar.id">
<span
class="size-2.5 rounded-full"
:style="{ backgroundColor: calendar.color }"
/>
{{ calendar.name }}
</SelectItem>
</SelectContent>
</Select>
<Button
type="button"
variant="outline"
size="icon"
:title="$t('calendars.new')"
@click="calendarFormOpen = true"
>
<Plus />
<span class="sr-only">{{ $t('calendars.new') }}</span>
</Button>
</div>
<p v-if="!calendars?.length" class="text-sm text-muted-foreground">
{{ $t('events.form.no-calendar') }}
</p>
</div>
<label class="flex items-center justify-between gap-2 text-sm font-medium">
{{ $t('events.form.all-day') }}
<Switch :model-value="allDay" @update:model-value="setAllDay" />
</label>
<div v-if="allDay" class="grid gap-4 sm:grid-cols-2">
<div class="flex flex-col gap-2">
<Label for="event-start-day">{{ $t('events.form.start-day') }}</Label>
<Input
id="event-start-day"
v-model="startDay"
type="date"
:aria-invalid="submitted && errors.start"
/>
</div>
<div class="flex flex-col gap-2">
<Label for="event-end-day">{{ $t('events.form.end-day') }}</Label>
<Input
id="event-end-day"
v-model="endDay"
type="date"
:min="startDay"
:aria-invalid="submitted && errors.end"
/>
</div>
</div>
<div v-else class="grid gap-4 sm:grid-cols-2">
<div class="flex flex-col gap-2">
<Label for="event-start">{{ $t('events.form.start') }}</Label>
<Input
id="event-start"
:model-value="start"
type="datetime-local"
:aria-invalid="submitted && errors.start"
@update:model-value="setStart"
/>
</div>
<div class="flex flex-col gap-2">
<Label for="event-end">
{{ $t('events.form.end') }}
<span class="font-normal text-muted-foreground">
({{ $t('courses.form.optional') }})
</span>
</Label>
<Input
id="event-end"
v-model="end"
type="datetime-local"
:min="start"
:aria-invalid="submitted && errors.end"
/>
</div>
<p class="text-xs text-muted-foreground sm:col-span-2">
{{ $t('events.form.no-end-hint') }}
</p>
</div>
<p v-if="submitted && errors.end" class="-mt-2 text-sm text-destructive">
{{ $t('events.form.errors.end') }}
</p>
<div class="flex flex-col gap-2">
<Label for="event-location">
{{ $t('events.form.location') }}
<span class="font-normal text-muted-foreground">
({{ $t('courses.form.optional') }})
</span>
</Label>
<div class="relative">
<MapPin
class="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground"
/>
<Input
id="event-location"
v-model="location"
class="pl-8"
:placeholder="$t('events.form.location-placeholder')"
/>
</div>
</div>
<div class="flex flex-col gap-2">
<Label for="event-description">
{{ $t('events.form.details') }}
<span class="font-normal text-muted-foreground">
({{ $t('courses.form.optional') }})
</span>
</Label>
<Textarea id="event-description" v-model="description" rows="3" />
</div>
</form>
<DialogFooter class="gap-2">
<Button
v-if="event"
variant="ghost"
class="mr-auto text-destructive hover:text-destructive"
@click="confirmDelete = true"
>
<Trash2 />
{{ $t('common.delete') }}
</Button>
<Button variant="outline" @click="open = false">{{ $t('common.cancel') }}</Button>
<Button type="submit" form="event-form" :disabled="save.isPending.value">
{{ $t('common.save') }}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<CalendarFormDialog v-model:open="calendarFormOpen" @saved="calendarId = $event" />
<ConfirmDeleteDialog
v-if="event"
v-model:open="confirmDelete"
:title="$t('events.delete-title', { name: event.title })"
@confirm="deleteEvent"
/>
</template>

View file

@ -0,0 +1,469 @@
<script setup lang="ts">
/**
* Month calendar of the events of the personal calendars and of the deadlines of the
* courses and associations of `kinds`. On a phone the days only show dots: what happens
* on the selected day is listed under the calendar, on every screen.
*
* Events and tasks stay apart: an event is edited in place (`edit-event`), a task leads
* to its course. `create-event` and `create-task` ask for a new one on the selected day.
*/
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import {
CalendarCheck,
CalendarPlus,
ChevronLeft,
ChevronRight,
ListTodo,
MapPin,
Plus,
Timer,
} from '@lucide/vue'
import TagBadge from '@/components/course/TagBadge.vue'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { useCalendarEvents, useCalendars } from '@/services/api/calendars'
import { useTags } from '@/services/api/tags'
import { useCalendarTasks } from '@/services/api/tasks'
import { dayKey, eventDayKeys, monthWeeks, weeksPeriod } from '@/utils/calendar'
import { isPast } from '@/utils/dates'
import { coursePageRoute, focusRoute, tasksTab } from '@/utils/routes'
import type { Calendar, CalendarEvent, CalendarTask, CourseKind } from '@/utils/types'
const props = defineProps<{ kinds: CourseKind[]; hiddenCalendars: number[] }>()
const emit = defineEmits<{
'create-event': [day: Date]
'create-task': [day: Date]
'edit-event': [event: CalendarEvent]
}>()
const { locale } = useI18n()
const { tagsById } = useTags()
/** Lines shown in a day cell on large screens, the others are counted */
const MAX_PER_DAY = 3
const today = new Date()
const month = ref(new Date(today.getFullYear(), today.getMonth(), 1))
const selectedDay = ref(dayKey(today))
const weeks = computed(() => monthWeeks(month.value.getFullYear(), month.value.getMonth()))
const period = computed(() => weeksPeriod(weeks.value))
const {
data: tasks,
isPending: tasksPending,
isError: tasksError,
refetch: refetchTasks,
} = useCalendarTasks(period)
const {
data: events,
isPending: eventsPending,
isError: eventsError,
refetch: refetchEvents,
} = useCalendarEvents(period)
const { data: calendars } = useCalendars()
const isPending = computed(() => tasksPending.value || eventsPending.value)
const isError = computed(() => tasksError.value || eventsError.value)
function refetch() {
refetchTasks()
refetchEvents()
}
const calendarsById = computed(
() => new Map<number, Calendar>((calendars.value ?? []).map((c) => [c.id, c])),
)
/**
* What happens on a day: the events lasting the whole day first (or going on since a
* previous day), then the events and the deadlines by time
*/
type DayItem =
| {
type: 'event'
key: string
event: CalendarEvent
color: string
wholeDay: boolean
at: number
}
| { type: 'task'; key: string; task: CalendarTask; at: number }
const itemsByDay = computed(() => {
const byDay = new Map<string, DayItem[]>()
const add = (key: string, item: DayItem) => byDay.set(key, [...(byDay.get(key) ?? []), item])
for (const event of events.value ?? []) {
const calendar = calendarsById.value.get(event.calendar_id)
if (!calendar || props.hiddenCalendars.includes(calendar.id)) continue
const startKey = dayKey(new Date(event.starts_at))
for (const key of eventDayKeys(event)) {
add(key, {
type: 'event',
key: `event-${event.id}`,
event,
color: calendar.color,
wholeDay: event.all_day || key !== startKey,
at: new Date(event.starts_at).getTime(),
})
}
}
for (const task of tasks.value ?? []) {
if (!props.kinds.includes(task.course_kind)) continue
add(dayKey(new Date(task.deadline)), {
type: 'task',
key: `task-${task.task_id}`,
task,
at: new Date(task.deadline).getTime(),
})
}
for (const items of byDay.values()) {
const wholeDay = (item: DayItem) => item.type === 'event' && item.wholeDay
items.sort((a, b) => Number(wholeDay(b)) - Number(wholeDay(a)) || a.at - b.at)
}
return byDay
})
const selectedItems = computed(() => itemsByDay.value.get(selectedDay.value) ?? [])
const monthLabel = computed(() =>
new Intl.DateTimeFormat(locale.value, { month: 'long', year: 'numeric' }).format(month.value),
)
const weekdayLabels = computed(() =>
weeks.value[0]!.map((day) =>
new Intl.DateTimeFormat(locale.value, { weekday: 'short' }).format(day),
),
)
const selectedDate = computed(() => {
const [year, m, d] = selectedDay.value.split('-').map(Number)
return new Date(year!, m! - 1, d)
})
const selectedLabel = computed(() =>
new Intl.DateTimeFormat(locale.value, { dateStyle: 'full' }).format(selectedDate.value),
)
function moveMonth(offset: number) {
const next = new Date(month.value.getFullYear(), month.value.getMonth() + offset, 1)
month.value = next
selectedDay.value = dayKey(
next.getMonth() === today.getMonth() && next.getFullYear() === today.getFullYear()
? today
: next,
)
}
function goToday() {
month.value = new Date(today.getFullYear(), today.getMonth(), 1)
selectedDay.value = dayKey(today)
}
function itemColor(item: DayItem) {
if (item.type === 'event') return item.color
return tagsById.value.get(item.task.tag_ids[0] ?? -1)?.color ?? 'var(--primary)'
}
function isLate(task: CalendarTask) {
return !task.done && isPast(task.deadline)
}
function time(iso: string) {
return new Intl.DateTimeFormat(locale.value, { hour: '2-digit', minute: '2-digit' }).format(
new Date(iso),
)
}
/** "10:00 – 11:30", "22 – 24 oct.", "ven. 10:00 – dim. 12:00"... */
function eventWhen(event: CalendarEvent): string {
const start = new Date(event.starts_at)
if (!event.ends_at) return time(event.starts_at)
const end = new Date(event.ends_at)
if (event.all_day) {
const last = new Date(end.getTime() - 1)
if (dayKey(last) === dayKey(start)) return ''
return new Intl.DateTimeFormat(locale.value, { day: 'numeric', month: 'short' }).formatRange(
start,
last,
)
}
const sameDay = dayKey(start) === dayKey(new Date(end.getTime() - 1))
return new Intl.DateTimeFormat(locale.value, {
...(sameDay ? {} : { weekday: 'short', day: 'numeric', month: 'short' }),
hour: '2-digit',
minute: '2-digit',
}).formatRange(start, end)
}
function taskLink(task: CalendarTask) {
return coursePageRoute({ id: task.course_id, kind: task.course_kind }, tasksTab(task.course_kind))
}
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center gap-2">
<h2 class="mr-auto text-lg font-semibold capitalize">{{ monthLabel }}</h2>
<Button variant="outline" size="sm" @click="goToday">{{ $t('calendar.today') }}</Button>
<Button
variant="outline"
size="icon-sm"
:title="$t('calendar.previous')"
@click="moveMonth(-1)"
>
<ChevronLeft />
<span class="sr-only">{{ $t('calendar.previous') }}</span>
</Button>
<Button variant="outline" size="icon-sm" :title="$t('calendar.next')" @click="moveMonth(1)">
<ChevronRight />
<span class="sr-only">{{ $t('calendar.next') }}</span>
</Button>
</div>
<div
class="overflow-hidden rounded-xl border bg-card transition-opacity"
:class="{ 'opacity-60': isPending }"
>
<div class="grid grid-cols-7 border-b">
<div
v-for="label in weekdayLabels"
:key="label"
class="py-2 text-center text-xs font-medium text-muted-foreground capitalize"
>
{{ label }}
</div>
</div>
<div
v-for="(week, index) in weeks"
:key="index"
class="grid grid-cols-7 [&:not(:last-child)]:border-b"
>
<!-- Not a <button>: it holds links -->
<div
v-for="day in week"
:key="dayKey(day)"
role="button"
tabindex="0"
class="flex min-h-14 min-w-0 cursor-pointer flex-col gap-1 border-l p-1 text-left transition-colors first:border-l-0 hover:bg-accent/40 md:min-h-28 md:p-1.5"
:class="{
'bg-muted/40 text-muted-foreground': day.getMonth() !== month.getMonth(),
'ring-2 ring-primary ring-inset': dayKey(day) === selectedDay,
}"
:aria-pressed="dayKey(day) === selectedDay"
@click="selectedDay = dayKey(day)"
@dblclick="emit('create-event', day)"
@keydown.enter.space.prevent="selectedDay = dayKey(day)"
>
<span
class="flex size-6 items-center justify-center self-center rounded-full text-xs tabular-nums md:self-start"
:class="{
'bg-primary font-semibold text-primary-foreground': dayKey(day) === dayKey(today),
}"
>
{{ day.getDate() }}
</span>
<!-- Phone: one dot per event or task -->
<span class="flex flex-wrap justify-center gap-0.5 md:hidden">
<span
v-for="item in itemsByDay.get(dayKey(day)) ?? []"
:key="item.key"
class="size-1.5 rounded-full"
:class="{ 'opacity-40': item.type === 'task' && item.task.done }"
:style="{ backgroundColor: itemColor(item) }"
/>
</span>
<!-- Large screens: the first events and tasks of the day -->
<span class="hidden min-w-0 flex-col gap-0.5 md:flex">
<template
v-for="item in (itemsByDay.get(dayKey(day)) ?? []).slice(0, MAX_PER_DAY)"
:key="item.key"
>
<template v-if="item.type === 'event'">
<!-- Whole day: a filled bar -->
<button
v-if="item.wholeDay"
type="button"
class="truncate rounded px-1 py-0.5 text-left text-xs font-medium text-white hover:brightness-110"
:style="{ backgroundColor: item.color }"
:title="item.event.title"
@click.stop="emit('edit-event', item.event)"
>
{{ item.event.title }}
</button>
<!-- At a time: a dot, the time and the title -->
<button
v-else
type="button"
class="flex min-w-0 items-center gap-1 rounded px-1 py-0.5 text-left text-xs hover:bg-accent"
:title="`${time(item.event.starts_at)} · ${item.event.title}`"
@click.stop="emit('edit-event', item.event)"
>
<span
class="size-1.5 shrink-0 rounded-full"
:style="{ backgroundColor: item.color }"
/>
<span class="shrink-0 text-muted-foreground tabular-nums">
{{ time(item.event.starts_at) }}
</span>
<span class="truncate">{{ item.event.title }}</span>
</button>
</template>
<RouterLink
v-else
:to="taskLink(item.task)"
class="truncate rounded border-l-2 px-1 py-0.5 text-xs hover:underline"
:class="{
'text-muted-foreground line-through': item.task.done,
'font-medium text-destructive': isLate(item.task),
}"
:style="{
borderLeftColor: itemColor(item),
backgroundColor: `color-mix(in oklab, ${itemColor(item)} 12%, transparent)`,
}"
:title="`${item.task.course_code ?? item.task.course_name} · ${item.task.name}`"
@click.stop
>
<span v-if="item.task.course_code" class="font-mono text-[0.625rem] opacity-70">
{{ item.task.course_code }}
</span>
{{ item.task.name }}
</RouterLink>
</template>
<span
v-if="(itemsByDay.get(dayKey(day))?.length ?? 0) > MAX_PER_DAY"
class="px-1 text-xs text-muted-foreground"
>
{{ $t('calendar.more', itemsByDay.get(dayKey(day))!.length - MAX_PER_DAY) }}
</span>
</span>
</div>
</div>
</div>
<p v-if="isError" class="text-sm text-destructive">
{{ $t('calendar.load-error') }}
<Button variant="link" size="sm" @click="refetch()">{{ $t('common.retry') }}</Button>
</p>
<!-- The selected day -->
<Card>
<CardHeader class="flex flex-row items-center justify-between gap-2">
<CardTitle class="text-base first-letter:uppercase">{{ selectedLabel }}</CardTitle>
<DropdownMenu>
<DropdownMenuTrigger as-child>
<Button variant="outline" size="sm">
<Plus />
{{ $t('calendar.add-that-day') }}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem @select="emit('create-event', selectedDate)">
<CalendarPlus />
{{ $t('events.new') }}
</DropdownMenuItem>
<DropdownMenuItem @select="emit('create-task', selectedDate)">
<ListTodo />
{{ $t('tasks.new') }}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</CardHeader>
<CardContent>
<div
v-if="!selectedItems.length"
class="flex flex-col items-center gap-2 py-4 text-center text-sm text-muted-foreground"
>
<CalendarCheck class="size-6" />
{{ $t('calendar.nothing') }}
</div>
<ul v-else class="flex flex-col gap-3">
<li v-for="item in selectedItems" :key="item.key" class="flex items-start gap-2">
<!-- An event: opened in place -->
<button
v-if="item.type === 'event'"
type="button"
class="group flex min-w-0 flex-1 flex-col gap-1 rounded-r-md border-l-2 py-0.5 pl-3 text-left transition-colors hover:bg-accent/50"
:style="{ borderLeftColor: item.color }"
@click="emit('edit-event', item.event)"
>
<span class="text-sm font-medium">{{ item.event.title }}</span>
<span class="flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground">
<span class="tabular-nums">
<template v-if="item.event.all_day">
{{ $t('events.all-day') }}
<template v-if="eventWhen(item.event)"> · {{ eventWhen(item.event) }}</template>
</template>
<template v-else>{{ eventWhen(item.event) }}</template>
</span>
<span v-if="item.event.location" class="flex min-w-0 items-center gap-1">
<MapPin class="size-3 shrink-0" />
<span class="truncate">{{ item.event.location }}</span>
</span>
<span class="flex items-center gap-1">
<span class="size-2 rounded-full" :style="{ backgroundColor: item.color }" />
{{ calendarsById.get(item.event.calendar_id)?.name }}
</span>
</span>
<span
v-if="item.event.description"
class="line-clamp-2 text-xs whitespace-pre-line text-muted-foreground"
>
{{ item.event.description }}
</span>
</button>
<!-- A task: leads to its course -->
<template v-else>
<RouterLink
:to="taskLink(item.task)"
class="flex min-w-0 flex-1 flex-col gap-1 border-l-2 pl-3 hover:underline"
:style="{ borderLeftColor: itemColor(item) }"
>
<span
class="text-sm font-medium"
:class="{ 'text-muted-foreground line-through': item.task.done }"
>
{{ item.task.name }}
</span>
<span class="text-xs text-muted-foreground">
{{ time(item.task.deadline) }} · {{ item.task.course_name }}
<template v-if="item.task.course_code">({{ item.task.course_code }})</template>
<span v-if="isLate(item.task)" class="font-medium text-destructive">
· {{ $t('tasks.late') }}
</span>
</span>
<span class="flex flex-wrap gap-1">
<template v-for="tagId in item.task.tag_ids" :key="tagId">
<TagBadge v-if="tagsById.get(tagId)" :tag="tagsById.get(tagId)!" />
</template>
</span>
</RouterLink>
<Button
v-if="!item.task.done"
variant="ghost"
size="icon-sm"
class="shrink-0"
:title="$t('focus.start')"
as-child
>
<RouterLink :to="focusRoute(item.task.task_id)">
<Timer />
<span class="sr-only">{{ $t('focus.start') }}</span>
</RouterLink>
</Button>
</template>
</li>
</ul>
</CardContent>
</Card>
</div>
</template>

View file

@ -1,277 +0,0 @@
<script setup lang="ts">
/**
* Month calendar of the deadlines of the courses and associations of `kinds`. On a phone
* the days only show dots: the tasks of the selected day are listed under the calendar,
* on every screen. `create` asks for a new task due on the selected day.
*/
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { CalendarCheck, ChevronLeft, ChevronRight, Plus, Timer } from '@lucide/vue'
import TagBadge from '@/components/course/TagBadge.vue'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { useTags } from '@/services/api/tags'
import { useCalendarTasks } from '@/services/api/tasks'
import { dayKey, monthWeeks, weeksPeriod } from '@/utils/calendar'
import { isPast } from '@/utils/dates'
import { coursePageRoute, focusRoute, tasksTab } from '@/utils/routes'
import type { CalendarTask, CourseKind } from '@/utils/types'
const props = defineProps<{ kinds: CourseKind[] }>()
const emit = defineEmits<{ create: [day: Date] }>()
const { locale } = useI18n()
const { tagsById } = useTags()
/** Tasks shown in a day cell on large screens, the others are counted */
const MAX_PER_DAY = 3
const today = new Date()
const month = ref(new Date(today.getFullYear(), today.getMonth(), 1))
const selectedDay = ref(dayKey(today))
const weeks = computed(() => monthWeeks(month.value.getFullYear(), month.value.getMonth()))
const {
data: tasks,
isPending,
isError,
refetch,
} = useCalendarTasks(() => weeksPeriod(weeks.value))
/** Tasks of each day, already sorted by deadline by the backend */
const tasksByDay = computed(() => {
const byDay = new Map<string, CalendarTask[]>()
for (const task of tasks.value ?? []) {
if (!props.kinds.includes(task.course_kind)) continue
const key = dayKey(new Date(task.deadline))
byDay.set(key, [...(byDay.get(key) ?? []), task])
}
return byDay
})
const selectedTasks = computed(() => tasksByDay.value.get(selectedDay.value) ?? [])
const monthLabel = computed(() =>
new Intl.DateTimeFormat(locale.value, { month: 'long', year: 'numeric' }).format(month.value),
)
const weekdayLabels = computed(() =>
weeks.value[0]!.map((day) =>
new Intl.DateTimeFormat(locale.value, { weekday: 'short' }).format(day),
),
)
const selectedDate = computed(() => {
const [year, m, d] = selectedDay.value.split('-').map(Number)
return new Date(year!, m! - 1, d)
})
const selectedLabel = computed(() =>
new Intl.DateTimeFormat(locale.value, { dateStyle: 'full' }).format(selectedDate.value),
)
function moveMonth(offset: number) {
const next = new Date(month.value.getFullYear(), month.value.getMonth() + offset, 1)
month.value = next
selectedDay.value = dayKey(
next.getMonth() === today.getMonth() && next.getFullYear() === today.getFullYear()
? today
: next,
)
}
function goToday() {
month.value = new Date(today.getFullYear(), today.getMonth(), 1)
selectedDay.value = dayKey(today)
}
function taskColor(task: CalendarTask) {
return tagsById.value.get(task.tag_ids[0] ?? -1)?.color ?? 'var(--primary)'
}
function isLate(task: CalendarTask) {
return !task.done && isPast(task.deadline)
}
function time(task: CalendarTask) {
return new Intl.DateTimeFormat(locale.value, { hour: '2-digit', minute: '2-digit' }).format(
new Date(task.deadline),
)
}
function taskLink(task: CalendarTask) {
return coursePageRoute({ id: task.course_id, kind: task.course_kind }, tasksTab(task.course_kind))
}
</script>
<template>
<div class="flex flex-col gap-4">
<div class="flex items-center gap-2">
<h2 class="mr-auto text-lg font-semibold capitalize">{{ monthLabel }}</h2>
<Button variant="outline" size="sm" @click="goToday">{{ $t('calendar.today') }}</Button>
<Button
variant="outline"
size="icon-sm"
:title="$t('calendar.previous')"
@click="moveMonth(-1)"
>
<ChevronLeft />
<span class="sr-only">{{ $t('calendar.previous') }}</span>
</Button>
<Button variant="outline" size="icon-sm" :title="$t('calendar.next')" @click="moveMonth(1)">
<ChevronRight />
<span class="sr-only">{{ $t('calendar.next') }}</span>
</Button>
</div>
<div
class="overflow-hidden rounded-xl border bg-card transition-opacity"
:class="{ 'opacity-60': isPending }"
>
<div class="grid grid-cols-7 border-b">
<div
v-for="label in weekdayLabels"
:key="label"
class="py-2 text-center text-xs font-medium text-muted-foreground capitalize"
>
{{ label }}
</div>
</div>
<div
v-for="(week, index) in weeks"
:key="index"
class="grid grid-cols-7 [&:not(:last-child)]:border-b"
>
<!-- Not a <button>: it holds links -->
<div
v-for="day in week"
:key="dayKey(day)"
role="button"
tabindex="0"
class="flex min-h-14 cursor-pointer min-w-0 flex-col gap-1 border-l p-1 text-left transition-colors first:border-l-0 hover:bg-accent/40 md:min-h-28 md:p-1.5"
:class="{
'bg-muted/40 text-muted-foreground': day.getMonth() !== month.getMonth(),
'ring-2 ring-primary ring-inset': dayKey(day) === selectedDay,
}"
:aria-pressed="dayKey(day) === selectedDay"
@click="selectedDay = dayKey(day)"
@keydown.enter.space.prevent="selectedDay = dayKey(day)"
>
<span
class="flex size-6 items-center justify-center self-center rounded-full text-xs tabular-nums md:self-start"
:class="{
'bg-primary font-semibold text-primary-foreground': dayKey(day) === dayKey(today),
}"
>
{{ day.getDate() }}
</span>
<!-- Phone: one dot per task -->
<span class="flex flex-wrap justify-center gap-0.5 md:hidden">
<span
v-for="task in tasksByDay.get(dayKey(day)) ?? []"
:key="task.task_id"
class="size-1.5 rounded-full"
:class="{ 'opacity-40': task.done }"
:style="{ backgroundColor: taskColor(task) }"
/>
</span>
<!-- Large screens: the first tasks of the day -->
<span class="hidden min-w-0 flex-col gap-0.5 md:flex">
<RouterLink
v-for="task in (tasksByDay.get(dayKey(day)) ?? []).slice(0, MAX_PER_DAY)"
:key="task.task_id"
:to="taskLink(task)"
class="truncate rounded border-l-2 px-1 py-0.5 text-xs hover:underline"
:class="{
'text-muted-foreground line-through': task.done,
'font-medium text-destructive': isLate(task),
}"
:style="{
borderLeftColor: taskColor(task),
backgroundColor: `color-mix(in oklab, ${taskColor(task)} 12%, transparent)`,
}"
:title="`${task.course_code ?? task.course_name} · ${task.name}`"
@click.stop
>
<span v-if="task.course_code" class="font-mono text-[0.625rem] opacity-70">
{{ task.course_code }}
</span>
{{ task.name }}
</RouterLink>
<span
v-if="(tasksByDay.get(dayKey(day))?.length ?? 0) > MAX_PER_DAY"
class="px-1 text-xs text-muted-foreground"
>
{{ $t('calendar.more', tasksByDay.get(dayKey(day))!.length - MAX_PER_DAY) }}
</span>
</span>
</div>
</div>
</div>
<p v-if="isError" class="text-sm text-destructive">
{{ $t('calendar.load-error') }}
<Button variant="link" size="sm" @click="refetch()">{{ $t('common.retry') }}</Button>
</p>
<Card>
<CardHeader class="flex flex-row items-center justify-between gap-2">
<CardTitle class="text-base first-letter:uppercase">{{ selectedLabel }}</CardTitle>
<Button variant="outline" size="sm" @click="emit('create', selectedDate)">
<Plus />
{{ $t('calendar.add-that-day') }}
</Button>
</CardHeader>
<CardContent>
<div
v-if="!selectedTasks.length"
class="flex flex-col items-center gap-2 py-4 text-center text-sm text-muted-foreground"
>
<CalendarCheck class="size-6" />
{{ $t('calendar.nothing') }}
</div>
<ul v-else class="flex flex-col gap-3">
<li v-for="task in selectedTasks" :key="task.task_id" class="flex items-start gap-2">
<RouterLink
:to="taskLink(task)"
class="flex min-w-0 flex-1 flex-col gap-1 border-l-2 pl-3 hover:underline"
:style="{ borderLeftColor: taskColor(task) }"
>
<span
class="text-sm font-medium"
:class="{ 'text-muted-foreground line-through': task.done }"
>
{{ task.name }}
</span>
<span class="text-xs text-muted-foreground">
{{ time(task) }} · {{ task.course_name }}
<template v-if="task.course_code">({{ task.course_code }})</template>
<span v-if="isLate(task)" class="font-medium text-destructive">
· {{ $t('tasks.late') }}
</span>
</span>
<span class="flex flex-wrap gap-1">
<template v-for="tagId in task.tag_ids" :key="tagId">
<TagBadge v-if="tagsById.get(tagId)" :tag="tagsById.get(tagId)!" />
</template>
</span>
</RouterLink>
<Button
v-if="!task.done"
variant="ghost"
size="icon-sm"
class="shrink-0"
:title="$t('focus.start')"
as-child
>
<RouterLink :to="focusRoute(task.task_id)">
<Timer />
<span class="sr-only">{{ $t('focus.start') }}</span>
</RouterLink>
</Button>
</li>
</ul>
</CardContent>
</Card>
</div>
</template>

View file

@ -1217,10 +1217,398 @@ export interface paths {
patch?: never
trace?: never
}
'/api/calendars': {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
/** Get every personal calendar */
get: {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
requestBody?: never
responses: {
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Calendar'][]
}
}
}
}
put?: never
/** Create a personal calendar, returns every calendar */
post: {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
requestBody: {
content: {
'application/json': components['schemas']['CalendarBody']
}
}
responses: {
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Calendar'][]
}
}
/** @description The calendar is invalid */
400: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
}
}
delete?: never
options?: never
head?: never
patch?: never
trace?: never
}
'/api/calendars/{id}': {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
get?: never
/** Rename or recolor a personal calendar, returns every calendar */
put: {
parameters: {
query?: never
header?: never
path: {
id: number
}
cookie?: never
}
requestBody: {
content: {
'application/json': components['schemas']['CalendarBody']
}
}
responses: {
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Calendar'][]
}
}
/** @description The calendar is invalid */
400: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
/** @description The calendar does not exist */
404: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
}
}
post?: never
/** Delete a personal calendar and its events, returns the calendars left */
delete: {
parameters: {
query?: never
header?: never
path: {
id: number
}
cookie?: never
}
requestBody?: never
responses: {
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Calendar'][]
}
}
/** @description The calendar does not exist */
404: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
}
}
options?: never
head?: never
patch?: never
trace?: never
}
'/api/events': {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
/** Get the events of every personal calendar happening in a period */
get: {
parameters: {
query: {
from: string
to: string
}
header?: never
path?: never
cookie?: never
}
requestBody?: never
responses: {
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Event'][]
}
}
/** @description The period is invalid */
400: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
}
}
put?: never
/** Add an event to a personal calendar */
post: {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
/** @description An event of a personal calendar */
requestBody: {
content: {
'application/json': components['schemas']['EventBody']
}
}
responses: {
/** @description Something happening in a personal calendar. Not a task: there is nothing to check. */
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Event']
}
}
/** @description The event is invalid */
400: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
/** @description The calendar does not exist */
404: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
}
}
delete?: never
options?: never
head?: never
patch?: never
trace?: never
}
'/api/events/{id}': {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
get?: never
/** Replace an event, possibly moving it to another calendar */
put: {
parameters: {
query?: never
header?: never
path: {
id: number
}
cookie?: never
}
/** @description An event of a personal calendar */
requestBody: {
content: {
'application/json': components['schemas']['EventBody']
}
}
responses: {
/** @description Something happening in a personal calendar. Not a task: there is nothing to check. */
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Event']
}
}
/** @description The event is invalid */
400: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
/** @description The event or the calendar does not exist */
404: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
}
}
post?: never
/** Delete an event */
delete: {
parameters: {
query?: never
header?: never
path: {
id: number
}
cookie?: never
}
requestBody?: never
responses: {
/** @description The event was deleted */
204: {
headers: {
[name: string]: unknown
}
content?: never
}
/** @description The event does not exist */
404: {
headers: {
[name: string]: unknown
}
content: {
'text/plain; charset=utf-8': unknown
}
}
}
}
options?: never
head?: never
patch?: never
trace?: never
}
'/api/me': {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
/** Get the person logged in */
get: {
parameters: {
query?: never
header?: never
path?: never
cookie?: never
}
requestBody?: never
responses: {
200: {
headers: {
[name: string]: unknown
}
content: {
'application/json': components['schemas']['Me']
}
}
}
}
put?: never
post?: never
delete?: never
options?: never
head?: never
patch?: never
trace?: never
}
}
export type webhooks = Record<string, never>
export interface components {
schemas: {
/** @description Personal calendar, apart from the courses and associations */
Calendar: {
/** @description Hex color of its events, e.g. `#2563eb` */
color: string
/** Format: int32 */
id: number
name: string
}
CalendarBody: {
/** @description Hex color, e.g. `#2563eb` */
color: string
name: string
}
CalendarPath: {
/** Format: int32 */
id: number
}
/** @description A task or subtask with a deadline, as shown in the calendar */
CalendarTask: {
course_code?: string | null
@ -1357,6 +1745,53 @@ export interface components {
*/
tag_ids: number[]
}
/** @description Something happening in a personal calendar. Not a task: there is nothing to check. */
Event: {
title: string
description?: string | null
/**
* @description From the midnight of its first day to the midnight after its last one, in the time
* zone of the user. Always has an end.
*/
all_day: boolean
/** Format: int32 */
calendar_id: number
/**
* Format: date-time
* @description Exclusive. `None` for a single moment: a deadline, a reminder...
*/
ends_at?: string | null
/** Format: int32 */
id: number
location?: string | null
/** Format: date-time */
starts_at: string
}
/** @description An event of a personal calendar */
EventBody: {
title: string
description?: string | null
/**
* @description From the midnight of the first day to the midnight after the last one, in local
* time: `ends_at` is required
* @default false
*/
all_day: boolean
/** Format: int32 */
calendar_id: number
/**
* Format: date-time
* @description Exclusive, after `starts_at`. `null` for a single moment (a deadline, a reminder).
*/
ends_at?: string | null
location?: string | null
/** Format: date-time */
starts_at: string
}
EventPath: {
/** Format: int32 */
id: number
}
FileKind: 'note' | 'upload'
/** @description A focus session started on a task */
FocusStart: {
@ -1481,6 +1916,14 @@ export interface components {
en: string
fr: string
}
Me: {
/** @description e.g. `Jane Doe`, when Authelia gives it */
display_name?: string | null
/** @description Where to log out (the portal of Authelia), when configured */
logout_url?: string | null
/** @description Login, e.g. `jdoe` */
username: string
}
/** @description Period `[from, to[`, at most 62 days */
PeriodQuery: {
/** Format: date-time */

View file

@ -3,6 +3,7 @@ app:
title: Studium
sidebar:
navigation: Navigation
logout: Log out ({name})
nav:
home: Home
schedule: Timetable
@ -242,7 +243,7 @@ files:
delete-description: The file will be permanently deleted.
calendar:
show: Show
nothing-shown: Turn on the courses or the associations to see their tasks.
nothing-shown: Everything is hidden. Turn on the courses, the associations or a calendar.
today: Today
previous: Previous month
next: Next month
@ -250,9 +251,9 @@ calendar:
previous-week: Previous week
next-week: Next week
more: '+{n} more'
nothing: Nothing due that day.
nothing: Nothing planned that day.
add-that-day: Add
load-error: Unable to load the deadlines.
load-error: Unable to load the calendar.
todo:
title: To do
empty: Nothing to do, enjoy!
@ -261,6 +262,49 @@ calendar:
week: This week
later: Later
undated: No deadline
calendars:
new: Calendar
edit: Edit the calendar
created: Calendar created
updated: Calendar updated
deleted: Calendar deleted
save-error: Unable to save the calendar
delete-error: Unable to delete the calendar
delete-title: Do you really want to delete the calendar "{name}"?
delete-description: All its events will be deleted for good.
form:
description: A personal calendar for your appointments, deadlines and events.
name: Name
name-placeholder: Personal
color: Color
events:
new: New event
edit: Edit the event
created: Event added
updated: Event updated
deleted: Event deleted
save-error: Unable to save the event
delete-error: Unable to delete the event
delete-title: Do you really want to delete "{name}"?
all-day: All day
form:
description: An appointment, a personal deadline or anything happening at some point.
title: Title
title-placeholder: Dentist appointment
calendar: Calendar
calendar-placeholder: Pick…
no-calendar: Create a calendar first with the + button.
all-day: All day
start: Start
end: End
start-day: First day
end-day: Last day
no-end-hint: Without an end, it is a single moment, like a deadline or a reminder.
location: Location
location-placeholder: Rolex Learning Center
details: Description
errors:
end: The end must come after the start.
focus:
start: Work on it (pomodoro)
back: Back to the pomodoro

View file

@ -3,6 +3,7 @@ app:
title: Studium
sidebar:
navigation: Navigation
logout: Se déconnecter ({name})
nav:
home: Accueil
schedule: Emploi du temps
@ -242,7 +243,7 @@ files:
delete-description: Le fichier sera supprimé définitivement.
calendar:
show: Afficher
nothing-shown: Active les cours ou les associations pour voir leurs tâches.
nothing-shown: Tout est masqué. Active les cours, les associations ou un calendrier.
today: Aujourd'hui
previous: Mois précédent
next: Mois suivant
@ -250,9 +251,9 @@ calendar:
previous-week: Semaine précédente
next-week: Semaine suivante
more: '+{n} autre | +{n} autres'
nothing: Rien à rendre ce jour-là.
nothing: Rien de prévu ce jour-là.
add-that-day: Ajouter
load-error: Impossible de charger les échéances.
load-error: Impossible de charger le calendrier.
todo:
title: À faire
empty: Rien à faire, profite !
@ -261,6 +262,49 @@ calendar:
week: Cette semaine
later: Plus tard
undated: Sans échéance
calendars:
new: Calendrier
edit: Modifier le calendrier
created: Calendrier créé
updated: Calendrier modifié
deleted: Calendrier supprimé
save-error: Impossible d'enregistrer le calendrier
delete-error: Impossible de supprimer le calendrier
delete-title: Voulez-vous vraiment supprimer le calendrier « {name} » ?
delete-description: Tous ses événements seront supprimés définitivement.
form:
description: Un calendrier personnel pour tes rendez-vous, échéances et événements.
name: Nom
name-placeholder: Perso
color: Couleur
events:
new: Nouvel événement
edit: Modifier l'événement
created: Événement ajouté
updated: Événement modifié
deleted: Événement supprimé
save-error: Impossible d'enregistrer l'événement
delete-error: Impossible de supprimer l'événement
delete-title: Voulez-vous vraiment supprimer « {name} » ?
all-day: Toute la journée
form:
description: Un rendez-vous, une échéance perso ou tout ce qui se passe à un moment donné.
title: Titre
title-placeholder: Rendez-vous chez le dentiste
calendar: Calendrier
calendar-placeholder: Choisis…
no-calendar: Crée d'abord un calendrier avec le bouton +.
all-day: Toute la journée
start: Début
end: Fin
start-day: Premier jour
end-day: Dernier jour
no-end-hint: Sans fin, c'est un moment précis, comme une échéance ou un rappel.
location: Lieu
location-placeholder: Rolex Learning Center
details: Description
errors:
end: La fin doit être après le début.
focus:
start: Travailler dessus (pomodoro)
back: Revenir au pomodoro

View file

@ -0,0 +1,100 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import { HttpStatus } from 'http-status-ts'
import { toValue, type MaybeRefOrGetter } from 'vue'
import type { Calendar, CalendarBody, EventBody } from '@/utils/types'
import { getClient } from './client'
// Personal calendars and their events. A change of a calendar answers with every
// calendar, which replaces the cache; the events are refetched after each change.
const CALENDARS_KEY = ['calendars']
const EVENTS_KEY = ['calendar-events']
function unexpected(status: number): never {
throw new Error(`Unexpected status code received: ${status}`)
}
export function useCalendars() {
return useQuery({
queryKey: CALENDARS_KEY,
queryFn: async () => {
const { data, response } = await getClient().GET('/api/calendars')
return response.status === HttpStatus.OK && data ? data : unexpected(response.status)
},
})
}
/** Create (no `id`), update or delete a personal calendar */
export function useCalendarMutations() {
const queryClient = useQueryClient()
const onSuccess = (calendars: Calendar[]) => {
queryClient.setQueryData(CALENDARS_KEY, calendars)
queryClient.invalidateQueries({ queryKey: EVENTS_KEY })
}
const save = useMutation({
mutationFn: async ({ id, body }: { id?: number; body: CalendarBody }) => {
const { data, response } =
id === undefined
? await getClient().POST('/api/calendars', { body })
: await getClient().PUT('/api/calendars/{id}', { params: { path: { id } }, body })
return response.status === HttpStatus.OK && data ? data : unexpected(response.status)
},
onSuccess,
})
const remove = useMutation({
mutationFn: async (id: number) => {
const { data, response } = await getClient().DELETE('/api/calendars/{id}', {
params: { path: { id } },
})
return response.status === HttpStatus.OK && data ? data : unexpected(response.status)
},
onSuccess,
})
return { save, remove }
}
/** Events of every personal calendar happening in `[from, to[` (ISO dates) */
export function useCalendarEvents(period: MaybeRefOrGetter<{ from: string; to: string }>) {
return useQuery({
queryKey: [...EVENTS_KEY, period],
queryFn: async () => {
const { data, response } = await getClient().GET('/api/events', {
params: { query: toValue(period) },
})
return response.status === HttpStatus.OK && data ? data : unexpected(response.status)
},
})
}
/** Create (no `id`), update or delete an event */
export function useEventMutations() {
const queryClient = useQueryClient()
const onSuccess = () => queryClient.invalidateQueries({ queryKey: EVENTS_KEY })
const save = useMutation({
mutationFn: async ({ id, body }: { id?: number; body: EventBody }) => {
const { data, response } =
id === undefined
? await getClient().POST('/api/events', { body })
: await getClient().PUT('/api/events/{id}', { params: { path: { id } }, body })
return response.status === HttpStatus.OK && data ? data : unexpected(response.status)
},
onSuccess,
})
const remove = useMutation({
mutationFn: async (id: number) => {
const { response } = await getClient().DELETE('/api/events/{id}', {
params: { path: { id } },
})
if (response.status !== HttpStatus.NO_CONTENT) unexpected(response.status)
},
onSuccess,
})
return { save, remove }
}

View file

@ -16,3 +16,18 @@ export function useVersion() {
},
})
}
/** The person logged in through Authelia */
export function useMe() {
return useQuery({
queryKey: ['me'],
staleTime: Infinity,
queryFn: async () => {
const { data, response } = await getClient().GET('/api/me')
if (response.status === HttpStatus.OK && data) {
return data
}
throw new Error(`Unexpected status code received ${response.status}`)
},
})
}

View file

@ -37,3 +37,34 @@ export function weeksPeriod(weeks: Date[][]): { from: string; to: string } {
end.setDate(end.getDate() + 1)
return { from: weeks[0]![0]!.toISOString(), to: end.toISOString() }
}
/** `<input type="date">` value ("2026-10-05", local time) -> local midnight of that day */
export function fromDayKey(key: string): Date {
const [year, month, day] = key.split('-').map(Number)
return new Date(year!, month! - 1, day)
}
/** The next day at midnight, local time */
export function nextDay(date: Date): Date {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1)
}
/**
* Keys of the days an event happens on, in local time: from its start to its exclusive
* end, or the day of its start for a single moment. At most `max` days.
*/
export function eventDayKeys(
event: { starts_at: string; ends_at?: string | null },
max = 62,
): string[] {
const start = new Date(event.starts_at)
// The end is exclusive: an event ending at midnight does not happen on that day
const last = event.ends_at ? new Date(new Date(event.ends_at).getTime() - 1) : start
const keys: string[] = []
const lastKey = dayKey(last)
for (let day = start; keys.length < max; day = nextDay(day)) {
keys.push(dayKey(day))
if (dayKey(day) >= lastKey) break
}
return keys
}

View file

@ -27,6 +27,10 @@ export type TagScope = Schemas['TagScope']
export type LectureNoteBody = Schemas['LectureNoteBody']
export type LectureNoteContent = Schemas['LectureNoteContent']
export type SavedLectureNote = Schemas['SavedLectureNote']
export type Calendar = Schemas['Calendar']
export type CalendarBody = Schemas['CalendarBody']
export type CalendarEvent = Schemas['Event']
export type EventBody = Schemas['EventBody']
/** Tag with its name resolved in the current locale */
export interface Tag {

View file

@ -1,56 +1,90 @@
<script setup lang="ts">
/**
* Deadlines of the courses and associations in a month calendar, next to everything left
* to do. Courses and associations can each be hidden, and tasks created from here.
* The personal calendars and the deadlines of the courses and associations in a month
* calendar, then everything left to do. Each source can be hidden. Events (personal
* calendars) and tasks (courses, associations) are created apart: they are not the same.
*/
import { computed, ref, watch } from 'vue'
import { BookOpen, Plus, Users } from '@lucide/vue'
import { BookOpen, CalendarPlus, ListTodo, Pencil, Plus, Users } from '@lucide/vue'
import TasksCalendar from '@/components/calendar/TasksCalendar.vue'
import CalendarFormDialog from '@/components/calendar/CalendarFormDialog.vue'
import EventFormDialog from '@/components/calendar/EventFormDialog.vue'
import MonthCalendar from '@/components/calendar/MonthCalendar.vue'
import TodoList from '@/components/calendar/TodoList.vue'
import TaskFormDialog from '@/components/course/TaskFormDialog.vue'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import type { CourseKind } from '@/utils/types'
import { useCalendars } from '@/services/api/calendars'
import type { Calendar, CalendarEvent, CourseKind } from '@/utils/types'
const KINDS: { kind: CourseKind; icon: typeof BookOpen }[] = [
{ kind: 'course', icon: BookOpen },
{ kind: 'association', icon: Users },
]
// Remembered in the browser: only a convenience
// Remembered in the browser: only a convenience. The hidden calendars are stored rather
// than the shown ones, so a new calendar is shown.
const STORAGE_KEY = 'calendar-kinds'
const HIDDEN_KEY = 'calendar-hidden'
function loadKinds(): CourseKind[] {
function load<T>(key: string, parse: (value: unknown) => T | undefined, fallback: T): T {
try {
const saved = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? 'null')
if (Array.isArray(saved)) return saved.filter((k) => k === 'course' || k === 'association')
return parse(JSON.parse(window.localStorage.getItem(key) ?? 'null')) ?? fallback
} catch {
// Unavailable or invalid: everything is shown
return fallback
}
return ['course', 'association']
}
const kinds = ref<CourseKind[]>(loadKinds())
watch(kinds, (value) => {
function remember(key: string, value: unknown) {
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value))
window.localStorage.setItem(key, JSON.stringify(value))
} catch {
// Not remembered
}
})
}
function toggle(kind: CourseKind) {
const kinds = ref<CourseKind[]>(
load(
STORAGE_KEY,
(saved) =>
Array.isArray(saved)
? saved.filter((k): k is CourseKind => k === 'course' || k === 'association')
: undefined,
['course', 'association'],
),
)
const hiddenCalendars = ref<number[]>(
load(
HIDDEN_KEY,
(saved) =>
Array.isArray(saved) ? saved.filter((id): id is number => typeof id === 'number') : undefined,
[],
),
)
watch(kinds, (value) => remember(STORAGE_KEY, value))
watch(hiddenCalendars, (value) => remember(HIDDEN_KEY, value))
function toggleKind(kind: CourseKind) {
kinds.value = kinds.value.includes(kind)
? kinds.value.filter((k) => k !== kind)
: [...kinds.value, kind]
}
const formOpen = ref(false)
function toggleCalendar(id: number) {
hiddenCalendars.value = hiddenCalendars.value.includes(id)
? hiddenCalendars.value.filter((hidden) => hidden !== id)
: [...hiddenCalendars.value, id]
}
const { data: calendars } = useCalendars()
// Tasks
const taskFormOpen = ref(false)
const defaultDeadline = ref<string>()
/** New task, due at the end of `day` when given */
function openForm(day?: Date) {
function newTask(day?: Date) {
if (day) {
const end = new Date(day)
end.setHours(23, 59, 0, 0)
@ -58,56 +92,158 @@ function openForm(day?: Date) {
} else {
defaultDeadline.value = undefined
}
formOpen.value = true
taskFormOpen.value = true
}
const nothingShown = computed(() => !kinds.value.length)
// Events
const eventFormOpen = ref(false)
const editedEvent = ref<CalendarEvent>()
const eventDay = ref<Date>()
function newEvent(day?: Date) {
editedEvent.value = undefined
eventDay.value = day
eventFormOpen.value = true
}
function editEvent(event: CalendarEvent) {
editedEvent.value = event
eventFormOpen.value = true
}
// Calendars
const calendarFormOpen = ref(false)
const editedCalendar = ref<Calendar>()
function openCalendarForm(calendar?: Calendar) {
editedCalendar.value = calendar
calendarFormOpen.value = true
}
const nothingShown = computed(
() =>
!kinds.value.length &&
(calendars.value ?? []).every((calendar) => hiddenCalendars.value.includes(calendar.id)),
)
const chip =
'inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors'
</script>
<template>
<div class="mx-auto flex max-w-7xl flex-col gap-4">
<div class="mx-auto flex max-w-5xl flex-col gap-4">
<div class="flex flex-wrap items-center gap-2">
<div class="flex gap-2" role="group" :aria-label="$t('calendar.show')">
<div class="flex flex-wrap gap-2" role="group" :aria-label="$t('calendar.show')">
<button
v-for="{ kind, icon } in KINDS"
:key="kind"
type="button"
class="inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors"
:class="
:class="[
chip,
kinds.includes(kind)
? 'border-primary bg-primary/10 font-medium text-primary'
: 'text-muted-foreground hover:bg-accent'
"
: 'text-muted-foreground hover:bg-accent',
]"
:aria-pressed="kinds.includes(kind)"
@click="toggle(kind)"
@click="toggleKind(kind)"
>
<component :is="icon" class="size-4" />
{{ $t(`nav.${kind}s`) }}
</button>
<!-- Personal calendars: shown or hidden, and edited with the pencil -->
<span
v-for="calendar in calendars"
:key="calendar.id"
class="group inline-flex items-center rounded-full border transition-colors"
:class="
hiddenCalendars.includes(calendar.id)
? 'text-muted-foreground hover:bg-accent'
: 'font-medium'
"
:style="
hiddenCalendars.includes(calendar.id)
? undefined
: {
borderColor: calendar.color,
color: calendar.color,
backgroundColor: `color-mix(in oklab, ${calendar.color} 10%, transparent)`,
}
"
>
<button
type="button"
class="inline-flex items-center gap-2 py-1.5 pr-1 pl-3 text-sm"
:aria-pressed="!hiddenCalendars.includes(calendar.id)"
@click="toggleCalendar(calendar.id)"
>
<span
class="size-2.5 rounded-full border-2"
:style="{
borderColor: calendar.color,
backgroundColor: hiddenCalendars.includes(calendar.id)
? 'transparent'
: calendar.color,
}"
/>
{{ calendar.name }}
</button>
<button
type="button"
class="mr-1 rounded-full p-1 opacity-50 transition-opacity group-hover:opacity-100 hover:bg-foreground/10 focus-visible:opacity-100"
:title="$t('calendars.edit')"
@click="openCalendarForm(calendar)"
>
<Pencil class="size-3" />
<span class="sr-only">{{ $t('calendars.edit') }}</span>
</button>
</span>
<button
type="button"
:class="[chip, 'border-dashed text-muted-foreground hover:bg-accent']"
@click="openCalendarForm()"
>
<Plus class="size-4" />
{{ $t('calendars.new') }}
</button>
</div>
<div class="ml-auto flex gap-2">
<Button variant="outline" @click="newTask()">
<ListTodo />
{{ $t('tasks.new') }}
</Button>
<Button @click="newEvent()">
<CalendarPlus />
{{ $t('events.new') }}
</Button>
</div>
<Button class="ml-auto" @click="openForm()">
<Plus />
{{ $t('tasks.new') }}
</Button>
</div>
<p v-if="nothingShown" class="text-sm text-muted-foreground">
{{ $t('calendar.nothing-shown') }}
</p>
<div class="grid items-start gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<TasksCalendar :kinds="kinds" class="min-w-0" @create="openForm" />
<MonthCalendar
:kinds="kinds"
:hidden-calendars="hiddenCalendars"
@create-event="newEvent"
@create-task="newTask"
@edit-event="editEvent"
/>
<Card class="lg:sticky lg:top-4 lg:max-h-[calc(100svh-6rem)] lg:overflow-y-auto">
<CardHeader>
<CardTitle class="text-base">{{ $t('calendar.todo.title') }}</CardTitle>
</CardHeader>
<CardContent>
<TodoList :kinds="kinds" />
</CardContent>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle class="text-base">{{ $t('calendar.todo.title') }}</CardTitle>
</CardHeader>
<CardContent>
<TodoList :kinds="kinds" />
</CardContent>
</Card>
<TaskFormDialog v-model:open="formOpen" :default-deadline="defaultDeadline" />
<TaskFormDialog v-model:open="taskFormOpen" :default-deadline="defaultDeadline" />
<EventFormDialog v-model:open="eventFormOpen" :event="editedEvent" :default-day="eventDay" />
<CalendarFormDialog v-model:open="calendarFormOpen" :calendar="editedCalendar" />
</div>
</template>

View file

@ -4,6 +4,9 @@
* quiet page. A ring fills up every 25 minutes and suggests a break, a fifth of the
* focus time. The notes and slides of the course open next to the clock.
*
* In full screen the page goes dark and immersive: slow lights in the color of the task
* drift behind the clock, and dim while paused.
*
* `?task=<id>` starts a session on the task (see `services/focus.ts`).
*/
import { computed, onBeforeUnmount, ref, useTemplateRef, watch } from 'vue'
@ -142,6 +145,17 @@ onBeforeUnmount(() => (document.title = originalTitle))
const container = useTemplateRef<HTMLElement>('container')
const { isFullscreen, toggle: toggleFullscreen } = useFullscreen(container)
/** Color of the lights of the full screen: the one of the task, or of the focus itself */
const ambient = computed(() => tagsById.value.get(task.value?.tag_ids[0] ?? -1)?.color ?? '#6366f1')
/** Cards on the lights of the full screen are made of frosted glass */
const surface = computed(() =>
isFullscreen.value ? 'border-white/10 bg-white/[0.06] backdrop-blur-xl' : 'bg-card',
)
const surfaceHover = computed(() =>
isFullscreen.value ? 'hover:bg-white/[0.12]' : 'hover:bg-accent',
)
// Resources of the course: its notes (and soon its slides), opened next to the clock
const showResources = ref(true)
const { data: files, isPending: filesPending } = useCourseFiles(() => task.value?.course.id)
@ -169,11 +183,35 @@ const choices = computed(() =>
<template>
<div
ref="container"
class="relative -m-4 flex min-h-[calc(100svh-3.5rem)] flex-col bg-gradient-to-b from-muted/40 to-background md:-m-6"
class="relative -m-4 flex min-h-[calc(100svh-3.5rem)] flex-col md:-m-6"
:class="
isFullscreen
? 'dark isolate min-h-svh overflow-hidden bg-[#07070c] text-foreground'
: 'bg-gradient-to-b from-muted/40 to-background'
"
:style="{ '--ambient': ambient }"
>
<!-- Full screen: lights drifting behind everything, dimmed while paused -->
<div
v-if="isFullscreen"
class="ambient pointer-events-none absolute inset-0 -z-10 transition-[opacity,filter] duration-[2s]"
:class="session && !isRunning ? 'opacity-40 saturate-50' : 'opacity-100'"
aria-hidden="true"
>
<span class="blob blob-1" />
<span class="blob blob-2" />
<span class="blob blob-3" />
<span class="vignette" />
</div>
<!-- Top bar: quiet, out of the way -->
<div class="flex items-center gap-2 px-4 pt-4 md:px-6">
<span class="text-sm text-muted-foreground first-letter:uppercase">{{ today }}</span>
<span
class="text-sm first-letter:uppercase"
:class="isFullscreen ? 'tracking-wide text-white/60' : 'text-muted-foreground'"
>
{{ today }}
</span>
<div class="ml-auto flex gap-1">
<Button
v-if="task"
@ -264,33 +302,52 @@ const choices = computed(() =>
</div>
<!-- Ring of the current cycle, the focus time inside -->
<div class="relative size-72 sm:size-96">
<svg viewBox="0 0 100 100" class="size-full -rotate-90" aria-hidden="true">
<div
class="relative"
:class="isFullscreen ? 'size-80 sm:size-[28rem]' : 'size-72 sm:size-96'"
>
<svg
viewBox="0 0 100 100"
class="size-full -rotate-90 overflow-visible"
:class="{ 'ring-glow': isFullscreen && isRunning }"
aria-hidden="true"
>
<circle
cx="50"
cy="50"
:r="RADIUS"
fill="none"
class="stroke-muted"
stroke-width="2"
:class="isFullscreen ? 'stroke-white/10' : 'stroke-muted'"
:stroke-width="isFullscreen ? 1 : 2"
/>
<circle
cx="50"
cy="50"
:r="RADIUS"
fill="none"
stroke-width="2.5"
:stroke-width="isFullscreen ? 1.5 : 2.5"
stroke-linecap="round"
class="transition-[stroke-dashoffset] duration-1000 ease-linear"
:class="isRunning ? 'stroke-primary' : 'stroke-muted-foreground/40'"
class="transition-[stroke-dashoffset,stroke] duration-1000 ease-linear"
:class="
isFullscreen
? isRunning
? 'stroke-[var(--ambient)]'
: 'stroke-white/30'
: isRunning
? 'stroke-primary'
: 'stroke-muted-foreground/40'
"
:stroke-dasharray="CIRCUMFERENCE"
:stroke-dashoffset="CIRCUMFERENCE * (1 - cycleProgress)"
/>
</svg>
<div class="absolute inset-0 flex flex-col items-center justify-center gap-2">
<span
class="font-mono text-6xl font-light tracking-tight tabular-nums sm:text-7xl"
:class="{ 'text-muted-foreground': !isRunning }"
class="font-extralight tracking-tighter tabular-nums"
:class="[
isFullscreen ? 'text-7xl sm:text-8xl' : 'text-6xl sm:text-7xl',
{ 'text-muted-foreground': !isRunning },
]"
role="timer"
:aria-label="$t('focus.elapsed')"
>
@ -305,7 +362,8 @@ const choices = computed(() =>
<span
v-for="i in Math.min(cycles, 8)"
:key="i"
class="size-2 rounded-full bg-primary/70"
class="size-2 rounded-full"
:class="isFullscreen ? 'bg-[var(--ambient)]' : 'bg-primary/70'"
/>
<span v-if="cycles > 8" class="text-xs text-muted-foreground"
>+{{ cycles - 8 }}</span
@ -323,6 +381,10 @@ const choices = computed(() =>
<Button
size="lg"
class="h-14 min-w-40 rounded-full text-base"
:class="{
'bg-[var(--ambient)] text-white shadow-[0_0_30px_-6px_var(--ambient)] hover:bg-[var(--ambient)] hover:brightness-110':
isFullscreen,
}"
:disabled="pending"
@click="togglePause"
>
@ -359,7 +421,12 @@ const choices = computed(() =>
<!-- Nothing running -->
<template v-else>
<div class="flex flex-col items-center gap-1">
<span class="font-mono text-7xl font-light tracking-tight tabular-nums sm:text-8xl">
<span
class="font-extralight tracking-tighter tabular-nums"
:class="
isFullscreen ? 'text-[clamp(6rem,16vw,13rem)] leading-none' : 'text-7xl sm:text-8xl'
"
>
{{ clock }}
</span>
<p class="text-muted-foreground">{{ $t('focus.pick') }}</p>
@ -373,7 +440,8 @@ const choices = computed(() =>
<li v-for="choice in choices" :key="choice.task.id">
<button
type="button"
class="flex w-full items-center gap-3 rounded-lg border bg-card px-3 py-2 text-left transition-colors hover:bg-accent disabled:opacity-60"
class="flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left transition-colors disabled:opacity-60"
:class="[surface, surfaceHover]"
:disabled="pending"
@click="run(() => focus.start(choice.task.id))"
>
@ -408,9 +476,13 @@ const choices = computed(() =>
<!-- Side: the clock when a resource is opened, and the resources -->
<aside v-if="task && showResources" class="flex min-w-0 flex-col gap-4">
<div v-if="openedFile" class="flex items-center gap-3 rounded-xl border bg-card p-3">
<div
v-if="openedFile"
class="flex items-center gap-3 rounded-xl border p-3"
:class="surface"
>
<span
class="font-mono text-3xl font-light tabular-nums"
class="text-3xl font-extralight tracking-tight tabular-nums"
:class="{ 'text-muted-foreground': !isRunning }"
>
{{ formatDuration(elapsed) }}
@ -429,7 +501,7 @@ const choices = computed(() =>
</Button>
</div>
<div class="flex flex-col gap-2 rounded-xl border bg-card p-3">
<div class="flex flex-col gap-2 rounded-xl border p-3" :class="surface">
<h3 class="text-sm font-medium">{{ $t('focus.resources') }}</h3>
<div v-if="filesPending" class="flex flex-col gap-2">
<Skeleton v-for="i in 3" :key="i" class="h-9" />
@ -441,8 +513,8 @@ const choices = computed(() =>
<li v-for="file in files" :key="file.id">
<button
type="button"
class="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-accent disabled:cursor-not-allowed disabled:opacity-50"
:class="{ 'bg-accent font-medium': openedFile?.id === file.id }"
class="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors disabled:cursor-not-allowed disabled:opacity-50"
:class="[surfaceHover, { 'bg-accent font-medium': openedFile?.id === file.id }]"
:disabled="!canOpen(file)"
@click="openedFile = file"
>
@ -459,3 +531,83 @@ const choices = computed(() =>
</div>
</div>
</template>
<style scoped>
/* Lights of the full screen: big blurred spots slowly drifting, in the color of the task */
.blob {
position: absolute;
width: 60vmax;
height: 60vmax;
border-radius: 9999px;
filter: blur(100px);
opacity: 0.75;
will-change: transform;
}
.blob-1 {
top: -20vmax;
left: -15vmax;
background: radial-gradient(circle, var(--ambient), transparent 65%);
animation: drift-1 38s ease-in-out infinite alternate;
}
.blob-2 {
right: -20vmax;
bottom: -25vmax;
background: radial-gradient(
circle,
color-mix(in oklab, var(--ambient) 40%, #4f46e5),
transparent 65%
);
animation: drift-2 46s ease-in-out infinite alternate;
}
.blob-3 {
top: 30%;
left: 40%;
width: 40vmax;
height: 40vmax;
opacity: 0.45;
background: radial-gradient(
circle,
color-mix(in oklab, var(--ambient) 30%, #0ea5e9),
transparent 65%
);
animation: drift-3 54s ease-in-out infinite alternate;
}
/* Darkens the edges, the eye stays on the clock */
.vignette {
position: absolute;
inset: 0;
background: radial-gradient(ellipse at center, transparent 35%, rgb(0 0 0 / 0.65) 100%);
}
.ring-glow {
filter: drop-shadow(0 0 6px color-mix(in oklab, var(--ambient) 70%, transparent));
}
@keyframes drift-1 {
to {
transform: translate(18vmax, 12vmax) scale(1.15);
}
}
@keyframes drift-2 {
to {
transform: translate(-16vmax, -14vmax) scale(0.9);
}
}
@keyframes drift-3 {
to {
transform: translate(-22vmax, 10vmax) scale(1.2);
}
}
@media (prefers-reduced-motion: reduce) {
.blob {
animation: none;
}
}
</style>

177
src/api/calendars.rs Normal file
View file

@ -0,0 +1,177 @@
//! Personal calendars and their events. A change of a calendar returns every calendar,
//! a change of an event returns the event.
use aide::{
axum::{
ApiRouter,
routing::{get_with, put_with},
},
transform::TransformOperation,
};
use axum::{
Json,
extract::{Path, Query},
http::StatusCode,
};
use crate::{
api::{
helpers::{desc, error_response},
models::{CalendarBody, CalendarPath, EventBody, EventPath, PeriodQuery},
},
core::{
controller::AppController,
models::calendar::{Calendar, Event},
},
};
pub fn routes() -> ApiRouter {
ApiRouter::new()
.api_route(
"/api/calendars",
get_with(get_calendars, get_calendars_docs)
.post_with(create_calendar, create_calendar_docs),
)
.api_route(
"/api/calendars/{id}",
put_with(update_calendar, update_calendar_docs)
.delete_with(delete_calendar, delete_calendar_docs),
)
.api_route(
"/api/events",
get_with(get_events, get_events_docs).post_with(create_event, create_event_docs),
)
.api_route(
"/api/events/{id}",
put_with(update_event, update_event_docs).delete_with(delete_event, delete_event_docs),
)
}
type CalendarsResult = Result<Json<Vec<Calendar>>, (StatusCode, String)>;
type EventResult = Result<Json<Event>, (StatusCode, String)>;
async fn get_calendars(controller: AppController) -> CalendarsResult {
match controller.get_calendars().await {
Ok(calendars) => Ok(Json(calendars)),
Err(err) => error_response("get_calendars", err),
}
}
fn get_calendars_docs(op: TransformOperation) -> TransformOperation {
op.tag("Calendars").summary("Get every personal calendar")
}
async fn create_calendar(
controller: AppController,
Json(body): Json<CalendarBody>,
) -> CalendarsResult {
match controller.create_calendar(body.into()).await {
Ok(calendars) => Ok(Json(calendars)),
Err(err) => error_response("create_calendar", err),
}
}
fn create_calendar_docs(op: TransformOperation) -> TransformOperation {
op.tag("Calendars")
.summary("Create a personal calendar, returns every calendar")
.response_with::<400, String, _>(desc("The calendar is invalid"))
}
async fn update_calendar(
controller: AppController,
Path(path): Path<CalendarPath>,
Json(body): Json<CalendarBody>,
) -> CalendarsResult {
match controller.update_calendar(path.id, body.into()).await {
Ok(calendars) => Ok(Json(calendars)),
Err(err) => error_response("update_calendar", err),
}
}
fn update_calendar_docs(op: TransformOperation) -> TransformOperation {
op.tag("Calendars")
.summary("Rename or recolor a personal calendar, returns every calendar")
.response_with::<400, String, _>(desc("The calendar is invalid"))
.response_with::<404, String, _>(desc("The calendar does not exist"))
}
async fn delete_calendar(
controller: AppController,
Path(path): Path<CalendarPath>,
) -> CalendarsResult {
match controller.delete_calendar(path.id).await {
Ok(calendars) => Ok(Json(calendars)),
Err(err) => error_response("delete_calendar", err),
}
}
fn delete_calendar_docs(op: TransformOperation) -> TransformOperation {
op.tag("Calendars")
.summary("Delete a personal calendar and its events, returns the calendars left")
.response_with::<404, String, _>(desc("The calendar does not exist"))
}
async fn get_events(
controller: AppController,
Query(period): Query<PeriodQuery>,
) -> Result<Json<Vec<Event>>, (StatusCode, String)> {
match controller.get_events(period.from, period.to).await {
Ok(events) => Ok(Json(events)),
Err(err) => error_response("get_events", err),
}
}
fn get_events_docs(op: TransformOperation) -> TransformOperation {
op.tag("Calendars")
.summary("Get the events of every personal calendar happening in a period")
.response_with::<400, String, _>(desc("The period is invalid"))
}
async fn create_event(controller: AppController, Json(body): Json<EventBody>) -> EventResult {
match controller.create_event(body.into()).await {
Ok(event) => Ok(Json(event)),
Err(err) => error_response("create_event", err),
}
}
fn create_event_docs(op: TransformOperation) -> TransformOperation {
op.tag("Calendars")
.summary("Add an event to a personal calendar")
.response_with::<400, String, _>(desc("The event is invalid"))
.response_with::<404, String, _>(desc("The calendar does not exist"))
}
async fn update_event(
controller: AppController,
Path(path): Path<EventPath>,
Json(body): Json<EventBody>,
) -> EventResult {
match controller.update_event(path.id, body.into()).await {
Ok(event) => Ok(Json(event)),
Err(err) => error_response("update_event", err),
}
}
fn update_event_docs(op: TransformOperation) -> TransformOperation {
op.tag("Calendars")
.summary("Replace an event, possibly moving it to another calendar")
.response_with::<400, String, _>(desc("The event is invalid"))
.response_with::<404, String, _>(desc("The event or the calendar does not exist"))
}
async fn delete_event(
controller: AppController,
Path(path): Path<EventPath>,
) -> Result<StatusCode, (StatusCode, String)> {
match controller.delete_event(path.id).await {
Ok(()) => Ok(StatusCode::NO_CONTENT),
Err(err) => error_response("delete_event", err),
}
}
fn delete_event_docs(op: TransformOperation) -> TransformOperation {
op.tag("Calendars")
.summary("Delete an event")
.response_with::<204, (), _>(desc("The event was deleted"))
.response_with::<404, String, _>(desc("The event does not exist"))
}

View file

@ -22,6 +22,7 @@ pub fn error_response<T>(fn_name: &str, err: ControllerError) -> Result<T, (Stat
ControllerError::Task(err) => Some(err.to_string()),
ControllerError::LectureNote(err) => Some(err.to_string()),
ControllerError::Focus(err) => Some(err.to_string()),
ControllerError::Calendar(err) => Some(err.to_string()),
_ => None,
};
match (invalid, err) {

View file

@ -2,6 +2,10 @@
//!
//! Handlers stay thin: they extract the controller, call it, and map
//! `ControllerError` to a status code. No business logic here.
//!
//! Authelia authenticates the people in front of the app, and gives their login in the
//! `Remote-User` header: each request gets a controller acting for that person. The app
//! must only be reachable through Authelia, or anyone could send this header.
use std::sync::Arc;
@ -13,12 +17,19 @@ use aide::{
use axum::{
Extension, Json, Router,
extract::FromRequestParts,
http::{StatusCode, request::Parts},
http::{HeaderMap, StatusCode, request::Parts},
};
use tracing::error;
use tracing::{error, warn};
use crate::core::controller::AppController;
use crate::{
core::{
controller::{AppController, AppServices},
models::user::User,
},
utils::config::AuthConfig,
};
mod calendars;
mod course_files;
mod courses;
mod docs;
@ -27,8 +38,9 @@ mod helpers;
mod models;
mod tags;
mod tasks;
mod users;
pub fn get_router(controller: AppController) -> Router {
pub fn get_router(services: AppServices, auth: AuthConfig) -> Router {
aide::generate::on_error(|err| error!("aide generated error: {err}"));
aide::generate::extract_schemas(true);
@ -46,25 +58,82 @@ pub fn get_router(controller: AppController) -> Router {
.merge(grades::routes())
.merge(tasks::routes())
.merge(course_files::routes())
.merge(calendars::routes())
.merge(users::routes())
.nest_api_service("/api/docs", docs::routes())
.finish_api_with(&mut api, docs::api_docs_metadata)
.layer(Extension(controller))
.layer(Extension(services))
.layer(Extension(Arc::new(auth)))
.layer(Extension(Arc::new(api)))
}
/// Lets a handler take an `AppController` as an argument
/// Header holding the login of the person, set by Authelia
const USER_HEADER: &str = "Remote-User";
/// Their display name, e.g. `Jane Doe`
const NAME_HEADER: &str = "Remote-Name";
/// Proves the request went through the reverse proxy (`auth.proxy_secret`)
const PROXY_SECRET_HEADER: &str = "X-Proxy-Secret";
fn header(headers: &HeaderMap, name: &str) -> Option<String> {
headers
.get(name)
.map(|value| String::from_utf8_lossy(value.as_bytes()).trim().to_owned())
.filter(|value| !value.is_empty())
}
/// Compares in a time that does not depend on where the values differ
fn same_secret(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0, |diff, (x, y)| diff | (x ^ y)) == 0
}
/// The person making the request: 401 without login (and without `default_user`) or
/// without the secret of the proxy, 403 for a login that cannot be a folder name
fn current_user(headers: &HeaderMap, auth: &AuthConfig) -> Result<User, (StatusCode, String)> {
if let Some(secret) = &auth.proxy_secret {
let sent = headers
.get(PROXY_SECRET_HEADER)
.map(|value| value.as_bytes())
.unwrap_or_default();
if !same_secret(sent, secret.as_bytes()) {
warn!("Refused a request that did not come through the reverse proxy");
return Err((StatusCode::UNAUTHORIZED, "Not authenticated".to_owned()));
}
}
let Some(username) = header(headers, USER_HEADER).or_else(|| auth.default_user.clone()) else {
return Err((StatusCode::UNAUTHORIZED, "Not authenticated".to_owned()));
};
if !User::is_valid_username(&username) {
warn!("Refused the login {username:?}: not usable as a folder name");
return Err((StatusCode::FORBIDDEN, "Invalid login".to_owned()));
}
Ok(User {
username,
display_name: header(headers, NAME_HEADER),
})
}
/// Lets a handler take an `AppController` as an argument, acting for the person making
/// the request
impl<S> FromRequestParts<S> for AppController
where
S: Send + Sync,
{
type Rejection = StatusCode;
type Rejection = (StatusCode, String);
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
parts
let missing = || {
(
StatusCode::INTERNAL_SERVER_ERROR,
"Unexpected error".to_owned(),
)
};
let services = parts.extensions.get::<AppServices>().ok_or_else(missing)?;
let auth = parts
.extensions
.get::<AppController>()
.cloned()
.ok_or(StatusCode::INTERNAL_SERVER_ERROR)
.get::<Arc<AuthConfig>>()
.ok_or_else(missing)?;
let user = current_user(&parts.headers, auth)?;
Ok(services.controller(user))
}
}
@ -73,3 +142,69 @@ impl OperationOutput for AppController {
type Inner = Self;
}
impl OperationInput for AppController {}
#[cfg(test)]
mod tests {
use axum::http::HeaderValue;
use super::*;
fn auth(default_user: Option<&str>) -> AuthConfig {
AuthConfig {
default_user: default_user.map(str::to_owned),
logout_url: None,
proxy_secret: None,
}
}
#[test]
fn the_user_comes_from_authelia() {
let mut headers = HeaderMap::new();
headers.insert(USER_HEADER, HeaderValue::from_static("jdoe"));
headers.insert(NAME_HEADER, HeaderValue::from_static("Jane Doe"));
let user = current_user(&headers, &auth(Some("dev"))).unwrap();
assert_eq!(user.username, "jdoe");
assert_eq!(user.display_name.as_deref(), Some("Jane Doe"));
}
#[test]
fn without_login() {
let headers = HeaderMap::new();
assert_eq!(
current_user(&headers, &auth(None)).unwrap_err().0,
StatusCode::UNAUTHORIZED
);
assert_eq!(
current_user(&headers, &auth(Some("dev"))).unwrap().username,
"dev"
);
}
#[test]
fn only_through_the_proxy() {
let auth = AuthConfig {
proxy_secret: Some("s3cret".to_owned()),
..auth(None)
};
let mut headers = HeaderMap::new();
headers.insert(USER_HEADER, HeaderValue::from_static("jdoe"));
assert_eq!(
current_user(&headers, &auth).unwrap_err().0,
StatusCode::UNAUTHORIZED
);
headers.insert(PROXY_SECRET_HEADER, HeaderValue::from_static("wrong!"));
assert!(current_user(&headers, &auth).is_err());
headers.insert(PROXY_SECRET_HEADER, HeaderValue::from_static("s3cret"));
assert_eq!(current_user(&headers, &auth).unwrap().username, "jdoe");
}
#[test]
fn a_login_cannot_leave_the_storage() {
let mut headers = HeaderMap::new();
headers.insert(USER_HEADER, HeaderValue::from_static(".."));
assert_eq!(
current_user(&headers, &auth(None)).unwrap_err().0,
StatusCode::FORBIDDEN
);
}
}

View file

@ -6,6 +6,7 @@ use schemars::JsonSchema;
use serde::Deserialize;
use crate::core::models::{
calendar::{CalendarData, CalendarId, EventData, EventId},
course::{CourseData, CourseId, CourseKind},
course_file::CourseFileId,
focus::TimetaggerRecord,
@ -42,6 +43,16 @@ pub struct LectureNotePath {
pub id: CourseFileId,
}
#[derive(Deserialize, JsonSchema)]
pub struct CalendarPath {
pub id: CalendarId,
}
#[derive(Deserialize, JsonSchema)]
pub struct EventPath {
pub id: EventId,
}
/// Period `[from, to[`, at most 62 days
#[derive(Deserialize, JsonSchema)]
pub struct PeriodQuery {
@ -125,6 +136,52 @@ pub struct LectureNoteBody {
pub content: String,
}
#[derive(Deserialize, JsonSchema)]
pub struct CalendarBody {
pub name: String,
/// Hex color, e.g. `#2563eb`
pub color: String,
}
/// An event of a personal calendar
#[derive(Deserialize, JsonSchema)]
pub struct EventBody {
pub calendar_id: CalendarId,
pub title: String,
pub location: Option<String>,
pub description: Option<String>,
pub starts_at: DateTime<Utc>,
/// Exclusive, after `starts_at`. `null` for a single moment (a deadline, a reminder).
pub ends_at: Option<DateTime<Utc>>,
/// From the midnight of the first day to the midnight after the last one, in local
/// time: `ends_at` is required
#[serde(default)]
pub all_day: bool,
}
impl From<CalendarBody> for CalendarData {
fn from(value: CalendarBody) -> Self {
CalendarData {
name: value.name,
color: value.color,
}
}
}
impl From<EventBody> for EventData {
fn from(value: EventBody) -> Self {
EventData {
calendar_id: value.calendar_id,
title: value.title,
location: value.location,
description: value.description,
starts_at: value.starts_at,
ends_at: value.ends_at,
all_day: value.all_day,
}
}
}
impl From<CourseBody> for CourseData {
fn from(value: CourseBody) -> Self {
CourseData {

43
src/api/users.rs Normal file
View file

@ -0,0 +1,43 @@
//! The person using the app, to show who is logged in
use std::sync::Arc;
use aide::{
axum::{ApiRouter, routing::get_with},
transform::TransformOperation,
};
use axum::{Extension, Json};
use schemars::JsonSchema;
use serde::Serialize;
use crate::{core::controller::AppController, utils::config::AuthConfig};
pub fn routes() -> ApiRouter {
ApiRouter::new().api_route("/api/me", get_with(get_me, get_me_docs))
}
#[derive(Serialize, JsonSchema)]
struct Me {
/// Login, e.g. `jdoe`
username: String,
/// e.g. `Jane Doe`, when Authelia gives it
display_name: Option<String>,
/// Where to log out (the portal of Authelia), when configured
logout_url: Option<String>,
}
async fn get_me(
controller: AppController,
Extension(auth): Extension<Arc<AuthConfig>>,
) -> Json<Me> {
let user = controller.user();
Json(Me {
username: user.username.clone(),
display_name: user.display_name.clone(),
logout_url: auth.logout_url.clone(),
})
}
fn get_me_docs(op: TransformOperation) -> TransformOperation {
op.tag("Users").summary("Get the person logged in")
}

View file

@ -0,0 +1,190 @@
//! Personal calendars and their events: appointments, personal deadlines, anything
//! happening at a time. Not tasks: an event is never done.
use chrono::{DateTime, Duration, Utc};
use thiserror::Error;
use crate::core::{
controller::{ControllerError, non_blank},
models::calendar::{Calendar, CalendarData, CalendarId, Event, EventData, EventId},
};
/// Longest period the calendar can ask for, a month view needs 6 weeks
const MAX_PERIOD_DAYS: i64 = 62;
impl super::AppController {
pub async fn get_calendars(&self) -> Result<Vec<Calendar>, ControllerError> {
Ok(self.db.get_calendars(self.owner()).await?)
}
/// Returns every calendar, the new one included
pub async fn create_calendar(
&self,
calendar: CalendarData,
) -> Result<Vec<Calendar>, ControllerError> {
let calendar = validate_calendar(calendar)?;
self.db.create_calendar(self.owner(), calendar).await?;
self.get_calendars().await
}
/// Returns every calendar
pub async fn update_calendar(
&self,
id: CalendarId,
calendar: CalendarData,
) -> Result<Vec<Calendar>, ControllerError> {
let calendar = validate_calendar(calendar)?;
self.db.update_calendar(self.owner(), id, calendar).await?;
self.get_calendars().await
}
/// Deletes the calendar and its events, returns the calendars left
pub async fn delete_calendar(&self, id: CalendarId) -> Result<Vec<Calendar>, ControllerError> {
self.db.delete_calendar(self.owner(), id).await?;
self.get_calendars().await
}
/// Events of every calendar happening in `[from, to[`, the earliest first
pub async fn get_events(
&self,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> Result<Vec<Event>, ControllerError> {
if from >= to || to - from > Duration::days(MAX_PERIOD_DAYS) {
return Err(CalendarsControllerError::InvalidPeriod(MAX_PERIOD_DAYS).into());
}
Ok(self.db.get_events(self.owner(), from, to).await?)
}
pub async fn create_event(&self, event: EventData) -> Result<Event, ControllerError> {
let event = validate_event(event)?;
// 404 rather than a foreign key error
self.db
.get_calendar(self.owner(), event.calendar_id)
.await?;
Ok(self.db.create_event(self.owner(), event).await?)
}
/// Replaces an event, possibly moving it to another calendar
pub async fn update_event(
&self,
id: EventId,
event: EventData,
) -> Result<Event, ControllerError> {
let event = validate_event(event)?;
self.db.get_event(self.owner(), id).await?;
self.db
.get_calendar(self.owner(), event.calendar_id)
.await?;
Ok(self.db.update_event(self.owner(), id, event).await?)
}
pub async fn delete_event(&self, id: EventId) -> Result<(), ControllerError> {
Ok(self.db.delete_event(self.owner(), id).await?)
}
}
fn is_hex_color(color: &str) -> bool {
color.len() == 7 && color.starts_with('#') && color[1..].chars().all(|c| c.is_ascii_hexdigit())
}
fn validate_calendar(calendar: CalendarData) -> Result<CalendarData, ControllerError> {
let name = calendar.name.trim().to_owned();
if name.is_empty() {
return Err(CalendarsControllerError::EmptyName.into());
}
let color = calendar.color.trim().to_lowercase();
if !is_hex_color(&color) {
return Err(CalendarsControllerError::InvalidColor.into());
}
Ok(CalendarData { name, color })
}
fn validate_event(event: EventData) -> Result<EventData, ControllerError> {
let title = event.title.trim().to_owned();
if title.is_empty() {
return Err(CalendarsControllerError::EmptyTitle.into());
}
match event.ends_at {
Some(ends_at) if ends_at <= event.starts_at => {
return Err(CalendarsControllerError::EndsBeforeStart.into());
}
None if event.all_day => return Err(CalendarsControllerError::AllDayWithoutEnd.into()),
_ => {}
}
Ok(EventData {
title,
location: non_blank(event.location),
description: non_blank(event.description),
..event
})
}
#[derive(Error, Debug)]
pub enum CalendarsControllerError {
#[error("The period must end after it starts, and last at most {0} days")]
InvalidPeriod(i64),
#[error("The name of the calendar is empty")]
EmptyName,
#[error("The color must be a hex color, e.g. #2563eb")]
InvalidColor,
#[error("The title of the event is empty")]
EmptyTitle,
#[error("An event must end after it starts")]
EndsBeforeStart,
#[error("An all-day event needs an end")]
AllDayWithoutEnd,
}
#[cfg(test)]
mod tests {
use chrono::TimeZone;
use super::*;
fn event(start_hour: u32, end_hour: Option<u32>, all_day: bool) -> EventData {
let at = |hour| Utc.with_ymd_and_hms(2026, 10, 22, hour, 0, 0).unwrap();
EventData {
calendar_id: 1,
title: " Dentist ".to_owned(),
location: Some(" ".to_owned()),
description: None,
starts_at: at(start_hour),
ends_at: end_hour.map(at),
all_day,
}
}
#[test]
fn trims_the_event() {
let event = validate_event(event(10, Some(11), false)).unwrap();
assert_eq!(event.title, "Dentist");
assert!(event.location.is_none());
}
#[test]
fn a_single_moment_has_no_end() {
assert!(validate_event(event(10, None, false)).is_ok());
assert!(validate_event(event(10, None, true)).is_err());
}
#[test]
fn an_event_ends_after_it_starts() {
assert!(validate_event(event(10, Some(10), false)).is_err());
assert!(validate_event(event(10, Some(9), false)).is_err());
}
#[test]
fn colors_are_hex() {
let calendar = |color: &str| CalendarData {
name: "Perso".to_owned(),
color: color.to_owned(),
};
assert_eq!(
validate_calendar(calendar("#AbCdEf")).unwrap().color,
"#abcdef"
);
assert!(validate_calendar(calendar("red")).is_err());
assert!(validate_calendar(calendar("#abcdeg")).is_err());
}
}

View file

@ -51,16 +51,16 @@ impl super::AppController {
course_id: CourseId,
) -> Result<Vec<CourseFile>, ControllerError> {
// 404 rather than an empty list for a course that does not exist
self.db.get_course(course_id).await?;
self.db.get_course(self.owner(), course_id).await?;
self.db
.get_course_files(course_id)
.get_course_files(self.owner(), course_id)
.await
.map_err(Into::into)
}
/// `NotFound` if the file does not exist or is not a note
async fn get_note(&self, id: CourseFileId) -> Result<CourseFile, ControllerError> {
let file = self.db.get_course_file(id).await?;
let file = self.db.get_course_file(self.owner(), id).await?;
if file.kind != FileKind::Note {
return Err(RepositoryError::NotFound(format!("lecture note {id}")).into());
}
@ -72,7 +72,7 @@ impl super::AppController {
id: CourseFileId,
) -> Result<LectureNoteContent, ControllerError> {
let note = self.get_note(id).await?;
let course = self.db.get_course(note.course_id).await?;
let course = self.db.get_course(self.owner(), note.course_id).await?;
let content = match self
.storage
.read_file(&markdown_path(&course, &note.path))
@ -92,7 +92,7 @@ impl super::AppController {
/// `NotFound` if the note does not exist or its last rendering failed
pub async fn get_lecture_note_pdf(&self, id: CourseFileId) -> Result<Vec<u8>, ControllerError> {
let note = self.get_note(id).await?;
let course = self.db.get_course(note.course_id).await?;
let course = self.db.get_course(self.owner(), note.course_id).await?;
self.storage
.read_file(&pdf_path(&course, &note.path))
.await
@ -106,13 +106,13 @@ impl super::AppController {
content: String,
) -> Result<SavedLectureNote, ControllerError> {
let title = validate_title(title)?;
let course = self.db.get_course(course_id).await?;
let course = self.db.get_course(self.owner(), course_id).await?;
let path = note_path(&title);
self.check_path_free(course_id, &path, None).await?;
let notes_tag = self.db.get_tag_id(NOTES_TAG).await?;
let note = self
.db
.create_lecture_note(course_id, title.clone(), path, &[notes_tag])
.create_lecture_note(self.owner(), course_id, title.clone(), path, &[notes_tag])
.await?;
self.save_lecture_note(&course, note, title, content).await
}
@ -125,7 +125,7 @@ impl super::AppController {
) -> Result<SavedLectureNote, ControllerError> {
let title = validate_title(title)?;
let note = self.get_note(id).await?;
let course = self.db.get_course(note.course_id).await?;
let course = self.db.get_course(self.owner(), note.course_id).await?;
// Renamed: its files follow
let path = note_path(&title);
@ -150,8 +150,8 @@ impl super::AppController {
pub async fn delete_lecture_note(&self, id: CourseFileId) -> Result<(), ControllerError> {
let note = self.get_note(id).await?;
let course = self.db.get_course(note.course_id).await?;
self.db.delete_course_file(id).await?;
let course = self.db.get_course(self.owner(), note.course_id).await?;
self.db.delete_course_file(self.owner(), id).await?;
self.storage
.delete_file(&markdown_path(&course, &note.path))
.await?;
@ -168,7 +168,7 @@ impl super::AppController {
path: &str,
except: Option<CourseFileId>,
) -> Result<(), ControllerError> {
let files = self.db.get_course_files(course_id).await?;
let files = self.db.get_course_files(self.owner(), course_id).await?;
if files
.iter()
.any(|file| file.path == path && Some(file.id) != except)
@ -213,7 +213,7 @@ impl super::AppController {
let note = self
.db
.update_lecture_note(note.id, title, note.path, pdf_error.is_none())
.update_lecture_note(self.owner(), note.id, title, note.path, pdf_error.is_none())
.await?;
Ok(SavedLectureNote { note, pdf_error })
}

View file

@ -1,6 +1,6 @@
//! Courses and associations, and their weekly time slots.
//!
//! Each one has a folder in the storage named after it, where its files live:
//! Each one has a folder in the storage of its owner, named after it, where its files live:
//! `Cours/CS-477 Advanced operating systems`, `Associations/AGEPoly`. The folder is
//! moved when the course is renamed.
@ -66,11 +66,14 @@ pub(crate) fn file_name(name: &str) -> String {
impl super::AppController {
pub async fn get_courses(&self) -> Result<Vec<Course>, ControllerError> {
self.db.get_courses().await.map_err(Into::into)
self.db.get_courses(self.owner()).await.map_err(Into::into)
}
pub async fn get_course(&self, id: CourseId) -> Result<Course, ControllerError> {
self.db.get_course(id).await.map_err(Into::into)
self.db
.get_course(self.owner(), id)
.await
.map_err(Into::into)
}
pub async fn create_course(&self, course: CourseData) -> Result<Course, ControllerError> {
@ -78,7 +81,7 @@ impl super::AppController {
let folder = course_folder(&course);
self.check_folder_free(&folder, None).await?;
self.db
.create_course(course, &folder)
.create_course(self.owner(), course, &folder)
.await
.map_err(Into::into)
}
@ -89,7 +92,7 @@ impl super::AppController {
id: CourseId,
course: CourseData,
) -> Result<Course, ControllerError> {
let existing = self.db.get_course(id).await?;
let existing = self.db.get_course(self.owner(), id).await?;
let course = validate_course(CourseData {
kind: existing.kind,
..course
@ -98,7 +101,7 @@ impl super::AppController {
if folder == existing.folder {
return self
.db
.update_course(id, course, &folder)
.update_course(self.owner(), id, course, &folder)
.await
.map_err(Into::into);
}
@ -110,7 +113,11 @@ impl super::AppController {
Err(RepositoryError::NotFound(_)) => false,
Err(err) => return Err(err.into()),
};
match self.db.update_course(id, course, &folder).await {
match self
.db
.update_course(self.owner(), id, course, &folder)
.await
{
Ok(course) => Ok(course),
Err(err) => {
if moved && let Err(err) = self.storage.rename(&folder, &existing.folder).await {
@ -123,8 +130,8 @@ impl super::AppController {
/// Deletes the course with everything attached to it, its files included
pub async fn delete_course(&self, id: CourseId) -> Result<(), ControllerError> {
let course = self.db.get_course(id).await?;
self.db.delete_course(id).await?;
let course = self.db.get_course(self.owner(), id).await?;
self.db.delete_course(self.owner(), id).await?;
self.storage.delete_dir(&course.folder).await?;
Ok(())
}
@ -135,7 +142,7 @@ impl super::AppController {
folder: &str,
except: Option<CourseId>,
) -> Result<(), ControllerError> {
let courses = self.db.get_courses().await?;
let courses = self.db.get_courses(self.owner()).await?;
if courses
.iter()
.any(|course| course.folder == folder && Some(course.id) != except)
@ -160,7 +167,10 @@ impl super::AppController {
return Err(CoursesControllerError::InvalidSlotTime.into());
}
self.check_tags(&[slot.tag_id], TagScope::Slot).await?;
self.db.add_slot(course_id, slot).await.map_err(Into::into)
self.db
.add_slot(self.owner(), course_id, slot)
.await
.map_err(Into::into)
}
pub async fn delete_slot(
@ -169,7 +179,7 @@ impl super::AppController {
slot_id: TimeSlotId,
) -> Result<Course, ControllerError> {
self.db
.delete_slot(course_id, slot_id)
.delete_slot(self.owner(), course_id, slot_id)
.await
.map_err(Into::into)
}

View file

@ -25,12 +25,12 @@ const MAX_SESSION_SECONDS: u32 = 24 * 3600;
impl super::AppController {
/// Starts a session on a task or a subtask
pub async fn start_focus(&self, task_id: TaskId) -> Result<FocusStart, ControllerError> {
let task = self.db.get_task(task_id).await?;
let task = self.db.get_task(self.owner(), task_id).await?;
let parent = match task.parent_id {
Some(parent_id) => Some(self.db.get_task(parent_id).await?),
Some(parent_id) => Some(self.db.get_task(self.owner(), parent_id).await?),
None => None,
};
let course = self.db.get_course(task.course_id).await?;
let course = self.db.get_course(self.owner(), task.course_id).await?;
let tag_ids = match &parent {
Some(parent) if task.tag_ids.is_empty() => parent.tag_ids.clone(),
_ => task.tag_ids.clone(),
@ -84,7 +84,10 @@ impl super::AppController {
if seconds > MAX_SESSION_SECONDS {
return Err(FocusControllerError::TooLong.into());
}
let time_spent = self.db.add_time_spent(task_id, seconds as i32).await?;
let time_spent = self
.db
.add_time_spent(self.owner(), task_id, seconds as i32)
.await?;
let timetagger_error = match (&self.time_tracker, record) {
(Some(tracker), Some(record)) => match tracker.stop(&record, Utc::now()).await {

View file

@ -16,7 +16,7 @@ impl super::AppController {
course_id: CourseId,
) -> Result<CourseGrades, ControllerError> {
// 404 rather than an empty list for a course that does not exist
self.db.get_course(course_id).await?;
self.db.get_course(self.owner(), course_id).await?;
self.course_grades(course_id).await
}
@ -27,8 +27,8 @@ impl super::AppController {
grade: GradeData,
) -> Result<CourseGrades, ControllerError> {
let grade = validate_grade(grade)?;
self.db.get_course(course_id).await?;
self.db.create_grade(course_id, grade).await?;
self.db.get_course(self.owner(), course_id).await?;
self.db.create_grade(self.owner(), course_id, grade).await?;
self.course_grades(course_id).await
}
@ -39,20 +39,20 @@ impl super::AppController {
grade: GradeData,
) -> Result<CourseGrades, ControllerError> {
let grade = validate_grade(grade)?;
let course_id = self.db.get_grade_course(id).await?;
self.db.update_grade(id, grade).await?;
let course_id = self.db.get_grade_course(self.owner(), id).await?;
self.db.update_grade(self.owner(), id, grade).await?;
self.course_grades(course_id).await
}
/// Returns the grades left in the course of the grade
pub async fn delete_grade(&self, id: GradeId) -> Result<CourseGrades, ControllerError> {
let course_id = self.db.get_grade_course(id).await?;
self.db.delete_grade(id).await?;
let course_id = self.db.get_grade_course(self.owner(), id).await?;
self.db.delete_grade(self.owner(), id).await?;
self.course_grades(course_id).await
}
async fn course_grades(&self, course_id: CourseId) -> Result<CourseGrades, ControllerError> {
let grades = self.db.get_grades(course_id).await?;
let grades = self.db.get_grades(self.owner(), course_id).await?;
Ok(summarize(grades))
}
}

View file

@ -5,24 +5,29 @@
//! One file per domain area, each one adding methods to `AppController`
//! through `impl super::AppController`.
use std::sync::Arc;
use std::{collections::HashMap, sync::Arc};
use thiserror::Error;
use crate::core::{
controller::{
calendars::CalendarsControllerError,
course_files::{LectureNotesControllerError, NotesSettings},
courses::CoursesControllerError,
focus::FocusControllerError,
grades::GradesControllerError,
tasks::TasksControllerError,
},
models::user::User,
repositories::{
DatabaseRepository, RepositoryError, pdf_renderer::PdfRenderer,
storage_repository::StorageRepository, time_tracker::TimeTracker,
DatabaseRepository, RepositoryError,
pdf_renderer::PdfRenderer,
storage_repository::{StorageRepository, UserStorage},
time_tracker::TimeTracker,
},
};
pub mod calendars;
pub mod course_files;
pub mod courses;
pub mod focus;
@ -30,33 +35,91 @@ pub mod grades;
pub mod tags;
pub mod tasks;
/// Entry point of the business logic. Cheap to clone: handlers get one per request.
/// What everyone shares, set up once at startup. Gives each request a controller acting
/// for the person making it.
#[derive(Clone)]
pub struct AppController {
pub struct AppServices {
db: Arc<Box<dyn DatabaseRepository + Send + Sync>>,
/// Root of the storage, a folder per person in it
storage: Arc<dyn StorageRepository>,
renderer: Arc<dyn PdfRenderer>,
notes: Arc<NotesSettings>,
/// `None` when TimeTagger is not configured
time_tracker: Option<Arc<dyn TimeTracker>>,
/// Absolute path of the logo of the notes
logo: Option<String>,
/// By login. Someone without settings can still use the app.
users: Arc<HashMap<String, UserSettings>>,
}
impl AppController {
/// What can be set for a person in the configuration
#[derive(Default)]
pub struct UserSettings {
/// Shown in the header of the notes, the name given by Authelia by default
pub student_name: Option<String>,
pub student_id: Option<String>,
/// Their TimeTagger account, `None` when they have none
pub time_tracker: Option<Arc<dyn TimeTracker>>,
}
impl AppServices {
pub fn new(
db: Arc<Box<dyn DatabaseRepository + Send + Sync>>,
storage: Arc<dyn StorageRepository>,
renderer: Arc<dyn PdfRenderer>,
notes: NotesSettings,
time_tracker: Option<Arc<dyn TimeTracker>>,
logo: Option<String>,
users: HashMap<String, UserSettings>,
) -> Self {
Self {
db,
storage,
renderer,
notes: Arc::new(notes),
time_tracker,
logo,
users: Arc::new(users),
}
}
/// Controller acting for `user`: it only sees their data and their folder of the
/// storage. The login must be a valid folder name (`User::is_valid_username`).
pub fn controller(&self, user: User) -> AppController {
let settings = self.users.get(&user.username);
let notes = NotesSettings {
student_name: settings
.and_then(|settings| settings.student_name.clone())
.or_else(|| user.display_name.clone()),
student_id: settings.and_then(|settings| settings.student_id.clone()),
logo: self.logo.clone(),
};
AppController {
db: self.db.clone(),
storage: Arc::new(UserStorage::new(self.storage.clone(), &user.username)),
renderer: self.renderer.clone(),
notes: Arc::new(notes),
time_tracker: settings.and_then(|settings| settings.time_tracker.clone()),
user: Arc::new(user),
}
}
}
/// Entry point of the business logic, for one person. Handlers get one per request.
#[derive(Clone)]
pub struct AppController {
db: Arc<Box<dyn DatabaseRepository + Send + Sync>>,
/// Their own folder of the storage
storage: Arc<dyn StorageRepository>,
renderer: Arc<dyn PdfRenderer>,
notes: Arc<NotesSettings>,
/// `None` when they have no TimeTagger account
time_tracker: Option<Arc<dyn TimeTracker>>,
user: Arc<User>,
}
impl AppController {
pub fn user(&self) -> &User {
&self.user
}
/// Login of the owner of everything this controller touches
fn owner(&self) -> &str {
&self.user.username
}
}
/// Every error the api may have to translate into a status code.
@ -79,6 +142,8 @@ pub enum ControllerError {
LectureNote(#[from] LectureNotesControllerError),
#[error("Focus specific error: {0}")]
Focus(#[from] FocusControllerError),
#[error("Calendar specific error: {0}")]
Calendar(#[from] CalendarsControllerError),
}
/// Trims a text, `None` when it is blank

View file

@ -30,18 +30,18 @@ impl super::AppController {
if from >= to || to - from > Duration::days(MAX_CALENDAR_DAYS) {
return Err(TasksControllerError::InvalidPeriod(MAX_CALENDAR_DAYS).into());
}
let tasks = self.db.get_dated_tasks(from, to).await?;
let courses = self.db.get_courses().await?;
let tasks = self.db.get_dated_tasks(self.owner(), from, to).await?;
let courses = self.db.get_courses(self.owner()).await?;
Ok(calendar(tasks, &courses, from, to))
}
/// Tasks not done of every course, with their subtasks: the ones with a deadline
/// first, the closest first
pub async fn get_todo_tasks(&self) -> Result<Vec<TodoTask>, ControllerError> {
let tasks = organize(self.db.get_todo_tasks().await?).tasks;
let tasks = organize(self.db.get_todo_tasks(self.owner()).await?).tasks;
let courses: HashMap<_, Course> = self
.db
.get_courses()
.get_courses(self.owner())
.await?
.into_iter()
.map(|course| (course.id, course))
@ -63,7 +63,7 @@ impl super::AppController {
course_id: CourseId,
) -> Result<CourseTasks, ControllerError> {
// 404 rather than an empty list for a course that does not exist
self.db.get_course(course_id).await?;
self.db.get_course(self.owner(), course_id).await?;
self.course_tasks(course_id).await
}
@ -75,9 +75,9 @@ impl super::AppController {
parent_id: Option<TaskId>,
task: TaskData,
) -> Result<CourseTasks, ControllerError> {
self.db.get_course(course_id).await?;
self.db.get_course(self.owner(), course_id).await?;
if let Some(parent_id) = parent_id {
let parent = self.db.get_task(parent_id).await?;
let parent = self.db.get_task(self.owner(), parent_id).await?;
if parent.course_id != course_id {
return Err(TasksControllerError::ParentInOtherCourse.into());
}
@ -86,7 +86,9 @@ impl super::AppController {
}
}
let task = self.validate_task(task, parent_id.is_some()).await?;
self.db.create_task(course_id, parent_id, task).await?;
self.db
.create_task(self.owner(), course_id, parent_id, task)
.await?;
self.course_tasks(course_id).await
}
@ -96,23 +98,23 @@ impl super::AppController {
id: TaskId,
task: TaskData,
) -> Result<CourseTasks, ControllerError> {
let existing = self.db.get_task(id).await?;
let existing = self.db.get_task(self.owner(), id).await?;
let task = self
.validate_task(task, existing.parent_id.is_some())
.await?;
self.db.update_task(id, task).await?;
self.db.update_task(self.owner(), id, task).await?;
self.course_tasks(existing.course_id).await
}
/// Deletes a task and its subtasks. Returns the tasks left in its course.
pub async fn delete_task(&self, id: TaskId) -> Result<CourseTasks, ControllerError> {
let existing = self.db.get_task(id).await?;
self.db.delete_task(id).await?;
let existing = self.db.get_task(self.owner(), id).await?;
self.db.delete_task(self.owner(), id).await?;
self.course_tasks(existing.course_id).await
}
async fn course_tasks(&self, course_id: CourseId) -> Result<CourseTasks, ControllerError> {
let tasks = self.db.get_tasks(course_id).await?;
let tasks = self.db.get_tasks(self.owner(), course_id).await?;
Ok(organize(tasks))
}

View file

@ -0,0 +1,50 @@
use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
pub type CalendarId = i32;
pub type EventId = i32;
/// Personal calendar, apart from the courses and associations
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Calendar {
pub id: CalendarId,
pub name: String,
/// Hex color of its events, e.g. `#2563eb`
pub color: String,
}
/// Content of a calendar, used to create or replace one
#[derive(Debug, Clone)]
pub struct CalendarData {
pub name: String,
pub color: String,
}
/// Something happening in a personal calendar. Not a task: there is nothing to check.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Event {
pub id: EventId,
pub calendar_id: CalendarId,
pub title: String,
pub location: Option<String>,
pub description: Option<String>,
pub starts_at: DateTime<Utc>,
/// Exclusive. `None` for a single moment: a deadline, a reminder...
pub ends_at: Option<DateTime<Utc>>,
/// From the midnight of its first day to the midnight after its last one, in the time
/// zone of the user. Always has an end.
pub all_day: bool,
}
/// Content of an event, used to create or replace one
#[derive(Debug, Clone)]
pub struct EventData {
pub calendar_id: CalendarId,
pub title: String,
pub location: Option<String>,
pub description: Option<String>,
pub starts_at: DateTime<Utc>,
pub ends_at: Option<DateTime<Utc>>,
pub all_day: bool,
}

View file

@ -1,3 +1,4 @@
pub mod calendar;
pub mod course;
pub mod course_file;
pub mod focus;
@ -6,3 +7,4 @@ pub mod localized_string;
pub mod tag;
pub mod task;
pub mod time_slot;
pub mod user;

39
src/core/models/user.rs Normal file
View file

@ -0,0 +1,39 @@
use schemars::JsonSchema;
use serde::Serialize;
/// The person using the app, as authenticated by Authelia in front of it. Owns their
/// courses, associations and calendars.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct User {
/// Login, e.g. `jdoe`. Also the folder of their files in the storage.
pub username: String,
/// e.g. `Jane Doe`, when Authelia gives it
pub display_name: Option<String>,
}
impl User {
/// A login usable as a folder name: letters, digits and `._@-`, not starting with a
/// dot (`..` would leave the storage)
pub fn is_valid_username(username: &str) -> bool {
!username.is_empty()
&& !username.starts_with('.')
&& username
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '@' | '-'))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn usernames_are_folder_names() {
assert!(User::is_valid_username("jdoe"));
assert!(User::is_valid_username("jane.doe@epfl.ch"));
assert!(!User::is_valid_username(""));
assert!(!User::is_valid_username(".."));
assert!(!User::is_valid_username("a/b"));
assert!(!User::is_valid_username("a b"));
}
}

View file

@ -0,0 +1,51 @@
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use crate::core::{
models::calendar::{Calendar, CalendarData, CalendarId, Event, EventData, EventId},
repositories::RepositoryError,
};
/// Everything is limited to the calendars of `owner`: the others are `NotFound`
#[async_trait]
pub trait CalendarsRepository {
/// Every personal calendar, in the order they were created
async fn get_calendars(&self, owner: &str) -> Result<Vec<Calendar>, RepositoryError>;
/// `NotFound` if the calendar does not exist
async fn get_calendar(&self, owner: &str, id: CalendarId) -> Result<Calendar, RepositoryError>;
async fn create_calendar(
&self,
owner: &str,
calendar: CalendarData,
) -> Result<(), RepositoryError>;
/// `NotFound` if the calendar does not exist
async fn update_calendar(
&self,
owner: &str,
id: CalendarId,
calendar: CalendarData,
) -> Result<(), RepositoryError>;
/// Deletes the calendar and its events. `NotFound` if the calendar does not exist.
async fn delete_calendar(&self, owner: &str, id: CalendarId) -> Result<(), RepositoryError>;
/// Events of every calendar happening in `[from, to[`, the earliest first: the ones
/// overlapping the period, and the single moments in it
async fn get_events(
&self,
owner: &str,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> Result<Vec<Event>, RepositoryError>;
/// `NotFound` if the event does not exist
async fn get_event(&self, owner: &str, id: EventId) -> Result<Event, RepositoryError>;
async fn create_event(&self, owner: &str, event: EventData) -> Result<Event, RepositoryError>;
/// `NotFound` if the event does not exist
async fn update_event(
&self,
owner: &str,
id: EventId,
event: EventData,
) -> Result<Event, RepositoryError>;
/// `NotFound` if the event does not exist
async fn delete_event(&self, owner: &str, id: EventId) -> Result<(), RepositoryError>;
}

View file

@ -9,17 +9,24 @@ use crate::core::{
repositories::RepositoryError,
};
/// Everything is limited to the courses of `owner`: the others are `NotFound`
#[async_trait]
pub trait CourseFilesRepository {
/// Files of a course, the oldest first
async fn get_course_files(
&self,
owner: &str,
course_id: CourseId,
) -> Result<Vec<CourseFile>, RepositoryError>;
/// `NotFound` if the file does not exist
async fn get_course_file(&self, id: CourseFileId) -> Result<CourseFile, RepositoryError>;
async fn get_course_file(
&self,
owner: &str,
id: CourseFileId,
) -> Result<CourseFile, RepositoryError>;
async fn create_lecture_note(
&self,
owner: &str,
course_id: CourseId,
name: String,
path: String,
@ -29,11 +36,16 @@ pub trait CourseFilesRepository {
/// does not exist.
async fn update_lecture_note(
&self,
owner: &str,
id: CourseFileId,
name: String,
path: String,
has_pdf: bool,
) -> Result<CourseFile, RepositoryError>;
/// `NotFound` if the file does not exist
async fn delete_course_file(&self, id: CourseFileId) -> Result<(), RepositoryError>;
async fn delete_course_file(
&self,
owner: &str,
id: CourseFileId,
) -> Result<(), RepositoryError>;
}

View file

@ -8,37 +8,43 @@ use crate::core::{
repositories::RepositoryError,
};
/// Everything is limited to the courses and associations of `owner`: the others are
/// `NotFound`
#[async_trait]
pub trait CoursesRepository {
/// Every course and association with its slots, sorted by name
async fn get_courses(&self) -> Result<Vec<Course>, RepositoryError>;
async fn get_courses(&self, owner: &str) -> Result<Vec<Course>, RepositoryError>;
/// `NotFound` if the course does not exist
async fn get_course(&self, id: CourseId) -> Result<Course, RepositoryError>;
async fn get_course(&self, owner: &str, id: CourseId) -> Result<Course, RepositoryError>;
/// Creates a course without any slot, its files in `folder`
async fn create_course(
&self,
owner: &str,
course: CourseData,
folder: &str,
) -> Result<Course, RepositoryError>;
/// Replaces the course, keeping its slots and its kind. `NotFound` if the course does not exist.
async fn update_course(
&self,
owner: &str,
id: CourseId,
course: CourseData,
folder: &str,
) -> Result<Course, RepositoryError>;
/// Deletes the course and everything attached to it. `NotFound` if it does not exist.
async fn delete_course(&self, id: CourseId) -> Result<(), RepositoryError>;
async fn delete_course(&self, owner: &str, id: CourseId) -> Result<(), RepositoryError>;
/// Returns the course with the new slot. `NotFound` if the course does not exist.
async fn add_slot(
&self,
owner: &str,
course_id: CourseId,
slot: TimeSlotData,
) -> Result<Course, RepositoryError>;
/// Returns the course without the slot. `NotFound` if the slot is not in the course.
async fn delete_slot(
&self,
owner: &str,
course_id: CourseId,
slot_id: TimeSlotId,
) -> Result<Course, RepositoryError>;

View file

@ -8,19 +8,31 @@ use crate::core::{
repositories::RepositoryError,
};
/// Everything is limited to the courses of `owner`: the others are `NotFound`
#[async_trait]
pub trait GradesRepository {
/// Grades of a course, in the order they were added
async fn get_grades(&self, course_id: CourseId) -> Result<Vec<Grade>, RepositoryError>;
async fn get_grades(
&self,
owner: &str,
course_id: CourseId,
) -> Result<Vec<Grade>, RepositoryError>;
/// Course of a grade. `NotFound` if the grade does not exist.
async fn get_grade_course(&self, id: GradeId) -> Result<CourseId, RepositoryError>;
async fn get_grade_course(&self, owner: &str, id: GradeId)
-> Result<CourseId, RepositoryError>;
async fn create_grade(
&self,
owner: &str,
course_id: CourseId,
grade: GradeData,
) -> Result<(), RepositoryError>;
/// `NotFound` if the grade does not exist
async fn update_grade(&self, id: GradeId, grade: GradeData) -> Result<(), RepositoryError>;
async fn update_grade(
&self,
owner: &str,
id: GradeId,
grade: GradeData,
) -> Result<(), RepositoryError>;
/// `NotFound` if the grade does not exist
async fn delete_grade(&self, id: GradeId) -> Result<(), RepositoryError>;
async fn delete_grade(&self, owner: &str, id: GradeId) -> Result<(), RepositoryError>;
}

View file

@ -8,11 +8,12 @@ use async_trait::async_trait;
use thiserror::Error;
use crate::core::repositories::{
course_files_repository::CourseFilesRepository, courses_repository::CoursesRepository,
grades_repository::GradesRepository, tags_repository::TagsRepository,
tasks_repository::TasksRepository,
calendars_repository::CalendarsRepository, course_files_repository::CourseFilesRepository,
courses_repository::CoursesRepository, grades_repository::GradesRepository,
tags_repository::TagsRepository, tasks_repository::TasksRepository,
};
pub mod calendars_repository;
pub mod course_files_repository;
pub mod courses_repository;
pub mod grades_repository;
@ -30,6 +31,7 @@ pub trait DatabaseRepository:
+ GradesRepository
+ TasksRepository
+ CourseFilesRepository
+ CalendarsRepository
+ Send
+ Sync
{

View file

@ -1,3 +1,5 @@
use std::sync::Arc;
use async_trait::async_trait;
use crate::core::repositories::RepositoryError;
@ -19,3 +21,48 @@ pub trait StorageRepository: Send + Sync {
/// `from` does not exist, an error if `to` already exists.
async fn rename(&self, from: &str, to: &str) -> Result<(), RepositoryError>;
}
/// The storage of a single person: their own folder in the storage, named after their
/// login (`jdoe/Cours/...`)
pub struct UserStorage {
inner: Arc<dyn StorageRepository>,
/// `jdoe/`
prefix: String,
}
impl UserStorage {
/// `username` must be a valid folder name (`User::is_valid_username`)
pub fn new(inner: Arc<dyn StorageRepository>, username: &str) -> Self {
Self {
inner,
prefix: format!("{username}/"),
}
}
fn path(&self, path: &str) -> String {
format!("{}{path}", self.prefix)
}
}
#[async_trait]
impl StorageRepository for UserStorage {
async fn read_file(&self, path: &str) -> Result<Vec<u8>, RepositoryError> {
self.inner.read_file(&self.path(path)).await
}
async fn write_file(&self, path: &str, content: &[u8]) -> Result<(), RepositoryError> {
self.inner.write_file(&self.path(path), content).await
}
async fn delete_file(&self, path: &str) -> Result<(), RepositoryError> {
self.inner.delete_file(&self.path(path)).await
}
async fn delete_dir(&self, path: &str) -> Result<(), RepositoryError> {
self.inner.delete_dir(&self.path(path)).await
}
async fn rename(&self, from: &str, to: &str) -> Result<(), RepositoryError> {
self.inner.rename(&self.path(from), &self.path(to)).await
}
}

View file

@ -9,33 +9,50 @@ use crate::core::{
repositories::RepositoryError,
};
/// Everything is limited to the courses of `owner`: the others are `NotFound`
#[async_trait]
pub trait TasksRepository {
/// Every task and subtask of a course, flat: `subtasks` is always empty
async fn get_tasks(&self, course_id: CourseId) -> Result<Vec<Task>, RepositoryError>;
async fn get_tasks(
&self,
owner: &str,
course_id: CourseId,
) -> Result<Vec<Task>, RepositoryError>;
/// Tasks and subtasks of every course with a deadline in `[from, to[`, and the parents
/// of those subtasks. Flat: `subtasks` is always empty.
async fn get_dated_tasks(
&self,
owner: &str,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> Result<Vec<Task>, RepositoryError>;
/// Tasks not done of every course, with all their subtasks. Flat: `subtasks` is always
/// empty.
async fn get_todo_tasks(&self) -> Result<Vec<Task>, RepositoryError>;
async fn get_todo_tasks(&self, owner: &str) -> Result<Vec<Task>, RepositoryError>;
/// A single task, `subtasks` empty. `NotFound` if the task does not exist.
async fn get_task(&self, id: TaskId) -> Result<Task, RepositoryError>;
async fn get_task(&self, owner: &str, id: TaskId) -> Result<Task, RepositoryError>;
async fn create_task(
&self,
owner: &str,
course_id: CourseId,
parent_id: Option<TaskId>,
task: TaskData,
) -> Result<(), RepositoryError>;
/// Replaces the task and its tags. `NotFound` if the task does not exist.
async fn update_task(&self, id: TaskId, task: TaskData) -> Result<(), RepositoryError>;
async fn update_task(
&self,
owner: &str,
id: TaskId,
task: TaskData,
) -> Result<(), RepositoryError>;
/// Adds `seconds` to the time spent on the task, returns the new total. `NotFound` if
/// the task does not exist.
async fn add_time_spent(&self, id: TaskId, seconds: i32) -> Result<i32, RepositoryError>;
async fn add_time_spent(
&self,
owner: &str,
id: TaskId,
seconds: i32,
) -> Result<i32, RepositoryError>;
/// Deletes the task and its subtasks. `NotFound` if the task does not exist.
async fn delete_task(&self, id: TaskId) -> Result<(), RepositoryError>;
async fn delete_task(&self, owner: &str, id: TaskId) -> Result<(), RepositoryError>;
}

View file

@ -1,12 +1,12 @@
use std::{path::Path, sync::Arc};
use std::{collections::HashMap, path::Path, sync::Arc};
use tower_http::services::{ServeDir, ServeFile};
use tracing::info;
use tracing::{info, warn};
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
use crate::{
core::{
controller::{AppController, course_files::NotesSettings},
controller::{AppServices, UserSettings},
repositories::time_tracker::TimeTracker,
},
services::{
@ -40,40 +40,54 @@ async fn main() {
let template_dir = Path::new(&config.notes.template_dir)
.canonicalize()
.expect("Unable to find the template directory of the notes");
let notes = NotesSettings {
student_name: config.notes.student_name.clone(),
student_id: config.notes.student_id.clone(),
logo: config
.notes
.logo
.as_ref()
.map(|logo| template_dir.join(logo).display().to_string()),
};
let logo = config
.notes
.logo
.as_ref()
.map(|logo| template_dir.join(logo).display().to_string());
let time_tracker = config.timetagger.as_ref().map(|timetagger| {
let url = timetagger
.url
.as_deref()
.unwrap_or("https://timetagger.app/api/v2");
info!("Focus sessions are counted in TimeTagger ({url})");
Arc::new(Timetagger::new(url, timetagger.token.clone())) as Arc<dyn TimeTracker>
});
let timetagger_url = config
.timetagger
.as_ref()
.and_then(|timetagger| timetagger.url.as_deref())
.unwrap_or("https://timetagger.app/api/v2");
let users: HashMap<String, UserSettings> = config
.users
.iter()
.map(|(username, user)| {
let time_tracker = user.timetagger_token.as_ref().map(|token| {
info!("Focus sessions of {username} are counted in TimeTagger ({timetagger_url})");
Arc::new(Timetagger::new(timetagger_url, token.clone())) as Arc<dyn TimeTracker>
});
let settings = UserSettings {
student_name: user.student_name.clone(),
student_id: user.student_id.clone(),
time_tracker,
};
(username.clone(), settings)
})
.collect();
let controller = AppController::new(
let services = AppServices::new(
Arc::new(Box::new(db)),
Arc::new(LocalStorage::new(&config.storage_dir)),
Arc::new(PandocRenderer::new(template_dir)),
notes,
time_tracker,
logo,
users,
);
if let Some(user) = &config.auth.default_user {
warn!("Requests without a Remote-User header act as {user}: for development only");
}
// Anything that is not an api route is served from the built frontend,
// falling back on index.html so the vue router can handle the path.
// (`fallback` and not `not_found_service`, which would force a 404 status)
let app =
api::get_router(controller).fallback_service(ServeDir::new(&config.frontend_dir).fallback(
ServeFile::new(format!("{}/index.html", config.frontend_dir)),
));
let app = api::get_router(services, config.auth.clone()).fallback_service(
ServeDir::new(&config.frontend_dir).fallback(ServeFile::new(format!(
"{}/index.html",
config.frontend_dir
))),
);
let bind_address = config.get_bind_address();
let listener = tokio::net::TcpListener::bind(&bind_address).await.unwrap();

View file

@ -0,0 +1,203 @@
//! Personal calendars and their events.
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use sqlx::{query, query_as};
use crate::{
core::{
models::calendar::{Calendar, CalendarData, CalendarId, Event, EventData, EventId},
repositories::{RepositoryError, calendars_repository::CalendarsRepository},
},
services::database::SqlxDatabase,
};
fn calendar_not_found(id: CalendarId) -> RepositoryError {
RepositoryError::NotFound(format!("calendar {id}"))
}
fn event_not_found(id: EventId) -> RepositoryError {
RepositoryError::NotFound(format!("event {id}"))
}
#[async_trait]
impl CalendarsRepository for SqlxDatabase {
async fn get_calendars(&self, owner: &str) -> Result<Vec<Calendar>, RepositoryError> {
Ok(query_as!(
Calendar,
"SELECT id, name, color FROM calendars WHERE owner = $1 ORDER BY id",
owner,
)
.fetch_all(&self.pool)
.await?)
}
async fn get_calendar(&self, owner: &str, id: CalendarId) -> Result<Calendar, RepositoryError> {
query_as!(
Calendar,
"SELECT id, name, color FROM calendars WHERE id = $1 AND owner = $2",
id,
owner,
)
.fetch_optional(&self.pool)
.await?
.ok_or_else(|| calendar_not_found(id))
}
async fn create_calendar(
&self,
owner: &str,
calendar: CalendarData,
) -> Result<(), RepositoryError> {
query!(
"INSERT INTO calendars (owner, name, color) VALUES ($1, $2, $3)",
owner,
calendar.name,
calendar.color,
)
.execute(&self.pool)
.await?;
Ok(())
}
async fn update_calendar(
&self,
owner: &str,
id: CalendarId,
calendar: CalendarData,
) -> Result<(), RepositoryError> {
let result = query!(
"UPDATE calendars SET name = $2, color = $3 WHERE id = $1 AND owner = $4",
id,
calendar.name,
calendar.color,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(calendar_not_found(id));
}
Ok(())
}
async fn delete_calendar(&self, owner: &str, id: CalendarId) -> Result<(), RepositoryError> {
// The events are removed by the `ON DELETE CASCADE`
let result = query!(
"DELETE FROM calendars WHERE id = $1 AND owner = $2",
id,
owner
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(calendar_not_found(id));
}
Ok(())
}
async fn get_events(
&self,
owner: &str,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> Result<Vec<Event>, RepositoryError> {
Ok(query_as!(
Event,
r#"SELECT id, calendar_id, title, location, description, starts_at, ends_at, all_day
FROM events
WHERE starts_at < $2
AND (ends_at > $1 OR (ends_at IS NULL AND starts_at >= $1))
AND calendar_id IN (SELECT id FROM calendars WHERE owner = $3)
ORDER BY starts_at, id"#,
from,
to,
owner,
)
.fetch_all(&self.pool)
.await?)
}
async fn get_event(&self, owner: &str, id: EventId) -> Result<Event, RepositoryError> {
query_as!(
Event,
r#"SELECT id, calendar_id, title, location, description, starts_at, ends_at, all_day
FROM events
WHERE id = $1 AND calendar_id IN (SELECT id FROM calendars WHERE owner = $2)"#,
id,
owner,
)
.fetch_optional(&self.pool)
.await?
.ok_or_else(|| event_not_found(id))
}
async fn create_event(&self, owner: &str, event: EventData) -> Result<Event, RepositoryError> {
let calendar_id = event.calendar_id;
query_as!(
Event,
r#"INSERT INTO events
(calendar_id, title, location, description, starts_at, ends_at, all_day)
SELECT id, $2, $3, $4, $5, $6, $7 FROM calendars WHERE id = $1 AND owner = $8
RETURNING id, calendar_id, title, location, description, starts_at, ends_at,
all_day"#,
event.calendar_id,
event.title,
event.location,
event.description,
event.starts_at,
event.ends_at,
event.all_day,
owner,
)
.fetch_optional(&self.pool)
.await?
.ok_or_else(|| calendar_not_found(calendar_id))
}
async fn update_event(
&self,
owner: &str,
id: EventId,
event: EventData,
) -> Result<Event, RepositoryError> {
// Both the event and the calendar it moves to must be theirs
query_as!(
Event,
r#"UPDATE events SET calendar_id = $2, title = $3, location = $4, description = $5,
starts_at = $6, ends_at = $7, all_day = $8
WHERE id = $1
AND calendar_id IN (SELECT id FROM calendars WHERE owner = $9)
AND $2 IN (SELECT id FROM calendars WHERE owner = $9)
RETURNING id, calendar_id, title, location, description, starts_at, ends_at,
all_day"#,
id,
event.calendar_id,
event.title,
event.location,
event.description,
event.starts_at,
event.ends_at,
event.all_day,
owner,
)
.fetch_optional(&self.pool)
.await?
.ok_or_else(|| event_not_found(id))
}
async fn delete_event(&self, owner: &str, id: EventId) -> Result<(), RepositoryError> {
let result = query!(
r#"DELETE FROM events
WHERE id = $1 AND calendar_id IN (SELECT id FROM calendars WHERE owner = $2)"#,
id,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(event_not_found(id));
}
Ok(())
}
}

View file

@ -60,6 +60,7 @@ fn not_found(id: CourseFileId) -> RepositoryError {
impl CourseFilesRepository for SqlxDatabase {
async fn get_course_files(
&self,
owner: &str,
course_id: CourseId,
) -> Result<Vec<CourseFile>, RepositoryError> {
query_as!(
@ -68,11 +69,13 @@ impl CourseFilesRepository for SqlxDatabase {
COALESCE(ARRAY_AGG(ft.tag_id ORDER BY ft.tag_id)
FILTER (WHERE ft.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM course_files f
JOIN courses c ON c.id = f.course_id AND c.owner = $2
LEFT JOIN file_tags ft ON ft.file_id = f.id
WHERE f.course_id = $1
GROUP BY f.id
ORDER BY f.created_at, f.id"#,
course_id,
owner,
)
.fetch_all(&self.pool)
.await?
@ -81,17 +84,23 @@ impl CourseFilesRepository for SqlxDatabase {
.collect()
}
async fn get_course_file(&self, id: CourseFileId) -> Result<CourseFile, RepositoryError> {
async fn get_course_file(
&self,
owner: &str,
id: CourseFileId,
) -> Result<CourseFile, RepositoryError> {
query_as!(
CourseFileDB,
r#"SELECT f.id, f.course_id, f.name, f.kind, f.path, f.has_pdf, f.created_at, f.updated_at,
COALESCE(ARRAY_AGG(ft.tag_id ORDER BY ft.tag_id)
FILTER (WHERE ft.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM course_files f
JOIN courses c ON c.id = f.course_id AND c.owner = $2
LEFT JOIN file_tags ft ON ft.file_id = f.id
WHERE f.id = $1
GROUP BY f.id"#,
id,
owner,
)
.fetch_optional(&self.pool)
.await?
@ -101,6 +110,7 @@ impl CourseFilesRepository for SqlxDatabase {
async fn create_lecture_note(
&self,
owner: &str,
course_id: CourseId,
name: String,
path: String,
@ -108,14 +118,17 @@ impl CourseFilesRepository for SqlxDatabase {
) -> Result<CourseFile, RepositoryError> {
let mut tx = self.pool.begin().await?;
let id = query!(
r#"INSERT INTO course_files (course_id, name, kind, path) VALUES ($1, $2, 'note', $3)
r#"INSERT INTO course_files (course_id, name, kind, path)
SELECT id, $2, 'note', $3 FROM courses WHERE id = $1 AND owner = $4
RETURNING id"#,
course_id,
name,
path,
owner,
)
.fetch_one(&mut *tx)
.fetch_optional(&mut *tx)
.await?
.ok_or_else(|| RepositoryError::NotFound(format!("course {course_id}")))?
.id;
query!(
r#"INSERT INTO file_tags (file_id, tag_id)
@ -126,11 +139,12 @@ impl CourseFilesRepository for SqlxDatabase {
.execute(&mut *tx)
.await?;
tx.commit().await?;
self.get_course_file(id).await
self.get_course_file(owner, id).await
}
async fn update_lecture_note(
&self,
owner: &str,
id: CourseFileId,
name: String,
path: String,
@ -138,24 +152,35 @@ impl CourseFilesRepository for SqlxDatabase {
) -> Result<CourseFile, RepositoryError> {
let result = query!(
r#"UPDATE course_files SET name = $2, path = $3, has_pdf = $4, updated_at = now()
WHERE id = $1 AND kind = 'note'"#,
WHERE id = $1 AND kind = 'note'
AND course_id IN (SELECT id FROM courses WHERE owner = $5)"#,
id,
name,
path,
has_pdf,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(not_found(id));
}
self.get_course_file(id).await
self.get_course_file(owner, id).await
}
async fn delete_course_file(&self, id: CourseFileId) -> Result<(), RepositoryError> {
let result = query!("DELETE FROM course_files WHERE id = $1", id)
.execute(&self.pool)
.await?;
async fn delete_course_file(
&self,
owner: &str,
id: CourseFileId,
) -> Result<(), RepositoryError> {
let result = query!(
r#"DELETE FROM course_files
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)"#,
id,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(not_found(id));
}

View file

@ -76,7 +76,8 @@ impl TryFrom<TimeSlotDB> for TimeSlot {
}
}
/// Slots of a course, sorted like `get_courses` does
/// Slots of a course, sorted like `get_courses` does. The owner of the course must have
/// been checked.
async fn get_slots(
executor: impl PgExecutor<'_>,
course_id: CourseId,
@ -96,11 +97,12 @@ async fn get_slots(
#[async_trait]
impl CoursesRepository for SqlxDatabase {
async fn get_courses(&self) -> Result<Vec<Course>, RepositoryError> {
async fn get_courses(&self, owner: &str) -> Result<Vec<Course>, RepositoryError> {
let courses = query_as!(
CourseDB,
r#"SELECT id, kind, name, code, teachers, main_page_url, folder
FROM courses ORDER BY name, id"#
FROM courses WHERE owner = $1 ORDER BY name, id"#,
owner,
)
.fetch_all(&self.pool)
.await?;
@ -108,8 +110,11 @@ impl CoursesRepository for SqlxDatabase {
let mut slots_by_course: HashMap<CourseId, Vec<TimeSlot>> = HashMap::new();
let slots = query_as!(
TimeSlotDB,
r#"SELECT id, course_id, tag_id, weekday, start_time, end_time
FROM time_slots ORDER BY weekday, start_time, id"#
r#"SELECT s.id, s.course_id, s.tag_id, s.weekday, s.start_time, s.end_time
FROM time_slots s JOIN courses c ON c.id = s.course_id
WHERE c.owner = $1
ORDER BY s.weekday, s.start_time, s.id"#,
owner,
)
.fetch_all(&self.pool)
.await?;
@ -130,12 +135,13 @@ impl CoursesRepository for SqlxDatabase {
.collect()
}
async fn get_course(&self, id: CourseId) -> Result<Course, RepositoryError> {
async fn get_course(&self, owner: &str, id: CourseId) -> Result<Course, RepositoryError> {
let row = query_as!(
CourseDB,
r#"SELECT id, kind, name, code, teachers, main_page_url, folder
FROM courses WHERE id = $1"#,
FROM courses WHERE id = $1 AND owner = $2"#,
id,
owner,
)
.fetch_optional(&self.pool)
.await?
@ -146,13 +152,14 @@ impl CoursesRepository for SqlxDatabase {
async fn create_course(
&self,
owner: &str,
course: CourseData,
folder: &str,
) -> Result<Course, RepositoryError> {
let row = query_as!(
CourseDB,
r#"INSERT INTO courses (kind, name, code, teachers, main_page_url, folder)
VALUES ($1, $2, $3, $4, $5, $6)
r#"INSERT INTO courses (owner, kind, name, code, teachers, main_page_url, folder)
VALUES ($7, $1, $2, $3, $4, $5, $6)
RETURNING id, kind, name, code, teachers, main_page_url, folder"#,
course.kind.as_str(),
course.name,
@ -160,6 +167,7 @@ impl CoursesRepository for SqlxDatabase {
&course.teachers,
course.main_page_url,
folder,
owner,
)
.fetch_one(&self.pool)
.await?;
@ -168,6 +176,7 @@ impl CoursesRepository for SqlxDatabase {
async fn update_course(
&self,
owner: &str,
id: CourseId,
course: CourseData,
folder: &str,
@ -176,7 +185,7 @@ impl CoursesRepository for SqlxDatabase {
CourseDB,
r#"UPDATE courses
SET name = $2, code = $3, teachers = $4, main_page_url = $5, folder = $6
WHERE id = $1
WHERE id = $1 AND owner = $7
RETURNING id, kind, name, code, teachers, main_page_url, folder"#,
id,
course.name,
@ -184,6 +193,7 @@ impl CoursesRepository for SqlxDatabase {
&course.teachers,
course.main_page_url,
folder,
owner,
)
.fetch_optional(&self.pool)
.await?
@ -192,11 +202,15 @@ impl CoursesRepository for SqlxDatabase {
row.with_slots(slots)
}
async fn delete_course(&self, id: CourseId) -> Result<(), RepositoryError> {
async fn delete_course(&self, owner: &str, id: CourseId) -> Result<(), RepositoryError> {
// Slots, grades, tasks and notes are removed by the `ON DELETE CASCADE`
let result = query!("DELETE FROM courses WHERE id = $1", id)
.execute(&self.pool)
.await?;
let result = query!(
"DELETE FROM courses WHERE id = $1 AND owner = $2",
id,
owner
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(RepositoryError::NotFound(format!("course {id}")));
}
@ -205,35 +219,41 @@ impl CoursesRepository for SqlxDatabase {
async fn add_slot(
&self,
owner: &str,
course_id: CourseId,
slot: TimeSlotData,
) -> Result<Course, RepositoryError> {
let result = query!(
r#"INSERT INTO time_slots (course_id, tag_id, weekday, start_time, end_time)
SELECT id, $2, $3, $4, $5 FROM courses WHERE id = $1"#,
SELECT id, $2, $3, $4, $5 FROM courses WHERE id = $1 AND owner = $6"#,
course_id,
slot.tag_id,
i16::from(slot.weekday),
slot.start_time,
slot.end_time,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(RepositoryError::NotFound(format!("course {course_id}")));
}
self.get_course(course_id).await
self.get_course(owner, course_id).await
}
async fn delete_slot(
&self,
owner: &str,
course_id: CourseId,
slot_id: TimeSlotId,
) -> Result<Course, RepositoryError> {
let result = query!(
"DELETE FROM time_slots WHERE id = $1 AND course_id = $2",
r#"DELETE FROM time_slots
WHERE id = $1 AND course_id = $2
AND course_id IN (SELECT id FROM courses WHERE owner = $3)"#,
slot_id,
course_id,
owner,
)
.execute(&self.pool)
.await?;
@ -242,6 +262,6 @@ impl CoursesRepository for SqlxDatabase {
"slot {slot_id} of course {course_id}"
)));
}
self.get_course(course_id).await
self.get_course(owner, course_id).await
}
}

View file

@ -39,12 +39,18 @@ fn not_found(id: GradeId) -> RepositoryError {
#[async_trait]
impl GradesRepository for SqlxDatabase {
async fn get_grades(&self, course_id: CourseId) -> Result<Vec<Grade>, RepositoryError> {
async fn get_grades(
&self,
owner: &str,
course_id: CourseId,
) -> Result<Vec<Grade>, RepositoryError> {
Ok(query_as!(
GradeDB,
r#"SELECT id, name, score, max_score, weight FROM grades
WHERE course_id = $1 ORDER BY id"#,
WHERE course_id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)
ORDER BY id"#,
course_id,
owner,
)
.fetch_all(&self.pool)
.await?
@ -53,42 +59,62 @@ impl GradesRepository for SqlxDatabase {
.collect())
}
async fn get_grade_course(&self, id: GradeId) -> Result<CourseId, RepositoryError> {
query!("SELECT course_id FROM grades WHERE id = $1", id)
.fetch_optional(&self.pool)
.await?
.map(|row| row.course_id)
.ok_or_else(|| not_found(id))
async fn get_grade_course(
&self,
owner: &str,
id: GradeId,
) -> Result<CourseId, RepositoryError> {
query!(
r#"SELECT course_id FROM grades
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)"#,
id,
owner,
)
.fetch_optional(&self.pool)
.await?
.map(|row| row.course_id)
.ok_or_else(|| not_found(id))
}
async fn create_grade(
&self,
owner: &str,
course_id: CourseId,
grade: GradeData,
) -> Result<(), RepositoryError> {
query!(
let result = query!(
r#"INSERT INTO grades (course_id, name, score, max_score, weight)
VALUES ($1, $2, $3, $4, $5)"#,
SELECT id, $2, $3, $4, $5 FROM courses WHERE id = $1 AND owner = $6"#,
course_id,
grade.name,
grade.score,
grade.max_score,
grade.weight,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(RepositoryError::NotFound(format!("course {course_id}")));
}
Ok(())
}
async fn update_grade(&self, id: GradeId, grade: GradeData) -> Result<(), RepositoryError> {
async fn update_grade(
&self,
owner: &str,
id: GradeId,
grade: GradeData,
) -> Result<(), RepositoryError> {
let result = query!(
r#"UPDATE grades SET name = $2, score = $3, max_score = $4, weight = $5
WHERE id = $1"#,
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $6)"#,
id,
grade.name,
grade.score,
grade.max_score,
grade.weight,
owner,
)
.execute(&self.pool)
.await?;
@ -98,10 +124,15 @@ impl GradesRepository for SqlxDatabase {
Ok(())
}
async fn delete_grade(&self, id: GradeId) -> Result<(), RepositoryError> {
let result = query!("DELETE FROM grades WHERE id = $1", id)
.execute(&self.pool)
.await?;
async fn delete_grade(&self, owner: &str, id: GradeId) -> Result<(), RepositoryError> {
let result = query!(
r#"DELETE FROM grades
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)"#,
id,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(not_found(id));
}

View file

@ -4,6 +4,7 @@
//! time: `dev-db` must be up and migrated, or the `.sqlx` offline data must be present
//! (`cargo sqlx prepare`).
mod calendars;
mod course_files;
mod courses;
mod grades;

View file

@ -71,7 +71,11 @@ async fn insert_tags(
#[async_trait]
impl TasksRepository for SqlxDatabase {
async fn get_tasks(&self, course_id: CourseId) -> Result<Vec<Task>, RepositoryError> {
async fn get_tasks(
&self,
owner: &str,
course_id: CourseId,
) -> Result<Vec<Task>, RepositoryError> {
Ok(query_as!(
TaskDB,
r#"SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,
@ -79,11 +83,13 @@ impl TasksRepository for SqlxDatabase {
COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)
FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM tasks t
JOIN courses c ON c.id = t.course_id AND c.owner = $2
LEFT JOIN task_tags tt ON tt.task_id = t.id
WHERE t.course_id = $1
GROUP BY t.id
ORDER BY t.id"#,
course_id,
owner,
)
.fetch_all(&self.pool)
.await?
@ -94,6 +100,7 @@ impl TasksRepository for SqlxDatabase {
async fn get_dated_tasks(
&self,
owner: &str,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> Result<Vec<Task>, RepositoryError> {
@ -104,6 +111,7 @@ impl TasksRepository for SqlxDatabase {
COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)
FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM tasks t
JOIN courses c ON c.id = t.course_id AND c.owner = $3
LEFT JOIN task_tags tt ON tt.task_id = t.id
WHERE (t.deadline >= $1 AND t.deadline < $2)
OR t.id IN (SELECT parent_id FROM tasks
@ -112,6 +120,7 @@ impl TasksRepository for SqlxDatabase {
ORDER BY t.id"#,
from,
to,
owner,
)
.fetch_all(&self.pool)
.await?
@ -120,7 +129,7 @@ impl TasksRepository for SqlxDatabase {
.collect())
}
async fn get_todo_tasks(&self) -> Result<Vec<Task>, RepositoryError> {
async fn get_todo_tasks(&self, owner: &str) -> Result<Vec<Task>, RepositoryError> {
Ok(query_as!(
TaskDB,
r#"SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,
@ -128,11 +137,13 @@ impl TasksRepository for SqlxDatabase {
COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)
FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM tasks t
JOIN courses c ON c.id = t.course_id AND c.owner = $1
LEFT JOIN task_tags tt ON tt.task_id = t.id
WHERE t.id IN (SELECT id FROM tasks WHERE parent_id IS NULL AND NOT done)
OR t.parent_id IN (SELECT id FROM tasks WHERE parent_id IS NULL AND NOT done)
GROUP BY t.id
ORDER BY t.id"#,
owner,
)
.fetch_all(&self.pool)
.await?
@ -141,7 +152,7 @@ impl TasksRepository for SqlxDatabase {
.collect())
}
async fn get_task(&self, id: TaskId) -> Result<Task, RepositoryError> {
async fn get_task(&self, owner: &str, id: TaskId) -> Result<Task, RepositoryError> {
query_as!(
TaskDB,
r#"SELECT t.id, t.course_id, t.parent_id, t.name, t.description, t.links,
@ -149,10 +160,12 @@ impl TasksRepository for SqlxDatabase {
COALESCE(ARRAY_AGG(tt.tag_id ORDER BY tt.tag_id)
FILTER (WHERE tt.tag_id IS NOT NULL), '{}') AS "tag_ids!"
FROM tasks t
JOIN courses c ON c.id = t.course_id AND c.owner = $2
LEFT JOIN task_tags tt ON tt.task_id = t.id
WHERE t.id = $1
GROUP BY t.id"#,
id,
owner,
)
.fetch_optional(&self.pool)
.await?
@ -162,6 +175,7 @@ impl TasksRepository for SqlxDatabase {
async fn create_task(
&self,
owner: &str,
course_id: CourseId,
parent_id: Option<TaskId>,
task: TaskData,
@ -169,7 +183,7 @@ impl TasksRepository for SqlxDatabase {
let mut tx = self.pool.begin().await?;
let id = query!(
r#"INSERT INTO tasks (course_id, parent_id, name, description, links, deadline, done)
VALUES ($1, $2, $3, $4, $5, $6, $7)
SELECT id, $2, $3, $4, $5, $6, $7 FROM courses WHERE id = $1 AND owner = $8
RETURNING id"#,
course_id,
parent_id,
@ -178,26 +192,34 @@ impl TasksRepository for SqlxDatabase {
&task.links,
task.deadline,
task.done,
owner,
)
.fetch_one(&mut *tx)
.fetch_optional(&mut *tx)
.await?
.ok_or_else(|| RepositoryError::NotFound(format!("course {course_id}")))?
.id;
insert_tags(&mut tx, id, &task.tag_ids).await?;
tx.commit().await?;
Ok(())
}
async fn update_task(&self, id: TaskId, task: TaskData) -> Result<(), RepositoryError> {
async fn update_task(
&self,
owner: &str,
id: TaskId,
task: TaskData,
) -> Result<(), RepositoryError> {
let mut tx = self.pool.begin().await?;
let result = query!(
r#"UPDATE tasks SET name = $2, description = $3, links = $4, deadline = $5, done = $6
WHERE id = $1"#,
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $7)"#,
id,
task.name,
task.description,
&task.links,
task.deadline,
task.done,
owner,
)
.execute(&mut *tx)
.await?;
@ -212,12 +234,19 @@ impl TasksRepository for SqlxDatabase {
Ok(())
}
async fn add_time_spent(&self, id: TaskId, seconds: i32) -> Result<i32, RepositoryError> {
async fn add_time_spent(
&self,
owner: &str,
id: TaskId,
seconds: i32,
) -> Result<i32, RepositoryError> {
query!(
r#"UPDATE tasks SET time_spent = time_spent + $2 WHERE id = $1
r#"UPDATE tasks SET time_spent = time_spent + $2
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $3)
RETURNING time_spent"#,
id,
seconds,
owner,
)
.fetch_optional(&self.pool)
.await?
@ -225,11 +254,16 @@ impl TasksRepository for SqlxDatabase {
.ok_or_else(|| not_found(id))
}
async fn delete_task(&self, id: TaskId) -> Result<(), RepositoryError> {
async fn delete_task(&self, owner: &str, id: TaskId) -> Result<(), RepositoryError> {
// The subtasks and the tags are removed by the `ON DELETE CASCADE`
let result = query!("DELETE FROM tasks WHERE id = $1", id)
.execute(&self.pool)
.await?;
let result = query!(
r#"DELETE FROM tasks
WHERE id = $1 AND course_id IN (SELECT id FROM courses WHERE owner = $2)"#,
id,
owner,
)
.execute(&self.pool)
.await?;
if result.rows_affected() == 0 {
return Err(not_found(id));
}

Some files were not shown because too many files have changed in this diff Show more