Compare commits
10 Commits
cfdc6862bc
...
e8411adac3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8411adac3 | ||
|
|
7110b1ab12 | ||
|
|
860120d9cf | ||
|
|
21107e9804 | ||
|
|
5106239c97 | ||
|
|
7889621b69 | ||
|
|
ce901d5f26 | ||
|
|
98cabfd51d | ||
|
|
577fa14d3d | ||
|
|
1046237771 |
234
README.md
Normal file
234
README.md
Normal file
@@ -0,0 +1,234 @@
|
||||
# jz.bm
|
||||
|
||||
The study dashboard backend of the part-time master's programme "Bezpieczeństwo międzynarodowe" (UWr): courses, meetings, timetable, deadlines, reading lists with per-student progress, and study materials.
|
||||
|
||||
```go
|
||||
import _ "git.golem15.com/jakub/sm-bm-plugin"
|
||||
```
|
||||
|
||||
## Overview
|
||||
|
||||
`jz.bm` is a SummerCMS plugin. It keeps the programme's data in `jz_bm_*` tables, serves it to signed-in students as a read-only JSON API under `/_bm/api/v1`, and gives administrators admin screens to edit it. Students write one thing only: which readings they have read.
|
||||
|
||||
Students are the users of `golem15.user`: the API sits behind its `jwt.auth` guard, and reading progress points at its `users` table. Course data is loaded from a JSON file with `bm:seed` and maintained in the admin afterwards.
|
||||
|
||||
Timestamps are stored in UTC (`TIMESTAMPTZ`) and written in RFC 3339 in Europe/Warsaw (`2026-10-03T08:00:00+02:00`). Dates are `YYYY-MM-DD`. A date or time typed without an offset (in the admin or in a seed file) is read as Polish time.
|
||||
|
||||
## Features
|
||||
|
||||
- Models: `Course` (przedmiot, one row per course and form), `Meeting` (zjazd), `ClassSession` (zajęcia), `Deadline` (terminarz), `Reading` (lektura), `ReadingProgress`, `Material` with file attachments (`system_files`, field `files`) and `Tag`, many-to-many through `jz_bm_material_tag`.
|
||||
- Courses that share an `elective_group` are alternatives ("do wyboru"), such as the specialisation courses.
|
||||
- A material without `published_at` is a draft; a material whose `published_at` lies in the future is not shown yet.
|
||||
- Cascades: deleting a course deletes its class sessions and readings and unlinks its deadlines and materials; deleting a meeting unlinks its sessions; deleting a reading or a user deletes the progress rows.
|
||||
- Admin screens for every model in a "Studia BM" navigation group, guarded by three permissions.
|
||||
- `bm:seed`: an idempotent upsert of meetings, courses, class sessions, deadlines and readings from a JSON file, all or nothing.
|
||||
|
||||
## API reference
|
||||
|
||||
Every route needs `Authorization: Bearer <golem15.user JWT>` (or the user plugin's token cookie) and answers 401 `{"error": true, "message": "..."}` without one. Responses are wrapped in `{"data": ...}`; `/materials` adds the `meta` block of `lagoon.Paginate`. A missing record, an unpublished material or a non-numeric `{id}` is a 404. Invalid query parameters are a 422 in Laravel's shape, with messages in the request locale:
|
||||
|
||||
```json
|
||||
{"message": "The to must be a date after or equal to from.", "errors": {"to": ["The to must be a date after or equal to from."]}}
|
||||
```
|
||||
|
||||
| Method | Path | Query | Answers |
|
||||
|--------|------|-------|---------|
|
||||
| GET | `/_bm/api/v1/dashboard` | | Next sessions, upcoming deadlines, current and next meeting, reading progress |
|
||||
| GET | `/_bm/api/v1/courses` | `semester` (1–4) | Every course with counters |
|
||||
| GET | `/_bm/api/v1/courses/{id}` | | One course with its sessions, readings and published materials |
|
||||
| GET | `/_bm/api/v1/schedule` | `from`, `to` (`YYYY-MM-DD`) | Class sessions starting in the range |
|
||||
| GET | `/_bm/api/v1/meetings` | | Every meeting |
|
||||
| GET | `/_bm/api/v1/deadlines` | `from`, `to` (`YYYY-MM-DD`) | Deadlines in the range |
|
||||
| GET | `/_bm/api/v1/readings` | `course` (ID) | Readings with the caller's `read_at` |
|
||||
| PUT | `/_bm/api/v1/readings/{id}/progress` | | Marks the reading read (idempotent) |
|
||||
| DELETE | `/_bm/api/v1/readings/{id}/progress` | | Clears the mark (idempotent) |
|
||||
| GET | `/_bm/api/v1/materials` | `course`, `tag` (slug), `type`, `page`, `per_page` (1–100) | One page of published materials |
|
||||
| GET | `/_bm/api/v1/materials/{id}` | | One published material with body, tags and files |
|
||||
|
||||
### Shared shapes
|
||||
|
||||
A course reference, embedded in other records:
|
||||
|
||||
```json
|
||||
{"id": 1, "code": null, "name": "…", "form": "wyklad", "semester": 1}
|
||||
```
|
||||
|
||||
`form` is one of `wyklad`, `cwiczenia`, `konwersatorium`, `seminarium`, `inne`.
|
||||
|
||||
A class session:
|
||||
|
||||
```json
|
||||
{"id": 1, "course_id": 1, "meeting_id": 1, "meeting_number": 1,
|
||||
"starts_at": "2026-10-03T08:00:00+02:00", "ends_at": "2026-10-03T09:30:00+02:00",
|
||||
"room": "237", "kind": null, "notes": null, "is_online": false,
|
||||
"course": {"id": 1, "code": null, "name": "…", "form": "wyklad", "semester": 1}}
|
||||
```
|
||||
|
||||
A meeting:
|
||||
|
||||
```json
|
||||
{"id": 1, "number": 1, "starts_on": "2026-10-03", "ends_on": "2026-10-04", "notes": null, "sessions_count": 12}
|
||||
```
|
||||
|
||||
A deadline (`kind` is one of `zaliczenie`, `egzamin`, `praca`, `organizacyjne`, `inne`; `course` is null when the deadline belongs to no course):
|
||||
|
||||
```json
|
||||
{"id": 1, "title": "…", "due_at": "2026-10-05T23:59:00+02:00", "kind": "organizacyjne", "description": null, "course_id": null, "course": null}
|
||||
```
|
||||
|
||||
A reading (`read_at` is the caller's, or null):
|
||||
|
||||
```json
|
||||
{"id": 1, "course_id": 1, "course": {…}, "title": "…", "author": null, "source": null, "url": null,
|
||||
"is_required": true, "sort_order": 1, "read_at": "2026-10-02T21:15:04+02:00"}
|
||||
```
|
||||
|
||||
A material in a list (`type` is one of `pdf`, `notatka`, `link`, `inne`; `files_count` counts public files):
|
||||
|
||||
```json
|
||||
{"id": 1, "course_id": 1, "course": {…}, "title": "…", "type": "notatka", "source": null, "url": null,
|
||||
"published_at": "2026-10-01T12:00:00+02:00", "tags": [{"id": 1, "name": "Geopolityka", "slug": "geopolityka"}], "files_count": 1}
|
||||
```
|
||||
|
||||
A course with counters (`readings_read` is the caller's; `materials` counts published materials):
|
||||
|
||||
```json
|
||||
{"id": 1, "code": null, "name": "…", "form": "wyklad", "lecturer": "…", "semester": 1, "ects": 8,
|
||||
"assessment": "egzamin", "elective_group": null, "description": null, "syllabus_url": null, "sort_order": 1,
|
||||
"counts": {"sessions": 6, "readings": 4, "readings_read": 1, "materials": 2}}
|
||||
```
|
||||
|
||||
### GET /dashboard
|
||||
|
||||
```json
|
||||
{"data": {
|
||||
"next_sessions": [<session>, …],
|
||||
"upcoming_deadlines": [<deadline>, …],
|
||||
"current_meeting": <meeting> | null,
|
||||
"next_meeting": <meeting> | null,
|
||||
"readings": {"total": 40, "read": 3, "required_total": 25, "required_read": 2}
|
||||
}}
|
||||
```
|
||||
|
||||
`next_sessions` are the first sessions that have not ended yet, by start time; `upcoming_deadlines` the first deadlines not yet due. Both hold `jz.bm.dashboard_limit` items (5). `current_meeting` is the meeting whose dates include today in Warsaw; `next_meeting` the first one that starts after today.
|
||||
|
||||
### GET /courses, GET /courses/{id}
|
||||
|
||||
`/courses` answers `{"data": [<course with counters>, …]}` in programme order (semester, `sort_order`, name). `/courses/{id}` answers one course with counters plus:
|
||||
|
||||
```json
|
||||
{"data": {…course with counters…,
|
||||
"sessions": [<session>, …],
|
||||
"readings": [<reading>, …],
|
||||
"materials": [<material>, …]}}
|
||||
```
|
||||
|
||||
### GET /schedule, GET /meetings, GET /deadlines
|
||||
|
||||
`/schedule` answers `{"data": [<session>, …]}` by start time: the sessions that start from midnight of `from` (default today) until the end of `to` (default no limit), in Warsaw. `/meetings` answers `{"data": [<meeting>, …]}` by number. `/deadlines` answers `{"data": [<deadline>, …]}` by due time; without `from` it starts now, so it lists the deadlines not yet due.
|
||||
|
||||
### GET /readings, PUT and DELETE /readings/{id}/progress
|
||||
|
||||
`/readings` answers `{"data": [<reading>, …]}` in course and `sort_order` order; an unknown `course` gives an empty list. The progress routes answer:
|
||||
|
||||
```json
|
||||
{"data": {"reading_id": 7, "read_at": "2026-10-02T21:15:04+02:00"}}
|
||||
```
|
||||
|
||||
Marking a read reading again keeps the first `read_at`. Clearing answers `read_at: null`, also when the reading was not marked.
|
||||
|
||||
### GET /materials, GET /materials/{id}
|
||||
|
||||
```json
|
||||
{"data": [<material>, …], "meta": {"current_page": 1, "last_page": 1, "per_page": 20, "total": 2}}
|
||||
```
|
||||
|
||||
Newest publication first. The detail adds the Markdown body and the public files; `url` starts with `storage.uploads.public_path_prefix`:
|
||||
|
||||
```json
|
||||
{"data": {…material…, "body": "# …",
|
||||
"files": [{"id": 3, "url": "/storage/uploads/5f1/d0c/2e9/5f1d0c2e9a7b4c3d8e6f.pdf", "name": "wyklad.pdf", "size": 123456, "mime": "application/pdf"}]}}
|
||||
```
|
||||
|
||||
## Student app
|
||||
|
||||
The built single-page app (Vue, source in the application repository's `frontend/`) is embedded from `public/` and served at `/`. Existing files are served as they are: `assets/*` (content-hashed) with `Cache-Control: public, max-age=31536000, immutable`, everything else with `no-cache` and an ETag (304 on revalidation). A GET for any other extension-less path answers `index.html` (client routes); a missing path with an extension is a 404. `/_user`, `/_bm`, `/_quizzes`, `/storage` and the admin path (`backend.uri`, default `/bmadmin`) are never answered by the app. Routes fails when `public/index.html` is missing. The output of `npm run build` in `frontend/` is committed in `public/`.
|
||||
|
||||
## Admin
|
||||
|
||||
Controllers (admin API path `<backend.uri>/api/v1/jz/bm/<name>`), all in the "Studia BM" navigation group:
|
||||
|
||||
| Controller | Permission |
|
||||
|------------|------------|
|
||||
| `jz.bm.courses`, `jz.bm.readings` | `jz.bm.access_courses` |
|
||||
| `jz.bm.meetings`, `jz.bm.class_sessions`, `jz.bm.deadlines` | `jz.bm.access_schedule` |
|
||||
| `jz.bm.materials`, `jz.bm.tags` | `jz.bm.access_materials` |
|
||||
|
||||
Courses, meetings, sessions and deadlines are picked through relation fields; a material's tags through a belongsToMany relation field. Dates are typed as `2026-10-03` and times as `2026-10-03 08:00` (Polish time) or RFC 3339; a value that does not parse is a 422 on its field. Labels are in Polish (`lang/pl`) and English (`lang/en`).
|
||||
|
||||
Two things the admin cannot do yet, because the framework does not offer them: upload a material's files (there is no file upload form widget, so files are attached as `system_files` rows outside the admin), and list a course's readings and sessions inside the course form (relation managers handle only belongsToMany links). Both are marked `TODO: requires SummerCMS change` in the code.
|
||||
|
||||
## Configuration
|
||||
|
||||
Defaults in `config/config.yaml`, read as `jz.bm.<key>`:
|
||||
|
||||
| Key | Default | Sets |
|
||||
|-----|---------|------|
|
||||
| `jz.bm.materials_per_page` | `20` | Default page size of `/materials` (clamped to 1–100). |
|
||||
| `jz.bm.dashboard_limit` | `5` | Sessions and deadlines on `/dashboard`. |
|
||||
|
||||
## CLI commands
|
||||
|
||||
### bm:seed
|
||||
|
||||
```sh
|
||||
./bin/bm bm:seed data/bm-2026-27.json
|
||||
./bin/bm bm:seed data/bm-2026-27.json --dry-run
|
||||
```
|
||||
|
||||
Reads a JSON file, validates all of it, and upserts it in one transaction. Each kind is matched on its identity, updated in place when a field changed, and created otherwise; rows that are not in the file are left alone, so running the same file again changes nothing. Any error (an unknown key in the document, a bad value, a course key or meeting number that does not exist in the file) names the record and writes nothing. `--dry-run` only validates. The command prints a table of created, updated and unchanged rows per kind.
|
||||
|
||||
| Kind | Identity |
|
||||
|------|----------|
|
||||
| meetings | `number` |
|
||||
| courses | `name` + `form` + `semester` |
|
||||
| class_sessions | course + `starts_at` |
|
||||
| deadlines | `title` + `due_at` |
|
||||
| readings | course + `title` |
|
||||
|
||||
The file format (every top-level array is optional, and nullable fields may be left out):
|
||||
|
||||
```json
|
||||
{
|
||||
"meetings": [{"number": 1, "starts_on": "2026-10-03", "ends_on": "2026-10-04", "notes": "stacjonarny"}],
|
||||
"courses": [{"key": "glob-w", "code": null, "name": "…", "form": "wyklad", "lecturer": "…", "semester": 1,
|
||||
"ects": 8, "assessment": "egzamin", "elective_group": null, "description": null, "syllabus_url": null, "sort_order": 1}],
|
||||
"class_sessions": [{"course": "glob-w", "meeting": 1, "starts_at": "2026-10-03T08:00:00+02:00", "ends_at": "2026-10-03T09:30:00+02:00",
|
||||
"room": "237", "kind": null, "is_online": false, "notes": null}],
|
||||
"deadlines": [{"title": "…", "due_at": "2026-10-05T23:59:00+02:00", "course": null, "kind": "organizacyjne", "description": null}],
|
||||
"readings": [{"course": "glob-w", "title": "…", "author": null, "source": null, "url": null, "is_required": true, "sort_order": 1}]
|
||||
}
|
||||
```
|
||||
|
||||
- `key` is a reference inside the file only; `course` in sessions, deadlines and readings names a course `key`, `meeting` in sessions a meeting `number`.
|
||||
- `form`: `wyklad`, `cwiczenia`, `konwersatorium`, `seminarium`, `inne`. `semester`: 1–4. `kind` of a deadline: `zaliczenie`, `egzamin`, `praca`, `organizacyjne`, `inne`.
|
||||
- Dates are `YYYY-MM-DD`; times RFC 3339 with an offset, or `YYYY-MM-DD HH:MM` in Polish time.
|
||||
- A blank optional text is stored as null.
|
||||
|
||||
`testdata/seed.example.json` is a small example with made-up data.
|
||||
|
||||
## Dependencies
|
||||
|
||||
- SummerCMS framework modules: `pact`, `party`, `backpack`, `surf`, `wire`, `bouncer`, `lagoon` (with `lagoon/attach`), `cabana`, `bonfire`, `phrasebook`.
|
||||
- The `golem15.user` plugin (`git.golem15.com/golem15/sm-user-plugin`): the `users` table and the `jwt.auth` middleware. `jz.bm` declares it in `Requires`, so its migrations run first.
|
||||
- GORM and gormigrate. Tests also use testcontainers-go and pgx.
|
||||
|
||||
## Testing
|
||||
|
||||
```sh
|
||||
go vet ./...
|
||||
go test ./... # unit tests and Postgres integration tests (Docker)
|
||||
go test -short ./... # unit tests only
|
||||
```
|
||||
|
||||
The integration tests start a `postgres:16-alpine` container through testcontainers and create a fresh database per test; they never touch a development database. They cover the migrations up and down, the schema constraints, `bm:seed` (idempotency, in-place updates, all-or-nothing), every API route through the real `jwt.auth` guard, and admin saves through the admin API.
|
||||
185
admin_test.go
Normal file
185
admin_test.go
Normal file
@@ -0,0 +1,185 @@
|
||||
package bm_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const adminAPI = "/backend/api/v1"
|
||||
|
||||
// adminToken creates an administrator whose role grants perms and signs in
|
||||
// through the admin API.
|
||||
func adminToken(t *testing.T, gdb *gorm.DB, h http.Handler, perms string) string {
|
||||
t.Helper()
|
||||
hash, err := bouncer.HashPassword(10, "admin-secret-password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var roleID uint
|
||||
if err := gdb.Raw(`INSERT INTO backend_user_roles (name, code, permissions, is_system, created_at, updated_at)
|
||||
VALUES ('BM', 'bm', ?, FALSE, NOW(), NOW()) RETURNING id`, perms).Scan(&roleID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gdb.Exec(`INSERT INTO backend_users (login, email, password, is_activated, is_superuser, role_id, created_at, updated_at)
|
||||
VALUES ('editor', 'editor@example.test', ?, TRUE, FALSE, ?, NOW(), NOW())`, hash, roleID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := adminSend(t, h, http.MethodPost, "/auth/login", "", map[string]string{"login": "editor", "password": "admin-secret-password"})
|
||||
var body struct {
|
||||
Data struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &body) != nil || body.Data.AccessToken == "" {
|
||||
t.Fatalf("admin login = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
return body.Data.AccessToken
|
||||
}
|
||||
|
||||
func adminSend(t *testing.T, h http.Handler, method, path, token string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader = bytes.NewReader(raw)
|
||||
}
|
||||
req := httptest.NewRequest(method, adminAPI+path, reader)
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
req.Header.Set("Accept-Language", "en")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func createdID(t *testing.T, rec *httptest.ResponseRecorder) uint {
|
||||
t.Helper()
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("create = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Data struct {
|
||||
ID uint `json:"id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || body.Data.ID == 0 {
|
||||
t.Fatalf("create body %s: %v", rec.Body.String(), err)
|
||||
}
|
||||
return body.Data.ID
|
||||
}
|
||||
|
||||
func TestAdminCRUDAgainstDatabase(t *testing.T) {
|
||||
app, plugins, gdb := migrated(t)
|
||||
h, err := surf.Assemble(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token := adminToken(t, gdb, h, `{"jz.bm.access_courses":1,"jz.bm.access_schedule":1,"jz.bm.access_materials":1}`)
|
||||
|
||||
courseID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/courses", token, map[string]any{
|
||||
"name": "Przedmiot testowy", "form": "seminarium", "semester": 2, "ects": 5, "elective_group": "", "lecturer": "dr X",
|
||||
}))
|
||||
var course models.Course
|
||||
gdb.Take(&course, courseID)
|
||||
if course.ElectiveGroup != nil || course.Lecturer == nil || course.ECTS == nil || *course.ECTS != 5 {
|
||||
t.Errorf("course = %+v", course)
|
||||
}
|
||||
if rec := adminSend(t, h, http.MethodPost, "/jz/bm/courses", token, map[string]any{"name": "X", "form": "lecture", "semester": 1}); rec.Code != http.StatusUnprocessableEntity {
|
||||
t.Errorf("bad form = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
meetingID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/meetings", token, map[string]any{
|
||||
"number": 1, "starts_on": "2030-10-05", "ends_on": "2030-10-06",
|
||||
}))
|
||||
if rec := adminSend(t, h, http.MethodPost, "/jz/bm/meetings", token, map[string]any{"number": 2, "starts_on": "5.10.2030", "ends_on": "2030-10-06"}); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "starts_on") {
|
||||
t.Errorf("bad date = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
sessionID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/class_sessions", token, map[string]any{
|
||||
"course": courseID, "meeting": meetingID, "starts_at": "2030-10-05 08:00", "ends_at": "2030-10-05 09:30", "room": "", "is_online": true,
|
||||
}))
|
||||
var stored time.Time
|
||||
gdb.Raw(`SELECT starts_at FROM jz_bm_class_sessions WHERE id = ?`, sessionID).Scan(&stored)
|
||||
if !stored.Equal(time.Date(2030, 10, 5, 6, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("stored starts_at = %v, want 06:00 UTC", stored)
|
||||
}
|
||||
var session models.ClassSession
|
||||
gdb.Take(&session, sessionID)
|
||||
if session.CourseID != courseID || session.MeetingID == nil || *session.MeetingID != meetingID || session.Room != nil || !session.IsOnline {
|
||||
t.Errorf("session = %+v", session)
|
||||
}
|
||||
rec := adminSend(t, h, http.MethodPost, "/jz/bm/class_sessions", token, map[string]any{
|
||||
"course": courseID, "starts_at": "2030-10-05 10:00", "ends_at": "wtorek",
|
||||
})
|
||||
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "ends_at") {
|
||||
t.Errorf("bad ends_at = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := adminSend(t, h, http.MethodGet, "/jz/bm/class_sessions", token, nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Przedmiot testowy") {
|
||||
t.Errorf("session list = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := adminSend(t, h, http.MethodGet, "/jz/bm/class_sessions/"+strconv.Itoa(int(sessionID)), token, nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "2030-10-05T08:00:00+02:00") {
|
||||
t.Errorf("session show = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
tagID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/tags", token, map[string]any{"name": "Geopolityka", "slug": "geopolityka"}))
|
||||
materialID := createdID(t, adminSend(t, h, http.MethodPost, "/jz/bm/materials", token, map[string]any{
|
||||
"title": "Notatka", "type": "notatka", "course": courseID, "tags": []uint{tagID}, "published_at": "", "body": "# Treść",
|
||||
}))
|
||||
var material models.Material
|
||||
gdb.Preload("Tags").Take(&material, materialID)
|
||||
if material.PublishedAt != nil || len(material.Tags) != 1 || material.CourseID == nil {
|
||||
t.Errorf("material = %+v", material)
|
||||
}
|
||||
rec = adminSend(t, h, http.MethodPut, "/jz/bm/materials/"+strconv.Itoa(int(materialID)), token, map[string]any{
|
||||
"title": "Notatka", "type": "notatka", "published_at": "2026-01-15 12:00",
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("publish = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
gdb.Take(&material, materialID)
|
||||
if material.PublishedAt == nil || *material.PublishedAt != "2026-01-15T12:00:00+01:00" {
|
||||
t.Errorf("published_at = %v", material.PublishedAt)
|
||||
}
|
||||
|
||||
// Permissions are per screen group.
|
||||
gdb.Exec(`UPDATE backend_user_roles SET permissions = '{"jz.bm.access_materials":1}'`)
|
||||
limited := adminToken2(t, gdb, h)
|
||||
if rec := adminSend(t, h, http.MethodGet, "/jz/bm/courses", limited, nil); rec.Code != http.StatusForbidden {
|
||||
t.Errorf("courses without access_courses = %d", rec.Code)
|
||||
}
|
||||
if rec := adminSend(t, h, http.MethodGet, "/jz/bm/materials", limited, nil); rec.Code != http.StatusOK {
|
||||
t.Errorf("materials with access_materials = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// adminToken2 signs the existing editor in again, after a role change.
|
||||
func adminToken2(t *testing.T, gdb *gorm.DB, h http.Handler) string {
|
||||
t.Helper()
|
||||
rec := adminSend(t, h, http.MethodPost, "/auth/login", "", map[string]string{"login": "editor", "password": "admin-secret-password"})
|
||||
var body struct {
|
||||
Data struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &body) != nil {
|
||||
t.Fatalf("admin login = %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
return body.Data.AccessToken
|
||||
}
|
||||
449
classes/seed.go
Normal file
449
classes/seed.go
Normal file
@@ -0,0 +1,449 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// SeedFile is the JSON document bm:seed reads. Every top-level array is
|
||||
// optional. Courses carry a seed-local key that class sessions, deadlines
|
||||
// and readings use to point at them; meetings are referenced by number.
|
||||
type SeedFile struct {
|
||||
Meetings []SeedMeeting `json:"meetings"`
|
||||
Courses []SeedCourse `json:"courses"`
|
||||
ClassSessions []SeedSession `json:"class_sessions"`
|
||||
Deadlines []SeedDeadline `json:"deadlines"`
|
||||
Readings []SeedReading `json:"readings"`
|
||||
}
|
||||
|
||||
// SeedMeeting is one meeting; its identity is Number.
|
||||
type SeedMeeting struct {
|
||||
Number int `json:"number"`
|
||||
StartsOn string `json:"starts_on"`
|
||||
EndsOn string `json:"ends_on"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// SeedCourse is one course; its identity is Name, Form and Semester. Key is
|
||||
// only a reference inside the file.
|
||||
type SeedCourse struct {
|
||||
Key string `json:"key"`
|
||||
Code *string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Form string `json:"form"`
|
||||
Lecturer *string `json:"lecturer"`
|
||||
Semester int `json:"semester"`
|
||||
ECTS *float64 `json:"ects"`
|
||||
Assessment *string `json:"assessment"`
|
||||
ElectiveGroup *string `json:"elective_group"`
|
||||
Description *string `json:"description"`
|
||||
SyllabusURL *string `json:"syllabus_url"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
||||
// SeedSession is one class session; its identity is the course and StartsAt.
|
||||
// Course is a course key, Meeting an optional meeting number.
|
||||
type SeedSession struct {
|
||||
Course string `json:"course"`
|
||||
Meeting *int `json:"meeting"`
|
||||
StartsAt string `json:"starts_at"`
|
||||
EndsAt string `json:"ends_at"`
|
||||
Room *string `json:"room"`
|
||||
Kind *string `json:"kind"`
|
||||
IsOnline bool `json:"is_online"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// SeedDeadline is one deadline; its identity is Title and DueAt. Course is
|
||||
// an optional course key.
|
||||
type SeedDeadline struct {
|
||||
Title string `json:"title"`
|
||||
DueAt string `json:"due_at"`
|
||||
Course *string `json:"course"`
|
||||
Kind string `json:"kind"`
|
||||
Description *string `json:"description"`
|
||||
}
|
||||
|
||||
// SeedReading is one reading; its identity is the course and Title.
|
||||
type SeedReading struct {
|
||||
Course string `json:"course"`
|
||||
Title string `json:"title"`
|
||||
Author *string `json:"author"`
|
||||
Source *string `json:"source"`
|
||||
URL *string `json:"url"`
|
||||
IsRequired bool `json:"is_required"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
||||
// SeedCounts counts the rows of one kind a seed created, updated or left
|
||||
// unchanged.
|
||||
type SeedCounts struct {
|
||||
Created int
|
||||
Updated int
|
||||
Unchanged int
|
||||
}
|
||||
|
||||
func (c *SeedCounts) record(created, changed bool) {
|
||||
switch {
|
||||
case created:
|
||||
c.Created++
|
||||
case changed:
|
||||
c.Updated++
|
||||
default:
|
||||
c.Unchanged++
|
||||
}
|
||||
}
|
||||
|
||||
// SeedSummary is the outcome of a seed, per kind.
|
||||
type SeedSummary struct {
|
||||
Meetings SeedCounts
|
||||
Courses SeedCounts
|
||||
ClassSessions SeedCounts
|
||||
Deadlines SeedCounts
|
||||
Readings SeedCounts
|
||||
}
|
||||
|
||||
// Rows returns the summary as table rows: kind, created, updated, unchanged.
|
||||
func (s SeedSummary) Rows() [][]string {
|
||||
row := func(name string, c SeedCounts) []string {
|
||||
return []string{name, fmt.Sprint(c.Created), fmt.Sprint(c.Updated), fmt.Sprint(c.Unchanged)}
|
||||
}
|
||||
return [][]string{
|
||||
row("meetings", s.Meetings),
|
||||
row("courses", s.Courses),
|
||||
row("class_sessions", s.ClassSessions),
|
||||
row("deadlines", s.Deadlines),
|
||||
row("readings", s.Readings),
|
||||
}
|
||||
}
|
||||
|
||||
// ParseSeed decodes a seed document. Unknown fields are an error, so a typo
|
||||
// in a key never drops data silently.
|
||||
func ParseSeed(r io.Reader) (*SeedFile, error) {
|
||||
body, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
var f SeedFile
|
||||
if err := dec.Decode(&f); err != nil {
|
||||
return nil, fmt.Errorf("bm:seed: %w", err)
|
||||
}
|
||||
if dec.More() {
|
||||
return nil, errors.New("bm:seed: trailing data after the JSON document")
|
||||
}
|
||||
return &f, nil
|
||||
}
|
||||
|
||||
// Validate checks the whole document before anything is written: required
|
||||
// fields, allowed values, dates and times, duplicate identities and that
|
||||
// every course key and meeting number a record points at exists in the
|
||||
// file. Each error names the record.
|
||||
func (f *SeedFile) Validate() error {
|
||||
var errs []error
|
||||
add := func(format string, args ...any) { errs = append(errs, fmt.Errorf(format, args...)) }
|
||||
|
||||
meetings := map[int]bool{}
|
||||
for i, m := range f.Meetings {
|
||||
at := fmt.Sprintf("meetings[%d] (number %d)", i, m.Number)
|
||||
if m.Number < 1 {
|
||||
add("%s: number must be a positive integer", at)
|
||||
}
|
||||
if meetings[m.Number] {
|
||||
add("%s: duplicate meeting number", at)
|
||||
}
|
||||
meetings[m.Number] = true
|
||||
start, err1 := models.ParseDate(m.StartsOn)
|
||||
end, err2 := models.ParseDate(m.EndsOn)
|
||||
if err1 != nil {
|
||||
add("%s: starts_on: %v", at, err1)
|
||||
}
|
||||
if err2 != nil {
|
||||
add("%s: ends_on: %v", at, err2)
|
||||
}
|
||||
if err1 == nil && err2 == nil && end.Before(start) {
|
||||
add("%s: ends_on is before starts_on", at)
|
||||
}
|
||||
}
|
||||
|
||||
keys := map[string]bool{}
|
||||
identities := map[string]bool{}
|
||||
for i, c := range f.Courses {
|
||||
at := fmt.Sprintf("courses[%d] (key %q)", i, c.Key)
|
||||
if strings.TrimSpace(c.Key) == "" {
|
||||
add("%s: key is required", at)
|
||||
} else if keys[c.Key] {
|
||||
add("%s: duplicate course key", at)
|
||||
}
|
||||
keys[c.Key] = true
|
||||
if strings.TrimSpace(c.Name) == "" {
|
||||
add("%s: name is required", at)
|
||||
}
|
||||
if !slices.Contains(models.CourseForms, c.Form) {
|
||||
add("%s: form %q is not one of %s", at, c.Form, strings.Join(models.CourseForms, ", "))
|
||||
}
|
||||
if c.Semester < 1 || c.Semester > 4 {
|
||||
add("%s: semester must be between 1 and 4", at)
|
||||
}
|
||||
id := fmt.Sprintf("%s\x00%s\x00%d", c.Name, c.Form, c.Semester)
|
||||
if identities[id] {
|
||||
add("%s: another course has the same name, form and semester", at)
|
||||
}
|
||||
identities[id] = true
|
||||
}
|
||||
|
||||
sessions := map[string]bool{}
|
||||
for i, s := range f.ClassSessions {
|
||||
at := fmt.Sprintf("class_sessions[%d] (course %q, starts_at %s)", i, s.Course, s.StartsAt)
|
||||
if !keys[s.Course] {
|
||||
add("%s: unknown course key %q", at, s.Course)
|
||||
}
|
||||
if s.Meeting != nil && !meetings[*s.Meeting] {
|
||||
add("%s: unknown meeting number %d", at, *s.Meeting)
|
||||
}
|
||||
start, err1 := models.ParseDateTime(s.StartsAt)
|
||||
end, err2 := models.ParseDateTime(s.EndsAt)
|
||||
if err1 != nil {
|
||||
add("%s: starts_at: %v", at, err1)
|
||||
}
|
||||
if err2 != nil {
|
||||
add("%s: ends_at: %v", at, err2)
|
||||
}
|
||||
if err1 == nil && err2 == nil {
|
||||
if !end.After(start) {
|
||||
add("%s: ends_at is not after starts_at", at)
|
||||
}
|
||||
id := s.Course + "\x00" + start.UTC().String()
|
||||
if sessions[id] {
|
||||
add("%s: duplicate session of the course at this time", at)
|
||||
}
|
||||
sessions[id] = true
|
||||
}
|
||||
}
|
||||
|
||||
deadlines := map[string]bool{}
|
||||
for i, d := range f.Deadlines {
|
||||
at := fmt.Sprintf("deadlines[%d] (%q)", i, d.Title)
|
||||
if strings.TrimSpace(d.Title) == "" {
|
||||
add("%s: title is required", at)
|
||||
}
|
||||
if d.Course != nil && !keys[*d.Course] {
|
||||
add("%s: unknown course key %q", at, *d.Course)
|
||||
}
|
||||
if !slices.Contains(models.DeadlineKinds, d.Kind) {
|
||||
add("%s: kind %q is not one of %s", at, d.Kind, strings.Join(models.DeadlineKinds, ", "))
|
||||
}
|
||||
due, err := models.ParseDateTime(d.DueAt)
|
||||
if err != nil {
|
||||
add("%s: due_at: %v", at, err)
|
||||
continue
|
||||
}
|
||||
id := d.Title + "\x00" + due.UTC().String()
|
||||
if deadlines[id] {
|
||||
add("%s: duplicate deadline (same title and due_at)", at)
|
||||
}
|
||||
deadlines[id] = true
|
||||
}
|
||||
|
||||
readings := map[string]bool{}
|
||||
for i, r := range f.Readings {
|
||||
at := fmt.Sprintf("readings[%d] (course %q, %q)", i, r.Course, r.Title)
|
||||
if !keys[r.Course] {
|
||||
add("%s: unknown course key %q", at, r.Course)
|
||||
}
|
||||
if strings.TrimSpace(r.Title) == "" {
|
||||
add("%s: title is required", at)
|
||||
}
|
||||
id := r.Course + "\x00" + r.Title
|
||||
if readings[id] {
|
||||
add("%s: duplicate reading of the course", at)
|
||||
}
|
||||
readings[id] = true
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// Seed validates f and upserts it in one transaction: meetings by number,
|
||||
// courses by name, form and semester, class sessions by course and start
|
||||
// time, deadlines by title and due time, readings by course and title. Rows
|
||||
// absent from the file are left alone. On any error nothing is written.
|
||||
func Seed(ctx context.Context, db *gorm.DB, f *SeedFile) (SeedSummary, error) {
|
||||
var sum SeedSummary
|
||||
if err := f.Validate(); err != nil {
|
||||
return sum, err
|
||||
}
|
||||
err := lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||
meetingIDs := map[int]uint{}
|
||||
for _, in := range f.Meetings {
|
||||
m := models.Meeting{}
|
||||
created, changed, err := upsert(tx, &m, clause.Eq{Column: "number", Value: in.Number}, func(m *models.Meeting) {
|
||||
m.Number = in.Number
|
||||
start, _ := models.ParseDate(in.StartsOn)
|
||||
end, _ := models.ParseDate(in.EndsOn)
|
||||
m.StartsOn = models.NewDate(start)
|
||||
m.EndsOn = models.NewDate(end)
|
||||
m.Notes = nz(in.Notes)
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("meeting %d: %w", in.Number, err)
|
||||
}
|
||||
sum.Meetings.record(created, changed)
|
||||
meetingIDs[in.Number] = m.ID
|
||||
}
|
||||
|
||||
courseIDs := map[string]uint{}
|
||||
for _, in := range f.Courses {
|
||||
c := models.Course{}
|
||||
where := clause.And(
|
||||
clause.Eq{Column: "name", Value: in.Name},
|
||||
clause.Eq{Column: "form", Value: in.Form},
|
||||
clause.Eq{Column: "semester", Value: in.Semester},
|
||||
)
|
||||
created, changed, err := upsert(tx, &c, where, func(c *models.Course) {
|
||||
c.Code = nz(in.Code)
|
||||
c.Name = in.Name
|
||||
c.Form = in.Form
|
||||
c.Lecturer = nz(in.Lecturer)
|
||||
c.Semester = in.Semester
|
||||
c.ECTS = in.ECTS
|
||||
c.Assessment = nz(in.Assessment)
|
||||
c.ElectiveGroup = nz(in.ElectiveGroup)
|
||||
c.Description = nz(in.Description)
|
||||
c.SyllabusURL = nz(in.SyllabusURL)
|
||||
c.SortOrder = in.SortOrder
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("course %q: %w", in.Key, err)
|
||||
}
|
||||
sum.Courses.record(created, changed)
|
||||
courseIDs[in.Key] = c.ID
|
||||
}
|
||||
|
||||
for _, in := range f.ClassSessions {
|
||||
start, _ := models.ParseDateTime(in.StartsAt)
|
||||
s := models.ClassSession{}
|
||||
where := clause.And(
|
||||
clause.Eq{Column: "course_id", Value: courseIDs[in.Course]},
|
||||
clause.Eq{Column: "starts_at", Value: start.UTC()},
|
||||
)
|
||||
created, changed, err := upsert(tx, &s, where, func(s *models.ClassSession) {
|
||||
s.CourseID = courseIDs[in.Course]
|
||||
s.MeetingID = nil
|
||||
if in.Meeting != nil {
|
||||
id := meetingIDs[*in.Meeting]
|
||||
s.MeetingID = &id
|
||||
}
|
||||
s.StartsAt = models.NewDateTime(start)
|
||||
end, _ := models.ParseDateTime(in.EndsAt)
|
||||
s.EndsAt = models.NewDateTime(end)
|
||||
s.Room = nz(in.Room)
|
||||
s.Kind = nz(in.Kind)
|
||||
s.IsOnline = in.IsOnline
|
||||
s.Notes = nz(in.Notes)
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("class session %s %s: %w", in.Course, in.StartsAt, err)
|
||||
}
|
||||
sum.ClassSessions.record(created, changed)
|
||||
}
|
||||
|
||||
for _, in := range f.Deadlines {
|
||||
due, _ := models.ParseDateTime(in.DueAt)
|
||||
d := models.Deadline{}
|
||||
where := clause.And(
|
||||
clause.Eq{Column: "title", Value: in.Title},
|
||||
clause.Eq{Column: "due_at", Value: due.UTC()},
|
||||
)
|
||||
created, changed, err := upsert(tx, &d, where, func(d *models.Deadline) {
|
||||
d.Title = in.Title
|
||||
d.DueAt = models.NewDateTime(due)
|
||||
d.CourseID = nil
|
||||
if in.Course != nil {
|
||||
id := courseIDs[*in.Course]
|
||||
d.CourseID = &id
|
||||
}
|
||||
d.Kind = in.Kind
|
||||
d.Description = nz(in.Description)
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("deadline %q: %w", in.Title, err)
|
||||
}
|
||||
sum.Deadlines.record(created, changed)
|
||||
}
|
||||
|
||||
for _, in := range f.Readings {
|
||||
r := models.Reading{}
|
||||
where := clause.And(
|
||||
clause.Eq{Column: "course_id", Value: courseIDs[in.Course]},
|
||||
clause.Eq{Column: "title", Value: in.Title},
|
||||
)
|
||||
created, changed, err := upsert(tx, &r, where, func(r *models.Reading) {
|
||||
r.CourseID = courseIDs[in.Course]
|
||||
r.Title = in.Title
|
||||
r.Author = nz(in.Author)
|
||||
r.Source = nz(in.Source)
|
||||
r.URL = nz(in.URL)
|
||||
r.IsRequired = in.IsRequired
|
||||
r.SortOrder = in.SortOrder
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("reading %q of %s: %w", in.Title, in.Course, err)
|
||||
}
|
||||
sum.Readings.record(created, changed)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return SeedSummary{}, err
|
||||
}
|
||||
return sum, nil
|
||||
}
|
||||
|
||||
// nz returns nil for a missing or blank optional text, as the models'
|
||||
// BeforeSave hooks store it, so an unchanged row compares equal.
|
||||
func nz(s *string) *string {
|
||||
if s == nil || strings.TrimSpace(*s) == "" {
|
||||
return nil
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// upsert loads the row matching where into row, applies set and writes it:
|
||||
// an insert when there was no row, an update when set changed a column, and
|
||||
// nothing otherwise. The comparison is on the row's own fields, before and
|
||||
// after set, as JSON.
|
||||
func upsert[T any](tx *gorm.DB, row *T, where clause.Expression, set func(*T)) (created, changed bool, err error) {
|
||||
res := tx.Clauses(where).Limit(1).Find(row)
|
||||
if res.Error != nil {
|
||||
return false, false, res.Error
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
set(row)
|
||||
return true, false, tx.Create(row).Error
|
||||
}
|
||||
before, err := json.Marshal(row)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
set(row)
|
||||
after, err := json.Marshal(row)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
if bytes.Equal(before, after) {
|
||||
return false, false, nil
|
||||
}
|
||||
return false, true, tx.Save(row).Error
|
||||
}
|
||||
117
classes/seed_test.go
Normal file
117
classes/seed_test.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package classes_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/jakub/sm-bm-plugin/classes"
|
||||
)
|
||||
|
||||
func parse(t *testing.T, doc string) *classes.SeedFile {
|
||||
t.Helper()
|
||||
f, err := classes.ParseSeed(strings.NewReader(doc))
|
||||
if err != nil {
|
||||
t.Fatalf("ParseSeed: %v", err)
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func TestExampleFixtureIsValid(t *testing.T) {
|
||||
fh, err := os.Open("../testdata/seed.example.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer fh.Close()
|
||||
f, err := classes.ParseSeed(fh)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Validate(); err != nil {
|
||||
t.Fatalf("Validate: %v", err)
|
||||
}
|
||||
if len(f.Meetings) != 2 || len(f.Courses) != 3 || len(f.ClassSessions) != 3 || len(f.Deadlines) != 2 || len(f.Readings) != 2 {
|
||||
t.Errorf("fixture counts = %d %d %d %d %d", len(f.Meetings), len(f.Courses), len(f.ClassSessions), len(f.Deadlines), len(f.Readings))
|
||||
}
|
||||
if f.Courses[2].ElectiveGroup == nil || *f.Courses[2].ElectiveGroup != "przyklad-do-wyboru" {
|
||||
t.Errorf("elective_group = %v", f.Courses[2].ElectiveGroup)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyDocumentIsValid(t *testing.T) {
|
||||
if err := parse(t, `{}`).Validate(); err != nil {
|
||||
t.Errorf("{}: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsUnknownFieldsAndTrailingData(t *testing.T) {
|
||||
for _, doc := range []string{
|
||||
`{"courses": [{"key": "a", "nmae": "typo"}]}`,
|
||||
`{"lectures": []}`,
|
||||
`{} {}`,
|
||||
`[]`,
|
||||
`{"meetings": [{"number": "one"}]}`,
|
||||
} {
|
||||
if _, err := classes.ParseSeed(strings.NewReader(doc)); err == nil {
|
||||
t.Errorf("ParseSeed(%s) accepted", doc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateNamesTheRecord(t *testing.T) {
|
||||
cases := []struct {
|
||||
doc string
|
||||
want []string
|
||||
}{
|
||||
{`{"class_sessions": [{"course": "ghost", "starts_at": "2030-10-05T08:00:00+02:00", "ends_at": "2030-10-05T09:00:00+02:00"}]}`,
|
||||
[]string{`class_sessions[0]`, `unknown course key "ghost"`}},
|
||||
{`{"courses": [{"key": "a", "name": "A", "form": "wyklad", "semester": 1}],
|
||||
"class_sessions": [{"course": "a", "meeting": 9, "starts_at": "2030-10-05T08:00:00+02:00", "ends_at": "2030-10-05T09:00:00+02:00"}]}`,
|
||||
[]string{`unknown meeting number 9`}},
|
||||
{`{"deadlines": [{"title": "X", "due_at": "2030-10-05T08:00:00+02:00", "course": "nope", "kind": "inne"}]}`,
|
||||
[]string{`deadlines[0] ("X")`, `unknown course key "nope"`}},
|
||||
{`{"readings": [{"course": "nope", "title": "Book"}]}`,
|
||||
[]string{`readings[0]`, `unknown course key "nope"`}},
|
||||
{`{"courses": [{"key": "a", "name": "A", "form": "lecture", "semester": 7}]}`,
|
||||
[]string{`form "lecture"`, `semester must be between 1 and 4`}},
|
||||
{`{"courses": [{"key": "a", "name": "A", "form": "wyklad", "semester": 1}, {"key": "a", "name": "A", "form": "wyklad", "semester": 1}]}`,
|
||||
[]string{`duplicate course key`, `same name, form and semester`}},
|
||||
{`{"meetings": [{"number": 1, "starts_on": "2030-10-06", "ends_on": "2030-10-05"}, {"number": 1, "starts_on": "05.10.2030", "ends_on": "2030-10-05"}]}`,
|
||||
[]string{`ends_on is before starts_on`, `duplicate meeting number`, `starts_on`}},
|
||||
{`{"courses": [{"key": "a", "name": "A", "form": "wyklad", "semester": 1}],
|
||||
"class_sessions": [{"course": "a", "starts_at": "2030-10-05 10:00", "ends_at": "2030-10-05 09:00"}]}`,
|
||||
[]string{`ends_at is not after starts_at`}},
|
||||
{`{"deadlines": [{"title": "", "due_at": "soon", "kind": "deadline"}]}`,
|
||||
[]string{`title is required`, `due_at`, `kind "deadline"`}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
err := parse(t, tc.doc).Validate()
|
||||
if err == nil {
|
||||
t.Errorf("Validate(%s) passed", tc.doc)
|
||||
continue
|
||||
}
|
||||
for _, want := range tc.want {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("Validate(%s) = %q, want it to mention %q", tc.doc, err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedValidatesBeforeTouchingTheDatabase(t *testing.T) {
|
||||
f := parse(t, `{"readings": [{"course": "ghost", "title": "Book"}]}`)
|
||||
// A nil database would panic if Seed reached it.
|
||||
if _, err := classes.Seed(t.Context(), nil, f); err == nil || !strings.Contains(err.Error(), "ghost") {
|
||||
t.Errorf("Seed = %v, want the unknown course error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummaryRows(t *testing.T) {
|
||||
var s classes.SeedSummary
|
||||
s.Courses.Created = 2
|
||||
s.Readings.Unchanged = 1
|
||||
rows := s.Rows()
|
||||
if len(rows) != 5 || rows[1][0] != "courses" || rows[1][1] != "2" || rows[4][3] != "1" {
|
||||
t.Errorf("Rows = %v", rows)
|
||||
}
|
||||
}
|
||||
@@ -1 +1,7 @@
|
||||
{}
|
||||
# Defaults for jz.bm, merged under the plugin ID: the application reads them
|
||||
# as jz.bm.<key> and can override them in its own config.
|
||||
|
||||
# Default page size of GET /_bm/api/v1/materials (clamped to 1..100).
|
||||
materials_per_page: 20
|
||||
# Number of class sessions and deadlines on GET /_bm/api/v1/dashboard.
|
||||
dashboard_limit: 5
|
||||
|
||||
58
console/seed.go
Normal file
58
console/seed.go
Normal file
@@ -0,0 +1,58 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package console
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/classes"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SeedCommand returns the bm:seed console command. withDB runs the
|
||||
// command's work with the application's database; the plugin supplies it.
|
||||
func SeedCommand(withDB func(ctx context.Context, fn func(*gorm.DB) error) error) bonfire.Command {
|
||||
return bonfire.Command{
|
||||
Name: "bm:seed",
|
||||
Description: "Upsert meetings, courses, class sessions, deadlines and readings from a JSON file",
|
||||
Args: []bonfire.Arg{{Name: "file", Description: "Path of the seed JSON file", Required: true}},
|
||||
Flags: []bonfire.Flag{
|
||||
{Name: "dry-run", Description: "Validate the file without writing", Bare: true},
|
||||
},
|
||||
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
||||
path, _ := in.Argument("file")
|
||||
if path == "" {
|
||||
return fmt.Errorf("bm:seed: a file is required")
|
||||
}
|
||||
fh, err := os.Open(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bm:seed: %w", err)
|
||||
}
|
||||
defer fh.Close()
|
||||
file, err := classes.ParseSeed(fh)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Validate(); err != nil {
|
||||
return fmt.Errorf("bm:seed: %s is not valid, nothing was written:\n%w", path, err)
|
||||
}
|
||||
if dry, _ := in.Flag("dry-run"); dry == "true" {
|
||||
out.Success(fmt.Sprintf("%s is valid: %d meetings, %d courses, %d class sessions, %d deadlines, %d readings", path,
|
||||
len(file.Meetings), len(file.Courses), len(file.ClassSessions), len(file.Deadlines), len(file.Readings)))
|
||||
return nil
|
||||
}
|
||||
return withDB(ctx, func(db *gorm.DB) error {
|
||||
sum, err := classes.Seed(ctx, db, file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("bm:seed: nothing was written: %w", err)
|
||||
}
|
||||
out.Table([]string{"kind", "created", "updated", "unchanged"}, sum.Rows())
|
||||
out.Success("bm:seed: " + path + " applied")
|
||||
return nil
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
69
console/seed_test.go
Normal file
69
console/seed_test.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package console_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/console"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestSeedCommandShape(t *testing.T) {
|
||||
cmd := console.SeedCommand(nil)
|
||||
if cmd.Name != "bm:seed" || cmd.Description == "" {
|
||||
t.Errorf("command = %q %q", cmd.Name, cmd.Description)
|
||||
}
|
||||
if len(cmd.Args) != 1 || cmd.Args[0].Name != "file" || !cmd.Args[0].Required {
|
||||
t.Errorf("Args = %+v, want one required file argument", cmd.Args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeedCommandChecksTheFileBeforeTheDatabase(t *testing.T) {
|
||||
called := false
|
||||
withDB := func(ctx context.Context, fn func(*gorm.DB) error) error {
|
||||
called = true
|
||||
return errors.New("no database in this test")
|
||||
}
|
||||
cmds := []bonfire.Command{console.SeedCommand(withDB)}
|
||||
dir := t.TempDir()
|
||||
invalid := filepath.Join(dir, "invalid.json")
|
||||
if err := os.WriteFile(invalid, []byte(`{"readings": [{"course": "ghost", "title": "X"}]}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broken := filepath.Join(dir, "broken.json")
|
||||
if err := os.WriteFile(broken, []byte(`{"courses": [`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
for _, args := range [][]string{nil, {filepath.Join(dir, "missing.json")}, {broken}, {invalid}} {
|
||||
if err := bonfire.Call(context.Background(), cmds, "bm:seed", args, &out); err == nil {
|
||||
t.Errorf("bm:seed %v succeeded", args)
|
||||
}
|
||||
}
|
||||
err := bonfire.Call(context.Background(), cmds, "bm:seed", []string{invalid}, &out)
|
||||
if err == nil || !strings.Contains(err.Error(), "nothing was written") || !strings.Contains(err.Error(), "ghost") {
|
||||
t.Errorf("invalid file error = %v", err)
|
||||
}
|
||||
if called {
|
||||
t.Error("bm:seed reached the database with an invalid file")
|
||||
}
|
||||
|
||||
out.Reset()
|
||||
if err := bonfire.Call(context.Background(), cmds, "bm:seed", []string{"../testdata/seed.example.json", "--dry-run"}, &out); err != nil {
|
||||
t.Fatalf("dry run: %v", err)
|
||||
}
|
||||
if called || !strings.Contains(out.String(), "3 courses") {
|
||||
t.Errorf("dry run called=%v output %q", called, out.String())
|
||||
}
|
||||
|
||||
err = bonfire.Call(context.Background(), cmds, "bm:seed", []string{"../testdata/seed.example.json"}, &out)
|
||||
if !called || err == nil {
|
||||
t.Errorf("valid file: called=%v err=%v, want the withDB error", called, err)
|
||||
}
|
||||
}
|
||||
35
controllers/admin_test.go
Normal file
35
controllers/admin_test.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
func TestTemporalHooksAnswerOnTheField(t *testing.T) {
|
||||
var hooks temporalHooks
|
||||
bad := &models.ClassSession{StartsAt: "2026-10-03 08:00", EndsAt: "wtorek"}
|
||||
for name, fn := range map[string]func(context.Context, any) error{
|
||||
"create": hooks.FormBeforeCreate,
|
||||
"update": hooks.FormBeforeUpdate,
|
||||
} {
|
||||
err := fn(context.Background(), bad)
|
||||
var ve *cabana.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("%s: err = %v, want a cabana.ValidationError", name, err)
|
||||
}
|
||||
if _, ok := ve.Details["ends_at"]; !ok {
|
||||
t.Errorf("%s: details %v name no ends_at", name, ve.Details)
|
||||
}
|
||||
}
|
||||
good := &models.ClassSession{StartsAt: "2026-10-03 08:00", EndsAt: "2026-10-03 09:30"}
|
||||
if err := hooks.FormBeforeCreate(context.Background(), good); err != nil {
|
||||
t.Errorf("valid session: %v", err)
|
||||
}
|
||||
if err := hooks.FormBeforeUpdate(context.Background(), &models.Tag{}); err != nil {
|
||||
t.Errorf("model without dates: %v", err)
|
||||
}
|
||||
}
|
||||
122
controllers/api/api.go
Normal file
122
controllers/api/api.go
Normal file
@@ -0,0 +1,122 @@
|
||||
// Package api holds the student-facing JSON handlers of the jz.bm plugin,
|
||||
// served under /_bm/api/v1 behind the golem15.user jwt.auth guard.
|
||||
//
|
||||
// Every response is built field by field and wrapped in {"data": ...}; a
|
||||
// paginated list adds {"meta": ...}. Timestamps are RFC 3339 in
|
||||
// Europe/Warsaw, dates are YYYY-MM-DD.
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||
"git.golem15.com/golem15/summercms/modules/wire"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Handlers serves the API. The plugin builds it in Routes; tests build it
|
||||
// with their own database and clock.
|
||||
type Handlers struct {
|
||||
// DB returns the application database, or nil while none is published.
|
||||
// It is resolved per request: the binary boots plugins before serve
|
||||
// publishes the database.
|
||||
DB func() *gorm.DB
|
||||
// Translator returns the application translator for validation
|
||||
// messages; nil gives English.
|
||||
Translator func() *phrasebook.Translator
|
||||
// Now is the clock; nil means time.Now.
|
||||
Now func() time.Time
|
||||
// PerPage is the default page size of /materials.
|
||||
PerPage int
|
||||
// DashboardLimit is the number of sessions and deadlines on /dashboard.
|
||||
DashboardLimit int
|
||||
}
|
||||
|
||||
func (h *Handlers) now() time.Time {
|
||||
if h.Now != nil {
|
||||
return h.Now()
|
||||
}
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func (h *Handlers) perPage() int {
|
||||
if h.PerPage > 0 {
|
||||
return min(h.PerPage, maxPerPage)
|
||||
}
|
||||
return defaultPerPage
|
||||
}
|
||||
|
||||
func (h *Handlers) dashboardLimit() int {
|
||||
if h.DashboardLimit > 0 {
|
||||
return h.DashboardLimit
|
||||
}
|
||||
return 5
|
||||
}
|
||||
|
||||
func (h *Handlers) translator() *phrasebook.Translator {
|
||||
if h.Translator == nil {
|
||||
return nil
|
||||
}
|
||||
return h.Translator()
|
||||
}
|
||||
|
||||
const (
|
||||
defaultPerPage = 20
|
||||
maxPerPage = 100
|
||||
)
|
||||
|
||||
// caller returns the signed-in user's ID. It answers 401 itself and returns
|
||||
// false when there is none (the jwt.auth guard normally answers first).
|
||||
func (h *Handlers) caller(w http.ResponseWriter, r *http.Request) (uint, bool) {
|
||||
user, ok := bouncer.User(r.Context())
|
||||
if !ok || user == nil || user.ID == 0 {
|
||||
wire.WriteJSON(w, http.StatusUnauthorized, map[string]any{"error": true, "message": "Unauthenticated."})
|
||||
return 0, false
|
||||
}
|
||||
return user.ID, true
|
||||
}
|
||||
|
||||
// db returns the database bound to the request context. It answers 503
|
||||
// itself and returns false while no database is published.
|
||||
func (h *Handlers) db(w http.ResponseWriter, r *http.Request) (*gorm.DB, bool) {
|
||||
var db *gorm.DB
|
||||
if h.DB != nil {
|
||||
db = h.DB()
|
||||
}
|
||||
if db == nil {
|
||||
wire.WriteJSON(w, http.StatusServiceUnavailable, map[string]any{"error": true, "message": "Database unavailable."})
|
||||
return nil, false
|
||||
}
|
||||
return db.WithContext(r.Context()), true
|
||||
}
|
||||
|
||||
func writeData(w http.ResponseWriter, v any) {
|
||||
wire.WriteJSON(w, http.StatusOK, map[string]any{"data": v})
|
||||
}
|
||||
|
||||
func writeNotFound(w http.ResponseWriter) {
|
||||
wire.WriteJSON(w, http.StatusNotFound, map[string]any{"error": true, "message": "Not found."})
|
||||
}
|
||||
|
||||
// writeValidation answers 422 with Laravel's validation body: the first
|
||||
// message and the errors object from lagoon.ValidateRequest.
|
||||
func writeValidation(w http.ResponseWriter, errs map[string][]string) {
|
||||
keys := make([]string, 0, len(errs))
|
||||
for k := range errs {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
message := "The given data was invalid."
|
||||
if len(keys) > 0 && len(errs[keys[0]]) > 0 {
|
||||
message = errs[keys[0]][0]
|
||||
}
|
||||
wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{"message": message, "errors": errs})
|
||||
}
|
||||
|
||||
func writeOpaque500(w http.ResponseWriter) { wire.WriteOpaque500(w) }
|
||||
|
||||
// writeJSONPage writes a lagoon.Page as it is: {data, meta}.
|
||||
func writeJSONPage(w http.ResponseWriter, page any) { wire.WriteJSON(w, http.StatusOK, page) }
|
||||
118
controllers/api/courses.go
Normal file
118
controllers/api/courses.go
Normal file
@@ -0,0 +1,118 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// courseRow is a course with its counters, as the counting query returns it.
|
||||
type courseRow struct {
|
||||
models.Course `gorm:"embedded"`
|
||||
SessionsCount int64 `gorm:"column:sessions_count"`
|
||||
ReadingsCount int64 `gorm:"column:readings_count"`
|
||||
ReadingsRead int64 `gorm:"column:readings_read"`
|
||||
MaterialsCount int64 `gorm:"column:materials_count"`
|
||||
}
|
||||
|
||||
func (c courseRow) counts() courseCounts {
|
||||
return courseCounts{Sessions: c.SessionsCount, Readings: c.ReadingsCount, ReadingsRead: c.ReadingsRead, Materials: c.MaterialsCount}
|
||||
}
|
||||
|
||||
// coursesWithCounts selects courses with their session, reading and
|
||||
// published material counts and the caller's read readings.
|
||||
func coursesWithCounts(db *gorm.DB, userID uint, now time.Time) *gorm.DB {
|
||||
return db.Table("jz_bm_courses AS c").Select(`c.*,
|
||||
(SELECT COUNT(*) FROM jz_bm_class_sessions s WHERE s.course_id = c.id) AS sessions_count,
|
||||
(SELECT COUNT(*) FROM jz_bm_readings r WHERE r.course_id = c.id) AS readings_count,
|
||||
(SELECT COUNT(*) FROM jz_bm_reading_progress p JOIN jz_bm_readings r ON r.id = p.reading_id
|
||||
WHERE r.course_id = c.id AND p.user_id = ?) AS readings_read,
|
||||
(SELECT COUNT(*) FROM jz_bm_materials m WHERE m.course_id = c.id
|
||||
AND m.published_at IS NOT NULL AND m.published_at <= ?) AS materials_count`, userID, now.UTC())
|
||||
}
|
||||
|
||||
// Courses answers GET /courses?semester=N: every course in programme order
|
||||
// with its counters.
|
||||
func (h *Handlers) Courses(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.caller(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
in := query(r, "semester")
|
||||
if !h.validate(w, r, in, coursesRules) {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := coursesWithCounts(db, userID, h.now())
|
||||
if semester := intParam(in, "semester", 0); semester != 0 {
|
||||
q = q.Where("c.semester = ?", semester)
|
||||
}
|
||||
var rows []courseRow
|
||||
if err := q.Order("c.semester, c.sort_order, c.name, c.id").Scan(&rows).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
out := make([]courseListJSON, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
out = append(out, courseListJSON{courseJSON: newCourseJSON(row.Course), Counts: row.counts()})
|
||||
}
|
||||
writeData(w, out)
|
||||
}
|
||||
|
||||
// Course answers GET /courses/{id}: the course with its counters, all its
|
||||
// class sessions, its readings with the caller's read state and its
|
||||
// published materials.
|
||||
func (h *Handlers) Course(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.caller(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := surf.IntParam(r, "id")
|
||||
if !ok {
|
||||
writeNotFound(w)
|
||||
return
|
||||
}
|
||||
now := h.now()
|
||||
var rows []courseRow
|
||||
if err := coursesWithCounts(db, userID, now).Where("c.id = ?", id).Limit(1).Scan(&rows).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
writeNotFound(w)
|
||||
return
|
||||
}
|
||||
row := rows[0]
|
||||
var sessions []models.ClassSession
|
||||
if err := preloadSession(db).Where("course_id = ?", row.ID).Order("starts_at, id").Find(&sessions).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
readings, err := listReadings(db, userID, row.ID)
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
materials, err := publishedMaterialsOfCourse(db, now, row.ID)
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeData(w, courseDetailJSON{
|
||||
courseJSON: newCourseJSON(row.Course),
|
||||
Counts: row.counts(),
|
||||
Sessions: newSessionsJSON(sessions),
|
||||
Readings: readings,
|
||||
Materials: materials,
|
||||
})
|
||||
}
|
||||
88
controllers/api/dashboard.go
Normal file
88
controllers/api/dashboard.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// dashboardJSON is the answer of /dashboard.
|
||||
type dashboardJSON struct {
|
||||
NextSessions []sessionJSON `json:"next_sessions"`
|
||||
UpcomingDeadlines []deadlineJSON `json:"upcoming_deadlines"`
|
||||
CurrentMeeting *meetingJSON `json:"current_meeting"`
|
||||
NextMeeting *meetingJSON `json:"next_meeting"`
|
||||
Readings readingsSummary `json:"readings"`
|
||||
}
|
||||
|
||||
// Dashboard answers GET /dashboard: the next class sessions (those not yet
|
||||
// over), the deadlines not yet due, the meeting under way today and the next
|
||||
// one, and the caller's reading progress.
|
||||
func (h *Handlers) Dashboard(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.caller(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
now := h.now().UTC()
|
||||
limit := h.dashboardLimit()
|
||||
out := dashboardJSON{}
|
||||
|
||||
var sessions []models.ClassSession
|
||||
if err := preloadSession(db).Where("ends_at > ?", now).Order("starts_at, id").Limit(limit).Find(&sessions).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
out.NextSessions = newSessionsJSON(sessions)
|
||||
|
||||
var deadlines []models.Deadline
|
||||
if err := db.Preload("Course").Where("due_at >= ?", now).Order("due_at, id").Limit(limit).Find(&deadlines).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
out.UpcomingDeadlines = newDeadlinesJSON(deadlines)
|
||||
|
||||
day := today(h.now()).Format(models.DateLayout)
|
||||
var err error
|
||||
if out.CurrentMeeting, err = meetingWhere(db, "starts_on <= ? AND ends_on >= ?", day, day); err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
if out.NextMeeting, err = meetingWhere(db, "starts_on > ?", day); err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
|
||||
err = db.Raw(`SELECT
|
||||
COUNT(*) AS total,
|
||||
COUNT(p.id) AS read,
|
||||
COUNT(*) FILTER (WHERE r.is_required) AS required_total,
|
||||
COUNT(p.id) FILTER (WHERE r.is_required) AS required_read
|
||||
FROM jz_bm_readings r
|
||||
LEFT JOIN jz_bm_reading_progress p ON p.reading_id = r.id AND p.user_id = ?`, userID).Scan(&out.Readings).Error
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeData(w, out)
|
||||
}
|
||||
|
||||
// meetingWhere returns the first meeting by start date that matches the
|
||||
// condition, with its session count, or nil.
|
||||
func meetingWhere(db *gorm.DB, cond string, args ...any) (*meetingJSON, error) {
|
||||
var m models.Meeting
|
||||
res := db.Where(cond, args...).Order("starts_on, number").Limit(1).Find(&m)
|
||||
if res.Error != nil || res.RowsAffected == 0 {
|
||||
return nil, res.Error
|
||||
}
|
||||
var sessions int64
|
||||
if err := db.Model(&models.ClassSession{}).Where("meeting_id = ?", m.ID).Count(&sessions).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := newMeetingJSON(m, sessions)
|
||||
return &out, nil
|
||||
}
|
||||
144
controllers/api/handlers_test.go
Normal file
144
controllers/api/handlers_test.go
Normal file
@@ -0,0 +1,144 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/controllers/api"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// noDB is a Handlers whose database is never published, so a request that
|
||||
// gets past authentication and validation answers 503.
|
||||
func noDB() *api.Handlers {
|
||||
return &api.Handlers{DB: func() *gorm.DB { return nil }}
|
||||
}
|
||||
|
||||
func serve(t *testing.T, h http.HandlerFunc, method, target string, user *bouncer.Principal, pathValues map[string]string) (int, map[string]any) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, target, nil)
|
||||
if user != nil {
|
||||
req = req.WithContext(bouncer.WithUser(req.Context(), user))
|
||||
}
|
||||
for k, v := range pathValues {
|
||||
req.SetPathValue(k, v)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h(rec, req)
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("%s %s: body is not JSON: %v\n%s", method, target, err, rec.Body.String())
|
||||
}
|
||||
return rec.Code, body
|
||||
}
|
||||
|
||||
func handlers(h *api.Handlers) map[string]http.HandlerFunc {
|
||||
return map[string]http.HandlerFunc{
|
||||
"dashboard": h.Dashboard,
|
||||
"courses": h.Courses,
|
||||
"course": h.Course,
|
||||
"schedule": h.Schedule,
|
||||
"meetings": h.Meetings,
|
||||
"deadlines": h.Deadlines,
|
||||
"readings": h.Readings,
|
||||
"mark": h.MarkRead,
|
||||
"unmark": h.UnmarkRead,
|
||||
"materials": h.Materials,
|
||||
"material": h.Material,
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryHandlerNeedsACaller(t *testing.T) {
|
||||
for name, fn := range handlers(noDB()) {
|
||||
code, body := serve(t, fn, http.MethodGet, "/", nil, map[string]string{"id": "1"})
|
||||
if code != http.StatusUnauthorized || body["error"] != true {
|
||||
t.Errorf("%s without a principal = %d %v, want 401", name, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryHandlerNeedsADatabase(t *testing.T) {
|
||||
user := &bouncer.Principal{ID: 7}
|
||||
for name, fn := range handlers(noDB()) {
|
||||
code, body := serve(t, fn, http.MethodGet, "/", user, map[string]string{"id": "1"})
|
||||
if code != http.StatusServiceUnavailable {
|
||||
t.Errorf("%s without a database = %d %v, want 503", name, code, body)
|
||||
}
|
||||
}
|
||||
// A nil DB func is the same as an unpublished database.
|
||||
code, _ := serve(t, (&api.Handlers{}).Meetings, http.MethodGet, "/", user, nil)
|
||||
if code != http.StatusServiceUnavailable {
|
||||
t.Errorf("nil DB func = %d, want 503", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQueryValidation(t *testing.T) {
|
||||
h := noDB()
|
||||
user := &bouncer.Principal{ID: 7}
|
||||
cases := []struct {
|
||||
name string
|
||||
fn http.HandlerFunc
|
||||
target string
|
||||
field string
|
||||
}{
|
||||
{"schedule from not a date", h.Schedule, "/?from=jutro", "from"},
|
||||
{"schedule from impossible date", h.Schedule, "/?from=2026-02-30", "from"},
|
||||
{"schedule from not ISO", h.Schedule, "/?from=03.10.2026", "from"},
|
||||
{"schedule to before from", h.Schedule, "/?from=2026-10-10&to=2026-10-01", "to"},
|
||||
{"deadlines to not a date", h.Deadlines, "/?to=10/01/2026", "to"},
|
||||
{"readings course not a number", h.Readings, "/?course=abc", "course"},
|
||||
{"readings course zero", h.Readings, "/?course=0", "course"},
|
||||
{"courses semester out of range", h.Courses, "/?semester=9", "semester"},
|
||||
{"materials type unknown", h.Materials, "/?type=video", "type"},
|
||||
{"materials page zero", h.Materials, "/?page=0", "page"},
|
||||
{"materials per_page too large", h.Materials, "/?per_page=1000", "per_page"},
|
||||
{"materials course negative", h.Materials, "/?course=-1", "course"},
|
||||
{"materials tag too long", h.Materials, "/?tag=" + longTag(), "tag"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
code, body := serve(t, tc.fn, http.MethodGet, tc.target, user, nil)
|
||||
if code != http.StatusUnprocessableEntity {
|
||||
t.Errorf("%s: status %d %v, want 422", tc.name, code, body)
|
||||
continue
|
||||
}
|
||||
errs, _ := body["errors"].(map[string]any)
|
||||
if msgs, _ := errs[tc.field].([]any); len(msgs) == 0 {
|
||||
t.Errorf("%s: errors %v have no %s message", tc.name, errs, tc.field)
|
||||
}
|
||||
if msg, _ := body["message"].(string); msg == "" {
|
||||
t.Errorf("%s: no message in %v", tc.name, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func longTag() string {
|
||||
b := make([]byte, 101)
|
||||
for i := range b {
|
||||
b[i] = 'a'
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestValidQueriesReachTheDatabase(t *testing.T) {
|
||||
h := noDB()
|
||||
user := &bouncer.Principal{ID: 7}
|
||||
for _, tc := range []struct {
|
||||
fn http.HandlerFunc
|
||||
target string
|
||||
}{
|
||||
{h.Schedule, "/?from=2026-10-01&to=2026-10-31"},
|
||||
{h.Schedule, "/?to=2026-10-31"},
|
||||
{h.Schedule, "/?from=2026-10-01&to=2026-10-01"},
|
||||
{h.Deadlines, "/"},
|
||||
{h.Readings, "/?course=3"},
|
||||
{h.Courses, "/?semester=2"},
|
||||
{h.Materials, "/?course=1&tag=geopolityka&type=pdf&page=2&per_page=10"},
|
||||
} {
|
||||
if code, body := serve(t, tc.fn, http.MethodGet, tc.target, user, nil); code != http.StatusServiceUnavailable {
|
||||
t.Errorf("%s = %d %v, want to pass validation (503 without a database)", tc.target, code, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
242
controllers/api/json.go
Normal file
242
controllers/api/json.go
Normal file
@@ -0,0 +1,242 @@
|
||||
package api
|
||||
|
||||
import "git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
|
||||
// courseRef is the short form of a course embedded in other records.
|
||||
type courseRef struct {
|
||||
ID uint `json:"id"`
|
||||
Code *string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Form string `json:"form"`
|
||||
Semester int `json:"semester"`
|
||||
}
|
||||
|
||||
func newCourseRef(c *models.Course) *courseRef {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
return &courseRef{ID: c.ID, Code: c.Code, Name: c.Name, Form: c.Form, Semester: c.Semester}
|
||||
}
|
||||
|
||||
// courseJSON is a course's own fields.
|
||||
type courseJSON struct {
|
||||
ID uint `json:"id"`
|
||||
Code *string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Form string `json:"form"`
|
||||
Lecturer *string `json:"lecturer"`
|
||||
Semester int `json:"semester"`
|
||||
ECTS *float64 `json:"ects"`
|
||||
Assessment *string `json:"assessment"`
|
||||
ElectiveGroup *string `json:"elective_group"`
|
||||
Description *string `json:"description"`
|
||||
SyllabusURL *string `json:"syllabus_url"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
||||
func newCourseJSON(c models.Course) courseJSON {
|
||||
return courseJSON{
|
||||
ID: c.ID,
|
||||
Code: c.Code,
|
||||
Name: c.Name,
|
||||
Form: c.Form,
|
||||
Lecturer: c.Lecturer,
|
||||
Semester: c.Semester,
|
||||
ECTS: c.ECTS,
|
||||
Assessment: c.Assessment,
|
||||
ElectiveGroup: c.ElectiveGroup,
|
||||
Description: c.Description,
|
||||
SyllabusURL: c.SyllabusURL,
|
||||
SortOrder: c.SortOrder,
|
||||
}
|
||||
}
|
||||
|
||||
// courseCounts are the per-course counters of /courses and /courses/{id}.
|
||||
type courseCounts struct {
|
||||
Sessions int64 `json:"sessions"`
|
||||
Readings int64 `json:"readings"`
|
||||
ReadingsRead int64 `json:"readings_read"`
|
||||
Materials int64 `json:"materials"`
|
||||
}
|
||||
|
||||
type courseListJSON struct {
|
||||
courseJSON
|
||||
Counts courseCounts `json:"counts"`
|
||||
}
|
||||
|
||||
type courseDetailJSON struct {
|
||||
courseJSON
|
||||
Counts courseCounts `json:"counts"`
|
||||
Sessions []sessionJSON `json:"sessions"`
|
||||
Readings []readingJSON `json:"readings"`
|
||||
Materials []materialListJSON `json:"materials"`
|
||||
}
|
||||
|
||||
// meetingJSON is one zjazd.
|
||||
type meetingJSON struct {
|
||||
ID uint `json:"id"`
|
||||
Number int `json:"number"`
|
||||
StartsOn string `json:"starts_on"`
|
||||
EndsOn string `json:"ends_on"`
|
||||
Notes *string `json:"notes"`
|
||||
SessionsCount int64 `json:"sessions_count"`
|
||||
}
|
||||
|
||||
func newMeetingJSON(m models.Meeting, sessions int64) meetingJSON {
|
||||
return meetingJSON{ID: m.ID, Number: m.Number, StartsOn: string(m.StartsOn), EndsOn: string(m.EndsOn), Notes: m.Notes, SessionsCount: sessions}
|
||||
}
|
||||
|
||||
// sessionJSON is one class session with its course.
|
||||
type sessionJSON struct {
|
||||
ID uint `json:"id"`
|
||||
CourseID uint `json:"course_id"`
|
||||
MeetingID *uint `json:"meeting_id"`
|
||||
MeetingNumber *int `json:"meeting_number"`
|
||||
StartsAt string `json:"starts_at"`
|
||||
EndsAt string `json:"ends_at"`
|
||||
Room *string `json:"room"`
|
||||
Kind *string `json:"kind"`
|
||||
Notes *string `json:"notes"`
|
||||
IsOnline bool `json:"is_online"`
|
||||
Course *courseRef `json:"course"`
|
||||
}
|
||||
|
||||
func newSessionJSON(s models.ClassSession) sessionJSON {
|
||||
out := sessionJSON{
|
||||
ID: s.ID,
|
||||
CourseID: s.CourseID,
|
||||
MeetingID: s.MeetingID,
|
||||
StartsAt: string(s.StartsAt),
|
||||
EndsAt: string(s.EndsAt),
|
||||
Room: s.Room,
|
||||
Kind: s.Kind,
|
||||
Notes: s.Notes,
|
||||
IsOnline: s.IsOnline,
|
||||
Course: newCourseRef(s.Course),
|
||||
}
|
||||
if s.Meeting != nil {
|
||||
n := s.Meeting.Number
|
||||
out.MeetingNumber = &n
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func newSessionsJSON(rows []models.ClassSession) []sessionJSON {
|
||||
out := make([]sessionJSON, 0, len(rows))
|
||||
for _, s := range rows {
|
||||
out = append(out, newSessionJSON(s))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// deadlineJSON is one terminarz entry.
|
||||
type deadlineJSON struct {
|
||||
ID uint `json:"id"`
|
||||
Title string `json:"title"`
|
||||
DueAt string `json:"due_at"`
|
||||
Kind string `json:"kind"`
|
||||
Description *string `json:"description"`
|
||||
CourseID *uint `json:"course_id"`
|
||||
Course *courseRef `json:"course"`
|
||||
}
|
||||
|
||||
func newDeadlinesJSON(rows []models.Deadline) []deadlineJSON {
|
||||
out := make([]deadlineJSON, 0, len(rows))
|
||||
for _, d := range rows {
|
||||
out = append(out, deadlineJSON{
|
||||
ID: d.ID,
|
||||
Title: d.Title,
|
||||
DueAt: string(d.DueAt),
|
||||
Kind: d.Kind,
|
||||
Description: d.Description,
|
||||
CourseID: d.CourseID,
|
||||
Course: newCourseRef(d.Course),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// readingJSON is one reading with the caller's read state.
|
||||
type readingJSON struct {
|
||||
ID uint `json:"id"`
|
||||
CourseID uint `json:"course_id"`
|
||||
Course *courseRef `json:"course"`
|
||||
Title string `json:"title"`
|
||||
Author *string `json:"author"`
|
||||
Source *string `json:"source"`
|
||||
URL *string `json:"url"`
|
||||
IsRequired bool `json:"is_required"`
|
||||
SortOrder int `json:"sort_order"`
|
||||
ReadAt *string `json:"read_at"`
|
||||
}
|
||||
|
||||
// tagJSON is one material tag.
|
||||
type tagJSON struct {
|
||||
ID uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Slug string `json:"slug"`
|
||||
}
|
||||
|
||||
func newTagsJSON(tags []models.Tag) []tagJSON {
|
||||
out := make([]tagJSON, 0, len(tags))
|
||||
for _, t := range tags {
|
||||
out = append(out, tagJSON{ID: t.ID, Name: t.Name, Slug: t.Slug})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// materialListJSON is a published material in a list.
|
||||
type materialListJSON struct {
|
||||
ID uint `json:"id"`
|
||||
CourseID *uint `json:"course_id"`
|
||||
Course *courseRef `json:"course"`
|
||||
Title string `json:"title"`
|
||||
Type string `json:"type"`
|
||||
Source *string `json:"source"`
|
||||
URL *string `json:"url"`
|
||||
PublishedAt string `json:"published_at"`
|
||||
Tags []tagJSON `json:"tags"`
|
||||
FilesCount int64 `json:"files_count"`
|
||||
}
|
||||
|
||||
func newMaterialListJSON(m models.Material, files int64) materialListJSON {
|
||||
out := materialListJSON{
|
||||
ID: m.ID,
|
||||
CourseID: m.CourseID,
|
||||
Course: newCourseRef(m.Course),
|
||||
Title: m.Title,
|
||||
Type: m.Type,
|
||||
Source: m.Source,
|
||||
URL: m.URL,
|
||||
Tags: newTagsJSON(m.Tags),
|
||||
FilesCount: files,
|
||||
}
|
||||
if m.PublishedAt != nil {
|
||||
out.PublishedAt = string(*m.PublishedAt)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// materialDetailJSON is a published material with its body and files.
|
||||
type materialDetailJSON struct {
|
||||
materialListJSON
|
||||
Body *string `json:"body"`
|
||||
Files []fileJSON `json:"files"`
|
||||
}
|
||||
|
||||
// fileJSON is one attached file.
|
||||
type fileJSON struct {
|
||||
ID uint `json:"id"`
|
||||
URL string `json:"url"`
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Mime string `json:"mime"`
|
||||
}
|
||||
|
||||
// readingsSummary is the reading progress block of /dashboard.
|
||||
type readingsSummary struct {
|
||||
Total int64 `json:"total"`
|
||||
Read int64 `json:"read"`
|
||||
RequiredTotal int64 `json:"required_total"`
|
||||
RequiredRead int64 `json:"required_read"`
|
||||
}
|
||||
183
controllers/api/materials.go
Normal file
183
controllers/api/materials.go
Normal file
@@ -0,0 +1,183 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// published scopes a material query to what students may see: a
|
||||
// publication time that has passed. A NULL published_at is a draft.
|
||||
func published(q *gorm.DB, now time.Time) *gorm.DB {
|
||||
return q.Where("jz_bm_materials.published_at IS NOT NULL AND jz_bm_materials.published_at <= ?", now.UTC())
|
||||
}
|
||||
|
||||
// materialFilter holds the validated filters of /materials.
|
||||
type materialFilter struct {
|
||||
CourseID uint
|
||||
Tag string
|
||||
Type string
|
||||
}
|
||||
|
||||
func (f materialFilter) apply(q *gorm.DB) *gorm.DB {
|
||||
if f.CourseID != 0 {
|
||||
q = q.Where("jz_bm_materials.course_id = ?", f.CourseID)
|
||||
}
|
||||
if f.Type != "" {
|
||||
q = q.Where("jz_bm_materials.type = ?", f.Type)
|
||||
}
|
||||
if f.Tag != "" {
|
||||
q = q.Where(`EXISTS (SELECT 1 FROM jz_bm_material_tag mt JOIN jz_bm_tags t ON t.id = mt.tag_id
|
||||
WHERE mt.material_id = jz_bm_materials.id AND t.slug = ?)`, f.Tag)
|
||||
}
|
||||
return q
|
||||
}
|
||||
|
||||
func preloadMaterial(q *gorm.DB) *gorm.DB {
|
||||
return q.Preload("Course").Preload("Tags", func(db *gorm.DB) *gorm.DB { return db.Order("jz_bm_tags.name") })
|
||||
}
|
||||
|
||||
// listMaterials returns one page of published materials, newest first.
|
||||
func listMaterials(db *gorm.DB, now time.Time, f materialFilter, page, perPage int) ([]materialListJSON, int64, error) {
|
||||
q := f.apply(published(db.Model(&models.Material{}), now))
|
||||
var total int64
|
||||
if err := q.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var rows []models.Material
|
||||
err := preloadMaterial(f.apply(published(db, now))).
|
||||
Order("jz_bm_materials.published_at DESC, jz_bm_materials.id DESC").
|
||||
Offset((page - 1) * perPage).Limit(perPage).
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
out, err := materialsJSON(db, rows)
|
||||
return out, total, err
|
||||
}
|
||||
|
||||
// materialsJSON builds list rows with their file counts.
|
||||
func materialsJSON(db *gorm.DB, rows []models.Material) ([]materialListJSON, error) {
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, m := range rows {
|
||||
ids = append(ids, strconv.FormatUint(uint64(m.ID), 10))
|
||||
}
|
||||
counts := map[string]int64{}
|
||||
if len(ids) > 0 {
|
||||
var found []struct {
|
||||
AttachmentID string
|
||||
Count int64
|
||||
}
|
||||
err := db.Model(&attach.File{}).
|
||||
Select("attachment_id, COUNT(*) AS count").
|
||||
Where("attachment_type = ? AND field = ? AND is_public AND attachment_id IN ?", models.Material{}.MorphName(), models.MaterialFilesField, ids).
|
||||
Group("attachment_id").
|
||||
Scan(&found).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range found {
|
||||
counts[row.AttachmentID] = row.Count
|
||||
}
|
||||
}
|
||||
out := make([]materialListJSON, 0, len(rows))
|
||||
for _, m := range rows {
|
||||
out = append(out, newMaterialListJSON(m, counts[strconv.FormatUint(uint64(m.ID), 10)]))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Materials answers GET /materials?course=&tag=&type=&page=&per_page=: a
|
||||
// page of published materials in the {data, meta} shape of lagoon.Paginate.
|
||||
func (h *Handlers) Materials(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.caller(w, r); !ok {
|
||||
return
|
||||
}
|
||||
in := query(r, "course", "tag", "type", "page", "per_page")
|
||||
if !h.validate(w, r, in, materialsRules) {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
filter := materialFilter{CourseID: uintParam(in, "course"), Tag: strings.TrimSpace(str(in, "tag")), Type: str(in, "type")}
|
||||
page := min(intParam(in, "page", 1), 100000)
|
||||
perPage := intParam(in, "per_page", h.perPage())
|
||||
rows, total, err := listMaterials(db, h.now(), filter, page, perPage)
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeJSONPage(w, lagoon.Paginate(rows, page, perPage, total))
|
||||
}
|
||||
|
||||
// Material answers GET /materials/{id}: one published material with its
|
||||
// body, tags and files. A draft or a future publication is a 404.
|
||||
func (h *Handlers) Material(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.caller(w, r); !ok {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := surf.IntParam(r, "id")
|
||||
if !ok {
|
||||
writeNotFound(w)
|
||||
return
|
||||
}
|
||||
var m models.Material
|
||||
res := preloadMaterial(published(db, h.now())).Where("jz_bm_materials.id = ?", id).Limit(1).Find(&m)
|
||||
if res.Error != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
writeNotFound(w)
|
||||
return
|
||||
}
|
||||
var files []attach.File
|
||||
err := db.Where("attachment_type = ? AND attachment_id = ? AND field = ?", m.MorphName(), strconv.FormatUint(uint64(m.ID), 10), models.MaterialFilesField).
|
||||
Order("sort_order, id").
|
||||
Find(&files).Error
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
out := materialDetailJSON{
|
||||
materialListJSON: newMaterialListJSON(m, int64(len(files))),
|
||||
Body: m.Body,
|
||||
Files: make([]fileJSON, 0, len(files)),
|
||||
}
|
||||
for i := range files {
|
||||
f := &files[i]
|
||||
if !f.Public() {
|
||||
continue
|
||||
}
|
||||
out.Files = append(out.Files, fileJSON{ID: f.ID, URL: f.URL(), Name: f.FileName, Size: f.FileSize, Mime: f.ContentType})
|
||||
}
|
||||
out.FilesCount = int64(len(out.Files))
|
||||
writeData(w, out)
|
||||
}
|
||||
|
||||
// publishedMaterialsOfCourse lists a course's published materials, newest
|
||||
// first, for /courses/{id}.
|
||||
func publishedMaterialsOfCourse(db *gorm.DB, now time.Time, courseID uint) ([]materialListJSON, error) {
|
||||
var rows []models.Material
|
||||
err := preloadMaterial(published(db, now)).
|
||||
Where("jz_bm_materials.course_id = ?", courseID).
|
||||
Order("jz_bm_materials.published_at DESC, jz_bm_materials.id DESC").
|
||||
Find(&rows).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return materialsJSON(db, rows)
|
||||
}
|
||||
113
controllers/api/params.go
Normal file
113
controllers/api/params.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
// Rule tables of the query parameters, in the order the errors are listed.
|
||||
// lagoon.ParseRules panics on a bad rule, so a mistake here stops start-up.
|
||||
var (
|
||||
dateRule = `nullable|regex:/^\d{4}-\d{2}-\d{2}$/|date`
|
||||
|
||||
// rangeRules check from and to alone; rangeRulesFrom also orders them
|
||||
// when both are given.
|
||||
rangeRules = []lagoon.RequestRule{
|
||||
{Field: "from", Rules: lagoon.ParseRules(dateRule)},
|
||||
{Field: "to", Rules: lagoon.ParseRules(dateRule)},
|
||||
}
|
||||
rangeRulesFrom = []lagoon.RequestRule{
|
||||
{Field: "from", Rules: lagoon.ParseRules(dateRule)},
|
||||
{Field: "to", Rules: lagoon.ParseRules(dateRule + "|after_or_equal:from")},
|
||||
}
|
||||
courseFilterRules = []lagoon.RequestRule{
|
||||
{Field: "course", Rules: lagoon.ParseRules("nullable|integer|min:1")},
|
||||
}
|
||||
coursesRules = []lagoon.RequestRule{
|
||||
{Field: "semester", Rules: lagoon.ParseRules("nullable|integer|between:1,4")},
|
||||
}
|
||||
materialsRules = []lagoon.RequestRule{
|
||||
{Field: "course", Rules: lagoon.ParseRules("nullable|integer|min:1")},
|
||||
{Field: "tag", Rules: lagoon.ParseRules("nullable|string|max:100")},
|
||||
{Field: "type", Rules: append(lagoon.ParseRules("nullable"), lagoon.In(models.MaterialTypes...))},
|
||||
{Field: "page", Rules: lagoon.ParseRules("nullable|integer|min:1")},
|
||||
{Field: "per_page", Rules: lagoon.ParseRules("nullable|integer|between:1,100")},
|
||||
}
|
||||
)
|
||||
|
||||
// query collects the named query parameters that are present into the input
|
||||
// map lagoon.ValidateRequest takes. A repeated parameter keeps its first
|
||||
// value.
|
||||
func query(r *http.Request, names ...string) map[string]any {
|
||||
q := r.URL.Query()
|
||||
in := make(map[string]any, len(names))
|
||||
for _, name := range names {
|
||||
if vals, ok := q[name]; ok && len(vals) > 0 {
|
||||
in[name] = vals[0]
|
||||
}
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// validate checks in against rules and answers 422 itself when it fails.
|
||||
func (h *Handlers) validate(w http.ResponseWriter, r *http.Request, in map[string]any, rules []lagoon.RequestRule) bool {
|
||||
errs, err := lagoon.ValidateRequest(r.Context(), nil, in, rules, h.translator())
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return false
|
||||
}
|
||||
if len(errs) > 0 {
|
||||
writeValidation(w, errs)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// str returns a validated string parameter, or "" when it is absent.
|
||||
func str(in map[string]any, name string) string {
|
||||
s, _ := in[name].(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// uintParam returns a validated positive integer parameter, or 0 when it is
|
||||
// absent.
|
||||
func uintParam(in map[string]any, name string) uint {
|
||||
n, err := strconv.ParseUint(str(in, name), 10, 64)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return uint(n)
|
||||
}
|
||||
|
||||
// intParam returns a validated integer parameter, or def when it is absent.
|
||||
func intParam(in map[string]any, name string, def int) int {
|
||||
n, err := strconv.Atoi(str(in, name))
|
||||
if err != nil {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// dayStart returns midnight in Europe/Warsaw of a validated YYYY-MM-DD
|
||||
// parameter, and false when it is absent.
|
||||
func dayStart(in map[string]any, name string) (time.Time, bool) {
|
||||
s := str(in, name)
|
||||
if s == "" {
|
||||
return time.Time{}, false
|
||||
}
|
||||
t, err := models.ParseDate(s)
|
||||
if err != nil {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return t, true
|
||||
}
|
||||
|
||||
// today returns midnight of now's calendar day in Europe/Warsaw.
|
||||
func today(now time.Time) time.Time {
|
||||
y, m, d := now.In(models.Location).Date()
|
||||
return time.Date(y, m, d, 0, 0, 0, 0, models.Location)
|
||||
}
|
||||
187
controllers/api/readings.go
Normal file
187
controllers/api/readings.go
Normal file
@@ -0,0 +1,187 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// readingRow is a reading joined with the caller's progress row.
|
||||
type readingRow struct {
|
||||
models.Reading `gorm:"embedded"`
|
||||
ReadAt *time.Time `gorm:"column:read_at"`
|
||||
}
|
||||
|
||||
// listReadings returns the readings, optionally of one course, in course and
|
||||
// reading order, each with the caller's read_at.
|
||||
func listReadings(db *gorm.DB, userID, courseID uint) ([]readingJSON, error) {
|
||||
q := db.Table("jz_bm_readings AS r").
|
||||
Select("r.*, p.read_at").
|
||||
Joins("JOIN jz_bm_courses c ON c.id = r.course_id").
|
||||
Joins("LEFT JOIN jz_bm_reading_progress p ON p.reading_id = r.id AND p.user_id = ?", userID)
|
||||
if courseID != 0 {
|
||||
q = q.Where("r.course_id = ?", courseID)
|
||||
}
|
||||
var rows []readingRow
|
||||
if err := q.Order("c.semester, c.sort_order, c.name, r.course_id, r.sort_order, r.id").Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
courses, err := coursesByID(db, readingCourseIDs(rows))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]readingJSON, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
item := readingJSON{
|
||||
ID: row.ID,
|
||||
CourseID: row.CourseID,
|
||||
Course: newCourseRef(courses[row.CourseID]),
|
||||
Title: row.Title,
|
||||
Author: row.Author,
|
||||
Source: row.Source,
|
||||
URL: row.URL,
|
||||
IsRequired: row.IsRequired,
|
||||
SortOrder: row.SortOrder,
|
||||
}
|
||||
if row.ReadAt != nil {
|
||||
s := string(models.NewDateTime(*row.ReadAt))
|
||||
item.ReadAt = &s
|
||||
}
|
||||
out = append(out, item)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func readingCourseIDs(rows []readingRow) []uint {
|
||||
seen := map[uint]bool{}
|
||||
var ids []uint
|
||||
for _, row := range rows {
|
||||
if !seen[row.CourseID] {
|
||||
seen[row.CourseID] = true
|
||||
ids = append(ids, row.CourseID)
|
||||
}
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// coursesByID loads the given courses keyed by ID.
|
||||
func coursesByID(db *gorm.DB, ids []uint) (map[uint]*models.Course, error) {
|
||||
out := map[uint]*models.Course{}
|
||||
if len(ids) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
var rows []models.Course
|
||||
if err := db.Where("id IN ?", ids).Find(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range rows {
|
||||
out[rows[i].ID] = &rows[i]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Readings answers GET /readings?course=ID: the reading lists with the
|
||||
// caller's read state. An unknown course gives an empty list.
|
||||
func (h *Handlers) Readings(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.caller(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
in := query(r, "course")
|
||||
if !h.validate(w, r, in, courseFilterRules) {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, err := listReadings(db, userID, uintParam(in, "course"))
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeData(w, out)
|
||||
}
|
||||
|
||||
// progressJSON is the answer of the progress routes.
|
||||
type progressJSON struct {
|
||||
ReadingID uint `json:"reading_id"`
|
||||
ReadAt *string `json:"read_at"`
|
||||
}
|
||||
|
||||
// readingFor resolves {id} to an existing reading and answers 404 itself
|
||||
// when there is none.
|
||||
func readingFor(w http.ResponseWriter, r *http.Request, db *gorm.DB) (uint, bool) {
|
||||
id, ok := surf.IntParam(r, "id")
|
||||
if !ok {
|
||||
writeNotFound(w)
|
||||
return 0, false
|
||||
}
|
||||
var reading models.Reading
|
||||
res := db.Select("id").Where("id = ?", id).Limit(1).Find(&reading)
|
||||
if res.Error != nil {
|
||||
writeOpaque500(w)
|
||||
return 0, false
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
writeNotFound(w)
|
||||
return 0, false
|
||||
}
|
||||
return reading.ID, true
|
||||
}
|
||||
|
||||
// MarkRead answers PUT /readings/{id}/progress: it marks the reading read
|
||||
// by the caller. Marking it again keeps the first read_at.
|
||||
func (h *Handlers) MarkRead(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.caller(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
readingID, ok := readingFor(w, r, db)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
now := h.now().UTC()
|
||||
err := db.Exec(`INSERT INTO jz_bm_reading_progress (reading_id, user_id, read_at) VALUES (?, ?, ?)
|
||||
ON CONFLICT (reading_id, user_id) DO NOTHING`, readingID, userID, now).Error
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
var progress models.ReadingProgress
|
||||
if err := db.Where("reading_id = ? AND user_id = ?", readingID, userID).Take(&progress).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
readAt := string(models.NewDateTime(progress.ReadAt))
|
||||
writeData(w, progressJSON{ReadingID: readingID, ReadAt: &readAt})
|
||||
}
|
||||
|
||||
// UnmarkRead answers DELETE /readings/{id}/progress: it clears the caller's
|
||||
// read mark. Clearing an unread reading is not an error.
|
||||
func (h *Handlers) UnmarkRead(w http.ResponseWriter, r *http.Request) {
|
||||
userID, ok := h.caller(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
readingID, ok := readingFor(w, r, db)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := db.Where("reading_id = ? AND user_id = ?", readingID, userID).Delete(&models.ReadingProgress{}).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeData(w, progressJSON{ReadingID: readingID})
|
||||
}
|
||||
137
controllers/api/schedule.go
Normal file
137
controllers/api/schedule.go
Normal file
@@ -0,0 +1,137 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// validRange validates ?from=&to= and returns the decoded input.
|
||||
func (h *Handlers) validRange(w http.ResponseWriter, r *http.Request) (map[string]any, bool) {
|
||||
in := query(r, "from", "to")
|
||||
rules := rangeRules
|
||||
if str(in, "from") != "" {
|
||||
rules = rangeRulesFrom
|
||||
}
|
||||
return in, h.validate(w, r, in, rules)
|
||||
}
|
||||
|
||||
// bounds turns validated from and to dates into a half-open instant range:
|
||||
// from midnight of from to midnight after to, in Europe/Warsaw. Without
|
||||
// from the lower bound is lower; without to there is no upper bound.
|
||||
func bounds(in map[string]any, lower time.Time) (time.Time, *time.Time) {
|
||||
if from, ok := dayStart(in, "from"); ok {
|
||||
lower = from
|
||||
}
|
||||
if to, ok := dayStart(in, "to"); ok {
|
||||
upper := to.AddDate(0, 0, 1)
|
||||
return lower, &upper
|
||||
}
|
||||
return lower, nil
|
||||
}
|
||||
|
||||
func preloadSession(q *gorm.DB) *gorm.DB {
|
||||
return q.Preload("Course").Preload("Meeting")
|
||||
}
|
||||
|
||||
// Schedule answers GET /schedule?from=YYYY-MM-DD&to=YYYY-MM-DD: the class
|
||||
// sessions starting in the range, by start time. from defaults to today.
|
||||
func (h *Handlers) Schedule(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.caller(w, r); !ok {
|
||||
return
|
||||
}
|
||||
in, ok := h.validRange(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
lower, upper := bounds(in, today(h.now()))
|
||||
q := preloadSession(db).Where("starts_at >= ?", lower.UTC())
|
||||
if upper != nil {
|
||||
q = q.Where("starts_at < ?", upper.UTC())
|
||||
}
|
||||
var rows []models.ClassSession
|
||||
if err := q.Order("starts_at, id").Find(&rows).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeData(w, newSessionsJSON(rows))
|
||||
}
|
||||
|
||||
// Meetings answers GET /meetings: every zjazd by number, with its session
|
||||
// count.
|
||||
func (h *Handlers) Meetings(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.caller(w, r); !ok {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var rows []models.Meeting
|
||||
if err := db.Order("number, id").Find(&rows).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
counts, err := countBy(db, "jz_bm_class_sessions", "meeting_id")
|
||||
if err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
out := make([]meetingJSON, 0, len(rows))
|
||||
for _, m := range rows {
|
||||
out = append(out, newMeetingJSON(m, counts[m.ID]))
|
||||
}
|
||||
writeData(w, out)
|
||||
}
|
||||
|
||||
// Deadlines answers GET /deadlines?from=&to=. Without from it lists the
|
||||
// deadlines not yet due; from and to are calendar days in Europe/Warsaw.
|
||||
func (h *Handlers) Deadlines(w http.ResponseWriter, r *http.Request) {
|
||||
if _, ok := h.caller(w, r); !ok {
|
||||
return
|
||||
}
|
||||
in, ok := h.validRange(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
db, ok := h.db(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
lower, upper := bounds(in, h.now())
|
||||
q := db.Preload("Course").Where("due_at >= ?", lower.UTC())
|
||||
if upper != nil {
|
||||
q = q.Where("due_at < ?", upper.UTC())
|
||||
}
|
||||
var rows []models.Deadline
|
||||
if err := q.Order("due_at, id").Find(&rows).Error; err != nil {
|
||||
writeOpaque500(w)
|
||||
return
|
||||
}
|
||||
writeData(w, newDeadlinesJSON(rows))
|
||||
}
|
||||
|
||||
// countBy counts the rows of table per value of a nullable foreign key
|
||||
// column. table and column are constants of this package, never input.
|
||||
func countBy(db *gorm.DB, table, column string) (map[uint]int64, error) {
|
||||
var rows []struct {
|
||||
Key uint
|
||||
Count int64
|
||||
}
|
||||
err := db.Table(table).
|
||||
Select(column + " AS key, COUNT(*) AS count").
|
||||
Where(column + " IS NOT NULL").
|
||||
Group(column).
|
||||
Scan(&rows).Error
|
||||
out := make(map[uint]int64, len(rows))
|
||||
for _, row := range rows {
|
||||
out[row.Key] = row.Count
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
47
controllers/class_sessions.go
Normal file
47
controllers/class_sessions.go
Normal file
@@ -0,0 +1,47 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
var (
|
||||
_ pact.AdminController = classSessionsAdmin{}
|
||||
_ pact.AdminRecordSource = classSessionsAdmin{}
|
||||
_ pact.AdminPermissioned = classSessionsAdmin{}
|
||||
)
|
||||
|
||||
// classSessionsAdmin is the admin controller for class sessions (zajęcia).
|
||||
type classSessionsAdmin struct{ temporalHooks }
|
||||
|
||||
func (classSessionsAdmin) ID() string { return "jz.bm.class_sessions" }
|
||||
func (classSessionsAdmin) ModelName() string { return "ClassSession" }
|
||||
func (classSessionsAdmin) ConfigDir() string { return "controllers/class_sessions" }
|
||||
|
||||
// NewRecord returns the model the generic admin handlers query and fill.
|
||||
func (classSessionsAdmin) NewRecord() any { return &models.ClassSession{} }
|
||||
|
||||
// RequiredPermissions is checked before any schema or record is served.
|
||||
func (classSessionsAdmin) RequiredPermissions() []string {
|
||||
return []string{PermSchedule}
|
||||
}
|
||||
|
||||
// AdminFieldRelations binds the course and meeting pickers.
|
||||
func (classSessionsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
|
||||
return []cabana.FieldRelationContract{
|
||||
courseRelation("course_id"),
|
||||
{
|
||||
Field: "meeting",
|
||||
Kind: "belongsTo",
|
||||
NewRelated: func() any { return &models.Meeting{} },
|
||||
ForeignKey: "meeting_id",
|
||||
LabelColumn: "number",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ClassSessionsController returns the jz.bm.class_sessions admin controller.
|
||||
func ClassSessionsController() pact.AdminController { return classSessionsAdmin{} }
|
||||
12
controllers/class_sessions/config_form.yaml
Normal file
12
controllers/class_sessions/config_form.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
name: jz.bm::lang.sessions.form
|
||||
form: ~/plugins/jz/bm/models/class_sessions/fields.yaml
|
||||
modelClass: ClassSession
|
||||
defaultRedirect: jz/bm/class_sessions
|
||||
|
||||
create:
|
||||
redirect: jz/bm/class_sessions/update/:id
|
||||
redirectClose: jz/bm/class_sessions
|
||||
|
||||
update:
|
||||
redirect: jz/bm/class_sessions
|
||||
redirectClose: jz/bm/class_sessions
|
||||
15
controllers/class_sessions/config_list.yaml
Normal file
15
controllers/class_sessions/config_list.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
list: ~/plugins/jz/bm/models/class_sessions/columns.yaml
|
||||
modelClass: ClassSession
|
||||
title: jz.bm::lang.sessions.title
|
||||
recordUrl: jz/bm/class_sessions/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 50
|
||||
perPageOptions: [20, 50, 100]
|
||||
showCheckboxes: true
|
||||
defaultSort:
|
||||
column: starts_at
|
||||
direction: asc
|
||||
toolbar:
|
||||
buttons: [create, delete]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
38
controllers/courses.go
Normal file
38
controllers/courses.go
Normal file
@@ -0,0 +1,38 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
var (
|
||||
_ pact.AdminController = coursesAdmin{}
|
||||
_ pact.AdminRecordSource = coursesAdmin{}
|
||||
_ pact.AdminPermissioned = coursesAdmin{}
|
||||
)
|
||||
|
||||
// coursesAdmin is the admin controller for courses (przedmioty).
|
||||
type coursesAdmin struct{}
|
||||
|
||||
func (coursesAdmin) ID() string { return "jz.bm.courses" }
|
||||
func (coursesAdmin) ModelName() string { return "Course" }
|
||||
func (coursesAdmin) ConfigDir() string { return "controllers/courses" }
|
||||
|
||||
// NewRecord returns the model the generic admin handlers query and fill.
|
||||
func (coursesAdmin) NewRecord() any { return &models.Course{} }
|
||||
|
||||
// RequiredPermissions is checked before any schema or record is served.
|
||||
func (coursesAdmin) RequiredPermissions() []string {
|
||||
return []string{PermCourses}
|
||||
}
|
||||
|
||||
// TODO: requires SummerCMS change. The course form should embed relation
|
||||
// managers for its readings and class sessions, but cabana relation managers
|
||||
// only link and unlink belongsToMany rows through a pivot; hasMany children
|
||||
// cannot be listed or edited from the parent form. Readings and class
|
||||
// sessions have their own screens, filtered by course.
|
||||
|
||||
// CoursesController returns the jz.bm.courses admin controller.
|
||||
func CoursesController() pact.AdminController { return coursesAdmin{} }
|
||||
12
controllers/courses/config_form.yaml
Normal file
12
controllers/courses/config_form.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
name: jz.bm::lang.courses.form
|
||||
form: ~/plugins/jz/bm/models/courses/fields.yaml
|
||||
modelClass: Course
|
||||
defaultRedirect: jz/bm/courses
|
||||
|
||||
create:
|
||||
redirect: jz/bm/courses/update/:id
|
||||
redirectClose: jz/bm/courses
|
||||
|
||||
update:
|
||||
redirect: jz/bm/courses
|
||||
redirectClose: jz/bm/courses
|
||||
15
controllers/courses/config_list.yaml
Normal file
15
controllers/courses/config_list.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
list: ~/plugins/jz/bm/models/courses/columns.yaml
|
||||
modelClass: Course
|
||||
title: jz.bm::lang.courses.title
|
||||
recordUrl: jz/bm/courses/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 50
|
||||
perPageOptions: [20, 50, 100]
|
||||
showCheckboxes: true
|
||||
defaultSort:
|
||||
column: sort_order
|
||||
direction: asc
|
||||
toolbar:
|
||||
buttons: [create, delete]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
38
controllers/deadlines.go
Normal file
38
controllers/deadlines.go
Normal file
@@ -0,0 +1,38 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
var (
|
||||
_ pact.AdminController = deadlinesAdmin{}
|
||||
_ pact.AdminRecordSource = deadlinesAdmin{}
|
||||
_ pact.AdminPermissioned = deadlinesAdmin{}
|
||||
)
|
||||
|
||||
// deadlinesAdmin is the admin controller for deadlines (terminarz).
|
||||
type deadlinesAdmin struct{ temporalHooks }
|
||||
|
||||
func (deadlinesAdmin) ID() string { return "jz.bm.deadlines" }
|
||||
func (deadlinesAdmin) ModelName() string { return "Deadline" }
|
||||
func (deadlinesAdmin) ConfigDir() string { return "controllers/deadlines" }
|
||||
|
||||
// NewRecord returns the model the generic admin handlers query and fill.
|
||||
func (deadlinesAdmin) NewRecord() any { return &models.Deadline{} }
|
||||
|
||||
// RequiredPermissions is checked before any schema or record is served.
|
||||
func (deadlinesAdmin) RequiredPermissions() []string {
|
||||
return []string{PermSchedule}
|
||||
}
|
||||
|
||||
// AdminFieldRelations binds the course picker.
|
||||
func (deadlinesAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
|
||||
return []cabana.FieldRelationContract{courseRelation("course_id")}
|
||||
}
|
||||
|
||||
// DeadlinesController returns the jz.bm.deadlines admin controller.
|
||||
func DeadlinesController() pact.AdminController { return deadlinesAdmin{} }
|
||||
12
controllers/deadlines/config_form.yaml
Normal file
12
controllers/deadlines/config_form.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
name: jz.bm::lang.deadlines.form
|
||||
form: ~/plugins/jz/bm/models/deadlines/fields.yaml
|
||||
modelClass: Deadline
|
||||
defaultRedirect: jz/bm/deadlines
|
||||
|
||||
create:
|
||||
redirect: jz/bm/deadlines/update/:id
|
||||
redirectClose: jz/bm/deadlines
|
||||
|
||||
update:
|
||||
redirect: jz/bm/deadlines
|
||||
redirectClose: jz/bm/deadlines
|
||||
15
controllers/deadlines/config_list.yaml
Normal file
15
controllers/deadlines/config_list.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
list: ~/plugins/jz/bm/models/deadlines/columns.yaml
|
||||
modelClass: Deadline
|
||||
title: jz.bm::lang.deadlines.title
|
||||
recordUrl: jz/bm/deadlines/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 50
|
||||
perPageOptions: [20, 50, 100]
|
||||
showCheckboxes: true
|
||||
defaultSort:
|
||||
column: due_at
|
||||
direction: asc
|
||||
toolbar:
|
||||
buttons: [create, delete]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
55
controllers/hooks.go
Normal file
55
controllers/hooks.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
// Permission codes of the plugin's admin screens.
|
||||
const (
|
||||
PermCourses = "jz.bm.access_courses"
|
||||
PermSchedule = "jz.bm.access_schedule"
|
||||
PermMaterials = "jz.bm.access_materials"
|
||||
)
|
||||
|
||||
// temporalHooks checks a model's Date and DateTime columns before every admin
|
||||
// save and answers a bad value as a 422 on its field. lagoon.Validate has no
|
||||
// date rules, so the model checks them itself (models.TemporalValidator).
|
||||
type temporalHooks struct{}
|
||||
|
||||
func (temporalHooks) FormBeforeCreate(_ context.Context, model any) error {
|
||||
return checkTemporal(model)
|
||||
}
|
||||
|
||||
func (temporalHooks) FormBeforeUpdate(_ context.Context, model any) error {
|
||||
return checkTemporal(model)
|
||||
}
|
||||
|
||||
func checkTemporal(model any) error {
|
||||
v, ok := model.(models.TemporalValidator)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
msgs := v.TemporalErrors()
|
||||
if len(msgs) == 0 {
|
||||
return nil
|
||||
}
|
||||
details := make(map[string]any, len(msgs))
|
||||
for field, m := range msgs {
|
||||
details[field] = m
|
||||
}
|
||||
return &cabana.ValidationError{Details: details}
|
||||
}
|
||||
|
||||
// courseRelation is the belongsTo picker of a course_id column.
|
||||
func courseRelation(foreignKey string) cabana.FieldRelationContract {
|
||||
return cabana.FieldRelationContract{
|
||||
Field: "course",
|
||||
Kind: "belongsTo",
|
||||
NewRelated: func() any { return &models.Course{} },
|
||||
ForeignKey: foreignKey,
|
||||
LabelColumn: "name",
|
||||
}
|
||||
}
|
||||
53
controllers/materials.go
Normal file
53
controllers/materials.go
Normal file
@@ -0,0 +1,53 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
var (
|
||||
_ pact.AdminController = materialsAdmin{}
|
||||
_ pact.AdminRecordSource = materialsAdmin{}
|
||||
_ pact.AdminPermissioned = materialsAdmin{}
|
||||
)
|
||||
|
||||
// materialsAdmin is the admin controller for materials.
|
||||
type materialsAdmin struct{ temporalHooks }
|
||||
|
||||
func (materialsAdmin) ID() string { return "jz.bm.materials" }
|
||||
func (materialsAdmin) ModelName() string { return "Material" }
|
||||
func (materialsAdmin) ConfigDir() string { return "controllers/materials" }
|
||||
|
||||
// NewRecord returns the model the generic admin handlers query and fill.
|
||||
func (materialsAdmin) NewRecord() any { return &models.Material{} }
|
||||
|
||||
// RequiredPermissions is checked before any schema or record is served.
|
||||
func (materialsAdmin) RequiredPermissions() []string {
|
||||
return []string{PermMaterials}
|
||||
}
|
||||
|
||||
// AdminFieldRelations binds the course picker and the tags.
|
||||
//
|
||||
// TODO: requires SummerCMS change. Materials carry their files as
|
||||
// system_files attachments (field "files"), but cabana has no file upload
|
||||
// form widget, so files are attached outside the admin form for now.
|
||||
func (materialsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
|
||||
return []cabana.FieldRelationContract{
|
||||
courseRelation("course_id"),
|
||||
{
|
||||
Field: "tags",
|
||||
Kind: "belongsToMany",
|
||||
NewRelated: func() any { return &models.Tag{} },
|
||||
NewPivot: func() any { return &models.MaterialTag{} },
|
||||
ParentForeignKey: "material_id",
|
||||
RelatedForeignKey: "tag_id",
|
||||
LabelColumn: "name",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// MaterialsController returns the jz.bm.materials admin controller.
|
||||
func MaterialsController() pact.AdminController { return materialsAdmin{} }
|
||||
12
controllers/materials/config_form.yaml
Normal file
12
controllers/materials/config_form.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
name: jz.bm::lang.materials.form
|
||||
form: ~/plugins/jz/bm/models/materials/fields.yaml
|
||||
modelClass: Material
|
||||
defaultRedirect: jz/bm/materials
|
||||
|
||||
create:
|
||||
redirect: jz/bm/materials/update/:id
|
||||
redirectClose: jz/bm/materials
|
||||
|
||||
update:
|
||||
redirect: jz/bm/materials
|
||||
redirectClose: jz/bm/materials
|
||||
15
controllers/materials/config_list.yaml
Normal file
15
controllers/materials/config_list.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
list: ~/plugins/jz/bm/models/materials/columns.yaml
|
||||
modelClass: Material
|
||||
title: jz.bm::lang.materials.title
|
||||
recordUrl: jz/bm/materials/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 50
|
||||
perPageOptions: [20, 50, 100]
|
||||
showCheckboxes: true
|
||||
defaultSort:
|
||||
column: created_at
|
||||
direction: desc
|
||||
toolbar:
|
||||
buttons: [create, delete]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
32
controllers/meetings.go
Normal file
32
controllers/meetings.go
Normal file
@@ -0,0 +1,32 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
var (
|
||||
_ pact.AdminController = meetingsAdmin{}
|
||||
_ pact.AdminRecordSource = meetingsAdmin{}
|
||||
_ pact.AdminPermissioned = meetingsAdmin{}
|
||||
)
|
||||
|
||||
// meetingsAdmin is the admin controller for meetings (zjazdy).
|
||||
type meetingsAdmin struct{ temporalHooks }
|
||||
|
||||
func (meetingsAdmin) ID() string { return "jz.bm.meetings" }
|
||||
func (meetingsAdmin) ModelName() string { return "Meeting" }
|
||||
func (meetingsAdmin) ConfigDir() string { return "controllers/meetings" }
|
||||
|
||||
// NewRecord returns the model the generic admin handlers query and fill.
|
||||
func (meetingsAdmin) NewRecord() any { return &models.Meeting{} }
|
||||
|
||||
// RequiredPermissions is checked before any schema or record is served.
|
||||
func (meetingsAdmin) RequiredPermissions() []string {
|
||||
return []string{PermSchedule}
|
||||
}
|
||||
|
||||
// MeetingsController returns the jz.bm.meetings admin controller.
|
||||
func MeetingsController() pact.AdminController { return meetingsAdmin{} }
|
||||
12
controllers/meetings/config_form.yaml
Normal file
12
controllers/meetings/config_form.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
name: jz.bm::lang.meetings.form
|
||||
form: ~/plugins/jz/bm/models/meetings/fields.yaml
|
||||
modelClass: Meeting
|
||||
defaultRedirect: jz/bm/meetings
|
||||
|
||||
create:
|
||||
redirect: jz/bm/meetings/update/:id
|
||||
redirectClose: jz/bm/meetings
|
||||
|
||||
update:
|
||||
redirect: jz/bm/meetings
|
||||
redirectClose: jz/bm/meetings
|
||||
15
controllers/meetings/config_list.yaml
Normal file
15
controllers/meetings/config_list.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
list: ~/plugins/jz/bm/models/meetings/columns.yaml
|
||||
modelClass: Meeting
|
||||
title: jz.bm::lang.meetings.title
|
||||
recordUrl: jz/bm/meetings/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 50
|
||||
perPageOptions: [20, 50, 100]
|
||||
showCheckboxes: true
|
||||
defaultSort:
|
||||
column: number
|
||||
direction: asc
|
||||
toolbar:
|
||||
buttons: [create, delete]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
38
controllers/readings.go
Normal file
38
controllers/readings.go
Normal file
@@ -0,0 +1,38 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
var (
|
||||
_ pact.AdminController = readingsAdmin{}
|
||||
_ pact.AdminRecordSource = readingsAdmin{}
|
||||
_ pact.AdminPermissioned = readingsAdmin{}
|
||||
)
|
||||
|
||||
// readingsAdmin is the admin controller for readings (lektury).
|
||||
type readingsAdmin struct{}
|
||||
|
||||
func (readingsAdmin) ID() string { return "jz.bm.readings" }
|
||||
func (readingsAdmin) ModelName() string { return "Reading" }
|
||||
func (readingsAdmin) ConfigDir() string { return "controllers/readings" }
|
||||
|
||||
// NewRecord returns the model the generic admin handlers query and fill.
|
||||
func (readingsAdmin) NewRecord() any { return &models.Reading{} }
|
||||
|
||||
// RequiredPermissions is checked before any schema or record is served.
|
||||
func (readingsAdmin) RequiredPermissions() []string {
|
||||
return []string{PermCourses}
|
||||
}
|
||||
|
||||
// AdminFieldRelations binds the course picker.
|
||||
func (readingsAdmin) AdminFieldRelations() []cabana.FieldRelationContract {
|
||||
return []cabana.FieldRelationContract{courseRelation("course_id")}
|
||||
}
|
||||
|
||||
// ReadingsController returns the jz.bm.readings admin controller.
|
||||
func ReadingsController() pact.AdminController { return readingsAdmin{} }
|
||||
12
controllers/readings/config_form.yaml
Normal file
12
controllers/readings/config_form.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
name: jz.bm::lang.readings.form
|
||||
form: ~/plugins/jz/bm/models/readings/fields.yaml
|
||||
modelClass: Reading
|
||||
defaultRedirect: jz/bm/readings
|
||||
|
||||
create:
|
||||
redirect: jz/bm/readings/update/:id
|
||||
redirectClose: jz/bm/readings
|
||||
|
||||
update:
|
||||
redirect: jz/bm/readings
|
||||
redirectClose: jz/bm/readings
|
||||
15
controllers/readings/config_list.yaml
Normal file
15
controllers/readings/config_list.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
list: ~/plugins/jz/bm/models/readings/columns.yaml
|
||||
modelClass: Reading
|
||||
title: jz.bm::lang.readings.title
|
||||
recordUrl: jz/bm/readings/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 50
|
||||
perPageOptions: [20, 50, 100]
|
||||
showCheckboxes: true
|
||||
defaultSort:
|
||||
column: sort_order
|
||||
direction: asc
|
||||
toolbar:
|
||||
buttons: [create, delete]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
32
controllers/tags.go
Normal file
32
controllers/tags.go
Normal file
@@ -0,0 +1,32 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
var (
|
||||
_ pact.AdminController = tagsAdmin{}
|
||||
_ pact.AdminRecordSource = tagsAdmin{}
|
||||
_ pact.AdminPermissioned = tagsAdmin{}
|
||||
)
|
||||
|
||||
// tagsAdmin is the admin controller for material tags.
|
||||
type tagsAdmin struct{}
|
||||
|
||||
func (tagsAdmin) ID() string { return "jz.bm.tags" }
|
||||
func (tagsAdmin) ModelName() string { return "Tag" }
|
||||
func (tagsAdmin) ConfigDir() string { return "controllers/tags" }
|
||||
|
||||
// NewRecord returns the model the generic admin handlers query and fill.
|
||||
func (tagsAdmin) NewRecord() any { return &models.Tag{} }
|
||||
|
||||
// RequiredPermissions is checked before any schema or record is served.
|
||||
func (tagsAdmin) RequiredPermissions() []string {
|
||||
return []string{PermMaterials}
|
||||
}
|
||||
|
||||
// TagsController returns the jz.bm.tags admin controller.
|
||||
func TagsController() pact.AdminController { return tagsAdmin{} }
|
||||
12
controllers/tags/config_form.yaml
Normal file
12
controllers/tags/config_form.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
name: jz.bm::lang.tags.form
|
||||
form: ~/plugins/jz/bm/models/tags/fields.yaml
|
||||
modelClass: Tag
|
||||
defaultRedirect: jz/bm/tags
|
||||
|
||||
create:
|
||||
redirect: jz/bm/tags/update/:id
|
||||
redirectClose: jz/bm/tags
|
||||
|
||||
update:
|
||||
redirect: jz/bm/tags
|
||||
redirectClose: jz/bm/tags
|
||||
15
controllers/tags/config_list.yaml
Normal file
15
controllers/tags/config_list.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
list: ~/plugins/jz/bm/models/tags/columns.yaml
|
||||
modelClass: Tag
|
||||
title: jz.bm::lang.tags.title
|
||||
recordUrl: jz/bm/tags/update/:id
|
||||
noRecordsMessage: backend::lang.list.no_records
|
||||
recordsPerPage: 50
|
||||
perPageOptions: [20, 50, 100]
|
||||
showCheckboxes: true
|
||||
defaultSort:
|
||||
column: name
|
||||
direction: asc
|
||||
toolbar:
|
||||
buttons: [create, delete]
|
||||
search:
|
||||
prompt: backend::lang.list.search_prompt
|
||||
89
go.mod
89
go.mod
@@ -2,39 +2,122 @@ module git.golem15.com/jakub/sm-bm-plugin
|
||||
|
||||
go 1.27.0
|
||||
|
||||
toolchain go1.27.0
|
||||
|
||||
require (
|
||||
git.golem15.com/golem15/sm-user-plugin v0.0.0
|
||||
git.golem15.com/golem15/summercms v0.0.0
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
||||
github.com/jackc/pgx/v5 v5.10.0
|
||||
github.com/testcontainers/testcontainers-go v0.44.0
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
||||
gorm.io/gorm v1.31.2
|
||||
)
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.2 // indirect
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/containerd/errdefs v1.0.0 // indirect
|
||||
github.com/containerd/errdefs/pkg v0.3.0 // indirect
|
||||
github.com/containerd/log v0.1.0 // indirect
|
||||
github.com/containerd/platforms v0.2.1 // indirect
|
||||
github.com/cpuguy83/dockercfg v0.3.2 // indirect
|
||||
github.com/disintegration/imaging v1.6.2 // indirect
|
||||
github.com/distribution/reference v0.6.0 // indirect
|
||||
github.com/docker/go-connections v0.7.0 // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/ebitengine/purego v0.10.1 // indirect
|
||||
github.com/felixge/httpsnoop v1.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.10.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-ole/go-ole v1.3.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.30.4 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.19.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/knadh/koanf/maps v0.1.2 // indirect
|
||||
github.com/knadh/koanf/parsers/yaml v1.1.1 // indirect
|
||||
github.com/knadh/koanf/providers/confmap v1.0.1 // indirect
|
||||
github.com/knadh/koanf/providers/env/v2 v2.0.1 // indirect
|
||||
github.com/knadh/koanf/providers/file v1.2.1 // indirect
|
||||
github.com/knadh/koanf/v2 v2.3.6 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/lib/pq v1.12.3 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect
|
||||
github.com/magiconair/properties v1.8.10 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/moby/docker-image-spec v1.3.1 // indirect
|
||||
github.com/moby/go-archive v0.2.0 // indirect
|
||||
github.com/moby/moby/api v1.55.0 // indirect
|
||||
github.com/moby/moby/client v0.5.0 // indirect
|
||||
github.com/moby/patternmatcher v0.6.1 // indirect
|
||||
github.com/moby/sys/sequential v0.7.0 // indirect
|
||||
github.com/moby/sys/user v0.4.0 // indirect
|
||||
github.com/moby/sys/userns v0.1.0 // indirect
|
||||
github.com/moby/term v0.5.2 // indirect
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1 // indirect
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.1 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
github.com/riverqueue/river v0.47.0 // indirect
|
||||
github.com/riverqueue/river/riverdriver v0.47.0 // indirect
|
||||
github.com/riverqueue/river/riverdriver/riverdatabasesql v0.47.0 // indirect
|
||||
github.com/riverqueue/river/riverdriver/riverpgxv5 v0.47.0 // indirect
|
||||
github.com/riverqueue/river/rivershared v0.47.0 // indirect
|
||||
github.com/riverqueue/river/rivertype v0.47.0 // indirect
|
||||
github.com/shirou/gopsutil/v4 v4.26.6 // indirect
|
||||
github.com/sirupsen/logrus v1.9.4 // indirect
|
||||
github.com/spf13/cobra v1.10.2 // indirect
|
||||
github.com/spf13/pflag v1.0.9 // indirect
|
||||
github.com/stretchr/testify v1.12.1 // indirect
|
||||
github.com/tidwall/gjson v1.19.0 // indirect
|
||||
github.com/tidwall/match v1.2.0 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tidwall/sjson v1.2.5 // indirect
|
||||
github.com/tklauser/go-sysconf v0.4.0 // indirect
|
||||
github.com/tklauser/numcpus v0.12.0 // indirect
|
||||
github.com/wneessen/go-mail v0.8.1 // indirect
|
||||
github.com/yuin/goldmark v1.8.6 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect
|
||||
go.opentelemetry.io/otel v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
gocloud.dev v0.46.0 // indirect
|
||||
golang.org/x/crypto v0.57.0 // indirect
|
||||
golang.org/x/image v0.46.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/term v0.46.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
gorm.io/gorm v1.31.2 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||
google.golang.org/api v0.272.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
|
||||
google.golang.org/grpc v1.79.3 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gorm.io/driver/postgres v1.6.3 // indirect
|
||||
)
|
||||
|
||||
replace git.golem15.com/golem15/summercms => ../../../../summercms.go
|
||||
|
||||
replace git.golem15.com/golem15/sm-user-plugin => ../../golem15/user
|
||||
|
||||
208
go.sum
208
go.sum
@@ -1,15 +1,79 @@
|
||||
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
|
||||
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
|
||||
cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE=
|
||||
cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU=
|
||||
cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM=
|
||||
cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c=
|
||||
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
|
||||
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
|
||||
cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc=
|
||||
cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU=
|
||||
cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE=
|
||||
cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI=
|
||||
cloud.google.com/go/storage v1.61.3 h1:VS//ZfBuPGDvakfD9xyPW1RGF1Vy3BWUoVZXgW1KMOg=
|
||||
cloud.google.com/go/storage v1.61.3/go.mod h1:JtqK8BBB7TWv0HVGHubtUdzYYrakOQIsMLffZ2Z/HWk=
|
||||
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
||||
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 h1:UnDZ/zFfG1JhH/DqxIZYU/1CUAlTUScoXD/LcM2Ykk8=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 h1:0s6TxfCu2KHkkZPnBfsQ2y5qia0jl3MMrmBhu3nCOYk=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0/go.mod h1:Mf6O40IAyB9zR/1J8nGDDPirZQQPbYJni8Yisy7NTMc=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.9 h1:/rYeyO2+HrMztAmxAq9++XJtFMqSIpSsNA0yDGALYq4=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.9/go.mod h1:+HsoOEX80qAVUitj1A2DhCNTjmb3edVyuDypb6LNEeo=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.20 h1:8VMDnWc/kEzxsI/1ngGM9mG81a8IGmIHD8KLcYGwagc=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.20/go.mod h1:PuwEpciweIXGULWeOeSTXtSbH4CW9mWdWrhdCKQI1sM=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.19 h1:yuFzSV1U0aRNYCQGVaTY2zW2M/L93pYHnXnrJUphYhU=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.19/go.mod h1:7y63L1kGzeoDlJaQ3Z578KrnmfBut96JjvJUzGwR+YE=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25 h1:0w6dCiO8iez+YKwRhRBlL1CH/E3GTfdkuzrwj1by8vo=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25/go.mod h1:9FDWUothyr5RCRAHc45XOiVCzUR8n/IhCYX+uVqw6vk=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3 h1:w5OoDiMN6x53ROmiIImGzmVcxXv2q1GXY+aKV4WAJYM=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/transfermanager v0.2.3/go.mod h1:dAhgYp776bX3LuWvnSCFwQEjNs6fuFg7YXIy5PXcP3Q=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25 h1:Uii3frf9ztec/ABM2/FSH9/z7PLzxfpG8h4RpkUFflQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25/go.mod h1:G6kntsA2GorAxDPbap6xgB2F+amSLUF8GJTi7PUoX44=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25 h1:r1+/l6m+WaUJF9HISEsNOLHSNj5EXYQxK8VX6Cz9NlA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25/go.mod h1:cKf+D+NMDK1LndD7BowHbBZPgR9V0/5HubH0PFWvA+c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26 h1:A1PmWU2zfkIm9EyFlJncFXL4W4phML+h8KjltUsCvNQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26/go.mod h1:dY4MRzXEizrD4hqtpKvWVGPX7QleSGGVY+EBolo1RmM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 h1:d5/908OJ4bXg8lyjeMPvXetEKqoDoLi5Owy1zNue3yg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10/go.mod h1:a57l7Hwh+FWI+we50g5NPJHYUKeJKfXbc4w8SyXu8Ig=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 h1:W/EyPFl9A5rXrtoilfwHYEvzHER+K4SpBPtMXi24Mos=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18/go.mod h1:UG50K+pvd/uy6xExbobg0rjqFBFZe6I3l75EPDZw4tg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25 h1:dD3dhHNglpd98gs72my22Ndqi1hqQGllFFg1F+twfxg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25/go.mod h1:0yAbjPfd64gG7mj85RW+fMEYdfBgCRZw8g/oWcL1pjc=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDbiit/GcBE2K4IUpMZymaA0kOz3xK978=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1 h1:1VwbP3qMNfxUDEXWki4rCE5iA+44VA1lokTz9HasGzw=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1/go.mod h1:vUtyoSj0OPji3kjIVSc/GlKuWEiL33f/WFxl6dmpy/A=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19 h1:N6pIsdFOW1Kd9S4KyFKXdGRBojPPxkP32+uHFWLv4Hc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19/go.mod h1:3gt5WJArFooNmyLONS+h/R4J+o86II8du38IgCwj9dE=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2 h1:hc+lBYiiTr8Zk4MTzIsQ92MeDWCIDvWGmzKUWOaBcOg=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2/go.mod h1:hU6fqB3OJA6/ePheD47LQnxvjYk6br6PtQxs+Q9ojvk=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3 h1:ErklX/7uhSbkAAeyQD/Y1OoQ9hO3SJXQNEgksORW3Js=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3/go.mod h1:ULe4HCzfKPiR6R3HEurE3b1upEkuk8AkMrOKtaOxKO8=
|
||||
github.com/aws/smithy-go v1.26.0 h1:9ouqbi+NyKP7fV3Te7UElCwdAb6Y8uk7LGwPE5tVe/s=
|
||||
github.com/aws/smithy-go v1.26.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik=
|
||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||
@@ -21,6 +85,11 @@ github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7np
|
||||
github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=
|
||||
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
|
||||
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||
@@ -29,26 +98,69 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY=
|
||||
github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7 h1:PdT4jVPbRb4R+0Ey2R0yJOdctVf4Whiq1Qi4necaZdg=
|
||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7/go.mod h1:3ouXglTuPrKF5+7cQyVGfvAXTU4vLMaYh9+EPl03uog=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.30.4 h1:9Rcod2ZPO6mOEG6b4GqyoHE/H6//Ze0RuhOo1hT1x0w=
|
||||
github.com/go-playground/validator/v10 v10.30.4/go.mod h1:numpT+RPLE91R9oYWMY/R9zRgJBewr3IXHko4OISPpk=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
|
||||
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=
|
||||
github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg=
|
||||
github.com/googleapis/gax-go/v2 v2.19.0 h1:fYQaUOiGwll0cGj7jmHT/0nPlcrZDFPrZRhTsoCr8hE=
|
||||
github.com/googleapis/gax-go/v2 v2.19.0/go.mod h1:w2ROXVdfGEVFXzmlciUU4EdjHgWvB5h2n6x/8XSTTJA=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0=
|
||||
github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
@@ -67,12 +179,18 @@ github.com/knadh/koanf/providers/file v1.2.1 h1:bEWbtQwYrA+W2DtdBrQWyXqJaJSG3KrP
|
||||
github.com/knadh/koanf/providers/file v1.2.1/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA=
|
||||
github.com/knadh/koanf/v2 v2.3.6 h1:JoQPSJmvS4aP0xNc8xMDr5tcrkSEInL23/Il7pITAKo=
|
||||
github.com/knadh/koanf/v2 v2.3.6/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=
|
||||
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
|
||||
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
|
||||
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
|
||||
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
|
||||
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRtzAscm/zF23XxJlbECiGPyRicsX+Ak=
|
||||
github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
|
||||
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
|
||||
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
|
||||
github.com/mdelapenya/tlscert v0.2.0/go.mod h1:O4njj3ELLnJjGdkN7M/vIVCpZ+Cf0L6muqOG4tLSl8o=
|
||||
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
|
||||
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
|
||||
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
|
||||
@@ -101,8 +219,25 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
|
||||
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/riverqueue/river v0.47.0 h1:j8HOEyiOE8gRRhVS2wllKams372TH1WWiH6xCakXHqc=
|
||||
github.com/riverqueue/river v0.47.0/go.mod h1:Wgmwx475ZBd8lQnNrJgyG2DWH7BfyNiSAtv0rC9bJBQ=
|
||||
github.com/riverqueue/river/riverdriver v0.47.0 h1:qU8VkjdMl9plqeRg57SxsDUM/i/eECaSYejZ7HynC60=
|
||||
github.com/riverqueue/river/riverdriver v0.47.0/go.mod h1:NOXl0fUiF1AT/TaQOjdx2A/c0Davn+SKbW8nAXWjfC4=
|
||||
github.com/riverqueue/river/riverdriver/riverdatabasesql v0.47.0 h1:4wckhMlLN08F76/GWxGF6vlrbs5HCMuV01dpUnvOGI4=
|
||||
github.com/riverqueue/river/riverdriver/riverdatabasesql v0.47.0/go.mod h1:EME1EGr7RU/vMUf61mpf9YXhsZJ+GlFk4AHrIHT+YdE=
|
||||
github.com/riverqueue/river/riverdriver/riverpgxv5 v0.47.0 h1:5N9nvemhQwbUElMxASw4oEaYJ/v6hiS5Y9VcOQfdC5g=
|
||||
github.com/riverqueue/river/riverdriver/riverpgxv5 v0.47.0/go.mod h1:ZboiXXZKC4+fTkxBxGRVmAsCuUu0NPYliqbWYuQAZyw=
|
||||
github.com/riverqueue/river/rivershared v0.47.0 h1:jdtFsBexCvLqTXf8wnDnGXvB/eeOtPKQZAmThkjFpLs=
|
||||
github.com/riverqueue/river/rivershared v0.47.0/go.mod h1:w8Pi1T+6ypyko5/hs9Mv7IIIKo4fAL9eXYnkVV/Y418=
|
||||
github.com/riverqueue/river/rivertype v0.47.0 h1:SzNavtLGR4nMT1QkrEYQ7n96OMatYsn/z3aJWhewmv0=
|
||||
github.com/riverqueue/river/rivertype v0.47.0/go.mod h1:XKkcRQR6zm8RR/JQa1Q2ywpj8uXQu21quPa4Lpw1Xhw=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=
|
||||
github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
|
||||
@@ -112,10 +247,30 @@ github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
|
||||
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/testcontainers/testcontainers-go v0.44.0 h1:/Fwh6HY1mIikhnm9e7HwoxGycx0lzRAE0f5VQpjFxzI=
|
||||
github.com/testcontainers/testcontainers-go v0.44.0/go.mod h1:IcnwQrYTO86xHXu5bvMaBH7ATlbS3Qn1M1QWW3c66rE=
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 h1:8fdv/9y3JMxjQ+ULAcOG8RtgeNu5t9XF9LolSXDuTwM=
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0/go.mod h1:CFr2LncGYokw+OKjXcr8ARCKG1SaC2UEnGxFBovE86g=
|
||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.19.0 h1:xwxm7n691Uf3u5OFjzngavjGTh55KX5q/9w9xHW88JU=
|
||||
github.com/tidwall/gjson v1.19.0/go.mod h1:V37/opeE/JbLUOfH0QTXiNez2l0RUjYUhpT4szFQAfc=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/match v1.2.0 h1:0pt8FlkOwjN2fPt4bIl4BoNxb98gGHN2ObFEDkrfZnM=
|
||||
github.com/tidwall/match v1.2.0/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||
github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU=
|
||||
github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI=
|
||||
github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4=
|
||||
@@ -128,27 +283,80 @@ github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.42.0 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.42.0/go.mod h1:W9zQ439utxymRrXsUOzZbFX4JhLxXU4+ZnCt8GG7yA8=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA=
|
||||
go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q=
|
||||
gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
|
||||
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=
|
||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/api v0.272.0 h1:eLUQZGnAS3OHn31URRf9sAmRk3w2JjMx37d2k8AjJmA=
|
||||
google.golang.org/api v0.272.0/go.mod h1:wKjowi5LNJc5qarNvDCvNQBn3rVK8nSy6jg2SwRwzIA=
|
||||
google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5 h1:JNfk58HZ8lfmXbYK2vx/UvsqIL59TzByCxPIX4TDmsE=
|
||||
google.golang.org/genproto v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:x5julN69+ED4PcFk/XWayw35O0lf/nGa4aNgODCmNmw=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5 h1:CogIeEXn4qWYzzQU0QqvYBM8yDF9cFYzDq9ojSpv0Js=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:EIQZ5bFCfRQDV4MhRle7+OgjNtZ6P1PiZBgAKuxXu/Y=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 h1:aJmi6DVGGIStN9Mobk/tZOOQUBbj0BPjZjjnOdoZKts=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.6.3 h1:bAn6O2pUa8LtpWEvL5NFU4+52Tfx8Ut7IVaIacCLcI0=
|
||||
gorm.io/driver/postgres v1.6.3/go.mod h1:0c4fQA44XhOklXDkgtuKqysHCycTa5i9e3EIpDGCwXk=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
|
||||
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
|
||||
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
|
||||
pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk=
|
||||
pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04=
|
||||
|
||||
@@ -1 +1,97 @@
|
||||
{}
|
||||
plugin:
|
||||
name: BM studies
|
||||
description: Courses, timetable, deadlines, readings and materials of the BM master's programme.
|
||||
permissions:
|
||||
access_courses: Manage courses and readings
|
||||
access_schedule: Manage meetings, class sessions and deadlines
|
||||
access_materials: Manage materials and tags
|
||||
navigation:
|
||||
courses: Courses
|
||||
readings: Readings
|
||||
meetings: Meetings
|
||||
sessions: Class sessions
|
||||
deadlines: Deadlines
|
||||
materials: Materials
|
||||
tags: Tags
|
||||
common:
|
||||
title: Title
|
||||
description: Description
|
||||
notes: Notes
|
||||
course: Course
|
||||
source: Source
|
||||
url: URL
|
||||
sort_order: Sort order
|
||||
created_at: Created
|
||||
none: — none —
|
||||
date_comment: A date in the YYYY-MM-DD form, such as 2026-10-03.
|
||||
datetime_comment: Date and time in Polish time, such as 2026-10-03 08:00.
|
||||
forms:
|
||||
wyklad: Lecture
|
||||
cwiczenia: Tutorial
|
||||
konwersatorium: Conversatorium
|
||||
seminarium: Seminar
|
||||
inne: Other
|
||||
courses:
|
||||
title: Courses
|
||||
form: Course
|
||||
name: Name
|
||||
form_type: Form
|
||||
code: Code
|
||||
lecturer: Lecturer
|
||||
semester: Semester
|
||||
ects: ECTS
|
||||
assessment: Assessment
|
||||
assessment_comment: Such as egzamin or zaliczenie na ocenę.
|
||||
elective_group: Elective group
|
||||
elective_group_comment: Courses with the same value are alternatives to choose from, such as specjalnosc.
|
||||
syllabus_url: Syllabus URL
|
||||
meetings:
|
||||
title: Meetings
|
||||
form: Meeting
|
||||
number: Meeting number
|
||||
starts_on: From
|
||||
ends_on: To
|
||||
sessions:
|
||||
title: Class sessions
|
||||
form: Class session
|
||||
meeting: Meeting
|
||||
starts_at: Starts
|
||||
ends_at: Ends
|
||||
room: Room
|
||||
kind: Kind
|
||||
is_online: Online
|
||||
deadlines:
|
||||
title: Deadlines
|
||||
form: Deadline
|
||||
due_at: Due
|
||||
kind: Kind
|
||||
deadline_kinds:
|
||||
zaliczenie: Credit
|
||||
egzamin: Exam
|
||||
praca: Paper
|
||||
organizacyjne: Administrative
|
||||
inne: Other
|
||||
readings:
|
||||
title: Readings
|
||||
form: Reading
|
||||
author: Author
|
||||
is_required: Required
|
||||
materials:
|
||||
title: Materials
|
||||
form: Material
|
||||
type: Type
|
||||
body: Body (Markdown)
|
||||
body_comment: A note in Markdown.
|
||||
published_at: Published
|
||||
published_at_comment: Leave empty for a draft that students do not see. Such as 2026-10-03 08:00.
|
||||
tags: Tags
|
||||
material_types:
|
||||
pdf: PDF
|
||||
notatka: Note
|
||||
link: Link
|
||||
inne: Other
|
||||
tags:
|
||||
title: Tags
|
||||
form: Tag
|
||||
name: Name
|
||||
slug: Slug
|
||||
|
||||
97
lang/pl/lang.yaml
Normal file
97
lang/pl/lang.yaml
Normal file
@@ -0,0 +1,97 @@
|
||||
plugin:
|
||||
name: Studia BM
|
||||
description: Przedmioty, plan zajęć, terminarz, lektury i materiały studiów magisterskich BM.
|
||||
permissions:
|
||||
access_courses: Zarządzanie przedmiotami i lekturami
|
||||
access_schedule: Zarządzanie zjazdami, zajęciami i terminarzem
|
||||
access_materials: Zarządzanie materiałami i tagami
|
||||
navigation:
|
||||
courses: Przedmioty
|
||||
readings: Lektury
|
||||
meetings: Zjazdy
|
||||
sessions: Zajęcia
|
||||
deadlines: Terminarz
|
||||
materials: Materiały
|
||||
tags: Tagi
|
||||
common:
|
||||
title: Tytuł
|
||||
description: Opis
|
||||
notes: Uwagi
|
||||
course: Przedmiot
|
||||
source: Źródło
|
||||
url: Adres URL
|
||||
sort_order: Kolejność
|
||||
created_at: Utworzono
|
||||
none: — brak —
|
||||
date_comment: Data w formacie RRRR-MM-DD, np. 2026-10-03.
|
||||
datetime_comment: Data i godzina czasu polskiego, np. 2026-10-03 08:00.
|
||||
forms:
|
||||
wyklad: Wykład
|
||||
cwiczenia: Ćwiczenia
|
||||
konwersatorium: Konwersatorium
|
||||
seminarium: Seminarium
|
||||
inne: Inne
|
||||
courses:
|
||||
title: Przedmioty
|
||||
form: Przedmiot
|
||||
name: Nazwa
|
||||
form_type: Forma zajęć
|
||||
code: Kod
|
||||
lecturer: Prowadzący
|
||||
semester: Semestr
|
||||
ects: ECTS
|
||||
assessment: Forma zaliczenia
|
||||
assessment_comment: Np. egzamin, zaliczenie na ocenę.
|
||||
elective_group: Grupa do wyboru
|
||||
elective_group_comment: Przedmioty o tej samej wartości są alternatywami do wyboru, np. specjalnosc.
|
||||
syllabus_url: Sylabus (URL)
|
||||
meetings:
|
||||
title: Zjazdy
|
||||
form: Zjazd
|
||||
number: Numer zjazdu
|
||||
starts_on: Od
|
||||
ends_on: Do
|
||||
sessions:
|
||||
title: Zajęcia
|
||||
form: Zajęcia
|
||||
meeting: Zjazd
|
||||
starts_at: Początek
|
||||
ends_at: Koniec
|
||||
room: Sala
|
||||
kind: Rodzaj
|
||||
is_online: Zdalnie
|
||||
deadlines:
|
||||
title: Terminarz
|
||||
form: Termin
|
||||
due_at: Termin
|
||||
kind: Rodzaj
|
||||
deadline_kinds:
|
||||
zaliczenie: Zaliczenie
|
||||
egzamin: Egzamin
|
||||
praca: Praca
|
||||
organizacyjne: Organizacyjne
|
||||
inne: Inne
|
||||
readings:
|
||||
title: Lektury
|
||||
form: Lektura
|
||||
author: Autor
|
||||
is_required: Obowiązkowa
|
||||
materials:
|
||||
title: Materiały
|
||||
form: Materiał
|
||||
type: Typ
|
||||
body: Treść (Markdown)
|
||||
body_comment: Notatka w Markdownie.
|
||||
published_at: Opublikowano
|
||||
published_at_comment: Puste pole to szkic, niewidoczny dla studentów. Np. 2026-10-03 08:00.
|
||||
tags: Tagi
|
||||
material_types:
|
||||
pdf: PDF
|
||||
notatka: Notatka
|
||||
link: Link
|
||||
inne: Inne
|
||||
tags:
|
||||
title: Tagi
|
||||
form: Tag
|
||||
name: Nazwa
|
||||
slug: Slug
|
||||
63
models/class_session.go
Normal file
63
models/class_session.go
Normal file
@@ -0,0 +1,63 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ClassSession is one block of classes (zajęcia) of a course.
|
||||
type ClassSession struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
CourseID uint `gorm:"column:course_id"`
|
||||
Course *Course `gorm:"foreignKey:CourseID"`
|
||||
MeetingID *uint `gorm:"column:meeting_id"`
|
||||
Meeting *Meeting `gorm:"foreignKey:MeetingID"`
|
||||
StartsAt DateTime `gorm:"column:starts_at"`
|
||||
EndsAt DateTime `gorm:"column:ends_at"`
|
||||
Room *string `gorm:"column:room"`
|
||||
Kind *string `gorm:"column:kind"`
|
||||
Notes *string `gorm:"column:notes"`
|
||||
IsOnline bool `gorm:"column:is_online"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
// TableName is the plugin table.
|
||||
func (ClassSession) TableName() string { return "jz_bm_class_sessions" }
|
||||
|
||||
// Fillable lists the columns mass assignment may set. course_id and
|
||||
// meeting_id are set through the admin relation pickers.
|
||||
func (ClassSession) Fillable() []string {
|
||||
return []string{"course_id", "meeting_id", "starts_at", "ends_at", "room", "kind", "notes", "is_online"}
|
||||
}
|
||||
|
||||
// Rules are checked by the admin API on every save.
|
||||
func (ClassSession) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"starts_at": "required",
|
||||
"ends_at": "required",
|
||||
"room": "nullable|max:100",
|
||||
"kind": "nullable|max:100",
|
||||
"is_online": "boolean",
|
||||
}
|
||||
}
|
||||
|
||||
// TemporalErrors checks the timestamps, which lagoon.Validate cannot.
|
||||
func (s *ClassSession) TemporalErrors() map[string][]string {
|
||||
e := temporalErrors{}
|
||||
e.dateTime("starts_at", s.StartsAt, true)
|
||||
e.dateTime("ends_at", s.EndsAt, true)
|
||||
if len(e) == 0 && !s.EndsAt.MustTime().After(s.StartsAt.MustTime()) {
|
||||
e.add("ends_at", "The ends at must be a date after starts at.")
|
||||
}
|
||||
return e.result()
|
||||
}
|
||||
|
||||
// BeforeSave stores NULL for empty optional text.
|
||||
func (s *ClassSession) BeforeSave(*gorm.DB) error {
|
||||
blank(&s.Room, &s.Kind, &s.Notes)
|
||||
return nil
|
||||
}
|
||||
16
models/class_sessions/columns.yaml
Normal file
16
models/class_sessions/columns.yaml
Normal file
@@ -0,0 +1,16 @@
|
||||
columns:
|
||||
starts_at:
|
||||
label: jz.bm::lang.sessions.starts_at
|
||||
ends_at:
|
||||
label: jz.bm::lang.sessions.ends_at
|
||||
course:
|
||||
label: jz.bm::lang.common.course
|
||||
relation: course
|
||||
select: name
|
||||
searchable: true
|
||||
room:
|
||||
label: jz.bm::lang.sessions.room
|
||||
searchable: true
|
||||
is_online:
|
||||
label: jz.bm::lang.sessions.is_online
|
||||
type: switch
|
||||
41
models/class_sessions/fields.yaml
Normal file
41
models/class_sessions/fields.yaml
Normal file
@@ -0,0 +1,41 @@
|
||||
fields:
|
||||
course:
|
||||
label: jz.bm::lang.common.course
|
||||
type: relation
|
||||
nameFrom: name
|
||||
span: left
|
||||
required: true
|
||||
meeting:
|
||||
label: jz.bm::lang.sessions.meeting
|
||||
type: relation
|
||||
nameFrom: number
|
||||
span: right
|
||||
emptyOption: jz.bm::lang.common.none
|
||||
starts_at:
|
||||
label: jz.bm::lang.sessions.starts_at
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
comment: jz.bm::lang.common.datetime_comment
|
||||
ends_at:
|
||||
label: jz.bm::lang.sessions.ends_at
|
||||
type: text
|
||||
span: right
|
||||
required: true
|
||||
comment: jz.bm::lang.common.datetime_comment
|
||||
room:
|
||||
label: jz.bm::lang.sessions.room
|
||||
type: text
|
||||
span: left
|
||||
kind:
|
||||
label: jz.bm::lang.sessions.kind
|
||||
type: text
|
||||
span: right
|
||||
is_online:
|
||||
label: jz.bm::lang.sessions.is_online
|
||||
type: switch
|
||||
span: left
|
||||
notes:
|
||||
label: jz.bm::lang.common.notes
|
||||
type: textarea
|
||||
size: small
|
||||
72
models/course.go
Normal file
72
models/course.go
Normal file
@@ -0,0 +1,72 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Course forms, the values of Course.Form.
|
||||
const (
|
||||
FormWyklad = "wyklad"
|
||||
FormCwiczenia = "cwiczenia"
|
||||
FormKonwersatorium = "konwersatorium"
|
||||
FormSeminarium = "seminarium"
|
||||
FormInne = "inne"
|
||||
)
|
||||
|
||||
// CourseForms lists the allowed Course.Form values.
|
||||
var CourseForms = []string{FormWyklad, FormCwiczenia, FormKonwersatorium, FormSeminarium, FormInne}
|
||||
|
||||
// Course is one przedmiot of the programme in one form (a lecture and its
|
||||
// tutorial are two courses).
|
||||
type Course struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Code *string `gorm:"column:code"`
|
||||
Name string `gorm:"column:name"`
|
||||
Form string `gorm:"column:form"`
|
||||
Lecturer *string `gorm:"column:lecturer"`
|
||||
Semester int `gorm:"column:semester"`
|
||||
ECTS *float64 `gorm:"column:ects"`
|
||||
Assessment *string `gorm:"column:assessment"`
|
||||
// ElectiveGroup marks alternatives ("do wyboru"): courses that share a
|
||||
// value are options of one choice, such as "specjalnosc".
|
||||
ElectiveGroup *string `gorm:"column:elective_group"`
|
||||
Description *string `gorm:"column:description"`
|
||||
SyllabusURL *string `gorm:"column:syllabus_url"`
|
||||
SortOrder int `gorm:"column:sort_order"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
// TableName is the plugin table.
|
||||
func (Course) TableName() string { return "jz_bm_courses" }
|
||||
|
||||
// Fillable lists the columns mass assignment may set.
|
||||
func (Course) Fillable() []string {
|
||||
return []string{"code", "name", "form", "lecturer", "semester", "ects", "assessment", "elective_group", "description", "syllabus_url", "sort_order"}
|
||||
}
|
||||
|
||||
// Rules are checked by the admin API on every save.
|
||||
func (Course) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"code": "nullable|max:50",
|
||||
"name": "required|max:255",
|
||||
"form": "required|in:wyklad,cwiczenia,konwersatorium,seminarium,inne",
|
||||
"lecturer": "nullable|max:255",
|
||||
"semester": "required|integer|between:1,4",
|
||||
"ects": "nullable|numeric|between:0,60",
|
||||
"assessment": "nullable|max:100",
|
||||
"elective_group": "nullable|max:100",
|
||||
"syllabus_url": "nullable|max:2048",
|
||||
"sort_order": "nullable|integer",
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeSave stores NULL for empty optional text.
|
||||
func (c *Course) BeforeSave(*gorm.DB) error {
|
||||
blank(&c.Code, &c.Lecturer, &c.Assessment, &c.ElectiveGroup, &c.Description, &c.SyllabusURL)
|
||||
return nil
|
||||
}
|
||||
17
models/courses/columns.yaml
Normal file
17
models/courses/columns.yaml
Normal file
@@ -0,0 +1,17 @@
|
||||
columns:
|
||||
name:
|
||||
label: jz.bm::lang.courses.name
|
||||
searchable: true
|
||||
form:
|
||||
label: jz.bm::lang.courses.form_type
|
||||
semester:
|
||||
label: jz.bm::lang.courses.semester
|
||||
lecturer:
|
||||
label: jz.bm::lang.courses.lecturer
|
||||
searchable: true
|
||||
ects:
|
||||
label: jz.bm::lang.courses.ects
|
||||
elective_group:
|
||||
label: jz.bm::lang.courses.elective_group
|
||||
sort_order:
|
||||
label: jz.bm::lang.common.sort_order
|
||||
58
models/courses/fields.yaml
Normal file
58
models/courses/fields.yaml
Normal file
@@ -0,0 +1,58 @@
|
||||
fields:
|
||||
name:
|
||||
label: jz.bm::lang.courses.name
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
form:
|
||||
label: jz.bm::lang.courses.form_type
|
||||
type: dropdown
|
||||
span: right
|
||||
required: true
|
||||
options:
|
||||
wyklad: jz.bm::lang.forms.wyklad
|
||||
cwiczenia: jz.bm::lang.forms.cwiczenia
|
||||
konwersatorium: jz.bm::lang.forms.konwersatorium
|
||||
seminarium: jz.bm::lang.forms.seminarium
|
||||
inne: jz.bm::lang.forms.inne
|
||||
semester:
|
||||
label: jz.bm::lang.courses.semester
|
||||
type: number
|
||||
span: left
|
||||
required: true
|
||||
default: 1
|
||||
code:
|
||||
label: jz.bm::lang.courses.code
|
||||
type: text
|
||||
span: right
|
||||
lecturer:
|
||||
label: jz.bm::lang.courses.lecturer
|
||||
type: text
|
||||
span: left
|
||||
ects:
|
||||
label: jz.bm::lang.courses.ects
|
||||
type: number
|
||||
span: right
|
||||
assessment:
|
||||
label: jz.bm::lang.courses.assessment
|
||||
type: text
|
||||
span: left
|
||||
comment: jz.bm::lang.courses.assessment_comment
|
||||
elective_group:
|
||||
label: jz.bm::lang.courses.elective_group
|
||||
type: text
|
||||
span: right
|
||||
comment: jz.bm::lang.courses.elective_group_comment
|
||||
sort_order:
|
||||
label: jz.bm::lang.common.sort_order
|
||||
type: number
|
||||
span: left
|
||||
default: 0
|
||||
syllabus_url:
|
||||
label: jz.bm::lang.courses.syllabus_url
|
||||
type: text
|
||||
span: right
|
||||
description:
|
||||
label: jz.bm::lang.common.description
|
||||
type: textarea
|
||||
size: large
|
||||
56
models/deadline.go
Normal file
56
models/deadline.go
Normal file
@@ -0,0 +1,56 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// DeadlineKinds lists the allowed Deadline.Kind values.
|
||||
var DeadlineKinds = []string{"zaliczenie", "egzamin", "praca", "organizacyjne", "inne"}
|
||||
|
||||
// Deadline is one entry of the terminarz: an exam, a submission or an
|
||||
// administrative date, optionally tied to a course.
|
||||
type Deadline struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Title string `gorm:"column:title"`
|
||||
DueAt DateTime `gorm:"column:due_at"`
|
||||
CourseID *uint `gorm:"column:course_id"`
|
||||
Course *Course `gorm:"foreignKey:CourseID"`
|
||||
Kind string `gorm:"column:kind"`
|
||||
Description *string `gorm:"column:description"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
// TableName is the plugin table.
|
||||
func (Deadline) TableName() string { return "jz_bm_deadlines" }
|
||||
|
||||
// Fillable lists the columns mass assignment may set.
|
||||
func (Deadline) Fillable() []string {
|
||||
return []string{"title", "due_at", "course_id", "kind", "description"}
|
||||
}
|
||||
|
||||
// Rules are checked by the admin API on every save.
|
||||
func (Deadline) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"title": "required|max:255",
|
||||
"due_at": "required",
|
||||
"kind": "required|in:zaliczenie,egzamin,praca,organizacyjne,inne",
|
||||
}
|
||||
}
|
||||
|
||||
// TemporalErrors checks the due time, which lagoon.Validate cannot.
|
||||
func (d *Deadline) TemporalErrors() map[string][]string {
|
||||
e := temporalErrors{}
|
||||
e.dateTime("due_at", d.DueAt, true)
|
||||
return e.result()
|
||||
}
|
||||
|
||||
// BeforeSave stores NULL for empty optional text.
|
||||
func (d *Deadline) BeforeSave(*gorm.DB) error {
|
||||
blank(&d.Description)
|
||||
return nil
|
||||
}
|
||||
12
models/deadlines/columns.yaml
Normal file
12
models/deadlines/columns.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
columns:
|
||||
due_at:
|
||||
label: jz.bm::lang.deadlines.due_at
|
||||
title:
|
||||
label: jz.bm::lang.common.title
|
||||
searchable: true
|
||||
kind:
|
||||
label: jz.bm::lang.deadlines.kind
|
||||
course:
|
||||
label: jz.bm::lang.common.course
|
||||
relation: course
|
||||
select: name
|
||||
33
models/deadlines/fields.yaml
Normal file
33
models/deadlines/fields.yaml
Normal file
@@ -0,0 +1,33 @@
|
||||
fields:
|
||||
title:
|
||||
label: jz.bm::lang.common.title
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
due_at:
|
||||
label: jz.bm::lang.deadlines.due_at
|
||||
type: text
|
||||
span: right
|
||||
required: true
|
||||
comment: jz.bm::lang.common.datetime_comment
|
||||
kind:
|
||||
label: jz.bm::lang.deadlines.kind
|
||||
type: dropdown
|
||||
span: left
|
||||
required: true
|
||||
options:
|
||||
zaliczenie: jz.bm::lang.deadline_kinds.zaliczenie
|
||||
egzamin: jz.bm::lang.deadline_kinds.egzamin
|
||||
praca: jz.bm::lang.deadline_kinds.praca
|
||||
organizacyjne: jz.bm::lang.deadline_kinds.organizacyjne
|
||||
inne: jz.bm::lang.deadline_kinds.inne
|
||||
course:
|
||||
label: jz.bm::lang.common.course
|
||||
type: relation
|
||||
nameFrom: name
|
||||
span: right
|
||||
emptyOption: jz.bm::lang.common.none
|
||||
description:
|
||||
label: jz.bm::lang.common.description
|
||||
type: textarea
|
||||
size: small
|
||||
75
models/material.go
Normal file
75
models/material.go
Normal file
@@ -0,0 +1,75 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MaterialTypes lists the allowed Material.Type values.
|
||||
var MaterialTypes = []string{"pdf", "notatka", "link", "inne"}
|
||||
|
||||
// MaterialFilesField is the system_files field of a material's attachments
|
||||
// (attachMany "files").
|
||||
const MaterialFilesField = "files"
|
||||
|
||||
// Material is a study material: a note, a link or uploaded files, optionally
|
||||
// tied to a course. A material without published_at is a draft and is not
|
||||
// served by the API.
|
||||
type Material struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
CourseID *uint `gorm:"column:course_id"`
|
||||
Course *Course `gorm:"foreignKey:CourseID"`
|
||||
Title string `gorm:"column:title"`
|
||||
Type string `gorm:"column:type"`
|
||||
Body *string `gorm:"column:body"`
|
||||
Source *string `gorm:"column:source"`
|
||||
URL *string `gorm:"column:url"`
|
||||
PublishedAt *DateTime `gorm:"column:published_at"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
|
||||
Tags []Tag `gorm:"many2many:jz_bm_material_tag;joinForeignKey:material_id;joinReferences:tag_id"`
|
||||
}
|
||||
|
||||
// TableName is the plugin table.
|
||||
func (Material) TableName() string { return "jz_bm_materials" }
|
||||
|
||||
// MorphName is the attachment_type of the material's system_files rows.
|
||||
func (Material) MorphName() string { return `Jz\Bm\Models\Material` }
|
||||
|
||||
// Fillable lists the columns mass assignment may set.
|
||||
func (Material) Fillable() []string {
|
||||
return []string{"course_id", "title", "type", "body", "source", "url", "published_at"}
|
||||
}
|
||||
|
||||
// Rules are checked by the admin API on every save.
|
||||
func (Material) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"title": "required|max:255",
|
||||
"type": "required|in:pdf,notatka,link,inne",
|
||||
"source": "nullable|max:500",
|
||||
"url": "nullable|max:2048",
|
||||
}
|
||||
}
|
||||
|
||||
// TemporalErrors checks published_at, which lagoon.Validate cannot.
|
||||
func (m *Material) TemporalErrors() map[string][]string {
|
||||
e := temporalErrors{}
|
||||
if m.PublishedAt != nil {
|
||||
e.dateTime("published_at", *m.PublishedAt, false)
|
||||
}
|
||||
return e.result()
|
||||
}
|
||||
|
||||
// BeforeSave stores NULL for empty optional text and an empty publication
|
||||
// time.
|
||||
func (m *Material) BeforeSave(*gorm.DB) error {
|
||||
blank(&m.Body, &m.Source, &m.URL)
|
||||
if m.PublishedAt != nil && *m.PublishedAt == "" {
|
||||
m.PublishedAt = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
12
models/material_tag.go
Normal file
12
models/material_tag.go
Normal file
@@ -0,0 +1,12 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
// MaterialTag is the pivot row between a material and a tag.
|
||||
type MaterialTag struct {
|
||||
MaterialID uint `gorm:"column:material_id;primaryKey"`
|
||||
TagID uint `gorm:"column:tag_id;primaryKey"`
|
||||
}
|
||||
|
||||
// TableName is the pivot table.
|
||||
func (MaterialTag) TableName() string { return "jz_bm_material_tag" }
|
||||
15
models/materials/columns.yaml
Normal file
15
models/materials/columns.yaml
Normal file
@@ -0,0 +1,15 @@
|
||||
columns:
|
||||
title:
|
||||
label: jz.bm::lang.common.title
|
||||
searchable: true
|
||||
type:
|
||||
label: jz.bm::lang.materials.type
|
||||
course:
|
||||
label: jz.bm::lang.common.course
|
||||
relation: course
|
||||
select: name
|
||||
published_at:
|
||||
label: jz.bm::lang.materials.published_at
|
||||
created_at:
|
||||
label: jz.bm::lang.common.created_at
|
||||
type: datetime
|
||||
46
models/materials/fields.yaml
Normal file
46
models/materials/fields.yaml
Normal file
@@ -0,0 +1,46 @@
|
||||
# Attached files (system_files, field "files") have no form widget yet; see
|
||||
# the TODO on materialsAdmin.AdminFieldRelations.
|
||||
fields:
|
||||
title:
|
||||
label: jz.bm::lang.common.title
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
type:
|
||||
label: jz.bm::lang.materials.type
|
||||
type: dropdown
|
||||
span: right
|
||||
required: true
|
||||
options:
|
||||
pdf: jz.bm::lang.material_types.pdf
|
||||
notatka: jz.bm::lang.material_types.notatka
|
||||
link: jz.bm::lang.material_types.link
|
||||
inne: jz.bm::lang.material_types.inne
|
||||
course:
|
||||
label: jz.bm::lang.common.course
|
||||
type: relation
|
||||
nameFrom: name
|
||||
span: left
|
||||
emptyOption: jz.bm::lang.common.none
|
||||
published_at:
|
||||
label: jz.bm::lang.materials.published_at
|
||||
type: text
|
||||
span: right
|
||||
comment: jz.bm::lang.materials.published_at_comment
|
||||
source:
|
||||
label: jz.bm::lang.common.source
|
||||
type: text
|
||||
span: left
|
||||
url:
|
||||
label: jz.bm::lang.common.url
|
||||
type: text
|
||||
span: right
|
||||
tags:
|
||||
label: jz.bm::lang.materials.tags
|
||||
type: relation
|
||||
nameFrom: name
|
||||
body:
|
||||
label: jz.bm::lang.materials.body
|
||||
type: textarea
|
||||
size: giant
|
||||
comment: jz.bm::lang.materials.body_comment
|
||||
52
models/meeting.go
Normal file
52
models/meeting.go
Normal file
@@ -0,0 +1,52 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Meeting is one zjazd: a weekend of classes of the part-time programme.
|
||||
type Meeting struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Number int `gorm:"column:number"`
|
||||
StartsOn Date `gorm:"column:starts_on"`
|
||||
EndsOn Date `gorm:"column:ends_on"`
|
||||
Notes *string `gorm:"column:notes"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
// TableName is the plugin table.
|
||||
func (Meeting) TableName() string { return "jz_bm_meetings" }
|
||||
|
||||
// Fillable lists the columns mass assignment may set.
|
||||
func (Meeting) Fillable() []string { return []string{"number", "starts_on", "ends_on", "notes"} }
|
||||
|
||||
// Rules are checked by the admin API on every save.
|
||||
func (Meeting) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"number": "required|integer|min:1|unique:jz_bm_meetings",
|
||||
"starts_on": "required",
|
||||
"ends_on": "required",
|
||||
}
|
||||
}
|
||||
|
||||
// TemporalErrors checks the dates, which lagoon.Validate cannot.
|
||||
func (m *Meeting) TemporalErrors() map[string][]string {
|
||||
e := temporalErrors{}
|
||||
e.date("starts_on", m.StartsOn, true)
|
||||
e.date("ends_on", m.EndsOn, true)
|
||||
if len(e) == 0 && m.EndsOn < m.StartsOn {
|
||||
e.add("ends_on", "The ends on must be a date after or equal to starts on.")
|
||||
}
|
||||
return e.result()
|
||||
}
|
||||
|
||||
// BeforeSave stores NULL for empty optional text.
|
||||
func (m *Meeting) BeforeSave(*gorm.DB) error {
|
||||
blank(&m.Notes)
|
||||
return nil
|
||||
}
|
||||
11
models/meetings/columns.yaml
Normal file
11
models/meetings/columns.yaml
Normal file
@@ -0,0 +1,11 @@
|
||||
columns:
|
||||
number:
|
||||
label: jz.bm::lang.meetings.number
|
||||
starts_on:
|
||||
label: jz.bm::lang.meetings.starts_on
|
||||
ends_on:
|
||||
label: jz.bm::lang.meetings.ends_on
|
||||
notes:
|
||||
label: jz.bm::lang.common.notes
|
||||
searchable: true
|
||||
sortable: false
|
||||
22
models/meetings/fields.yaml
Normal file
22
models/meetings/fields.yaml
Normal file
@@ -0,0 +1,22 @@
|
||||
fields:
|
||||
number:
|
||||
label: jz.bm::lang.meetings.number
|
||||
type: number
|
||||
span: left
|
||||
required: true
|
||||
starts_on:
|
||||
label: jz.bm::lang.meetings.starts_on
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
comment: jz.bm::lang.common.date_comment
|
||||
ends_on:
|
||||
label: jz.bm::lang.meetings.ends_on
|
||||
type: text
|
||||
span: right
|
||||
required: true
|
||||
comment: jz.bm::lang.common.date_comment
|
||||
notes:
|
||||
label: jz.bm::lang.common.notes
|
||||
type: textarea
|
||||
size: small
|
||||
50
models/nullable.go
Normal file
50
models/nullable.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package models
|
||||
|
||||
import "strings"
|
||||
|
||||
// blank clears each optional text column whose value is empty or only
|
||||
// whitespace, so an emptied admin text input stores NULL rather than "".
|
||||
func blank(fields ...**string) {
|
||||
for _, f := range fields {
|
||||
if *f != nil && strings.TrimSpace(**f) == "" {
|
||||
*f = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// temporalErrors is a field-to-messages map in the shape of lagoon.Validate.
|
||||
type temporalErrors map[string][]string
|
||||
|
||||
func (e temporalErrors) add(field, msg string) { e[field] = append(e[field], msg) }
|
||||
|
||||
func (e temporalErrors) dateTime(field string, v DateTime, required bool) {
|
||||
switch {
|
||||
case v == "" && required:
|
||||
e.add(field, "The "+strings.ReplaceAll(field, "_", " ")+" field is required.")
|
||||
case v != "" && !v.Valid():
|
||||
e.add(field, "The "+strings.ReplaceAll(field, "_", " ")+" must be a date and time such as 2026-10-03 08:00.")
|
||||
}
|
||||
}
|
||||
|
||||
func (e temporalErrors) date(field string, v Date, required bool) {
|
||||
switch {
|
||||
case v == "" && required:
|
||||
e.add(field, "The "+strings.ReplaceAll(field, "_", " ")+" field is required.")
|
||||
case v != "" && !v.Valid():
|
||||
e.add(field, "The "+strings.ReplaceAll(field, "_", " ")+" must be a date in the YYYY-MM-DD form.")
|
||||
}
|
||||
}
|
||||
|
||||
func (e temporalErrors) result() map[string][]string {
|
||||
if len(e) == 0 {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// TemporalValidator is implemented by models with Date or DateTime columns.
|
||||
// The admin controllers call it before a save, because lagoon.Validate has
|
||||
// no date rules.
|
||||
type TemporalValidator interface {
|
||||
TemporalErrors() map[string][]string
|
||||
}
|
||||
50
models/reading.go
Normal file
50
models/reading.go
Normal file
@@ -0,0 +1,50 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Reading is one lektura on a course's reading list.
|
||||
type Reading struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
CourseID uint `gorm:"column:course_id"`
|
||||
Course *Course `gorm:"foreignKey:CourseID"`
|
||||
Title string `gorm:"column:title"`
|
||||
Author *string `gorm:"column:author"`
|
||||
Source *string `gorm:"column:source"`
|
||||
URL *string `gorm:"column:url"`
|
||||
IsRequired bool `gorm:"column:is_required"`
|
||||
SortOrder int `gorm:"column:sort_order"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
// TableName is the plugin table.
|
||||
func (Reading) TableName() string { return "jz_bm_readings" }
|
||||
|
||||
// Fillable lists the columns mass assignment may set.
|
||||
func (Reading) Fillable() []string {
|
||||
return []string{"course_id", "title", "author", "source", "url", "is_required", "sort_order"}
|
||||
}
|
||||
|
||||
// Rules are checked by the admin API on every save.
|
||||
func (Reading) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"title": "required|max:500",
|
||||
"author": "nullable|max:255",
|
||||
"source": "nullable|max:500",
|
||||
"url": "nullable|max:2048",
|
||||
"is_required": "boolean",
|
||||
"sort_order": "nullable|integer",
|
||||
}
|
||||
}
|
||||
|
||||
// BeforeSave stores NULL for empty optional text.
|
||||
func (r *Reading) BeforeSave(*gorm.DB) error {
|
||||
blank(&r.Author, &r.Source, &r.URL)
|
||||
return nil
|
||||
}
|
||||
17
models/reading_progress.go
Normal file
17
models/reading_progress.go
Normal file
@@ -0,0 +1,17 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// ReadingProgress records that a user (a golem15.user users row) has read a
|
||||
// reading. One row per reading and user.
|
||||
type ReadingProgress struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
ReadingID uint `gorm:"column:reading_id"`
|
||||
UserID uint `gorm:"column:user_id"`
|
||||
ReadAt time.Time `gorm:"column:read_at"`
|
||||
}
|
||||
|
||||
// TableName is the plugin table.
|
||||
func (ReadingProgress) TableName() string { return "jz_bm_reading_progress" }
|
||||
17
models/readings/columns.yaml
Normal file
17
models/readings/columns.yaml
Normal file
@@ -0,0 +1,17 @@
|
||||
columns:
|
||||
title:
|
||||
label: jz.bm::lang.common.title
|
||||
searchable: true
|
||||
author:
|
||||
label: jz.bm::lang.readings.author
|
||||
searchable: true
|
||||
course:
|
||||
label: jz.bm::lang.common.course
|
||||
relation: course
|
||||
select: name
|
||||
searchable: true
|
||||
is_required:
|
||||
label: jz.bm::lang.readings.is_required
|
||||
type: switch
|
||||
sort_order:
|
||||
label: jz.bm::lang.common.sort_order
|
||||
33
models/readings/fields.yaml
Normal file
33
models/readings/fields.yaml
Normal file
@@ -0,0 +1,33 @@
|
||||
fields:
|
||||
course:
|
||||
label: jz.bm::lang.common.course
|
||||
type: relation
|
||||
nameFrom: name
|
||||
span: left
|
||||
required: true
|
||||
is_required:
|
||||
label: jz.bm::lang.readings.is_required
|
||||
type: switch
|
||||
span: right
|
||||
title:
|
||||
label: jz.bm::lang.common.title
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
author:
|
||||
label: jz.bm::lang.readings.author
|
||||
type: text
|
||||
span: right
|
||||
source:
|
||||
label: jz.bm::lang.common.source
|
||||
type: text
|
||||
span: left
|
||||
url:
|
||||
label: jz.bm::lang.common.url
|
||||
type: text
|
||||
span: right
|
||||
sort_order:
|
||||
label: jz.bm::lang.common.sort_order
|
||||
type: number
|
||||
span: left
|
||||
default: 0
|
||||
28
models/tag.go
Normal file
28
models/tag.go
Normal file
@@ -0,0 +1,28 @@
|
||||
// Code generated by summer make. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// Tag labels materials.
|
||||
type Tag struct {
|
||||
ID uint `gorm:"column:id;primaryKey"`
|
||||
Name string `gorm:"column:name"`
|
||||
Slug string `gorm:"column:slug"`
|
||||
CreatedAt time.Time `gorm:"column:created_at"`
|
||||
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||
}
|
||||
|
||||
// TableName is the plugin table.
|
||||
func (Tag) TableName() string { return "jz_bm_tags" }
|
||||
|
||||
// Fillable lists the columns mass assignment may set.
|
||||
func (Tag) Fillable() []string { return []string{"name", "slug"} }
|
||||
|
||||
// Rules are checked by the admin API on every save.
|
||||
func (Tag) Rules() map[string]string {
|
||||
return map[string]string{
|
||||
"name": "required|max:100",
|
||||
"slug": "required|max:100|unique:jz_bm_tags",
|
||||
}
|
||||
}
|
||||
7
models/tags/columns.yaml
Normal file
7
models/tags/columns.yaml
Normal file
@@ -0,0 +1,7 @@
|
||||
columns:
|
||||
name:
|
||||
label: jz.bm::lang.tags.name
|
||||
searchable: true
|
||||
slug:
|
||||
label: jz.bm::lang.tags.slug
|
||||
searchable: true
|
||||
11
models/tags/fields.yaml
Normal file
11
models/tags/fields.yaml
Normal file
@@ -0,0 +1,11 @@
|
||||
fields:
|
||||
name:
|
||||
label: jz.bm::lang.tags.name
|
||||
type: text
|
||||
span: left
|
||||
required: true
|
||||
slug:
|
||||
label: jz.bm::lang.tags.slug
|
||||
type: text
|
||||
span: right
|
||||
required: true
|
||||
186
models/temporal.go
Normal file
186
models/temporal.go
Normal file
@@ -0,0 +1,186 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
_ "time/tzdata" // Europe/Warsaw must resolve on hosts without zoneinfo.
|
||||
)
|
||||
|
||||
// Location is the time zone the programme runs in. Timestamps are stored in
|
||||
// UTC (TIMESTAMPTZ) and shown in this zone; a date or time typed without an
|
||||
// offset is read in it.
|
||||
var Location = mustLoadLocation("Europe/Warsaw")
|
||||
|
||||
func mustLoadLocation(name string) *time.Location {
|
||||
loc, err := time.LoadLocation(name)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("jz.bm: load location %s: %v", name, err))
|
||||
}
|
||||
return loc
|
||||
}
|
||||
|
||||
// DateLayout is the textual form of a Date.
|
||||
const DateLayout = "2006-01-02"
|
||||
|
||||
// dateTimeLayouts are the forms ParseDateTime accepts. RFC 3339 carries its
|
||||
// own offset; the others are wall-clock times in Location.
|
||||
var dateTimeLayouts = []string{
|
||||
"2006-01-02T15:04",
|
||||
"2006-01-02 15:04",
|
||||
"2006-01-02T15:04:05",
|
||||
"2006-01-02 15:04:05",
|
||||
}
|
||||
|
||||
// ParseDateTime reads an RFC 3339 timestamp, or a wall-clock time
|
||||
// ("2026-10-03 08:00") in Location.
|
||||
func ParseDateTime(s string) (time.Time, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
for _, layout := range dateTimeLayouts {
|
||||
if t, err := time.ParseInLocation(layout, s, Location); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("jz.bm: %q is not a date and time", s)
|
||||
}
|
||||
|
||||
// ParseDate reads a YYYY-MM-DD calendar date.
|
||||
func ParseDate(s string) (time.Time, error) {
|
||||
t, err := time.ParseInLocation(DateLayout, strings.TrimSpace(s), Location)
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("jz.bm: %q is not a YYYY-MM-DD date", s)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// DateTime is a TIMESTAMPTZ column held as RFC 3339 text in Location
|
||||
// ("2026-10-03T08:00:00+02:00").
|
||||
//
|
||||
// It is a string type rather than time.Time because the admin form has no
|
||||
// date picker and lagoon.Fill cannot write text into a time.Time field, while
|
||||
// cabana treats any struct-typed field as a relation. A string type is filled
|
||||
// from the form's text input, and Value checks and normalises it.
|
||||
// TODO: requires SummerCMS change (a datetime form field type and Fill
|
||||
// support for time.Time) to use time.Time here.
|
||||
type DateTime string
|
||||
|
||||
// NewDateTime returns t as a DateTime in Location.
|
||||
func NewDateTime(t time.Time) DateTime {
|
||||
return DateTime(t.In(Location).Format(time.RFC3339))
|
||||
}
|
||||
|
||||
// Time parses the value.
|
||||
func (d DateTime) Time() (time.Time, error) { return ParseDateTime(string(d)) }
|
||||
|
||||
// MustTime parses the value and returns the zero time when it does not parse.
|
||||
// Values read from the database always parse.
|
||||
func (d DateTime) MustTime() time.Time {
|
||||
t, _ := d.Time()
|
||||
return t
|
||||
}
|
||||
|
||||
// Valid reports whether the value parses.
|
||||
func (d DateTime) Valid() bool {
|
||||
_, err := d.Time()
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Value stores the instant in UTC. An empty value is SQL NULL.
|
||||
func (d DateTime) Value() (driver.Value, error) {
|
||||
if strings.TrimSpace(string(d)) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
t, err := d.Time()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.UTC(), nil
|
||||
}
|
||||
|
||||
// Scan reads a TIMESTAMPTZ (or its text) and normalises it to Location.
|
||||
func (d *DateTime) Scan(src any) error {
|
||||
switch v := src.(type) {
|
||||
case nil:
|
||||
*d = ""
|
||||
case time.Time:
|
||||
*d = NewDateTime(v)
|
||||
case string:
|
||||
return d.scanText(v)
|
||||
case []byte:
|
||||
return d.scanText(string(v))
|
||||
default:
|
||||
return fmt.Errorf("jz.bm: cannot scan %T into DateTime", src)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DateTime) scanText(s string) error {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
*d = ""
|
||||
return nil
|
||||
}
|
||||
t, err := ParseDateTime(s)
|
||||
if err != nil {
|
||||
// Postgres text output: "2026-10-03 06:00:00+00".
|
||||
t, err = time.Parse("2006-01-02 15:04:05-07", s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
*d = NewDateTime(t)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Date is a DATE column held as YYYY-MM-DD text, for the same reason as
|
||||
// DateTime.
|
||||
type Date string
|
||||
|
||||
// NewDate returns the calendar date of t in Location.
|
||||
func NewDate(t time.Time) Date { return Date(t.In(Location).Format(DateLayout)) }
|
||||
|
||||
// Time returns midnight of the date in Location.
|
||||
func (d Date) Time() (time.Time, error) { return ParseDate(string(d)) }
|
||||
|
||||
// Valid reports whether the value is a YYYY-MM-DD date.
|
||||
func (d Date) Valid() bool {
|
||||
_, err := d.Time()
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Value stores the date as text; Postgres casts it to DATE. An empty value is
|
||||
// SQL NULL.
|
||||
func (d Date) Value() (driver.Value, error) {
|
||||
if strings.TrimSpace(string(d)) == "" {
|
||||
return nil, nil
|
||||
}
|
||||
t, err := d.Time()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t.Format(DateLayout), nil
|
||||
}
|
||||
|
||||
// Scan reads a DATE. The driver hands it over as midnight UTC, so the
|
||||
// calendar fields are taken as they are, without a zone conversion.
|
||||
func (d *Date) Scan(src any) error {
|
||||
switch v := src.(type) {
|
||||
case nil:
|
||||
*d = ""
|
||||
case time.Time:
|
||||
*d = Date(v.Format(DateLayout))
|
||||
case string:
|
||||
*d = Date(strings.TrimSpace(v))
|
||||
if len(*d) > len(DateLayout) {
|
||||
*d = (*d)[:len(DateLayout)]
|
||||
}
|
||||
case []byte:
|
||||
return d.Scan(string(v))
|
||||
default:
|
||||
return fmt.Errorf("jz.bm: cannot scan %T into Date", src)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
136
models/temporal_test.go
Normal file
136
models/temporal_test.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package models_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
)
|
||||
|
||||
func TestParseDateTimeForms(t *testing.T) {
|
||||
want := time.Date(2026, 10, 3, 6, 0, 0, 0, time.UTC)
|
||||
for _, in := range []string{
|
||||
"2026-10-03T08:00:00+02:00",
|
||||
"2026-10-03T06:00:00Z",
|
||||
"2026-10-03 08:00",
|
||||
"2026-10-03T08:00",
|
||||
" 2026-10-03 08:00:00 ",
|
||||
} {
|
||||
got, err := models.ParseDateTime(in)
|
||||
if err != nil {
|
||||
t.Errorf("ParseDateTime(%q): %v", in, err)
|
||||
continue
|
||||
}
|
||||
if !got.Equal(want) {
|
||||
t.Errorf("ParseDateTime(%q) = %v, want %v", in, got, want)
|
||||
}
|
||||
}
|
||||
// Winter time: a wall-clock time in December is UTC+1.
|
||||
got, err := models.ParseDateTime("2026-12-01 08:00")
|
||||
if err != nil || !got.Equal(time.Date(2026, 12, 1, 7, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("winter wall clock = %v, %v", got, err)
|
||||
}
|
||||
for _, bad := range []string{"", "tomorrow", "2026-13-01 08:00", "2026-10-03"} {
|
||||
if _, err := models.ParseDateTime(bad); err == nil {
|
||||
t.Errorf("ParseDateTime(%q) accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDateTimeRoundTrip(t *testing.T) {
|
||||
d := models.DateTime("2026-10-03 08:00")
|
||||
v, err := d.Value()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stored, ok := v.(time.Time)
|
||||
if !ok || stored.Location() != time.UTC || stored.Hour() != 6 {
|
||||
t.Fatalf("Value = %#v, want 06:00 UTC", v)
|
||||
}
|
||||
var read models.DateTime
|
||||
if err := read.Scan(stored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if read != "2026-10-03T08:00:00+02:00" {
|
||||
t.Errorf("Scan = %q, want the Warsaw RFC 3339 form", read)
|
||||
}
|
||||
if err := read.Scan("2026-10-03 06:00:00+00"); err != nil || read != "2026-10-03T08:00:00+02:00" {
|
||||
t.Errorf("Scan(postgres text) = %q, %v", read, err)
|
||||
}
|
||||
if err := read.Scan(nil); err != nil || read != "" {
|
||||
t.Errorf("Scan(nil) = %q, %v", read, err)
|
||||
}
|
||||
if v, err := models.DateTime("").Value(); err != nil || v != nil {
|
||||
t.Errorf("empty Value = %v, %v; want NULL", v, err)
|
||||
}
|
||||
if _, err := models.DateTime("soon").Value(); err == nil {
|
||||
t.Error("an unparsable DateTime was stored")
|
||||
}
|
||||
if err := read.Scan(42); err == nil {
|
||||
t.Error("Scan(int) succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDateRoundTrip(t *testing.T) {
|
||||
var d models.Date
|
||||
if err := d.Scan(time.Date(2026, 10, 3, 0, 0, 0, 0, time.UTC)); err != nil || d != "2026-10-03" {
|
||||
t.Errorf("Scan(time) = %q, %v", d, err)
|
||||
}
|
||||
if err := d.Scan([]byte("2026-10-04")); err != nil || d != "2026-10-04" {
|
||||
t.Errorf("Scan(bytes) = %q, %v", d, err)
|
||||
}
|
||||
if v, err := models.Date("2026-10-03").Value(); err != nil || v != "2026-10-03" {
|
||||
t.Errorf("Value = %v, %v", v, err)
|
||||
}
|
||||
if _, err := models.Date("03.10.2026").Value(); err == nil {
|
||||
t.Error("a non-ISO date was stored")
|
||||
}
|
||||
if models.NewDate(time.Date(2026, 10, 2, 23, 30, 0, 0, time.UTC)) != "2026-10-03" {
|
||||
t.Error("NewDate does not use the Warsaw calendar day")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemporalErrors(t *testing.T) {
|
||||
s := &models.ClassSession{StartsAt: "2026-10-03 10:00", EndsAt: "2026-10-03 09:00"}
|
||||
if errs := s.TemporalErrors(); len(errs["ends_at"]) != 1 {
|
||||
t.Errorf("end before start: %v", errs)
|
||||
}
|
||||
s = &models.ClassSession{StartsAt: "bad"}
|
||||
errs := s.TemporalErrors()
|
||||
if len(errs["starts_at"]) != 1 || len(errs["ends_at"]) != 1 {
|
||||
t.Errorf("bad and missing: %v", errs)
|
||||
}
|
||||
m := &models.Meeting{StartsOn: "2026-10-04", EndsOn: "2026-10-03"}
|
||||
if errs := m.TemporalErrors(); len(errs["ends_on"]) != 1 {
|
||||
t.Errorf("meeting order: %v", errs)
|
||||
}
|
||||
ok := &models.Meeting{StartsOn: "2026-10-03", EndsOn: "2026-10-04"}
|
||||
if errs := ok.TemporalErrors(); errs != nil {
|
||||
t.Errorf("valid meeting: %v", errs)
|
||||
}
|
||||
draft := &models.Material{}
|
||||
if errs := draft.TemporalErrors(); errs != nil {
|
||||
t.Errorf("draft material: %v", errs)
|
||||
}
|
||||
bad := models.DateTime("yesterday")
|
||||
if errs := (&models.Material{PublishedAt: &bad}).TemporalErrors(); len(errs["published_at"]) != 1 {
|
||||
t.Errorf("bad published_at: %v", errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeforeSaveBlanksOptionalText(t *testing.T) {
|
||||
empty, space := "", " "
|
||||
c := &models.Course{Code: &empty, Lecturer: &space}
|
||||
if err := c.BeforeSave(nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Code != nil || c.Lecturer != nil {
|
||||
t.Errorf("blank text kept: %v %v", c.Code, c.Lecturer)
|
||||
}
|
||||
pub := models.DateTime("")
|
||||
m := &models.Material{PublishedAt: &pub}
|
||||
_ = m.BeforeSave(nil)
|
||||
if m.PublishedAt != nil {
|
||||
t.Error("an empty published_at was not cleared to a draft")
|
||||
}
|
||||
}
|
||||
98
plugin.go
98
plugin.go
@@ -1,14 +1,19 @@
|
||||
package bm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"io/fs"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/console"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/controllers"
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -20,6 +25,9 @@ var (
|
||||
_ pact.HasCommands = (*Plugin)(nil)
|
||||
_ pact.HasJobs = (*Plugin)(nil)
|
||||
_ pact.HasAdminControllers = (*Plugin)(nil)
|
||||
_ pact.AdminAssets = (*Plugin)(nil)
|
||||
_ pact.HasPermissions = (*Plugin)(nil)
|
||||
_ pact.HasNavigation = (*Plugin)(nil)
|
||||
)
|
||||
|
||||
//go:embed config
|
||||
@@ -31,14 +39,35 @@ var langFS embed.FS
|
||||
//go:embed views/mail
|
||||
var mailFS embed.FS
|
||||
|
||||
// Plugin is the jz.bm plugin.
|
||||
type Plugin struct{}
|
||||
//go:embed controllers/*/*.yaml models/*/*.yaml
|
||||
var adminFS embed.FS
|
||||
|
||||
func (p *Plugin) ID() string { return "jz.bm" }
|
||||
func (p *Plugin) Requires() []string { return nil }
|
||||
// Plugin is the jz.bm plugin: the study dashboard backend of the BM
|
||||
// (Bezpieczeństwo międzynarodowe) master's programme.
|
||||
type Plugin struct {
|
||||
app *backpack.App
|
||||
// publicFS is the tree of the student app. Nil means the embedded
|
||||
// public/ directory; tests plant their own.
|
||||
publicFS fs.FS
|
||||
}
|
||||
|
||||
func (p *Plugin) Register(*backpack.App) error { return nil }
|
||||
func (p *Plugin) Boot(*backpack.App) error { return nil }
|
||||
func (p *Plugin) ID() string { return "jz.bm" }
|
||||
|
||||
// Requires golem15.user: its users table holds the students, and its
|
||||
// jwt.auth middleware guards the API.
|
||||
func (p *Plugin) Requires() []string { return []string{"golem15.user"} }
|
||||
|
||||
func (p *Plugin) Register(app *backpack.App) error {
|
||||
p.app = app
|
||||
return nil
|
||||
}
|
||||
|
||||
// Boot keeps the application, so route handlers and commands can reach its
|
||||
// services, such as the database, when they run.
|
||||
func (p *Plugin) Boot(app *backpack.App) error {
|
||||
p.app = app
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Plugin) ConfigFS() fs.FS { return configFS }
|
||||
func (p *Plugin) LangFS() fs.FS { return langFS }
|
||||
@@ -49,12 +78,67 @@ func (p *Plugin) MailLayouts() map[string]string { return nil }
|
||||
|
||||
func (p *Plugin) Models() []any { return generatedModels() }
|
||||
func (p *Plugin) Migrations() []*gormigrate.Migration { return generatedMigrations() }
|
||||
func (p *Plugin) Commands() []bonfire.Command { return generatedCommands() }
|
||||
func (p *Plugin) Jobs() []pact.Job { return generatedJobs() }
|
||||
func (p *Plugin) AdminControllers() []pact.AdminController {
|
||||
return generatedAdminControllers()
|
||||
}
|
||||
|
||||
// Commands returns the generated commands plus bm:seed, which needs the
|
||||
// database and so is built here with the plugin's withDB.
|
||||
func (p *Plugin) Commands() []bonfire.Command {
|
||||
return append(generatedCommands(), console.SeedCommand(p.withDB))
|
||||
}
|
||||
|
||||
// AdminFS is the admin YAML the controllers read.
|
||||
func (p *Plugin) AdminFS() fs.FS { return adminFS }
|
||||
|
||||
// Permissions replaces registerPermissions().
|
||||
func (p *Plugin) Permissions() []pact.Permission {
|
||||
tab := "jz.bm::lang.plugin.name"
|
||||
return []pact.Permission{
|
||||
{Code: controllers.PermCourses, Tab: tab, Label: "jz.bm::lang.permissions.access_courses"},
|
||||
{Code: controllers.PermSchedule, Tab: tab, Label: "jz.bm::lang.permissions.access_schedule"},
|
||||
{Code: controllers.PermMaterials, Tab: tab, Label: "jz.bm::lang.permissions.access_materials"},
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation replaces registerNavigation(): one "Studia BM" group with a
|
||||
// side item per screen.
|
||||
func (p *Plugin) Navigation() []pact.NavigationItem {
|
||||
return []pact.NavigationItem{{
|
||||
Code: "bm",
|
||||
Label: "jz.bm::lang.plugin.name",
|
||||
Icon: "icon-graduation-cap",
|
||||
Permissions: []string{controllers.PermCourses, controllers.PermSchedule, controllers.PermMaterials},
|
||||
Order: 300,
|
||||
Controller: "jz.bm.courses",
|
||||
SideMenu: []pact.NavigationItem{
|
||||
{Code: "courses", Label: "jz.bm::lang.navigation.courses", Icon: "icon-book", Permissions: []string{controllers.PermCourses}, Controller: "jz.bm.courses"},
|
||||
{Code: "readings", Label: "jz.bm::lang.navigation.readings", Icon: "icon-bookmark", Permissions: []string{controllers.PermCourses}, Controller: "jz.bm.readings"},
|
||||
{Code: "meetings", Label: "jz.bm::lang.navigation.meetings", Icon: "icon-calendar", Permissions: []string{controllers.PermSchedule}, Controller: "jz.bm.meetings"},
|
||||
{Code: "sessions", Label: "jz.bm::lang.navigation.sessions", Icon: "icon-clock-o", Permissions: []string{controllers.PermSchedule}, Controller: "jz.bm.class_sessions"},
|
||||
{Code: "deadlines", Label: "jz.bm::lang.navigation.deadlines", Icon: "icon-flag", Permissions: []string{controllers.PermSchedule}, Controller: "jz.bm.deadlines"},
|
||||
{Code: "materials", Label: "jz.bm::lang.navigation.materials", Icon: "icon-file-text-o", Permissions: []string{controllers.PermMaterials}, Controller: "jz.bm.materials"},
|
||||
{Code: "tags", Label: "jz.bm::lang.navigation.tags", Icon: "icon-tags", Permissions: []string{controllers.PermMaterials}, Controller: "jz.bm.tags"},
|
||||
},
|
||||
}}
|
||||
}
|
||||
|
||||
// withDB runs fn with the application's database: the one the serve command
|
||||
// published, or, when a console command runs, one opened from the config for
|
||||
// the duration of fn.
|
||||
func (p *Plugin) withDB(ctx context.Context, fn func(*gorm.DB) error) error {
|
||||
if gdb, ok := p.app.Lookup[*gorm.DB](); ok && gdb != nil {
|
||||
return fn(gdb)
|
||||
}
|
||||
sqlDB, gdb, err := lagoon.OpenFromApp(ctx, p.app)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sqlDB.Close()
|
||||
return fn(gdb)
|
||||
}
|
||||
|
||||
func init() {
|
||||
party.Register(&Plugin{})
|
||||
}
|
||||
|
||||
178
plugin_test.go
Normal file
178
plugin_test.go
Normal file
@@ -0,0 +1,178 @@
|
||||
package bm_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
_ "git.golem15.com/golem15/sm-user-plugin"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
bm "git.golem15.com/jakub/sm-bm-plugin"
|
||||
)
|
||||
|
||||
const (
|
||||
testUserSecret = "jz-bm-test-only-user-jwt-secret-32bytes"
|
||||
testAdminSecret = "jz-bm-test-only-admin-jwt-secret-32bytes"
|
||||
)
|
||||
|
||||
// testConfig is the application config the tests boot with: the HTTP
|
||||
// limits, the golem15.user JWT secret and the admin secret.
|
||||
func testConfig(t *testing.T) *compass.Config {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
httpYAML := "body_limits:\n default_bytes: 1048576\n upload_bytes: 10485760\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, "http.yaml"), []byte(httpYAML), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{
|
||||
Dir: dir,
|
||||
Environ: []string{
|
||||
"SUMMER_ENV=testing",
|
||||
"SUMMER_GOLEM15__USER__JWT__SECRET=" + testUserSecret,
|
||||
"SUMMER_ADMIN__JWT__SECRET=" + testAdminSecret,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
// activate boots golem15.user and jz.bm the way the generated main does.
|
||||
func activate(t *testing.T, app *backpack.App) []party.Plugin {
|
||||
t.Helper()
|
||||
plugins, err := party.Activate(app, []string{"golem15.user", "jz.bm"})
|
||||
if err != nil {
|
||||
t.Fatalf("Activate: %v", err)
|
||||
}
|
||||
return plugins
|
||||
}
|
||||
|
||||
func bmPlugin(t *testing.T, plugins []party.Plugin) *bm.Plugin {
|
||||
t.Helper()
|
||||
for _, p := range plugins {
|
||||
if b, ok := p.(*bm.Plugin); ok {
|
||||
return b
|
||||
}
|
||||
}
|
||||
t.Fatal("jz.bm was not activated")
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestPluginActivates(t *testing.T) {
|
||||
app := backpack.New(testConfig(t))
|
||||
p := bmPlugin(t, activate(t, app))
|
||||
if p.ID() != "jz.bm" || !slices.Equal(p.Requires(), []string{"golem15.user"}) {
|
||||
t.Errorf("ID %q Requires %v", p.ID(), p.Requires())
|
||||
}
|
||||
if n := len(p.Models()); n != 9 {
|
||||
t.Errorf("Models = %d, want 9", n)
|
||||
}
|
||||
if n := len(p.Migrations()); n != 10 {
|
||||
t.Errorf("Migrations = %d, want 10", n)
|
||||
}
|
||||
if !slices.ContainsFunc(p.Commands(), func(c bonfire.Command) bool { return c.Name == "bm:seed" }) {
|
||||
t.Error("bm:seed is not registered")
|
||||
}
|
||||
if got := app.Config.Int("jz.bm.materials_per_page"); got != 20 {
|
||||
t.Errorf("jz.bm.materials_per_page = %d, want the default 20", got)
|
||||
}
|
||||
if got := app.Config.Int("jz.bm.dashboard_limit"); got != 5 {
|
||||
t.Errorf("jz.bm.dashboard_limit = %d, want the default 5", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRoutes(t *testing.T) {
|
||||
app := backpack.New(testConfig(t))
|
||||
plugins := activate(t, app)
|
||||
router, err := surf.BuildRouter(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildRouter: %v", err)
|
||||
}
|
||||
want := []string{
|
||||
"GET /_bm/api/v1/dashboard",
|
||||
"GET /_bm/api/v1/courses",
|
||||
"GET /_bm/api/v1/courses/{id}",
|
||||
"GET /_bm/api/v1/schedule",
|
||||
"GET /_bm/api/v1/meetings",
|
||||
"GET /_bm/api/v1/deadlines",
|
||||
"GET /_bm/api/v1/readings",
|
||||
"PUT /_bm/api/v1/readings/{id}/progress",
|
||||
"DELETE /_bm/api/v1/readings/{id}/progress",
|
||||
"GET /_bm/api/v1/materials",
|
||||
"GET /_bm/api/v1/materials/{id}",
|
||||
}
|
||||
var got []string
|
||||
for _, rt := range router.Routes() {
|
||||
if rt.PluginID != "jz.bm" {
|
||||
continue
|
||||
}
|
||||
if rt.Method+" "+rt.Pattern == "GET /{path...}" {
|
||||
// The student app, public by design; see static_test.go.
|
||||
if len(rt.Middleware) != 0 {
|
||||
t.Errorf("the student app has middleware %v", rt.Middleware)
|
||||
}
|
||||
continue
|
||||
}
|
||||
got = append(got, rt.Method+" "+rt.Pattern)
|
||||
if !slices.Contains(rt.Middleware, "jwt.auth") {
|
||||
t.Errorf("%s %s is not behind jwt.auth: %v", rt.Method, rt.Pattern, rt.Middleware)
|
||||
}
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("routes =\n%v\nwant\n%v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminCompiles(t *testing.T) {
|
||||
app := backpack.New(testConfig(t))
|
||||
plugins := activate(t, app)
|
||||
p := bmPlugin(t, plugins)
|
||||
routes, err := cabana.Activate(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatalf("cabana.Activate: %v", err)
|
||||
}
|
||||
if routes == nil {
|
||||
t.Fatal("no admin routes")
|
||||
}
|
||||
declared := map[string]bool{}
|
||||
for _, perm := range p.Permissions() {
|
||||
declared[perm.Code] = true
|
||||
}
|
||||
for _, ctl := range p.AdminControllers() {
|
||||
perms := ctl.(pact.AdminPermissioned).RequiredPermissions()
|
||||
for _, code := range perms {
|
||||
if !declared[code] {
|
||||
t.Errorf("%s requires undeclared %s", ctl.ID(), code)
|
||||
}
|
||||
}
|
||||
if rec := ctl.(pact.AdminRecordSource).NewRecord(); rec == nil {
|
||||
t.Errorf("%s has no record model", ctl.ID())
|
||||
}
|
||||
form, err := cabana.CompileForm("jz.bm", ctl, p.AdminFS())
|
||||
if err != nil {
|
||||
t.Errorf("%s form: %v", ctl.ID(), err)
|
||||
} else if len(form.Fields) == 0 {
|
||||
t.Errorf("%s form has no fields", ctl.ID())
|
||||
}
|
||||
if _, err := cabana.CompileList("jz.bm", ctl, p.AdminFS()); err != nil {
|
||||
t.Errorf("%s list: %v", ctl.ID(), err)
|
||||
}
|
||||
editor := &bouncer.Principal{ID: 1, Backend: true, PermissionGrants: map[string]bool{"jz.bm.*": true}}
|
||||
if !cabana.Allows(editor, perms) {
|
||||
t.Errorf("jz.bm.* does not open %s", ctl.ID())
|
||||
}
|
||||
}
|
||||
nav := p.Navigation()
|
||||
if len(nav) != 1 || len(nav[0].SideMenu) != 7 {
|
||||
t.Errorf("navigation = %+v, want one group with 7 side items", nav)
|
||||
}
|
||||
}
|
||||
661
postgres_test.go
Normal file
661
postgres_test.go
Normal file
@@ -0,0 +1,661 @@
|
||||
package bm_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"git.golem15.com/golem15/summercms/modules/surf"
|
||||
"git.golem15.com/jakub/sm-bm-plugin/models"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// The database tests run against a throwaway testcontainers Postgres, never
|
||||
// a developer database. Under -short the container is not started and the
|
||||
// tests skip; in a full run a missing Docker daemon fails the package.
|
||||
var (
|
||||
pgContainer *postgres.PostgresContainer
|
||||
pgAdmin *sql.DB
|
||||
pgDSN string
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
if !isShort() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
err := startPostgres(ctx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "jz.bm: testcontainers postgres: %v\n", err)
|
||||
stopPostgres()
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
code := m.Run()
|
||||
stopPostgres()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func isShort() bool {
|
||||
for _, a := range os.Args {
|
||||
if a == "-test.short" || a == "-test.short=true" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func startPostgres(ctx context.Context) error {
|
||||
ctr, err := postgres.Run(ctx,
|
||||
"postgres:16-alpine",
|
||||
postgres.WithDatabase("bm"),
|
||||
postgres.WithUsername("bm"),
|
||||
postgres.WithPassword("bm"),
|
||||
postgres.BasicWaitStrategies(),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pgContainer = ctr
|
||||
dsn, err := ctr.ConnectionString(ctx, "sslmode=disable")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
db, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
_ = db.Close()
|
||||
return err
|
||||
}
|
||||
pgAdmin, pgDSN = db, dsn
|
||||
return nil
|
||||
}
|
||||
|
||||
func stopPostgres() {
|
||||
if pgAdmin != nil {
|
||||
_ = pgAdmin.Close()
|
||||
}
|
||||
if pgContainer != nil {
|
||||
_ = testcontainers.TerminateContainer(pgContainer)
|
||||
}
|
||||
}
|
||||
|
||||
// testDatabase creates a database for one test and drops it afterwards.
|
||||
func testDatabase(t *testing.T) (*sql.DB, string) {
|
||||
t.Helper()
|
||||
if testing.Short() {
|
||||
t.Skip("requires testcontainers postgres")
|
||||
}
|
||||
if pgAdmin == nil {
|
||||
t.Fatal("postgres unavailable: the container was not started")
|
||||
}
|
||||
name := "bm_" + strings.ToLower(strings.NewReplacer("/", "_", "-", "_").Replace(t.Name()))
|
||||
quoted := `"` + strings.ReplaceAll(name, `"`, `""`) + `"`
|
||||
if _, err := pgAdmin.ExecContext(t.Context(), `CREATE DATABASE `+quoted+` TEMPLATE template0 ENCODING 'UTF8'`); err != nil {
|
||||
t.Fatalf("create %s: %v", name, err)
|
||||
}
|
||||
u, err := url.Parse(pgDSN)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u.Path = "/" + name
|
||||
dsn := u.String()
|
||||
db, err := sql.Open("pgx", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = db.Close()
|
||||
_, _ = pgAdmin.ExecContext(context.Background(), `DROP DATABASE IF EXISTS `+quoted+` WITH (FORCE)`)
|
||||
})
|
||||
return db, dsn
|
||||
}
|
||||
|
||||
// migrated activates golem15.user and jz.bm, migrates a fresh database and
|
||||
// publishes it on the application, as serve does.
|
||||
func migrated(t *testing.T) (*backpack.App, []party.Plugin, *gorm.DB) {
|
||||
t.Helper()
|
||||
sqlDB, _ := testDatabase(t)
|
||||
gdb, err := lagoon.Use(t.Context(), sqlDB)
|
||||
if err != nil {
|
||||
t.Fatalf("lagoon.Use: %v", err)
|
||||
}
|
||||
app := backpack.New(testConfig(t))
|
||||
plugins := activate(t, app)
|
||||
if err := lagoon.Migrate(gdb, plugins); err != nil {
|
||||
t.Fatalf("lagoon.Migrate: %v", err)
|
||||
}
|
||||
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
||||
t.Fatalf("lagoon.Publish: %v", err)
|
||||
}
|
||||
return app, plugins, gdb
|
||||
}
|
||||
|
||||
var bmTables = []string{
|
||||
"jz_bm_meetings", "jz_bm_courses", "jz_bm_class_sessions", "jz_bm_deadlines", "jz_bm_readings",
|
||||
"jz_bm_reading_progress", "jz_bm_tags", "jz_bm_materials", "jz_bm_material_tag",
|
||||
}
|
||||
|
||||
func TestMigrateUpAndRollback(t *testing.T) {
|
||||
_, plugins, gdb := migrated(t)
|
||||
m := gdb.Migrator()
|
||||
for _, table := range bmTables {
|
||||
if !m.HasTable(table) {
|
||||
t.Errorf("%s is missing after migrate", table)
|
||||
}
|
||||
}
|
||||
if !m.HasColumn(&models.Course{}, "elective_group") {
|
||||
t.Error("jz_bm_courses has no elective_group")
|
||||
}
|
||||
n := len(bmPlugin(t, plugins).Migrations())
|
||||
for i := 0; i < n; i++ {
|
||||
if err := lagoon.RollbackLast(gdb, plugins, "jz.bm"); err != nil {
|
||||
t.Fatalf("rollback %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
for _, table := range bmTables {
|
||||
if m.HasTable(table) {
|
||||
t.Errorf("%s is still there after rolling every migration back", table)
|
||||
}
|
||||
}
|
||||
if !m.HasTable("users") {
|
||||
t.Error("rolling back jz.bm dropped golem15.user's users table")
|
||||
}
|
||||
if err := lagoon.Migrate(gdb, plugins); err != nil {
|
||||
t.Fatalf("migrate again: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchemaConstraints(t *testing.T) {
|
||||
_, _, gdb := migrated(t)
|
||||
exec := func(sql string, args ...any) error { return gdb.Exec(sql, args...).Error }
|
||||
if err := exec(`INSERT INTO jz_bm_courses (name, form, semester) VALUES ('A', 'wyklad', 1)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, bad := range []string{
|
||||
`INSERT INTO jz_bm_courses (name, form, semester) VALUES ('A', 'wyklad', 1)`,
|
||||
`INSERT INTO jz_bm_courses (name, form, semester) VALUES ('B', 'lecture', 1)`,
|
||||
`INSERT INTO jz_bm_meetings (number, starts_on, ends_on) VALUES (1, '2030-10-06', '2030-10-05')`,
|
||||
`INSERT INTO jz_bm_class_sessions (course_id, starts_at, ends_at) VALUES (999, NOW(), NOW() + interval '1 hour')`,
|
||||
`INSERT INTO jz_bm_deadlines (title, due_at, kind) VALUES ('X', NOW(), 'party')`,
|
||||
`INSERT INTO jz_bm_materials (title, type) VALUES ('X', 'video')`,
|
||||
} {
|
||||
if err := exec(bad); err == nil {
|
||||
t.Errorf("accepted: %s", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func seedFixture(t *testing.T, plugins []party.Plugin, path string) string {
|
||||
t.Helper()
|
||||
var out bytes.Buffer
|
||||
if err := bonfire.Call(t.Context(), bmPlugin(t, plugins).Commands(), "bm:seed", []string{path}, &out); err != nil {
|
||||
t.Fatalf("bm:seed %s: %v\n%s", path, err, out.String())
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func count(t *testing.T, gdb *gorm.DB, table string) int64 {
|
||||
t.Helper()
|
||||
var n int64
|
||||
if err := gdb.Table(table).Count(&n).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestSeedCommandIsIdempotent(t *testing.T) {
|
||||
_, plugins, gdb := migrated(t)
|
||||
out := seedFixture(t, plugins, "testdata/seed.example.json")
|
||||
if !strings.Contains(out, "courses") {
|
||||
t.Errorf("summary = %q", out)
|
||||
}
|
||||
want := map[string]int64{"jz_bm_meetings": 2, "jz_bm_courses": 3, "jz_bm_class_sessions": 3, "jz_bm_deadlines": 2, "jz_bm_readings": 2}
|
||||
for table, n := range want {
|
||||
if got := count(t, gdb, table); got != n {
|
||||
t.Errorf("%s = %d rows, want %d", table, got, n)
|
||||
}
|
||||
}
|
||||
var session models.ClassSession
|
||||
if err := gdb.Preload("Course").Preload("Meeting").Where("room = ?", "101").Take(&session).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session.StartsAt != "2030-10-05T08:00:00+02:00" || session.Course.Name != "Przedmiot przykładowy A" || session.Meeting.Number != 1 {
|
||||
t.Errorf("session = %+v", session)
|
||||
}
|
||||
var stored time.Time
|
||||
if err := gdb.Raw(`SELECT starts_at FROM jz_bm_class_sessions WHERE room = '101'`).Scan(&stored).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !stored.Equal(time.Date(2030, 10, 5, 6, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("stored starts_at = %v, want 06:00 UTC", stored)
|
||||
}
|
||||
var course models.Course
|
||||
if err := gdb.Where("form = ?", "konwersatorium").Take(&course).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if course.ElectiveGroup == nil || *course.ElectiveGroup != "przyklad-do-wyboru" || course.Code != nil {
|
||||
t.Errorf("course = %+v", course)
|
||||
}
|
||||
var ids []uint
|
||||
gdb.Model(&models.Course{}).Order("id").Pluck("id", &ids)
|
||||
|
||||
// A second run changes nothing and keeps the IDs.
|
||||
out = seedFixture(t, plugins, "testdata/seed.example.json")
|
||||
for _, row := range []string{"meetings\t0\t0\t2", "courses\t0\t0\t3", "class_sessions\t0\t0\t3", "deadlines\t0\t0\t2", "readings\t0\t0\t2"} {
|
||||
if !strings.Contains(out, row) {
|
||||
t.Errorf("second run summary lacks %q:\n%s", row, out)
|
||||
}
|
||||
}
|
||||
for table, n := range want {
|
||||
if got := count(t, gdb, table); got != n {
|
||||
t.Errorf("after the second run %s = %d rows, want %d", table, got, n)
|
||||
}
|
||||
}
|
||||
var again []uint
|
||||
gdb.Model(&models.Course{}).Order("id").Pluck("id", &again)
|
||||
if fmt.Sprint(ids) != fmt.Sprint(again) {
|
||||
t.Errorf("course IDs changed: %v -> %v", ids, again)
|
||||
}
|
||||
|
||||
// A changed field updates the row in place.
|
||||
dir := t.TempDir()
|
||||
changed := filepath.Join(dir, "changed.json")
|
||||
writeJSON(t, changed, `{"courses": [{"key": "a", "name": "Przedmiot przykładowy A", "form": "wyklad", "semester": 1, "lecturer": "dr Inna Osoba", "sort_order": 1}],
|
||||
"class_sessions": [{"course": "a", "starts_at": "2030-10-05T08:00:00+02:00", "ends_at": "2030-10-05T10:00:00+02:00", "room": "105"}]}`)
|
||||
seedFixture(t, plugins, changed)
|
||||
var updated models.Course
|
||||
gdb.Where("id = ?", ids[0]).Take(&updated)
|
||||
if updated.Lecturer == nil || *updated.Lecturer != "dr Inna Osoba" || count(t, gdb, "jz_bm_courses") != 3 {
|
||||
t.Errorf("course after update = %+v", updated)
|
||||
}
|
||||
gdb.Where("course_id = ?", ids[0]).Take(&session)
|
||||
if session.Room == nil || *session.Room != "105" || session.MeetingID != nil || count(t, gdb, "jz_bm_class_sessions") != 3 {
|
||||
t.Errorf("session after update = %+v", session)
|
||||
}
|
||||
|
||||
// An unknown key fails the whole file: the valid meeting is not written.
|
||||
invalid := filepath.Join(dir, "invalid.json")
|
||||
writeJSON(t, invalid, `{"meetings": [{"number": 3, "starts_on": "2030-11-01", "ends_on": "2030-11-02"}],
|
||||
"readings": [{"course": "ghost", "title": "X"}]}`)
|
||||
var buf bytes.Buffer
|
||||
err := bonfire.Call(t.Context(), bmPlugin(t, plugins).Commands(), "bm:seed", []string{invalid}, &buf)
|
||||
if err == nil || !strings.Contains(err.Error(), "ghost") {
|
||||
t.Errorf("invalid seed err = %v", err)
|
||||
}
|
||||
if got := count(t, gdb, "jz_bm_meetings"); got != 2 {
|
||||
t.Errorf("an invalid file wrote meetings: %d rows", got)
|
||||
}
|
||||
|
||||
// A database error inside the transaction rolls back the rows before it.
|
||||
clash := filepath.Join(dir, "clash.json")
|
||||
writeJSON(t, clash, `{"meetings": [{"number": 4, "starts_on": "2030-12-01", "ends_on": "2030-12-02"}],
|
||||
"courses": [{"key": "x", "name": "`+strings.Repeat("x", 300)+`", "form": "inne", "semester": 2}]}`)
|
||||
if err := bonfire.Call(t.Context(), bmPlugin(t, plugins).Commands(), "bm:seed", []string{clash}, &buf); err == nil {
|
||||
t.Error("a name longer than the column was accepted")
|
||||
}
|
||||
if got := count(t, gdb, "jz_bm_meetings"); got != 2 {
|
||||
t.Errorf("a failed seed kept its meetings: %d rows", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSeedCommandOpensDatabase runs bm:seed the way the binary does:
|
||||
// nothing is published on the app, so the command opens database.dsn.
|
||||
func TestSeedCommandOpensDatabase(t *testing.T) {
|
||||
_, _, gdb := migrated(t)
|
||||
var name string
|
||||
if err := gdb.Raw("SELECT current_database()").Scan(&name).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u, err := url.Parse(pgDSN)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u.Path = "/" + name
|
||||
app := backpack.New(testConfig(t))
|
||||
plugins := activate(t, app)
|
||||
if err := app.Config.Set("database.dsn", u.String()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := app.Config.Set("app.key", base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedFixture(t, plugins, "testdata/seed.example.json")
|
||||
if got := count(t, gdb, "jz_bm_courses"); got != 3 {
|
||||
t.Errorf("courses = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func writeJSON(t *testing.T, path, body string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// apiClient drives the assembled application as a signed-in user.
|
||||
type apiClient struct {
|
||||
t *testing.T
|
||||
h http.Handler
|
||||
token string
|
||||
}
|
||||
|
||||
func (c apiClient) do(method, path string) (int, map[string]any) {
|
||||
c.t.Helper()
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
c.h.ServeHTTP(rec, req)
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
c.t.Fatalf("%s %s = %d, not JSON: %s", method, path, rec.Code, rec.Body.String())
|
||||
}
|
||||
return rec.Code, body
|
||||
}
|
||||
|
||||
func (c apiClient) ok(method, path string) map[string]any {
|
||||
c.t.Helper()
|
||||
code, body := c.do(method, path)
|
||||
if code != http.StatusOK {
|
||||
c.t.Fatalf("%s %s = %d %v, want 200", method, path, code, body)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func createUser(t *testing.T, gdb *gorm.DB, email string) uint {
|
||||
t.Helper()
|
||||
var id uint
|
||||
if err := gdb.Raw(`INSERT INTO users (email) VALUES (?) RETURNING id`, email).Scan(&id).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func tokenFor(t *testing.T, id uint) string {
|
||||
t.Helper()
|
||||
token, _, err := bouncer.Mint(testUserSecret, strconv.FormatUint(uint64(id), 10), "http://127.0.0.1/api/login", time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func list(body map[string]any) []map[string]any {
|
||||
raw, _ := body["data"].([]any)
|
||||
out := make([]map[string]any, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
out = append(out, item.(map[string]any))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func obj(v any) map[string]any {
|
||||
m, _ := v.(map[string]any)
|
||||
return m
|
||||
}
|
||||
|
||||
func id(v any) string { return strconv.Itoa(int(v.(float64))) }
|
||||
|
||||
func TestAPIAgainstDatabase(t *testing.T) {
|
||||
app, plugins, gdb := migrated(t)
|
||||
seedFixture(t, plugins, "testdata/seed.example.json")
|
||||
h, err := surf.Assemble(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatalf("Assemble: %v", err)
|
||||
}
|
||||
alice := apiClient{t: t, h: h, token: tokenFor(t, createUser(t, gdb, "alice@example.test"))}
|
||||
bob := apiClient{t: t, h: h, token: tokenFor(t, createUser(t, gdb, "bob@example.test"))}
|
||||
guest := apiClient{t: t, h: h}
|
||||
|
||||
if code, body := guest.do("GET", "/_bm/api/v1/dashboard"); code != http.StatusUnauthorized {
|
||||
t.Errorf("guest dashboard = %d %v, want 401", code, body)
|
||||
}
|
||||
|
||||
var courseA, courseAC models.Course
|
||||
gdb.Where("form = ?", "wyklad").Take(&courseA)
|
||||
gdb.Where("form = ?", "cwiczenia").Take(&courseAC)
|
||||
|
||||
// Materials: a published note with tags and files, a published link, a
|
||||
// draft and one scheduled for the future.
|
||||
past := models.DateTime("2026-01-15 12:00")
|
||||
future := models.DateTime("2099-01-01 12:00")
|
||||
note := models.Material{CourseID: &courseA.ID, Title: "Notatka", Type: "notatka", Body: ptr("# Nagłówek"), PublishedAt: &past}
|
||||
link := models.Material{CourseID: &courseAC.ID, Title: "Link", Type: "link", URL: ptr("https://example.test"), PublishedAt: &past}
|
||||
draft := models.Material{CourseID: &courseA.ID, Title: "Szkic", Type: "notatka"}
|
||||
later := models.Material{CourseID: &courseA.ID, Title: "Później", Type: "pdf", PublishedAt: &future}
|
||||
for _, m := range []*models.Material{¬e, &link, &draft, &later} {
|
||||
if err := gdb.Create(m).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
geo := models.Tag{Name: "Geopolityka", Slug: "geopolityka"}
|
||||
alpha := models.Tag{Name: "Alfa", Slug: "alfa"}
|
||||
gdb.Create(&geo)
|
||||
gdb.Create(&alpha)
|
||||
gdb.Create(&[]models.MaterialTag{{MaterialID: note.ID, TagID: geo.ID}, {MaterialID: note.ID, TagID: alpha.ID}, {MaterialID: draft.ID, TagID: geo.ID}})
|
||||
private := false
|
||||
for i, f := range []attach.File{
|
||||
{DiskName: "aaaaaaaaaaaaaaaaaaaaaaaa.pdf", FileName: "wyklad.pdf", FileSize: 1234, ContentType: "application/pdf"},
|
||||
{DiskName: "bbbbbbbbbbbbbbbbbbbbbbbb.pdf", FileName: "prywatny.pdf", FileSize: 99, ContentType: "application/pdf", IsPublic: &private},
|
||||
} {
|
||||
f.Field = models.MaterialFilesField
|
||||
f.AttachmentType = models.Material{}.MorphName()
|
||||
f.AttachmentID = strconv.FormatUint(uint64(note.ID), 10)
|
||||
f.SortOrder = i
|
||||
if err := gdb.Create(&f).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Dashboard: the fixture lies in 2030, so everything is upcoming.
|
||||
dash := obj(alice.ok("GET", "/_bm/api/v1/dashboard")["data"])
|
||||
sessions, _ := dash["next_sessions"].([]any)
|
||||
if len(sessions) != 3 {
|
||||
t.Fatalf("next_sessions = %v", dash["next_sessions"])
|
||||
}
|
||||
first := obj(sessions[0])
|
||||
if first["starts_at"] != "2030-10-05T08:00:00+02:00" || first["ends_at"] != "2030-10-05T09:30:00+02:00" ||
|
||||
obj(first["course"])["name"] != "Przedmiot przykładowy A" || first["meeting_number"] != float64(1) || first["room"] != "101" {
|
||||
t.Errorf("first session = %v", first)
|
||||
}
|
||||
if deadlines, _ := dash["upcoming_deadlines"].([]any); len(deadlines) != 2 || obj(deadlines[1])["due_at"] != "2030-11-30T23:59:00+01:00" {
|
||||
t.Errorf("upcoming_deadlines = %v", dash["upcoming_deadlines"])
|
||||
}
|
||||
if dash["current_meeting"] != nil || obj(dash["next_meeting"])["number"] != float64(1) || obj(dash["next_meeting"])["starts_on"] != "2030-10-05" {
|
||||
t.Errorf("meetings = %v / %v", dash["current_meeting"], dash["next_meeting"])
|
||||
}
|
||||
if r := obj(dash["readings"]); r["total"] != float64(2) || r["read"] != float64(0) || r["required_total"] != float64(1) || r["required_read"] != float64(0) {
|
||||
t.Errorf("readings = %v", r)
|
||||
}
|
||||
|
||||
// Reading progress is per user and idempotent.
|
||||
var required models.Reading
|
||||
gdb.Where("is_required").Take(&required)
|
||||
rid := strconv.FormatUint(uint64(required.ID), 10)
|
||||
marked := obj(alice.ok("PUT", "/_bm/api/v1/readings/"+rid+"/progress")["data"])
|
||||
readAt, _ := marked["read_at"].(string)
|
||||
if marked["reading_id"] != float64(required.ID) || !strings.HasSuffix(readAt, "+01:00") && !strings.HasSuffix(readAt, "+02:00") {
|
||||
t.Errorf("mark = %v", marked)
|
||||
}
|
||||
if again := obj(alice.ok("PUT", "/_bm/api/v1/readings/"+rid+"/progress")["data"]); again["read_at"] != readAt {
|
||||
t.Errorf("marking again changed read_at: %v -> %v", readAt, again["read_at"])
|
||||
}
|
||||
if r := obj(obj(alice.ok("GET", "/_bm/api/v1/dashboard")["data"])["readings"]); r["read"] != float64(1) || r["required_read"] != float64(1) {
|
||||
t.Errorf("alice readings = %v", r)
|
||||
}
|
||||
if r := obj(obj(bob.ok("GET", "/_bm/api/v1/dashboard")["data"])["readings"]); r["read"] != float64(0) {
|
||||
t.Errorf("bob sees alice's progress: %v", r)
|
||||
}
|
||||
for _, path := range []string{"/_bm/api/v1/readings/99999/progress"} {
|
||||
if code, _ := alice.do("PUT", path); code != http.StatusNotFound {
|
||||
t.Errorf("PUT %s = %d, want 404", path, code)
|
||||
}
|
||||
if code, _ := alice.do("DELETE", path); code != http.StatusNotFound {
|
||||
t.Errorf("DELETE %s = %d, want 404", path, code)
|
||||
}
|
||||
}
|
||||
|
||||
// Readings list with the caller's state.
|
||||
readings := list(alice.ok("GET", "/_bm/api/v1/readings?course="+strconv.FormatUint(uint64(courseA.ID), 10)))
|
||||
if len(readings) != 2 || readings[0]["title"] != "Lektura przykładowa 1" || readings[0]["read_at"] != readAt || readings[1]["read_at"] != nil {
|
||||
t.Errorf("alice readings = %v", readings)
|
||||
}
|
||||
if obj(readings[0]["course"])["form"] != "wyklad" || readings[0]["author"] != "A. Autor" || readings[0]["is_required"] != true {
|
||||
t.Errorf("reading = %v", readings[0])
|
||||
}
|
||||
if bobs := list(bob.ok("GET", "/_bm/api/v1/readings")); len(bobs) != 2 || bobs[0]["read_at"] != nil {
|
||||
t.Errorf("bob readings = %v", bobs)
|
||||
}
|
||||
if none := list(alice.ok("GET", "/_bm/api/v1/readings?course=99999")); len(none) != 0 {
|
||||
t.Errorf("unknown course readings = %v", none)
|
||||
}
|
||||
|
||||
// Courses with counters.
|
||||
courses := list(alice.ok("GET", "/_bm/api/v1/courses"))
|
||||
if len(courses) != 3 || courses[0]["name"] != "Przedmiot przykładowy A" || courses[0]["form"] != "wyklad" {
|
||||
t.Fatalf("courses = %v", courses)
|
||||
}
|
||||
if c := obj(courses[0]["counts"]); c["sessions"] != float64(1) || c["readings"] != float64(2) || c["readings_read"] != float64(1) || c["materials"] != float64(1) {
|
||||
t.Errorf("course A counts = %v", c)
|
||||
}
|
||||
if courses[0]["ects"] != float64(4) || courses[1]["ects"] != 2.5 || courses[2]["elective_group"] != "przyklad-do-wyboru" || courses[0]["elective_group"] != nil {
|
||||
t.Errorf("course fields = %v", courses)
|
||||
}
|
||||
if two := list(alice.ok("GET", "/_bm/api/v1/courses?semester=2")); len(two) != 0 {
|
||||
t.Errorf("semester 2 = %v", two)
|
||||
}
|
||||
detail := obj(alice.ok("GET", "/_bm/api/v1/courses/"+strconv.FormatUint(uint64(courseA.ID), 10))["data"])
|
||||
if s, _ := detail["sessions"].([]any); len(s) != 1 {
|
||||
t.Errorf("detail sessions = %v", detail["sessions"])
|
||||
}
|
||||
if r, _ := detail["readings"].([]any); len(r) != 2 || obj(r[0])["read_at"] != readAt {
|
||||
t.Errorf("detail readings = %v", detail["readings"])
|
||||
}
|
||||
if m, _ := detail["materials"].([]any); len(m) != 1 || obj(m[0])["title"] != "Notatka" || obj(m[0])["files_count"] != float64(1) {
|
||||
t.Errorf("detail materials = %v", detail["materials"])
|
||||
}
|
||||
if code, _ := alice.do("GET", "/_bm/api/v1/courses/99999"); code != http.StatusNotFound {
|
||||
t.Errorf("missing course = %d, want 404", code)
|
||||
}
|
||||
|
||||
// Schedule, meetings and deadlines.
|
||||
if day := list(alice.ok("GET", "/_bm/api/v1/schedule?from=2030-10-05&to=2030-10-05")); len(day) != 2 {
|
||||
t.Errorf("schedule of 5 Oct = %v", day)
|
||||
}
|
||||
if rest := list(alice.ok("GET", "/_bm/api/v1/schedule?from=2030-10-06")); len(rest) != 1 || rest[0]["is_online"] != true {
|
||||
t.Errorf("schedule from 6 Oct = %v", rest)
|
||||
}
|
||||
if all := list(alice.ok("GET", "/_bm/api/v1/schedule")); len(all) != 3 {
|
||||
t.Errorf("schedule from today = %v", all)
|
||||
}
|
||||
if none := list(alice.ok("GET", "/_bm/api/v1/schedule?to=2026-01-01")); len(none) != 0 {
|
||||
t.Errorf("schedule up to a past day = %v", none)
|
||||
}
|
||||
meetings := list(alice.ok("GET", "/_bm/api/v1/meetings"))
|
||||
if len(meetings) != 2 || meetings[0]["sessions_count"] != float64(2) || meetings[0]["notes"] != "przykład" || meetings[1]["ends_on"] != "2030-10-20" {
|
||||
t.Errorf("meetings = %v", meetings)
|
||||
}
|
||||
if d := list(alice.ok("GET", "/_bm/api/v1/deadlines")); len(d) != 2 || d[0]["kind"] != "organizacyjne" || d[0]["course"] != nil {
|
||||
t.Errorf("deadlines = %v", d)
|
||||
}
|
||||
if d := list(alice.ok("GET", "/_bm/api/v1/deadlines?from=2030-11-01")); len(d) != 1 || obj(d[0]["course"])["form"] != "cwiczenia" {
|
||||
t.Errorf("deadlines from November = %v", d)
|
||||
}
|
||||
|
||||
// Materials: published only, filtered, paginated.
|
||||
page := alice.ok("GET", "/_bm/api/v1/materials")
|
||||
items := list(page)
|
||||
if len(items) != 2 || obj(page["meta"])["total"] != float64(2) || obj(page["meta"])["per_page"] != float64(20) {
|
||||
t.Fatalf("materials = %v", page)
|
||||
}
|
||||
for _, f := range []struct{ query, title string }{
|
||||
{"?tag=geopolityka", "Notatka"},
|
||||
{"?type=link", "Link"},
|
||||
{"?course=" + strconv.FormatUint(uint64(courseAC.ID), 10), "Link"},
|
||||
} {
|
||||
got := list(alice.ok("GET", "/_bm/api/v1/materials"+f.query))
|
||||
if len(got) != 1 || got[0]["title"] != f.title {
|
||||
t.Errorf("materials%s = %v, want %s", f.query, got, f.title)
|
||||
}
|
||||
}
|
||||
if got := list(alice.ok("GET", "/_bm/api/v1/materials?tag=nieznany")); len(got) != 0 {
|
||||
t.Errorf("unknown tag = %v", got)
|
||||
}
|
||||
paged := alice.ok("GET", "/_bm/api/v1/materials?per_page=1&page=2")
|
||||
if got := list(paged); len(got) != 1 || obj(paged["meta"])["last_page"] != float64(2) || obj(paged["meta"])["current_page"] != float64(2) {
|
||||
t.Errorf("page 2 of 2 = %v", paged)
|
||||
}
|
||||
shown := obj(alice.ok("GET", "/_bm/api/v1/materials/"+strconv.FormatUint(uint64(note.ID), 10))["data"])
|
||||
files, _ := shown["files"].([]any)
|
||||
if shown["body"] != "# Nagłówek" || len(files) != 1 || shown["files_count"] != float64(1) || shown["published_at"] != "2026-01-15T12:00:00+01:00" {
|
||||
t.Errorf("material = %v", shown)
|
||||
}
|
||||
if f := obj(files[0]); f["name"] != "wyklad.pdf" || f["size"] != float64(1234) || f["mime"] != "application/pdf" ||
|
||||
!strings.HasPrefix(f["url"].(string), "/storage/uploads/aaa/aaa/aaa/") {
|
||||
t.Errorf("file = %v", f)
|
||||
}
|
||||
if tags, _ := shown["tags"].([]any); len(tags) != 2 || obj(tags[0])["slug"] != "alfa" {
|
||||
t.Errorf("tags = %v", shown["tags"])
|
||||
}
|
||||
for _, hidden := range []uint{draft.ID, later.ID, 99999} {
|
||||
if code, _ := alice.do("GET", "/_bm/api/v1/materials/"+strconv.FormatUint(uint64(hidden), 10)); code != http.StatusNotFound {
|
||||
t.Errorf("material %d = %d, want 404", hidden, code)
|
||||
}
|
||||
}
|
||||
|
||||
// Unmarking clears the state; unmarking again is fine.
|
||||
if cleared := obj(alice.ok("DELETE", "/_bm/api/v1/readings/"+rid+"/progress")["data"]); cleared["read_at"] != nil {
|
||||
t.Errorf("unmark = %v", cleared)
|
||||
}
|
||||
alice.ok("DELETE", "/_bm/api/v1/readings/"+rid+"/progress")
|
||||
if count(t, gdb, "jz_bm_reading_progress") != 0 {
|
||||
t.Error("progress rows remain after unmarking")
|
||||
}
|
||||
|
||||
// Bad parameters answer 422 through the whole stack.
|
||||
code, body := alice.do("GET", "/_bm/api/v1/schedule?from=2030-10-10&to=2030-10-01")
|
||||
if code != http.StatusUnprocessableEntity || obj(body["errors"])["to"] == nil {
|
||||
t.Errorf("bad range = %d %v", code, body)
|
||||
}
|
||||
if msg, _ := body["message"].(string); msg == "" || strings.HasPrefix(msg, "validation.") {
|
||||
t.Errorf("422 message %q is not translated", msg)
|
||||
}
|
||||
|
||||
// Deleting a course cascades to its sessions and readings, and unlinks
|
||||
// its materials.
|
||||
gdb.Exec(`DELETE FROM jz_bm_courses WHERE id = ?`, courseA.ID)
|
||||
if n := count(t, gdb, "jz_bm_readings"); n != 0 {
|
||||
t.Errorf("readings after deleting the course = %d", n)
|
||||
}
|
||||
var orphan models.Material
|
||||
gdb.Where("id = ?", note.ID).Take(&orphan)
|
||||
if orphan.CourseID != nil {
|
||||
t.Errorf("material kept course_id %v", *orphan.CourseID)
|
||||
}
|
||||
}
|
||||
|
||||
func ptr(s string) *string { return &s }
|
||||
1
public/assets/CourseView-X-33fQnj.js
Normal file
1
public/assets/CourseView-X-33fQnj.js
Normal file
File diff suppressed because one or more lines are too long
1
public/assets/CoursesView-J2JUkxxq.js
Normal file
1
public/assets/CoursesView-J2JUkxxq.js
Normal file
@@ -0,0 +1 @@
|
||||
import{_ as C}from"./PageHead.vue_vue_type_script_setup_true_lang-BUSgwkrI.js";import{_ as w}from"./LoadState.vue_vue_type_script_setup_true_lang-DF4LiBqt.js";import{_ as B}from"./ElectiveBar.vue_vue_type_script_setup_true_lang-CFL2E96J.js";import{d as z,p as $,C as x,q as S,c as t,h as m,i as k,b as r,o as s,a as o,F as c,y as v,e as n,r as V,s as h,k as E,t as a,B as F,D as N,m as _}from"./index-DQ8t_00h.js";import{F as j,c as f}from"./format-bcE-cYHJ.js";const L={key:0,class:"chips",role:"group","aria-label":"Semestr"},D=["aria-pressed"],M=["aria-pressed","onClick"],P={key:1,class:"stack",style:{"margin-top":"10px"}},R={class:"row-main"},T={class:"badge"},q={class:"muted small",style:{margin:"0 0 6px"}},A={key:0},O={key:1},U={key:2},W={class:"small",style:{margin:"0"}},G={key:0,class:"badge alert"},H={class:"muted"},I={key:2,class:"empty"},se=z({__name:"CoursesView",setup(J){const i=$(),g=x(),l=V(null);S(()=>{i.loadCourses()});const p=h(()=>[...new Set((i.courses??[]).map(u=>u.semester))].sort((u,d)=>u-d)),y=h(()=>i.visibleCourses.filter(u=>l.value===null||u.semester===l.value));return(u,d)=>{const b=E("router-link");return s(),t("div",null,[m(C,{eyebrow:"Program studiów",title:"Przedmioty"}),m(w,{ready:r(i).loaded.courses,error:r(i).error,onRetry:d[1]||(d[1]=e=>r(i).retry())},{default:k(()=>[m(B),p.value.length>1?(s(),t("div",L,[o("button",{class:"chip",type:"button","aria-pressed":l.value===null,onClick:d[0]||(d[0]=e=>l.value=null)},"Wszystkie",8,D),(s(!0),t(c,null,v(p.value,e=>(s(),t("button",{key:e,class:"chip",type:"button","aria-pressed":l.value===e,onClick:K=>l.value=e},"Semestr "+a(e),9,M))),128))])):n("",!0),y.value.length?(s(),t("div",P,[(s(!0),t(c,null,v(y.value,e=>(s(),F(b,{key:e.id,to:`/przedmioty/${e.id}`,class:"card link"},{default:k(()=>[o("div",R,[o("h3",null,a(e.name),1),o("span",T,a(r(j)[e.form]),1)]),o("p",q,[e.lecturer?(s(),t("span",A,a(e.lecturer),1)):n("",!0),e.ects?(s(),t("span",O," · "+a(e.ects)+" ECTS",1)):n("",!0),e.assessment?(s(),t("span",U," · "+a(e.assessment),1)):n("",!0)]),o("p",W,[r(N)(e,r(g).choices)?(s(),t("span",G,"do wyboru")):n("",!0),o("span",H,[_(a(r(f)(e.counts.sessions,"zajęcia","zajęcia","zajęć")),1),e.counts.readings?(s(),t(c,{key:0},[_(" · lektury "+a(e.counts.readings_read)+"/"+a(e.counts.readings),1)],64)):n("",!0),e.counts.materials?(s(),t(c,{key:1},[_(" · "+a(r(f)(e.counts.materials,"materiał","materiały","materiałów")),1)],64)):n("",!0)])])]),_:2},1032,["to"]))),128))])):(s(),t("p",I,"Brak przedmiotów."))]),_:1},8,["ready","error"])])}}});export{se as default};
|
||||
1
public/assets/DashboardView-Bxuecz7-.js
Normal file
1
public/assets/DashboardView-Bxuecz7-.js
Normal file
File diff suppressed because one or more lines are too long
1
public/assets/DeadlinesView-C664w7Wt.js
Normal file
1
public/assets/DeadlinesView-C664w7Wt.js
Normal file
@@ -0,0 +1 @@
|
||||
import{_ as B}from"./PageHead.vue_vue_type_script_setup_true_lang-BUSgwkrI.js";import{_ as x}from"./LoadState.vue_vue_type_script_setup_true_lang-DF4LiBqt.js";import{_ as C}from"./ElectiveBar.vue_vue_type_script_setup_true_lang-CFL2E96J.js";import{d as $,p as N,q as T,c as o,h as m,i as v,b as s,r as y,o as t,F as h,y as f,a as n,t as a,e as u,s as k,k as V,x as L,m as g,B as M}from"./index-DQ8t_00h.js";import{d as w,r as E,b as D,a as F,K as b,c as K}from"./format-bcE-cYHJ.js";const P={key:0,class:"rows card"},S={class:"row-main"},j={class:"title"},q={class:"muted small"},A={class:"badge"},I={key:0,class:"small",style:{margin:"6px 0 0"}},R={key:1,class:"empty"},U={key:2,class:"section"},Z=["aria-pressed"],G={key:0,class:"rows card past",style:{"margin-top":"10px"}},H={class:"row-main"},J={class:"title"},O={class:"when"},Q={class:"muted small"},te=$({__name:"DeadlinesView",setup(W){const r=N(),i=y(new Date),l=y(!1);T(()=>{i.value=new Date,Promise.all([r.loadDeadlines(),r.loadCourses()])});const p=k(()=>r.deadlines.filter(c=>Date.parse(c.due_at)>=i.value.getTime())),_=k(()=>r.deadlines.filter(c=>Date.parse(c.due_at)<i.value.getTime()).reverse());return(c,d)=>{const z=V("router-link");return t(),o("div",null,[m(B,{eyebrow:"Zaliczenia, egzaminy, sprawy organizacyjne",title:"Terminarz"}),m(x,{ready:s(r).loaded.deadlines&&s(r).loaded.courses,error:s(r).error,onRetry:d[1]||(d[1]=e=>s(r).retry())},{default:v(()=>[m(C),p.value.length?(t(),o("ul",P,[(t(!0),o(h,null,f(p.value,e=>(t(),o("li",{key:e.id},[n("div",S,[n("span",j,a(e.title),1),n("span",{class:L(["badge",{alert:s(w)(e.due_at,i.value)<=3}])},a(s(E)(e.due_at,i.value)),3)]),n("div",q,[g(a(s(D)(e.due_at))+", "+a(s(F)(e.due_at))+" · ",1),n("span",A,a(s(b)[e.kind]),1),e.course?(t(),M(z,{key:0,to:`/przedmioty/${e.course.id}`},{default:v(()=>[g(" · "+a(e.course.name),1)]),_:2},1032,["to"])):u("",!0)]),e.description?(t(),o("p",I,a(e.description),1)):u("",!0)]))),128))])):(t(),o("p",R,"Brak nadchodzących terminów.")),_.value.length?(t(),o("div",U,[n("button",{class:"chip",type:"button","aria-pressed":l.value,onClick:d[0]||(d[0]=e=>l.value=!l.value)},"Minione ("+a(_.value.length)+")",9,Z),l.value?(t(),o("ul",G,[(t(!0),o(h,null,f(_.value,e=>(t(),o("li",{key:e.id},[n("div",H,[n("span",J,a(e.title),1),n("span",O,a(s(K)(Math.abs(s(w)(e.due_at,i.value)),"dzień","dni","dni"))+" temu",1)]),n("div",Q,a(s(D)(e.due_at))+" · "+a(s(b)[e.kind]),1)]))),128))])):u("",!0)])):u("",!0)]),_:1},8,["ready","error"])])}}});export{te as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{d as l,C as d,p as u,b as e,o as a,c as r,m as i,t as m,h as y,i as w,e as n,a as h,s as _,k}from"./index-DQ8t_00h.js";import{c as b}from"./format-bcE-cYHJ.js";const g={key:0,class:"stack",style:{"margin-bottom":"16px"}},v={key:0,class:"notice"},z={key:1,class:"chips wrap"},C=["aria-pressed"],V=l({__name:"ElectiveBar",setup(f){const t=d(),o=u(),c=_(()=>b(o.pendingElectives.length,"grupa przedmiotów do wyboru","grupy przedmiotów do wyboru","grup przedmiotów do wyboru"));return(x,s)=>{const p=k("router-link");return e(o).pendingElectives.length||e(t).hasChoices?(a(),r("div",g,[e(o).pendingElectives.length?(a(),r("p",v,[i(" Masz "+m(c.value)+". Do czasu wyboru widać wszystkie alternatywy. ",1),y(p,{to:{name:"profile",hash:"#wybor"}},{default:w(()=>[...s[1]||(s[1]=[i("Wybierz",-1)])]),_:1})])):n("",!0),e(t).hasChoices?(a(),r("div",z,[h("button",{class:"chip",type:"button","aria-pressed":e(t).showAll,onClick:s[0]||(s[0]=E=>e(t).setShowAll(!e(t).showAll))},"Pokaż wszystkie przedmioty do wyboru",8,C)])):n("",!0)])):n("",!0)}}});export{V as _};
|
||||
1
public/assets/ForgotView-Bj9nwgXG.js
Normal file
1
public/assets/ForgotView-Bj9nwgXG.js
Normal file
@@ -0,0 +1 @@
|
||||
import{d as f,c as t,a,g as y,t as n,e as m,w as _,v as k,h as w,i as b,r,k as h,o,m as g,n as x}from"./index-DQ8t_00h.js";import{f as V}from"./forms-Diah5cld.js";const B={class:"auth"},C={key:0,class:"notice",role:"status"},N={key:0,class:"notice error",role:"alert",style:{"margin-bottom":"14px"}},W={class:"field"},j={key:0,class:"error-text"},M=["disabled"],z={class:"auth-links"},I=f({__name:"ForgotView",setup(A){const l=r(""),i=r(!1),u=r(!1),s=r(null);async function c(){i.value=!0,s.value=null;try{await x.forgotPassword(l.value.trim()),u.value=!0}catch(d){s.value=V(d)}finally{i.value=!1}}return(d,e)=>{const p=h("router-link");return o(),t("div",B,[e[3]||(e[3]=a("header",{class:"page-head"},[a("span",{class:"eyebrow"},"BM II° · UWr"),a("h1",null,"Przypomnij hasło")],-1)),u.value?(o(),t("p",C,"Jeśli konto o tym adresie istnieje, wysłaliśmy na nie wiadomość z linkiem do ustawienia nowego hasła.")):(o(),t("form",{key:1,onSubmit:y(c,["prevent"]),novalidate:""},[s.value?.message?(o(),t("div",N,n(s.value.message),1)):m("",!0),a("div",W,[e[1]||(e[1]=a("label",{for:"email"},"Adres e-mail",-1)),_(a("input",{id:"email","onUpdate:modelValue":e[0]||(e[0]=v=>l.value=v),type:"email",autocomplete:"email",inputmode:"email",required:"",autofocus:""},null,512),[[k,l.value]]),s.value?.fields.email?(o(),t("p",j,n(s.value.fields.email),1)):m("",!0)]),a("button",{class:"btn primary block",type:"submit",disabled:i.value||!l.value},n(i.value?"Wysyłanie…":"Wyślij link"),9,M)],32)),a("div",z,[w(p,{to:"/logowanie"},{default:b(()=>[...e[2]||(e[2]=[g("Wróć do logowania",-1)])]),_:1})])])}}});export{I as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{d as n,c as r,m as l,t as i,a as o,M as d,o as s}from"./index-DQ8t_00h.js";const y={key:0,class:"notice error",role:"alert"},c={key:1,class:"stack","aria-busy":"true","aria-label":"Wczytywanie"},m=n({__name:"LoadState",props:{loading:{type:Boolean},error:{},ready:{type:Boolean}},emits:["retry"],setup(e){return(a,t)=>e.error&&!e.ready?(s(),r("div",y,[l(i(e.error)+" ",1),o("button",{class:"linkish",type:"button",onClick:t[0]||(t[0]=u=>a.$emit("retry"))},"Spróbuj ponownie")])):e.ready?d(a.$slots,"default",{},void 0,void 0,2):(s(),r("div",c,[...t[1]||(t[1]=[o("div",{class:"skeleton"},null,-1),o("div",{class:"skeleton"},null,-1),o("div",{class:"skeleton"},null,-1)])]))}});export{m as _};
|
||||
1
public/assets/LoginView-CDHiD0sE.js
Normal file
1
public/assets/LoginView-CDHiD0sE.js
Normal file
@@ -0,0 +1 @@
|
||||
import{d as j,u as V,c as o,a as s,b as C,e as d,t as m,w as v,v as b,f as N,g as q,h as w,i as k,j as B,r as l,k as M,l as U,o as r,m as _}from"./index-DQ8t_00h.js";import{s as Z,f as z}from"./forms-Diah5cld.js";const R={class:"auth"},S={key:0,class:"notice",role:"status"},A={key:0,class:"notice error",role:"alert",style:{"margin-bottom":"14px"}},D={class:"field"},E={key:0,class:"error-text"},I={class:"field"},L={key:0,class:"error-text"},T={class:"check",style:{"margin-bottom":"16px"}},H=["disabled"],P={class:"auth-links"},J=j({__name:"LoginView",setup(W){const g=V(),c=B(),x=U(),i=l(""),u=l(""),p=l(!0),n=l(!1),t=l(null);async function h(){n.value=!0,t.value=null;try{await g.login(i.value.trim(),u.value,p.value),await x.replace(Z(c.query.redirect))}catch(f){t.value=z(f)}finally{n.value=!1}}return(f,e)=>{const y=M("router-link");return r(),o("div",R,[e[8]||(e[8]=s("header",{class:"page-head"},[s("span",{class:"eyebrow"},"BM II° · UWr"),s("h1",null,"Zaloguj się")],-1)),C(c).query.expired?(r(),o("p",S,"Sesja wygasła. Zaloguj się ponownie.")):d("",!0),s("form",{onSubmit:q(h,["prevent"]),novalidate:""},[t.value?.message?(r(),o("div",A,m(t.value.message),1)):d("",!0),s("div",D,[e[3]||(e[3]=s("label",{for:"email"},"Adres e-mail",-1)),v(s("input",{id:"email","onUpdate:modelValue":e[0]||(e[0]=a=>i.value=a),type:"email",autocomplete:"username",inputmode:"email",required:"",autofocus:""},null,512),[[b,i.value]]),t.value?.fields.email?(r(),o("p",E,m(t.value.fields.email),1)):d("",!0)]),s("div",I,[e[4]||(e[4]=s("label",{for:"password"},"Hasło",-1)),v(s("input",{id:"password","onUpdate:modelValue":e[1]||(e[1]=a=>u.value=a),type:"password",autocomplete:"current-password",required:""},null,512),[[b,u.value]]),t.value?.fields.password?(r(),o("p",L,m(t.value.fields.password),1)):d("",!0)]),s("label",T,[v(s("input",{"onUpdate:modelValue":e[2]||(e[2]=a=>p.value=a),type:"checkbox"},null,512),[[N,p.value]]),e[5]||(e[5]=s("span",null,"Pamiętaj mnie na tym urządzeniu",-1))]),s("button",{class:"btn primary block",type:"submit",disabled:n.value||!i.value||!u.value},m(n.value?"Logowanie…":"Zaloguj się"),9,H)],32),s("div",P,[w(y,{to:"/przypomnij-haslo"},{default:k(()=>[...e[6]||(e[6]=[_("Nie pamiętam hasła",-1)])]),_:1}),w(y,{to:"/rejestracja"},{default:k(()=>[...e[7]||(e[7]=[_("Załóż konto",-1)])]),_:1})])])}}});export{J as default};
|
||||
6
public/assets/MaterialView-CvNG1uCh.js
Normal file
6
public/assets/MaterialView-CvNG1uCh.js
Normal file
@@ -0,0 +1,6 @@
|
||||
import{_ as C}from"./PageHead.vue_vue_type_script_setup_true_lang-BUSgwkrI.js";import{_ as E}from"./LoadState.vue_vue_type_script_setup_true_lang-DF4LiBqt.js";import{d as L,q as V,A as z,c as u,h as k,i as g,r as B,E as A,G as H,o as l,F as y,b,m as j,a as d,B as W,t as f,e as h,y as M,s as N,k as D}from"./index-DQ8t_00h.js";import{T as F,i as P,j as G}from"./format-bcE-cYHJ.js";const O={"&":"&","<":"<",">":">",'"':""","'":"'"};function _(o){return o.replace(/[&<>"']/g,t=>O[t])}function T(o){const t=o.trim().replace(/[\u0000-\u001f\u007f\s]+/g,"");return/^https?:\/\/[^/]/i.test(t)||/^mailto:[^\s]+$/i.test(t)||t.startsWith("/")&&!t.startsWith("//")||t.startsWith("#")?t:null}function w(o){const t=[],s=i=>`\0${t.push(i)-1}\0`;let e=o.replace(/\u0000/g,"");return e=e.replace(/`([^`\n]+)`/g,(i,c)=>s(`<code>${_(c)}</code>`)),e=e.replace(/\[([^\]\n]+)\]\(([^()\s]*(?:\([^()\s]*\)[^()\s]*)*)\)/g,(i,c,r)=>{const p=T(r),a=S(_(c));if(!p)return s(a);const n=/^https?:/i.test(p)?' target="_blank" rel="noopener noreferrer nofollow"':"";return s(`<a href="${_(p)}"${n}>${a}</a>`)}),e=S(_(e)),e.replace(/\u0000(\d+)\u0000/g,(i,c)=>t[Number(c)]??"")}function S(o){return o.replace(/\*\*([^*\n]+)\*\*/g,"<strong>$1</strong>").replace(/(^|[\s(])\*([^*\n]+)\*(?=$|[\s).,;:!?])/g,"$1<em>$2</em>").replace(/(^|[\s(])_([^_\n]+)_(?=$|[\s).,;:!?])/g,"$1<em>$2</em>")}function q(o){if(!o)return"";const t=o.replace(/\r\n?/g,`
|
||||
`).split(`
|
||||
`),s=[];let e=0;const i=r=>r.trim()==="",c=r=>/^(#{1,6})\s/.test(r)||/^```/.test(r)||/^>\s?/.test(r)||/^\s*([-*+]|\d+[.)])\s+/.test(r)||/^(-{3,}|\*{3,}|_{3,})\s*$/.test(r);for(;e<t.length;){const r=t[e];if(i(r)){e++;continue}if(/^```/.test(r)){const n=[];for(e++;e<t.length&&!/^```/.test(t[e]);)n.push(t[e++]);e++,s.push(`<pre><code>${_(n.join(`
|
||||
`))}</code></pre>`);continue}const p=/^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(r);if(p){const n=Math.min(p[1].length+1,6);s.push(`<h${n}>${w(p[2])}</h${n}>`),e++;continue}if(/^(-{3,}|\*{3,}|_{3,})\s*$/.test(r)){s.push("<hr>"),e++;continue}if(/^>\s?/.test(r)){const n=[];for(;e<t.length&&/^>\s?/.test(t[e]);)n.push(t[e++].replace(/^>\s?/,""));s.push(`<blockquote>${q(n.join(`
|
||||
`))}</blockquote>`);continue}const a=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(r);if(a){const n=/\d/.test(a[1]),v=[];for(;e<t.length;){const $=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(t[e]);if(!$||/\d/.test($[1])!==n)break;let x=$[2];for(e++;e<t.length&&/^\s{2,}\S/.test(t[e])&&!/^\s*([-*+]|\d+[.)])\s+/.test(t[e]);)x+=" "+t[e++].trim();v.push(`<li>${w(x)}</li>`)}s.push(n?`<ol>${v.join("")}</ol>`:`<ul>${v.join("")}</ul>`);continue}const m=[r];for(e++;e<t.length&&!i(t[e])&&!c(t[e]);)m.push(t[e++]);s.push(`<p>${m.map(n=>w(n.trim())).join(" ")}</p>`)}return s.join(`
|
||||
`)}const R={class:"muted small"},U={key:1},Y={key:0},I={key:1},J=["href"],K=["innerHTML"],Q={key:3,class:"section","aria-labelledby":"files-h"},X={class:"rows"},Z=["href"],ee={class:"when"},oe=L({__name:"MaterialView",props:{id:{}},setup(o){const t=o,s=B(null),e=B("");async function i(){s.value=null,e.value="";try{s.value=await A.material(Number(t.id))}catch(p){e.value=H(p)}}V(i),z(()=>t.id,i);const c=N(()=>q(s.value?.body)),r=N(()=>s.value?.url?T(s.value.url):null);return(p,a)=>{const m=D("router-link");return l(),u("div",null,[k(E,{ready:!!s.value,error:e.value,onRetry:a[0]||(a[0]=n=>i())},{default:g(()=>[s.value?(l(),u(y,{key:0},[k(C,{eyebrow:`${b(F)[s.value.type]}${s.value.published_at?" · "+b(P)(s.value.published_at):""}`,title:s.value.title},{default:g(()=>[k(m,{class:"btn small ghost",to:"/materialy"},{default:g(()=>[...a[1]||(a[1]=[j("← Materiały",-1)])]),_:1})]),_:1},8,["eyebrow","title"]),d("p",R,[s.value.course?(l(),W(m,{key:0,to:`/przedmioty/${s.value.course.id}`},{default:g(()=>[j(f(s.value.course.name),1)]),_:1},8,["to"])):h("",!0),s.value.source?(l(),u("span",U," · "+f(s.value.source),1)):h("",!0)]),s.value.tags.length?(l(),u("p",Y,[(l(!0),u(y,null,M(s.value.tags,n=>(l(),u("span",{key:n.id,class:"badge",style:{"margin-right":"4px"}},f(n.name),1))),128))])):h("",!0),r.value?(l(),u("p",I,[d("a",{class:"btn small",href:r.value,target:"_blank",rel:"noopener noreferrer"},"Otwórz link",8,J)])):h("",!0),c.value?(l(),u("div",{key:2,class:"prose card",innerHTML:c.value},null,8,K)):h("",!0),s.value.files.length?(l(),u("section",Q,[a[2]||(a[2]=d("div",{class:"section-head"},[d("h2",{id:"files-h"},"Pliki")],-1)),d("ul",X,[(l(!0),u(y,null,M(s.value.files,n=>(l(),u("li",{key:n.id,class:"row-main"},[d("a",{href:n.url,target:"_blank",rel:"noopener noreferrer",download:""},f(n.name),9,Z),d("span",ee,f(b(G)(n.size)),1)]))),128))])])):h("",!0)],64)):h("",!0)]),_:1},8,["ready","error"])])}}});export{oe as default};
|
||||
1
public/assets/MaterialsView-BC2-qh9D.js
Normal file
1
public/assets/MaterialsView-BC2-qh9D.js
Normal file
@@ -0,0 +1 @@
|
||||
import{d as V,p as j,q as $,E as D,G as E,A as P,c as a,h as A,a as l,w as N,H as B,F as c,y as v,b as y,g as F,e as d,m as L,t as n,I as W,r as m,s as M,o as s,k as q,B as U,i as G}from"./index-DQ8t_00h.js";import{_ as H}from"./PageHead.vue_vue_type_script_setup_true_lang-BUSgwkrI.js";import{T as S,i as I,c as O}from"./format-bcE-cYHJ.js";const R={class:"field"},Y=["value"],J={class:"field"},K=["value"],Q={key:0,class:"chips wrap",role:"group","aria-label":"Tagi",style:{"margin-bottom":"12px"}},X=["aria-pressed","onClick"],Z={key:2,class:"notice error",role:"alert"},ee={key:3,class:"stack","aria-busy":"true"},te=["aria-busy"],se={class:"row-main"},ae={class:"badge"},le={class:"muted small",style:{margin:"0"}},oe={key:0},ne={key:1},ie={key:2},re={key:0,style:{margin:"6px 0 0"}},ue={key:1,class:"empty",style:{"margin-top":"12px"}},de={key:2,class:"btn-row",style:{"margin-top":"16px","justify-content":"space-between","align-items":"center"},"aria-label":"Strony"},pe=["disabled"],ce={class:"muted small nums"},ve=["disabled"],fe=V({__name:"MaterialsView",setup(ye){const h=j(),o=W({course:"",type:"",tag:""}),i=m(1),u=m(null),b=m(!1),g=m(""),k=m(new Map);$(()=>{h.loadCourses(),_()});let f=0;async function _(){const r=++f;b.value=!0,g.value="";try{const t=await D.materials({course:o.course?Number(o.course):null,type:o.type||null,tag:o.tag||null,page:i.value});if(r!==f)return;u.value=t;for(const w of t.data)for(const e of w.tags)k.value.set(e.slug,e);k.value=new Map(k.value)}catch(t){r===f&&(g.value=E(t))}finally{r===f&&(b.value=!1)}}P(o,()=>{i.value=1,_()});function C(r){i.value=r,_(),window.scrollTo({top:0})}const x=M(()=>[...k.value.values()].sort((r,t)=>r.name.localeCompare(t.name,"pl"))),z=M(()=>!!(o.course||o.type||o.tag)),T=()=>Object.assign(o,{course:"",type:"",tag:""});return(r,t)=>{const w=q("router-link");return s(),a("div",null,[A(H,{eyebrow:"Notatki, PDF-y, linki",title:"Materiały"}),l("form",{class:"grid-2",style:{"margin-bottom":"8px"},onSubmit:t[2]||(t[2]=F(()=>{},["prevent"]))},[l("div",R,[t[7]||(t[7]=l("label",{for:"f-course"},"Przedmiot",-1)),N(l("select",{id:"f-course","onUpdate:modelValue":t[0]||(t[0]=e=>o.course=e)},[t[6]||(t[6]=l("option",{value:""},"Wszystkie",-1)),(s(!0),a(c,null,v(y(h).visibleCourses,e=>(s(),a("option",{key:e.id,value:String(e.id)},n(e.name)+" ("+n(e.form==="wyklad"?"wykład":e.form==="cwiczenia"?"ćwiczenia":e.form)+")",9,Y))),128))],512),[[B,o.course]])]),l("div",J,[t[9]||(t[9]=l("label",{for:"f-type"},"Rodzaj",-1)),N(l("select",{id:"f-type","onUpdate:modelValue":t[1]||(t[1]=e=>o.type=e)},[t[8]||(t[8]=l("option",{value:""},"Wszystkie",-1)),(s(!0),a(c,null,v(y(S),(e,p)=>(s(),a("option",{key:p,value:p},n(e),9,K))),128))],512),[[B,o.type]])])],32),x.value.length?(s(),a("div",Q,[(s(!0),a(c,null,v(x.value,e=>(s(),a("button",{key:e.slug,class:"chip",type:"button","aria-pressed":o.tag===e.slug,onClick:p=>o.tag=o.tag===e.slug?"":e.slug},n(e.name),9,X))),128))])):d("",!0),z.value?(s(),a("button",{key:1,class:"linkish small",type:"button",onClick:T},"Wyczyść filtry")):d("",!0),g.value?(s(),a("div",Z,[L(n(g.value)+" ",1),l("button",{class:"linkish",type:"button",onClick:t[3]||(t[3]=e=>_())},"Spróbuj ponownie")])):u.value?(s(),a(c,{key:4},[u.value.data.length?(s(),a("div",{key:0,class:"stack",style:{"margin-top":"12px"},"aria-busy":b.value},[(s(!0),a(c,null,v(u.value.data,e=>(s(),U(w,{key:e.id,to:`/materialy/${e.id}`,class:"card link"},{default:G(()=>[l("div",se,[l("h3",null,n(e.title),1),l("span",ae,n(y(S)[e.type]),1)]),l("p",le,[e.course?(s(),a("span",oe,n(e.course.name),1)):d("",!0),e.published_at?(s(),a("span",ne," · "+n(y(I)(e.published_at)),1)):d("",!0),e.files_count?(s(),a("span",ie," · "+n(y(O)(e.files_count,"plik","pliki","plików")),1)):d("",!0)]),e.tags.length?(s(),a("p",re,[(s(!0),a(c,null,v(e.tags,p=>(s(),a("span",{key:p.id,class:"badge",style:{"margin-right":"4px"}},n(p.name),1))),128))])):d("",!0)]),_:2},1032,["to"]))),128))],8,te)):(s(),a("p",ue,n(z.value?"Nic nie pasuje do filtrów.":"Nie ma jeszcze żadnych materiałów."),1)),u.value.meta.last_page>1?(s(),a("nav",de,[l("button",{class:"btn small",type:"button",disabled:i.value<=1,onClick:t[4]||(t[4]=e=>C(i.value-1))},"← Poprzednia",8,pe),l("span",ce,n(i.value)+" / "+n(u.value.meta.last_page),1),l("button",{class:"btn small",type:"button",disabled:i.value>=u.value.meta.last_page,onClick:t[5]||(t[5]=e=>C(i.value+1))},"Następna →",8,ve)])):d("",!0)],64)):(s(),a("div",ee,[...t[10]||(t[10]=[l("div",{class:"skeleton"},null,-1),l("div",{class:"skeleton"},null,-1)])]))])}}});export{fe as default};
|
||||
1
public/assets/MoreView-RXFOLzBh.js
Normal file
1
public/assets/MoreView-RXFOLzBh.js
Normal file
@@ -0,0 +1 @@
|
||||
import{_ as d}from"./PageHead.vue_vue_type_script_setup_true_lang-BUSgwkrI.js";import{d as u,u as _,c as i,h as a,a as t,F as p,y,b as r,t as o,o as l,i as h,_ as f,k as b}from"./index-DQ8t_00h.js";const g={class:"stack"},k={class:"row-main",style:{"align-items":"center"}},w={class:"muted small"},C=u({__name:"MoreView",setup(z){const n=_(),c=[{to:"/terminarz",label:"Terminarz",hint:"Zaliczenia, egzaminy, sprawy organizacyjne",icon:"flag"},{to:"/przedmioty",label:"Przedmioty",hint:"Program studiów, prowadzący, materiały",icon:"grad"},{to:"/materialy",label:"Materiały",hint:"Notatki, PDF-y, linki",icon:"file"},{to:"/profil",label:"Profil",hint:"Dane, hasło, wybór przedmiotów",icon:"user"}];return(v,s)=>{const m=b("router-link");return l(),i("div",null,[a(d,{eyebrow:"Pozostałe",title:"Więcej"}),t("div",g,[(l(),i(p,null,y(c,e=>a(m,{key:e.to,to:e.to,class:"card link"},{default:h(()=>[t("div",k,[t("div",null,[t("h3",null,o(e.label),1),t("span",w,o(e.hint),1)]),a(f,{name:"chevron",style:{width:"20px",height:"20px"}})])]),_:2},1032,["to"])),64)),t("button",{class:"btn miss",type:"button",onClick:s[0]||(s[0]=e=>r(n).logout())},"Wyloguj ("+o(r(n).displayName)+")",1)])])}}});export{C as default};
|
||||
1
public/assets/NotFoundView-RpXujwmT.js
Normal file
1
public/assets/NotFoundView-RpXujwmT.js
Normal file
@@ -0,0 +1 @@
|
||||
import{o as r,c,a as o,h as l,i,m as d,k as p}from"./index-DQ8t_00h.js";const _=(s,e)=>{const t=s.__vccOpts||s;for(const[n,a]of e)t[n]=a;return t},u={},f={class:"stack"};function k(s,e){const t=p("router-link");return r(),c("div",f,[e[1]||(e[1]=o("header",{class:"page-head"},[o("span",{class:"eyebrow"},"404"),o("h1",null,"Nie ma takiej strony")],-1)),o("p",null,[l(t,{to:"/"},{default:i(()=>[...e[0]||(e[0]=[d("Wróć na pulpit",-1)])]),_:1})])])}const x=_(u,[["render",k]]);export{x as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{d as r,c as s,t as o,e as c,a as t,M as d,o as a}from"./index-DQ8t_00h.js";const l={class:"page-head"},i={key:0,class:"eyebrow"},_={class:"row"},h={class:"btn-row"},u=r({__name:"PageHead",props:{eyebrow:{},title:{}},setup(e){return(n,m)=>(a(),s("header",l,[e.eyebrow?(a(),s("span",i,o(e.eyebrow),1)):c("",!0),t("div",_,[t("h1",null,o(e.title),1),t("div",h,[d(n.$slots,"default")])])]))}});export{u as _};
|
||||
1
public/assets/ProfileView-gtoaH_yd.js
Normal file
1
public/assets/ProfileView-gtoaH_yd.js
Normal file
File diff suppressed because one or more lines are too long
1
public/assets/QuizView-BMpeVj2N.js
Normal file
1
public/assets/QuizView-BMpeVj2N.js
Normal file
File diff suppressed because one or more lines are too long
1
public/assets/QuizzesView-DPmdlLPx.js
Normal file
1
public/assets/QuizzesView-DPmdlLPx.js
Normal file
@@ -0,0 +1 @@
|
||||
import{_ as g}from"./PageHead.vue_vue_type_script_setup_true_lang-BUSgwkrI.js";import{_ as w}from"./LoadState.vue_vue_type_script_setup_true_lang-DF4LiBqt.js";import{q as z,_ as x}from"./quizzes-YHx1UcLp.js";import{d as j,q as B,c as s,h as d,i as k,r as m,G as N,o as t,F as p,y as V,B as $,a as o,t as n,e as l,m as _,b as h,k as b}from"./index-DQ8t_00h.js";import{c as f}from"./format-bcE-cYHJ.js";const C={key:0,class:"stack"},F={key:0,class:"muted small",style:{margin:"0 0 8px"}},Q={class:"small",style:{margin:"0"}},T={key:1,class:"empty"},A={key:2,class:"section","aria-labelledby":"hist-h"},D={class:"card"},R=j({__name:"QuizzesView",setup(E){const i=m(null),c=m([]),u=m("");async function y(){u.value="";try{const[r,a]=await Promise.all([z.list(),z.attempts()]);i.value=r,c.value=a.data}catch(r){u.value=N(r)}}return B(y),(r,a)=>{const v=b("router-link");return t(),s("div",null,[d(g,{eyebrow:"Fiszki i testy",title:"Quizy"}),d(w,{ready:i.value!==null,error:u.value,onRetry:a[0]||(a[0]=e=>y())},{default:k(()=>[i.value?.length?(t(),s("div",C,[(t(!0),s(p,null,V(i.value,e=>(t(),$(v,{key:e.id,to:`/quizy/${e.slug}`,class:"card link accent"},{default:k(()=>[o("h3",null,n(e.title),1),e.description?(t(),s("p",F,n(e.description),1)):l("",!0),o("p",Q,[_(n(h(f)(e.question_count,"pytanie","pytania","pytań")),1),e.round_size?(t(),s(p,{key:0},[_(" · rundy po "+n(e.round_size),1)],64)):l("",!0),e.attempts_count?(t(),s(p,{key:1},[_(" · "+n(h(f)(e.attempts_count,"zakończone podejście","zakończone podejścia","zakończonych podejść")),1)],64)):l("",!0)])]),_:2},1032,["to"]))),128))])):(t(),s("p",T,"Nie ma jeszcze żadnych quizów.")),c.value.length?(t(),s("section",A,[a[1]||(a[1]=o("div",{class:"section-head"},[o("h2",{id:"hist-h"},"Historia podejść")],-1)),o("div",D,[d(x,{attempts:c.value,"show-quiz":""},null,8,["attempts"])])])):l("",!0)]),_:1},8,["ready","error"])])}}});export{R as default};
|
||||
@@ -0,0 +1 @@
|
||||
import{i as d}from"./format-bcE-cYHJ.js";import{d as c,o as a,c as t,a as n,m as g,t as r,e as i,b as m}from"./index-DQ8t_00h.js";const u={class:"reading"},h=["checked"],k={class:"text"},f={key:0,class:"muted"},b={key:1,class:"muted mono"},y=["href","aria-label"],z=c({__name:"ReadingItem",props:{reading:{}},emits:["toggle"],setup(e){return(o,l)=>(a(),t("li",u,[n("label",null,[n("input",{type:"checkbox",checked:!!e.reading.read_at,onChange:l[0]||(l[0]=s=>o.$emit("toggle",s.target.checked))},null,40,h),n("span",k,[g(r(e.reading.title)+" ",1),e.reading.author||e.reading.source?(a(),t("small",f," · "+r([e.reading.author,e.reading.source].filter(Boolean).join(", ")),1)):i("",!0),e.reading.read_at?(a(),t("small",b," · przeczytano "+r(m(d)(e.reading.read_at)),1)):i("",!0)])]),e.reading.url?(a(),t("a",{key:0,href:e.reading.url,target:"_blank",rel:"noopener noreferrer",class:"small","aria-label":`Otwórz: ${e.reading.title}`},"link",8,y)):i("",!0)]))}});export{z as _};
|
||||
1
public/assets/ReadingsView-BNHsWvL0.js
Normal file
1
public/assets/ReadingsView-BNHsWvL0.js
Normal file
@@ -0,0 +1 @@
|
||||
import{_ as q}from"./PageHead.vue_vue_type_script_setup_true_lang-BUSgwkrI.js";import{_ as x}from"./LoadState.vue_vue_type_script_setup_true_lang-DF4LiBqt.js";import{_ as T}from"./ElectiveBar.vue_vue_type_script_setup_true_lang-CFL2E96J.js";import{_ as b}from"./ReadingItem.vue_vue_type_script_setup_true_lang-D2V28lYN.js";import{d as $,p as B,q as R,c as l,h as m,i as w,b as i,o as n,a as t,t as r,z as C,F as _,y as h,e as g,r as V,s as v,k as F,m as L,B as z}from"./index-DQ8t_00h.js";import{c as M,F as N}from"./format-bcE-cYHJ.js";const S={class:"card","aria-label":"Postęp czytania"},D={style:{margin:"0 0 8px"}},P={class:"big-num nums"},E={class:"muted"},O={class:"muted small"},j=["aria-valuenow"],A={class:"chips wrap",style:{"margin-top":"12px"}},G=["aria-pressed"],I=["aria-labelledby"],U={class:"section-head"},W=["id"],H={class:"badge",style:{"margin-left":"8px"}},J={class:"muted small nums"},K={class:"subhead"},Q={class:"rows"},X={class:"subhead"},Y={class:"rows"},Z={key:0,class:"empty",style:{"margin-top":"16px"}},le=$({__name:"ReadingsView",setup(ee){const s=B(),c=V(!1);R(()=>{Promise.all([s.loadReadings(),s.loadCourses()])});const f=v(()=>{const p=new Map;for(const o of s.readings)p.set(o.course_id,[...p.get(o.course_id)??[],o]);const u=o=>s.courseById.get(o)?.sort_order??0;return[...p].sort(([o],[e])=>u(o)-u(e)).map(([,o])=>{const e=c.value?o.filter(a=>!a.read_at):o;return{course:o[0].course,required:e.filter(a=>a.is_required),optional:e.filter(a=>!a.is_required),read:o.filter(a=>a.read_at).length,total:o.length}}).filter(o=>o.required.length+o.optional.length>0)}),d=v(()=>s.readingStats),k=v(()=>d.value.requiredTotal?Math.round(d.value.requiredRead/d.value.requiredTotal*100):0);return(p,u)=>{const o=F("router-link");return n(),l("div",null,[m(q,{eyebrow:"Do przeczytania",title:"Lektury"}),m(x,{ready:i(s).loaded.readings&&i(s).loaded.courses,error:i(s).error,onRetry:u[1]||(u[1]=e=>i(s).retry())},{default:w(()=>[m(T),t("section",S,[t("p",D,[t("span",P,r(d.value.requiredRead),1),t("span",E," z "+r(d.value.requiredTotal)+" obowiązkowych",1),t("span",O," · łącznie "+r(d.value.read)+" z "+r(d.value.total),1)]),t("div",{class:"progress-bar",role:"progressbar","aria-valuenow":k.value,"aria-valuemin":"0","aria-valuemax":"100","aria-label":"Przeczytane lektury obowiązkowe"},[t("span",{style:C({width:k.value+"%"})},null,4)],8,j)]),t("div",A,[t("button",{class:"chip",type:"button","aria-pressed":c.value,onClick:u[0]||(u[0]=e=>c.value=!c.value)},"Tylko nieprzeczytane",8,G)]),(n(!0),l(_,null,h(f.value,e=>(n(),l("section",{key:e.course.id,class:"section","aria-labelledby":`c${e.course.id}`},[t("div",U,[t("h2",{id:`c${e.course.id}`},[m(o,{to:`/przedmioty/${e.course.id}`,style:{color:"inherit","text-decoration":"none"}},{default:w(()=>[L(r(e.course.name),1)]),_:2},1032,["to"]),t("span",H,r(i(N)[e.course.form]),1)],8,W),t("span",J,r(e.read)+"/"+r(e.total),1)]),e.required.length?(n(),l(_,{key:0},[t("h3",K,"Obowiązkowe · "+r(e.required.length),1),t("ul",Q,[(n(!0),l(_,null,h(e.required,a=>(n(),z(b,{key:a.id,reading:a,onToggle:y=>i(s).toggleReading(a.id,y)},null,8,["reading","onToggle"]))),128))])],64)):g("",!0),e.optional.length?(n(),l(_,{key:1},[t("h3",X,"Dodatkowe · "+r(e.optional.length),1),t("ul",Y,[(n(!0),l(_,null,h(e.optional,a=>(n(),z(b,{key:a.id,reading:a,onToggle:y=>i(s).toggleReading(a.id,y)},null,8,["reading","onToggle"]))),128))])],64)):g("",!0)],8,I))),128)),f.value.length?g("",!0):(n(),l("p",Z,r(c.value?"Wszystko przeczytane. Gratulacje!":i(M)(0,"lektura","lektury","lektur")+" do wyświetlenia."),1))]),_:1},8,["ready","error"])])}}});export{le as default};
|
||||
1
public/assets/RegisterView-Qnu1-ShV.js
Normal file
1
public/assets/RegisterView-Qnu1-ShV.js
Normal file
@@ -0,0 +1 @@
|
||||
import{d as q,u as N,c as o,a as s,t as n,h as _,i as g,g as B,e as u,w as d,v as m,r as l,k as C,o as i,m as x,l as I}from"./index-DQ8t_00h.js";import{f as M}from"./forms-Diah5cld.js";const h={class:"auth"},j={key:0,class:"stack"},S={class:"notice",role:"status"},Z={key:0,class:"notice error",role:"alert",style:{"margin-bottom":"14px"}},A={class:"field"},D={key:0,class:"error-text"},E={class:"field"},P={key:0,class:"error-text"},R={class:"field"},T={key:0,class:"error-text"},H={class:"field"},K={key:0,class:"error-text"},W={class:"field"},F=["disabled"],G={class:"auth-links"},Q=q({__name:"RegisterView",setup(J){const V=N(),z=I(),v=l(""),f=l(""),w=l(""),c=l(""),y=l(""),p=l(!1),t=l(null),k=l("");async function U(){p.value=!0,t.value=null;try{const r=await V.register({name:v.value.trim(),surname:f.value.trim(),email:w.value.trim(),password:c.value,password_confirmation:y.value},!0);r.signedIn?await z.replace("/"):k.value=r.message||"Konto zostało utworzone. Sprawdź pocztę, aby je aktywować."}catch(r){t.value=M(r)}finally{p.value=!1}}return(r,e)=>{const b=C("router-link");return i(),o("div",h,[e[12]||(e[12]=s("header",{class:"page-head"},[s("span",{class:"eyebrow"},"BM II° · UWr"),s("h1",null,"Załóż konto")],-1)),k.value?(i(),o("div",j,[s("p",S,n(k.value),1),_(b,{class:"btn",to:"/logowanie"},{default:g(()=>[...e[5]||(e[5]=[x("Przejdź do logowania",-1)])]),_:1})])):(i(),o("form",{key:1,onSubmit:B(U,["prevent"]),novalidate:""},[t.value?.message?(i(),o("div",Z,n(t.value.message),1)):u("",!0),s("div",A,[e[6]||(e[6]=s("label",{for:"name"},"Imię",-1)),d(s("input",{id:"name","onUpdate:modelValue":e[0]||(e[0]=a=>v.value=a),type:"text",autocomplete:"given-name",required:""},null,512),[[m,v.value]]),t.value?.fields.name?(i(),o("p",D,n(t.value.fields.name),1)):u("",!0)]),s("div",E,[e[7]||(e[7]=s("label",{for:"surname"},"Nazwisko",-1)),d(s("input",{id:"surname","onUpdate:modelValue":e[1]||(e[1]=a=>f.value=a),type:"text",autocomplete:"family-name",required:""},null,512),[[m,f.value]]),t.value?.fields.surname?(i(),o("p",P,n(t.value.fields.surname),1)):u("",!0)]),s("div",R,[e[8]||(e[8]=s("label",{for:"email"},"Adres e-mail",-1)),d(s("input",{id:"email","onUpdate:modelValue":e[2]||(e[2]=a=>w.value=a),type:"email",autocomplete:"email",inputmode:"email",required:""},null,512),[[m,w.value]]),t.value?.fields.email?(i(),o("p",T,n(t.value.fields.email),1)):u("",!0)]),s("div",H,[e[9]||(e[9]=s("label",{for:"password"},"Hasło (min. 8 znaków)",-1)),d(s("input",{id:"password","onUpdate:modelValue":e[3]||(e[3]=a=>c.value=a),type:"password",autocomplete:"new-password",required:""},null,512),[[m,c.value]]),t.value?.fields.password?(i(),o("p",K,n(t.value.fields.password),1)):u("",!0)]),s("div",W,[e[10]||(e[10]=s("label",{for:"confirmation"},"Powtórz hasło",-1)),d(s("input",{id:"confirmation","onUpdate:modelValue":e[4]||(e[4]=a=>y.value=a),type:"password",autocomplete:"new-password",required:""},null,512),[[m,y.value]])]),s("button",{class:"btn primary block",type:"submit",disabled:p.value},n(p.value?"Zakładanie…":"Załóż konto"),9,F)],32)),s("div",G,[_(b,{to:"/logowanie"},{default:g(()=>[...e[11]||(e[11]=[x("Mam już konto",-1)])]),_:1})])])}}});export{Q as default};
|
||||
1
public/assets/ResetView-D72OhW_K.js
Normal file
1
public/assets/ResetView-D72OhW_K.js
Normal file
@@ -0,0 +1 @@
|
||||
import{d as _,r as t,c as a,a as o,h as g,i as x,g as V,t as m,e as v,b as q,w as c,v as f,j as z,k as N,o as l,m as h,n as B}from"./index-DQ8t_00h.js";import{f as C}from"./forms-Diah5cld.js";const U={class:"auth"},M={key:0,class:"stack"},Z={key:0,class:"notice error",role:"alert",style:{"margin-bottom":"14px"}},j={key:1,class:"field"},D={class:"field"},E={key:0,class:"error-text"},I={class:"field"},P=["disabled"],A=_({__name:"ResetView",setup(R){const u=z(),i=t(typeof u.query.code=="string"?u.query.code:""),n=t(""),p=t(""),d=t(!1),w=t(!1),s=t(null);async function b(){d.value=!0,s.value=null;try{await B.resetPassword({code:i.value.trim(),password:n.value,password_confirmation:p.value}),w.value=!0}catch(y){s.value=C(y)}finally{d.value=!1}}return(y,e)=>{const k=N("router-link");return l(),a("div",U,[e[8]||(e[8]=o("header",{class:"page-head"},[o("span",{class:"eyebrow"},"BM II° · UWr"),o("h1",null,"Nowe hasło")],-1)),w.value?(l(),a("div",M,[e[4]||(e[4]=o("p",{class:"notice",role:"status"},"Hasło zostało zmienione.",-1)),g(k,{class:"btn primary",to:"/logowanie"},{default:x(()=>[...e[3]||(e[3]=[h("Zaloguj się",-1)])]),_:1})])):(l(),a("form",{key:1,onSubmit:V(b,["prevent"]),novalidate:""},[s.value?.message?(l(),a("div",Z,m(s.value.message),1)):v("",!0),q(u).query.code?v("",!0):(l(),a("div",j,[e[5]||(e[5]=o("label",{for:"code"},"Kod z wiadomości",-1)),c(o("input",{id:"code","onUpdate:modelValue":e[0]||(e[0]=r=>i.value=r),type:"text",autocomplete:"one-time-code",required:""},null,512),[[f,i.value]])])),o("div",D,[e[6]||(e[6]=o("label",{for:"password"},"Nowe hasło (min. 8 znaków)",-1)),c(o("input",{id:"password","onUpdate:modelValue":e[1]||(e[1]=r=>n.value=r),type:"password",autocomplete:"new-password",required:""},null,512),[[f,n.value]]),s.value?.fields.password?(l(),a("p",E,m(s.value.fields.password),1)):v("",!0)]),o("div",I,[e[7]||(e[7]=o("label",{for:"confirmation"},"Powtórz hasło",-1)),c(o("input",{id:"confirmation","onUpdate:modelValue":e[2]||(e[2]=r=>p.value=r),type:"password",autocomplete:"new-password",required:""},null,512),[[f,p.value]])]),o("button",{class:"btn primary block",type:"submit",disabled:d.value||!i.value||!n.value},m(d.value?"Zapisywanie…":"Zapisz hasło"),9,P)],32))])}}});export{A as default};
|
||||
1
public/assets/ScheduleView-CFxdYZ5C.js
Normal file
1
public/assets/ScheduleView-CFxdYZ5C.js
Normal file
File diff suppressed because one or more lines are too long
1
public/assets/format-bcE-cYHJ.js
Normal file
1
public/assets/format-bcE-cYHJ.js
Normal file
@@ -0,0 +1 @@
|
||||
const d="Europe/Warsaw",w="pl-PL";function g(n,t,e,a){const i=Math.abs(n);if(i===1)return t;const u=i%10,m=i%100;return u>=2&&u<=4&&!(m>=12&&m<=14)?e:a}function y(n,t,e,a){return`${n} ${g(n,t,e,a)}`}const r=(n,t=d)=>new Intl.DateTimeFormat(w,{timeZone:t,...n}),D=r({hour:"2-digit",minute:"2-digit",hourCycle:"h23"}),z=r({weekday:"long",day:"numeric",month:"long"}),h=r({day:"numeric",month:"long",year:"numeric"});r({day:"numeric",month:"short"});r({weekday:"long"});const p=new Intl.DateTimeFormat("sv-SE",{timeZone:d,year:"numeric",month:"2-digit",day:"2-digit"});function s(n){return new Date(`${n}T12:00:00Z`)}const l=n=>r(n,"UTC"),T=n=>D.format(new Date(n)),E=n=>z.format(new Date(n)),L=n=>h.format(new Date(n)),F=n=>`${L(n)}, ${T(n)}`,$=n=>p.format(typeof n=="string"?new Date(n):n),k=(n=new Date)=>$(n);function j(n,t=new Date){const e=Date.parse(`${k(t)}T00:00:00Z`),a=Date.parse(`${$(n)}T00:00:00Z`);return Math.round((a-e)/864e5)}function B(n,t=new Date){const e=j(n,t);return e===0?"dzisiaj":e===1?"jutro":e===-1?"wczoraj":e>1?`za ${y(e,"dzień","dni","dni")}`:`${y(-e,"dzień","dni","dni")} temu`}function K(n,t){if(n===t)return l({day:"numeric",month:"long",year:"numeric"}).format(s(n));const[e,a]=n.split("-"),[i,u]=t.split("-"),m=c=>l({day:"numeric"}).format(s(c)),o=c=>l({day:"numeric",month:"long"}).format(s(c)),f=c=>l({year:"numeric"}).format(s(c));return e===i&&a===u?`${m(n)}–${o(t)} ${f(t)}`:e===i?`${o(n)} – ${o(t)} ${f(t)}`:`${o(n)} ${f(n)} – ${o(t)} ${f(t)}`}function Z(n){return n?/online/i.test(n)?"online":/stacjonarn/i.test(n)?"stacjonarny":null:null}function M(n){return n?n.trim().toLowerCase()==="online"?"":n.trim():""}const S={wyklad:"wykład",cwiczenia:"ćwiczenia",konwersatorium:"konwersatorium",seminarium:"seminarium",inne:"zajęcia"},x={zaliczenie:"zaliczenie",egzamin:"egzamin",praca:"praca",organizacyjne:"organizacyjne",inne:"inne"},A={pdf:"PDF",notatka:"notatka",link:"link",inne:"inne"};function C(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(0)} KB`:`${(n/1024/1024).toFixed(1).replace(".",",")} MB`}export{S as F,x as K,A as T,T as a,E as b,y as c,j as d,F as e,K as f,Z as g,$ as h,L as i,C as j,M as m,B as r,k as t};
|
||||
1
public/assets/forms-Diah5cld.js
Normal file
1
public/assets/forms-Diah5cld.js
Normal file
@@ -0,0 +1 @@
|
||||
import{O as o}from"./index-DQ8t_00h.js";function a(s){if(s instanceof o){const e={};for(const[r,t]of Object.entries(s.errors))t.length&&(e[r]=t[0]);return{message:Object.keys(e).length&&Object.values(e).includes(s.message)?"":s.message,fields:e}}return{message:"Coś poszło nie tak. Spróbuj ponownie.",fields:{}}}function f(s){return typeof s=="string"&&s.startsWith("/")&&!s.startsWith("//")&&!s.startsWith("/\\")?s:"/"}export{a as f,f as s};
|
||||
1
public/assets/index-CFsBP3m0.css
Normal file
1
public/assets/index-CFsBP3m0.css
Normal file
File diff suppressed because one or more lines are too long
3
public/assets/index-DQ8t_00h.js
Normal file
3
public/assets/index-DQ8t_00h.js
Normal file
File diff suppressed because one or more lines are too long
1
public/assets/quizzes-YHx1UcLp.js
Normal file
1
public/assets/quizzes-YHx1UcLp.js
Normal file
@@ -0,0 +1 @@
|
||||
import{e as p}from"./format-bcE-cYHJ.js";import{d as z,o,c as a,F as c,y as h,a as d,m,t as n,b as _,x as q,e as l,L as r}from"./index-DQ8t_00h.js";const y={class:"rows"},$={class:"row-main"},k={class:"title"},w=["aria-label"],f={key:1,class:"badge"},b={class:"muted small"},S=z({__name:"AttemptList",props:{attempts:{},showQuiz:{type:Boolean}},setup(e){const s=u=>`${Math.round(u.score_points)}/${Math.round(u.max_points)}`;return(u,g)=>(o(),a("ul",y,[(o(!0),a(c,null,h(e.attempts,t=>(o(),a("li",{key:t.id},[d("div",$,[d("span",k,[e.showQuiz?(o(),a(c,{key:0},[m(n(t.quiz_title),1)],64)):(o(),a(c,{key:1},[m(n(_(p)(t.started_at)),1)],64))]),t.completed_at?(o(),a("span",{key:0,class:q(["badge",t.passed?"online":""]),"aria-label":`Wynik ${s(t)}`},n(s(t)),11,w)):(o(),a("span",f,"niezakończona"))]),d("div",b,[e.showQuiz?(o(),a(c,{key:0},[m(n(_(p)(t.started_at))+" · ",1)],64)):l("",!0),t.category?(o(),a(c,{key:1},[m(n(t.category)+" · ",1)],64)):l("",!0),m(" odpowiedzi: "+n(t.answered_count),1),t.completed_at&&t.score_percent!==null?(o(),a(c,{key:2},[m(" · "+n(String(t.score_percent).replace(".",","))+"% puli",1)],64)):l("",!0)])]))),128))]))}}),i="/_quizzes/api/v1",T={list:e=>r.request(`${i}/quizzes`,{query:{context:e}}),quiz:(e,s)=>r.request(`${i}/quizzes/${encodeURIComponent(e)}`,{query:{category:s}}),start:(e,s)=>r.request(`${i}/quizzes/${encodeURIComponent(e)}/attempts`,{method:"POST",body:s?{category:s}:{}}),answer:(e,s)=>r.request(`${i}/attempts/${e}/answers`,{method:"POST",body:s}),finish:e=>r.request(`${i}/attempts/${e}/finish`,{method:"POST"}),attempt:e=>r.request(`${i}/attempts/${e}`),attempts:(e,s)=>r.raw(`${i}/attempts`,{query:{quiz:e,page:s}})};export{S as _,T as q};
|
||||
1
public/favicon.svg
Normal file
1
public/favicon.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#2F5A4B"/><text x="16" y="22" text-anchor="middle" font-family="Arial Narrow,Arial,sans-serif" font-weight="700" font-size="17" fill="#F3F4F1">BM</text></svg>
|
||||
|
After Width: | Height: | Size: 261 B |
24
public/index.html
Normal file
24
public/index.html
Normal file
@@ -0,0 +1,24 @@
|
||||
<!doctype html>
|
||||
<html lang="pl">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<meta name="theme-color" content="#F3F4F1" media="(prefers-color-scheme: light)" />
|
||||
<meta name="theme-color" content="#141917" media="(prefers-color-scheme: dark)" />
|
||||
<title>BM II° – plan studiów</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css2?family=Archivo+Narrow:wght@500;600;700&family=Source+Serif+4:ital,opsz,wght@0,8..60,400;0,8..60,600;1,8..60,400&family=IBM+Plex+Mono:wght@400;500&display=swap"
|
||||
/>
|
||||
<script type="module" crossorigin src="/assets/index-DQ8t_00h.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-CFsBP3m0.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<noscript>Ta aplikacja wymaga włączonego JavaScriptu.</noscript>
|
||||
</body>
|
||||
</html>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user