Compare commits
257 Commits
4e1feddb45
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3800c5bdad | ||
|
|
12d575a84b | ||
|
|
c14b6d7062 | ||
|
|
a7c5468cbc | ||
|
|
4da8750c60 | ||
|
|
cf40f626e6 | ||
|
|
99a826f6c9 | ||
|
|
51fe2614fa | ||
|
|
56dc094b45 | ||
|
|
520fdf7862 | ||
|
|
e2cc38686f | ||
|
|
0bcc7567bb | ||
|
|
6654785f25 | ||
|
|
99a69202b9 | ||
|
|
55bb450d27 | ||
|
|
e28d55ad58 | ||
|
|
b110bb6d01 | ||
|
|
2892b51101 | ||
|
|
871e94b298 | ||
|
|
c3ab78cc57 | ||
|
|
c7370bda03 | ||
|
|
a15d91dfe6 | ||
|
|
fecb1fddca | ||
|
|
2028f1a544 | ||
|
|
40c747a837 | ||
|
|
40a55721ab | ||
|
|
d4518a0671 | ||
|
|
74f63a7721 | ||
|
|
bd3d7fc7bd | ||
|
|
c00288e256 | ||
|
|
b5de96660a | ||
|
|
96bb05a4ba | ||
|
|
4e07fcf38b | ||
|
|
b74f8e1bb1 | ||
|
|
188365f412 | ||
|
|
824f35590b | ||
|
|
43cb84e8f4 | ||
|
|
afe8e2b32c | ||
|
|
ca38875660 | ||
|
|
8538f76b13 | ||
|
|
2a7d4c7410 | ||
|
|
ed10e58383 | ||
|
|
b65cba5ed2 | ||
|
|
afe79f1a48 | ||
|
|
0e5e39b0dc | ||
|
|
4860b6ee2a | ||
|
|
c025a38709 | ||
|
|
581ea7e349 | ||
|
|
596175cd1c | ||
|
|
1aaf353066 | ||
|
|
441def9a34 | ||
|
|
736b59b5c0 | ||
|
|
a8592aeaec | ||
|
|
8b006be138 | ||
|
|
299a806862 | ||
|
|
fb782cf5ef | ||
|
|
224f5e2ad0 | ||
|
|
96379934d7 | ||
|
|
29a5658b01 | ||
|
|
73135df7a6 | ||
|
|
57f47cc77e | ||
|
|
5d21e79be5 | ||
|
|
ff0883002b | ||
|
|
7f927741d4 | ||
|
|
3bf48546e3 | ||
|
|
6817323f8e | ||
|
|
11283118d6 | ||
|
|
6c91ec0385 | ||
|
|
39db59c71a | ||
|
|
5f643350c5 | ||
|
|
ab41797e57 | ||
|
|
e35855f472 | ||
|
|
0e5805efd2 | ||
|
|
de99b538d2 | ||
|
|
c08b5b764e | ||
|
|
d63a4bec4a | ||
|
|
b35c9b483e | ||
|
|
30ea0fad9d | ||
|
|
62d5c738f9 | ||
|
|
f0f419ff7e | ||
|
|
0494710ce0 | ||
|
|
713e24863d | ||
|
|
b3bc422f46 | ||
|
|
c0016418cc | ||
|
|
4d52c4f54d | ||
|
|
db1608fa38 | ||
|
|
4728cde771 | ||
|
|
2f6fc1ff20 | ||
|
|
9698d70164 | ||
|
|
7370fd611f | ||
|
|
f5a5ed9d8d | ||
|
|
a5d71925fc | ||
|
|
b03ba09b65 | ||
|
|
befa61e1e9 | ||
|
|
15ac3216ff | ||
|
|
2896efa8e0 | ||
|
|
588358a20f | ||
|
|
11c85d56d1 | ||
|
|
8bab26e003 | ||
|
|
bc78d2c470 | ||
|
|
2447315fd3 | ||
|
|
cde231d43c | ||
|
|
a0f8aeb791 | ||
|
|
2ca4e9d39f | ||
|
|
c71f4eb68c | ||
|
|
189d329e76 | ||
|
|
18898c7a0f | ||
|
|
f347af7eff | ||
|
|
e59d5fd4c0 | ||
|
|
62f6c27806 | ||
|
|
cc02419e8d | ||
|
|
c331e72de6 | ||
|
|
a1f8d294a3 | ||
|
|
5607f70852 | ||
|
|
eecb6c2be6 | ||
|
|
2fd3ec9ab2 | ||
|
|
cad3744a57 | ||
|
|
ffb374c81c | ||
|
|
3b905e0436 | ||
|
|
f1b5ba2a71 | ||
|
|
184854a2de | ||
|
|
f5c2cf4636 | ||
|
|
91e0eaad8e | ||
|
|
5a811d0079 | ||
|
|
8c2a5d24ec | ||
|
|
4f076165ef | ||
|
|
3a87a17017 | ||
|
|
4e63323019 | ||
|
|
8b2c4e1bdc | ||
|
|
10d717a3ba | ||
|
|
e9f50810da | ||
|
|
67697fa90e | ||
|
|
97b406c7e0 | ||
|
|
568497d09d | ||
|
|
1558bb02b4 | ||
|
|
01de6e7548 | ||
|
|
c9defa5a81 | ||
|
|
462155f07b | ||
|
|
fa46fc18d7 | ||
|
|
4239245902 | ||
|
|
b49218b45b | ||
|
|
ace9a4888e | ||
|
|
435bec7988 | ||
|
|
12146037f0 | ||
|
|
ff7b71792f | ||
|
|
2e24175ec8 | ||
|
|
18ba242647 | ||
|
|
6d1b358b7c | ||
|
|
2140bd8206 | ||
|
|
52e171cb20 | ||
|
|
74d1a43559 | ||
|
|
2d453dbc78 | ||
|
|
4baaa63430 | ||
|
|
26b6d4e7db | ||
|
|
f4dfce826b | ||
|
|
53d9f79476 | ||
|
|
ed48d18c1d | ||
|
|
f76c6d0fe5 | ||
|
|
d9feb80b2a | ||
|
|
d780115515 | ||
|
|
af3523c9bb | ||
|
|
dddffd22d5 | ||
|
|
e0d1f51bf1 | ||
|
|
6a42b91420 | ||
|
|
5773462b4c | ||
|
|
681a1a4cd0 | ||
|
|
69fea65bf9 | ||
|
|
068b99d030 | ||
|
|
8807d31274 | ||
|
|
50ee983e27 | ||
|
|
f45740d8b3 | ||
|
|
aa1cef6e7b | ||
|
|
791510b46d | ||
|
|
fe6d2c5db1 | ||
|
|
d2861077a4 | ||
|
|
645b265c80 | ||
|
|
382dd5958f | ||
|
|
47d84b6bf2 | ||
|
|
97601586c5 | ||
|
|
2c445c0e76 | ||
|
|
a53dc41367 | ||
|
|
251b3bf778 | ||
|
|
bb2116ae9f | ||
|
|
bd72135a2f | ||
|
|
ad0caa7c17 | ||
|
|
076d75effe | ||
|
|
571f659b19 | ||
|
|
10dbd07cb9 | ||
|
|
314da3e246 | ||
|
|
672de8a994 | ||
|
|
13940ca834 | ||
|
|
b5d6912b26 | ||
|
|
02d0adef78 | ||
|
|
4c502e40f8 | ||
|
|
17ee6c1f08 | ||
|
|
86e70b7256 | ||
|
|
9aea1ccb56 | ||
|
|
42a9049c0a | ||
|
|
9936275443 | ||
|
|
20c5f6f589 | ||
|
|
c099479740 | ||
|
|
ca835059c2 | ||
|
|
9548a2cd15 | ||
|
|
a218391ea5 | ||
|
|
fd59b02c3a | ||
|
|
649bd39df9 | ||
|
|
1c894f8ae6 | ||
|
|
105b8f1e34 | ||
|
|
06f85d4c54 | ||
|
|
b53c0b9849 | ||
|
|
eebc355f95 | ||
|
|
e142e5d4d7 | ||
|
|
143e81fc41 | ||
|
|
4aa63c74e2 | ||
|
|
168c877970 | ||
|
|
94f3120add | ||
|
|
a8c199b719 | ||
|
|
17eb83c760 | ||
|
|
44c335b089 | ||
|
|
87ef197823 | ||
|
|
a9e635f40e | ||
|
|
04e28b96c8 | ||
|
|
880fcb5bcf | ||
|
|
9bdc358e59 | ||
|
|
ed21730a38 | ||
|
|
4b558020af | ||
|
|
5106b04175 | ||
|
|
025a59938b | ||
|
|
d26196a7f1 | ||
|
|
84fd0554bd | ||
|
|
55f2a043c6 | ||
|
|
a1e7ae8071 | ||
|
|
a06fce26ef | ||
|
|
c41624152a | ||
|
|
64d4ba9542 | ||
|
|
0370f36e9e | ||
|
|
a85e0597d7 | ||
|
|
e32c6bbfd6 | ||
|
|
e26ee5af1d | ||
|
|
d74189f0b7 | ||
|
|
877e3f35cf | ||
|
|
9a1a79fb9a | ||
|
|
2a9ac4c0f0 | ||
|
|
510874b87c | ||
|
|
e02385118f | ||
|
|
71b35242eb | ||
|
|
bcadb28017 | ||
|
|
7f61dbd205 | ||
|
|
5d0a1401d8 | ||
|
|
a98a0fcd53 | ||
|
|
d1c715ab0c | ||
|
|
0222aa9ea2 | ||
|
|
5ff0e4ec10 | ||
|
|
b94f1f48aa | ||
|
|
9fa428c63a | ||
|
|
5a633dccee | ||
|
|
fec1cfcb30 |
@@ -1 +1,2 @@
|
|||||||
src/db.sqlite3
|
src/db.sqlite3
|
||||||
|
.claude
|
||||||
|
|||||||
1
.gitattributes
vendored
Normal file
1
.gitattributes
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
16
.gitignore
vendored
16
.gitignore
vendored
@@ -1,17 +1,18 @@
|
|||||||
# Created by https://www.toptal.com/developers/gitignore/api/django
|
# Created by https://www.toptal.com/developers/gitignore/api/django
|
||||||
# Edit at https://www.toptal.com/developers/gitignore?templates=django
|
# Edit at https://www.toptal.com/developers/gitignore?templates=django
|
||||||
|
|
||||||
|
### Claude ###
|
||||||
|
.claude
|
||||||
|
|
||||||
### Django ###
|
### Django ###
|
||||||
*.log
|
*.log
|
||||||
*.pot
|
*.pot
|
||||||
*.pyc
|
*.pyc
|
||||||
__pycache__/
|
__pycache__/
|
||||||
local_settings.py
|
local_settings.py
|
||||||
db.sqlite3
|
*.sqlite3
|
||||||
db.sqlite3-journal
|
*.sqlite3-journal
|
||||||
container.db.sqlite3
|
|
||||||
media
|
media
|
||||||
src/static
|
|
||||||
|
|
||||||
# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
|
# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/
|
||||||
# in your Git repository. Update and uncomment the following line accordingly.
|
# in your Git repository. Update and uncomment the following line accordingly.
|
||||||
@@ -45,6 +46,13 @@ share/python-wheels/
|
|||||||
*.egg
|
*.egg
|
||||||
MANIFEST
|
MANIFEST
|
||||||
|
|
||||||
|
# Static files
|
||||||
|
src/static/*
|
||||||
|
!src/static/tests/
|
||||||
|
!src/static/tests/**
|
||||||
|
!/src/static_src/tests/lib/
|
||||||
|
src/functional_tests/screendumps
|
||||||
|
|
||||||
# PyInstaller
|
# PyInstaller
|
||||||
# Usually these files are written by a python script from a template
|
# Usually these files are written by a python script from a template
|
||||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||||
|
|||||||
98
.woodpecker.yaml
Normal file
98
.woodpecker.yaml
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
services:
|
||||||
|
- name: postgres
|
||||||
|
image: postgres:16
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: python_tdd_test
|
||||||
|
POSTGRES_USER: postgres
|
||||||
|
POSTGRES_PASSWORD: postgres
|
||||||
|
|
||||||
|
- name: redis
|
||||||
|
image: redis:7
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: test-UTs-n-ITs
|
||||||
|
image: python:3.13-slim
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql://postgres:postgres@postgres/python_tdd_test
|
||||||
|
CELERY_BROKER_URL: redis://redis:6379/0
|
||||||
|
REDIS_URL: redis://redis:6379/1
|
||||||
|
commands:
|
||||||
|
- pip install -r requirements.txt
|
||||||
|
- cd ./src
|
||||||
|
- python manage.py test apps
|
||||||
|
when:
|
||||||
|
- event: push
|
||||||
|
|
||||||
|
- name: test-two-browser-FTs
|
||||||
|
image: gitea.earthmanrpg.me/discoman/python-tdd-ci:latest
|
||||||
|
environment:
|
||||||
|
HEADLESS: 1
|
||||||
|
CELERY_BROKER_URL: redis://redis:6379/0
|
||||||
|
REDIS_URL: redis://redis:6379/1
|
||||||
|
STRIPE_SECRET_KEY:
|
||||||
|
from_secret: stripe_secret_key
|
||||||
|
STRIPE_PUBLISHABLE_KEY:
|
||||||
|
from_secret: stripe_publishable_key
|
||||||
|
commands:
|
||||||
|
- pip install -r requirements.txt
|
||||||
|
- cd ./src
|
||||||
|
- python manage.py collectstatic --noinput
|
||||||
|
- python manage.py test functional_tests --tag=two-browser
|
||||||
|
- python manage.py test functional_tests --tag=channels
|
||||||
|
when:
|
||||||
|
- event: push
|
||||||
|
|
||||||
|
- name: test-FTs
|
||||||
|
image: gitea.earthmanrpg.me/discoman/python-tdd-ci:latest
|
||||||
|
environment:
|
||||||
|
HEADLESS: 1
|
||||||
|
CELERY_BROKER_URL: redis://redis:6379/0
|
||||||
|
REDIS_URL: redis://redis:6379/1
|
||||||
|
STRIPE_SECRET_KEY:
|
||||||
|
from_secret: stripe_secret_key
|
||||||
|
STRIPE_PUBLISHABLE_KEY:
|
||||||
|
from_secret: stripe_publishable_key
|
||||||
|
commands:
|
||||||
|
- pip install -r requirements.txt
|
||||||
|
- cd ./src
|
||||||
|
- python manage.py collectstatic --noinput
|
||||||
|
- python manage.py test functional_tests --parallel --exclude-tag=channels --exclude-tag=two-browser
|
||||||
|
when:
|
||||||
|
- event: push
|
||||||
|
|
||||||
|
- name: screendumps
|
||||||
|
image: gitea.earthmanrpg.me/discoman/python-tdd-ci:latest
|
||||||
|
commands:
|
||||||
|
- cat ./src/functional_tests/screendumps/*.html || echo "No screendumps found"
|
||||||
|
when:
|
||||||
|
- event: push
|
||||||
|
status: failure
|
||||||
|
|
||||||
|
- name: build-and-push
|
||||||
|
image: docker:cli
|
||||||
|
environment:
|
||||||
|
REGISTRY_PASSWORD:
|
||||||
|
from_secret: gitea_registry_password
|
||||||
|
commands:
|
||||||
|
- echo "$REGISTRY_PASSWORD" | docker login gitea.earthmanrpg.me -u discoman --password-stdin
|
||||||
|
- docker build -t gitea.earthmanrpg.me/discoman/gamearray:latest .
|
||||||
|
- docker push gitea.earthmanrpg.me/discoman/gamearray:latest
|
||||||
|
when:
|
||||||
|
- branch: main
|
||||||
|
event: push
|
||||||
|
|
||||||
|
- name: deploy
|
||||||
|
image: alpine
|
||||||
|
environment:
|
||||||
|
SSH_KEY:
|
||||||
|
from_secret: deploy_ssh_key
|
||||||
|
commands:
|
||||||
|
- apk add --no-cache openssh-client
|
||||||
|
- mkdir -p ~/.ssh
|
||||||
|
- printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519
|
||||||
|
- chmod 600 ~/.ssh/id_ed25519
|
||||||
|
- ssh -o StrictHostKeyChecking=no discoman@staging.earthmanrpg.me /opt/gamearray/deploy.sh
|
||||||
|
when:
|
||||||
|
- branch: main
|
||||||
|
event: push
|
||||||
|
|
||||||
148
CLAUDE.md
Normal file
148
CLAUDE.md
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
# EarthmanRPG — Project Context
|
||||||
|
|
||||||
|
Originally built following Harry Percival's *Test-Driven Development with Python* (3rd ed., complete through ch. 25). Now an ongoing game app — EarthmanRPG — extended well beyond the book.
|
||||||
|
|
||||||
|
## Browser Integration
|
||||||
|
**Claudezilla** is installed — a Firefox extension + native host that lets Claude observe and interact with the browser directly.
|
||||||
|
|
||||||
|
### Tool names
|
||||||
|
Tools are available as `mcp__claudezilla__firefox_*`, e.g.:
|
||||||
|
- `mcp__claudezilla__firefox_screenshot` — capture current tab
|
||||||
|
- `mcp__claudezilla__firefox_navigate` — navigate to URL
|
||||||
|
- `mcp__claudezilla__firefox_get_page_state` — structured JSON (faster than screenshot)
|
||||||
|
- `mcp__claudezilla__firefox_create_window` — open new tab (returns `tabId`)
|
||||||
|
- `mcp__claudezilla__firefox_diagnose` — check connection status
|
||||||
|
- `mcp__claudezilla__firefox_set_private_mode` — disable private mode to use session cookies
|
||||||
|
|
||||||
|
All tools require a `tabId` except `firefox_create_window` and `firefox_diagnose`.
|
||||||
|
|
||||||
|
### If tools aren't available in a session
|
||||||
|
MCP servers load at session startup only. **Start a new Claude Code conversation** (hit "+" in the sidebar) — no need to reboot VSCode, just open a fresh chat. Always call `firefox_diagnose` first to confirm the connection is live.
|
||||||
|
|
||||||
|
### Correct startup sequence
|
||||||
|
1. Firefox open with Claudezilla extension active (native host must be running)
|
||||||
|
2. Open a new Claude Code conversation → tools appear as `mcp__claudezilla__firefox_*`
|
||||||
|
3. Call `firefox_diagnose` to confirm before depending on any tool
|
||||||
|
|
||||||
|
### Setup (already done — for reference)
|
||||||
|
The native messaging host requires a `.bat` wrapper on Windows (Firefox can't execute `.js` directly):
|
||||||
|
- Wrapper: `E:\ClaudeLibrary\claudezilla\host\claudezilla.bat` — contains `@echo off` / `node "%~dp0index.js" %*`
|
||||||
|
- Manifest: `C:\Users\adamc\AppData\Roaming\claudezilla\claudezilla.json` — points to the `.bat` file
|
||||||
|
- Registry: `HKCU\SOFTWARE\Mozilla\NativeMessagingHosts\claudezilla` → manifest path
|
||||||
|
- MCP server: registered in `~/.claude.json` (NOT `~/.claude/settings.json` or `~/.claude/mcp.json`) — use the CLI to register:
|
||||||
|
```
|
||||||
|
claude mcp add --scope user claudezilla "D:/Program Files/nodejs/node.exe" "E:/ClaudeLibrary/claudezilla/mcp/server.js"
|
||||||
|
```
|
||||||
|
- Permission: `mcp__claudezilla__*` in `~/.claude/settings.json` `permissions.allow`
|
||||||
|
|
||||||
|
**Config file gotcha:** The Claude Code CLI and VSCode extension read user-level MCP servers from `~/.claude.json` (home dir, single file) — NOT from `~/.claude/settings.json` or `~/.claude/mcp.json`. Always use `claude mcp add --scope user` to register; never hand-edit. Verify registration with `claude mcp list`.
|
||||||
|
|
||||||
|
**BOM gotcha:** PowerShell writes JSON files with a UTF-8 BOM, which causes `JSON.parse` to throw. Never use PowerShell `Set-Content` to write any Claude config JSON — use the Write tool or the CLI instead.
|
||||||
|
|
||||||
|
Native host: `E:\ClaudeLibrary\claudezilla\host\`. Extension: `claudezilla@boot.industries`.
|
||||||
|
|
||||||
|
## Stack
|
||||||
|
- **Python 3.13 / Django 6.0 / Django Channels** (ASGI via Daphne/uvicorn)
|
||||||
|
- **Celery + Redis** (async email, channel layer)
|
||||||
|
- **django-compressor + SCSS** (`src/static_src/scss/core.scss`)
|
||||||
|
- **Selenium** (functional tests) + Django test framework (integration/unit tests)
|
||||||
|
- **Stripe** (payment, sandbox only so far)
|
||||||
|
- **Hosting:** DigitalOcean staging (`staging.earthmanrpg.me`) | CI: Gitea + Woodpecker
|
||||||
|
|
||||||
|
## Project Layout
|
||||||
|
|
||||||
|
The app pairs follow a tripartite structure:
|
||||||
|
- **1st-person** (personal UX): `lyric` (backend — auth, user, tokens) · `dashboard` (frontend — notes, applets, wallet UI)
|
||||||
|
- **3rd-person** (game table UX): `epic` (backend — rooms, gates, role select, game logic) · `gameboard` (frontend — room listing, gameboard UI)
|
||||||
|
- **2nd-person** (inter-player events): `drama` (backend — activity streams, provenance) · `billboard` (frontend — provenance feed, embeddable in dashboard/gameboard)
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
apps/
|
||||||
|
lyric/ # auth (magic-link email), user model, token economy
|
||||||
|
dashboard/ # Notes (formerly Lists), applets, wallet UI [1st-person frontend]
|
||||||
|
epic/ # rooms, gates, role select, game logic [3rd-person backend]
|
||||||
|
gameboard/ # room listing, gameboard UI [3rd-person frontend]
|
||||||
|
drama/ # activity streams, provenance system [2nd-person backend]
|
||||||
|
billboard/ # provenance feed, embeds in dashboard/gameboard [2nd-person frontend]
|
||||||
|
api/ # REST API
|
||||||
|
applets/ # Applet model + context helpers
|
||||||
|
core/ # settings, urls, asgi, runner
|
||||||
|
static_src/ # SCSS source
|
||||||
|
templates/
|
||||||
|
functional_tests/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Template directory convention
|
||||||
|
Templates live under `templates/apps/<frontend-app>/`, not under the backend app that owns the view logic. Specifically:
|
||||||
|
- `lyric/` views → `templates/apps/dashboard/`
|
||||||
|
- `epic/` views → `templates/apps/gameboard/`
|
||||||
|
- `drama/` views → `templates/apps/billboard/`
|
||||||
|
|
||||||
|
Backend apps (`lyric`, `epic`, `drama`) have **no** `templates/` subdirectory.
|
||||||
|
|
||||||
|
## Dev Commands
|
||||||
|
```bash
|
||||||
|
# Dev server (ASGI — required for WebSockets; no npm/webpack build step)
|
||||||
|
cd src
|
||||||
|
uvicorn core.asgi:application --host 0.0.0.0 --port 8000 --reload --app-dir src
|
||||||
|
|
||||||
|
# Integration + unit tests only (from project root — targets src/apps, skips src/functional_tests)
|
||||||
|
python src/manage.py test src/apps
|
||||||
|
|
||||||
|
# Functional tests only
|
||||||
|
python src/manage.py test src/functional_tests
|
||||||
|
|
||||||
|
# All tests (integration + unit + FT)
|
||||||
|
python src/manage.py test src
|
||||||
|
```
|
||||||
|
|
||||||
|
**Test tags:** The only tag in use is `channels` — for async consumer tests that require a live Redis channel layer.
|
||||||
|
- Exclude channels tests: `python src/manage.py test src/apps --exclude-tag=channels`
|
||||||
|
- Channels tests only: `python src/manage.py test src/apps --tag=channels`
|
||||||
|
|
||||||
|
FTs are isolated by **directory path** (`src/functional_tests/`), not by tag.
|
||||||
|
|
||||||
|
Test runner is `core.runner.RobustCompressorTestRunner` — handles the Windows compressor PermissionError by deleting stale CACHE at startup + monkey-patching retry logic.
|
||||||
|
|
||||||
|
## CI/CD
|
||||||
|
- Git remote: `git@gitea:discoman/python-tdd.git` (port 222, key `~/.ssh/gitea_keys/id_ed25519_python-tdd`)
|
||||||
|
- Gitea: `https://gitea.earthmanrpg.me` | Woodpecker CI: `https://ci.earthmanrpg.me`
|
||||||
|
- Push to `main` triggers Woodpecker → deploys to staging
|
||||||
|
|
||||||
|
## SCSS Import Order
|
||||||
|
`core.scss`: `rootvars → applets → base → button-pad → dashboard → gameboard → palette-picker → room → billboard → game-kit → wallet-tokens`
|
||||||
|
|
||||||
|
## Critical Gotchas
|
||||||
|
|
||||||
|
### TransactionTestCase flushes migration data
|
||||||
|
FTs use `TransactionTestCase` which flushes migration-seeded rows. Any IT/FT `setUp` that needs `Applet` rows must call `Applet.objects.get_or_create(slug=..., defaults={...})` — never rely on migration data surviving.
|
||||||
|
|
||||||
|
### Static files in tests
|
||||||
|
`StaticLiveServerTestCase` serves via `STATICFILES_FINDERS` only — NOT from `STATIC_ROOT`. JS/CSS that lives only in `src/static/` (STATIC_ROOT, gitignored) is a silent 404 in CI. All app JS must live in `src/apps/<app>/static/` or `src/static_src/`.
|
||||||
|
|
||||||
|
### msgpack integer key bug (Django Channels)
|
||||||
|
`channels_redis` uses msgpack with `strict_map_key=True` — integer dict keys in `group_send` payloads raise `ValueError` and crash consumers. Always use `str(slot_number)` as dict keys.
|
||||||
|
|
||||||
|
### Multi-browser FTs in CI
|
||||||
|
Any FT opening a second browser must pass `FirefoxOptions` with `--headless` when `HEADLESS` env var is set. Bare `webdriver.Firefox()` crashes in headless CI with `Process unexpectedly closed with status 1`.
|
||||||
|
|
||||||
|
### Selenium + CSS text-transform
|
||||||
|
Selenium `.text` returns visually rendered text. CSS `text-transform: uppercase` causes `assertIn("Test Room", body.text)` to fail. Assert against the uppercased string or use `body.text.upper()`.
|
||||||
|
|
||||||
|
### Tooltip portal pattern
|
||||||
|
`mask-image` on grid containers clips `position: absolute` tooltips. Use `#id_tooltip_portal` (`position: fixed; z-index: 9999`) at page root. See `gameboard.js` + `wallet.js`.
|
||||||
|
|
||||||
|
### Applet menus + container-type
|
||||||
|
`container-type: inline-size` creates a containing block for all positioned descendants — applet menus must live OUTSIDE `#id_applets_container` to be viewport-fixed.
|
||||||
|
|
||||||
|
### ABU session auth
|
||||||
|
`create_pre_authenticated_session` must set `HASH_SESSION_KEY = user.get_session_auth_hash()` and hardcode `BACKEND_SESSION_KEY` to the passwordless backend string.
|
||||||
|
|
||||||
|
### Magic login email mock paths
|
||||||
|
- View tests: `apps.lyric.views.send_login_email_task.delay`
|
||||||
|
- Task unit tests: `apps.lyric.tasks.requests.post`
|
||||||
|
- FTs: mock both with `side_effect=send_login_email_task`
|
||||||
|
|
||||||
|
## Teaching Style
|
||||||
|
User prefers guided learning: describe what to type and why, let them write the code, then review together. But for now, given user's accelerated timetable, please respond with complete code snippets for user to transcribe directly.
|
||||||
@@ -15,7 +15,9 @@ RUN python manage.py collectstatic --noinput
|
|||||||
|
|
||||||
ENV DJANGO_DEBUG_FALSE=1
|
ENV DJANGO_DEBUG_FALSE=1
|
||||||
|
|
||||||
|
RUN DJANGO_SECRET_KEY=build-dummy DJANGO_ALLOWED_HOST=localhost python manage.py compress
|
||||||
|
|
||||||
RUN adduser --uid 1234 nonroot
|
RUN adduser --uid 1234 nonroot
|
||||||
|
|
||||||
USER nonroot
|
USER nonroot
|
||||||
CMD ["gunicorn", "--bind", ":8888", "core.wsgi:application"]
|
CMD ["gunicorn", "--bind", ":8888", "-k", "uvicorn.workers.UvicornWorker", "core.asgi:application"]
|
||||||
8
Dockerfile.ci
Normal file
8
Dockerfile.ci
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
FROM python:3.13-slim
|
||||||
|
|
||||||
|
COPY requirements.dev.txt requirements.dev.txt
|
||||||
|
RUN pip install -r requirements.dev.txt
|
||||||
|
RUN apt update -y && apt install -y firefox-esr
|
||||||
|
|
||||||
|
COPY infra/debug-ci.py debug-ci.py
|
||||||
|
CMD ["python", "debug-ci.py"]
|
||||||
3
ansible.cfg
Normal file
3
ansible.cfg
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
[defaults]
|
||||||
|
inventory = infra/inventory.ini
|
||||||
|
vault_password_file = ~/.vault-pass.txt
|
||||||
209
infra/CD-PLAN.md
Normal file
209
infra/CD-PLAN.md
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
# Continuous Deployment: Auto-deploy to staging when CI passes
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
CI is complete (Percival ch. 25). The Woodpecker pipeline runs 57 UTs + 9 FTs on every push to Gitea, but deployment to staging is still manual (`ansible-playbook infra/deploy-playbook.yaml`). This plan adds CD: when tests pass on the `main` branch, the pipeline automatically builds the Docker image, pushes it to the Gitea container registry, and deploys it to `staging.earthmanrpg.me`.
|
||||||
|
|
||||||
|
**Architecture:** Build in CI pipeline -> push to Gitea registry -> SSH to staging -> pull + restart
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 1: Enable Docker socket in Woodpecker pipeline steps
|
||||||
|
|
||||||
|
The Woodpecker agent already has the Docker socket mounted (line 53 of `infra/cicd/docker-compose.yaml`), but pipeline steps (containers the agent launches) don't inherit it. We need to tell the agent to pass it through.
|
||||||
|
|
||||||
|
### 1a. Edit `infra/cicd/docker-compose.yaml` -- add env var to `woodpecker-agent`
|
||||||
|
|
||||||
|
Add this to the agent's `environment:` block:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- WOODPECKER_BACKEND_DOCKER_VOLUMES=/var/run/docker.sock:/var/run/docker.sock
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why:** This makes the host Docker socket available inside every pipeline step container. Without it, the `docker build` and `docker push` commands in our pipeline step would fail with "cannot connect to Docker daemon."
|
||||||
|
|
||||||
|
### 1b. Re-deploy CI stack
|
||||||
|
|
||||||
|
From WSL:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ansible-playbook infra/cicd-playbook.yaml -i infra/inventory.ini --ask-vault-pass
|
||||||
|
```
|
||||||
|
|
||||||
|
This uploads the updated docker-compose and restarts the CI services.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 2: Prepare staging server for CD
|
||||||
|
|
||||||
|
Currently `deploy-playbook.yaml` does everything in one shot: installs Docker, builds the image locally, uploads it, runs it with inline `env:` vars, copies static files, migrates. For CD, we need to split "one-time setup" from "per-deploy actions."
|
||||||
|
|
||||||
|
### 2a. Create `infra/gamearray.env.j2` -- container env file template (new file)
|
||||||
|
|
||||||
|
```
|
||||||
|
DJANGO_DEBUG_FALSE=1
|
||||||
|
DJANGO_SECRET_KEY={{ secret_key.content | b64decode }}
|
||||||
|
DJANGO_ALLOWED_HOST={{ django_allowed_host }}
|
||||||
|
DJANGO_DB_PATH=/home/nonroot/db.sqlite3
|
||||||
|
EMAIL_HOST_USER={{ email_host_user }}
|
||||||
|
EMAIL_HOST_PASSWORD={{ email_host_password }}
|
||||||
|
MAILGUN_API_KEY={{ mailgun_api_key }}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why:** Instead of passing env vars inline in `docker run`, we template a `.env` file onto the staging server. The deploy script references it with `--env-file`. This keeps secrets out of the pipeline YAML and on the server, managed by Ansible vault.
|
||||||
|
|
||||||
|
### 2b. Create `infra/deploy.sh.j2` -- deploy script template (new file)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
#!/bin/bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
IMAGE=gitea.earthmanrpg.me/discoman/gamearray:latest
|
||||||
|
|
||||||
|
echo "==> Pulling latest image..."
|
||||||
|
docker pull "$IMAGE"
|
||||||
|
|
||||||
|
echo "==> Stopping old container..."
|
||||||
|
docker stop gamearray 2>/dev/null || true
|
||||||
|
docker rm gamearray 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "==> Starting new container..."
|
||||||
|
docker run -d --name gamearray \
|
||||||
|
--env-file /opt/gamearray/gamearray.env \
|
||||||
|
-p 127.0.0.1:8888:8888 \
|
||||||
|
"$IMAGE"
|
||||||
|
|
||||||
|
echo "==> Running migrations..."
|
||||||
|
docker exec gamearray ./manage.py migrate
|
||||||
|
|
||||||
|
echo "==> Copying static files..."
|
||||||
|
sudo docker cp gamearray:/src/static/. /var/www/gamearray/static/
|
||||||
|
|
||||||
|
echo "==> Deploy complete."
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why:** A single script the pipeline calls via SSH. Keeps the pipeline YAML clean and lets us test deploys manually too (`ssh staging /opt/gamearray/deploy.sh`).
|
||||||
|
|
||||||
|
### 2c. Update `infra/deploy-playbook.yaml` -- add env file, deploy script, and registry login
|
||||||
|
|
||||||
|
Add these tasks (after the existing "Read secret key" task):
|
||||||
|
|
||||||
|
1. **Create `/opt/gamearray/` directory** on staging
|
||||||
|
2. **Template `gamearray.env.j2`** to `/opt/gamearray/gamearray.env` (mode 0600)
|
||||||
|
3. **Template `deploy.sh.j2`** to `/opt/gamearray/deploy.sh` (mode 0755)
|
||||||
|
4. **Docker login to Gitea registry** -- so the deploy script can `docker pull`
|
||||||
|
|
||||||
|
For the Docker login, use a Gitea access token (created in the browser, stored in the staging vault):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: Login to Gitea container registry
|
||||||
|
ansible.builtin.command:
|
||||||
|
cmd: docker login gitea.earthmanrpg.me -u discoman -p {{ gitea_registry_token }}
|
||||||
|
no_log: true
|
||||||
|
```
|
||||||
|
|
||||||
|
**Vault additions** needed for staging (`infra/group_vars/staging/vault.yaml`):
|
||||||
|
- `gitea_registry_token` -- a Gitea personal access token with `package:read` scope
|
||||||
|
|
||||||
|
### 2d. Run the deploy playbook
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ansible-playbook infra/deploy-playbook.yaml -i infra/inventory.ini -l staging --ask-vault-pass
|
||||||
|
```
|
||||||
|
|
||||||
|
This sets up the staging server: env file, deploy script, and registry auth.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 3: Woodpecker secrets
|
||||||
|
|
||||||
|
Two secrets need to be added via the Woodpecker UI (`https://ci.earthmanrpg.me` -> repo settings -> Secrets):
|
||||||
|
|
||||||
|
### 3a. `deploy_ssh_key`
|
||||||
|
|
||||||
|
Generate a dedicated SSH key pair for CD:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_cd_deploy -C "woodpecker-cd"
|
||||||
|
```
|
||||||
|
|
||||||
|
- Add the **public key** to `~/.ssh/authorized_keys` on staging (as `discoman` user)
|
||||||
|
- Paste the **private key** contents into a Woodpecker secret named `deploy_ssh_key`
|
||||||
|
|
||||||
|
### 3b. `gitea_registry_password`
|
||||||
|
|
||||||
|
The Gitea access token (same one from Stage 2c, or a separate one with `package:read,package:write` scope).
|
||||||
|
|
||||||
|
- Paste into a Woodpecker secret named `gitea_registry_password`
|
||||||
|
- The `build-and-push` step will use this to `docker login` + `docker push`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 4: Update `.woodpecker.yaml`
|
||||||
|
|
||||||
|
Add two new steps after `screendumps`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- name: build-and-push
|
||||||
|
image: docker:cli
|
||||||
|
environment:
|
||||||
|
REGISTRY_PASSWORD:
|
||||||
|
from_secret: gitea_registry_password
|
||||||
|
commands:
|
||||||
|
- echo "$REGISTRY_PASSWORD" | docker login gitea.earthmanrpg.me -u discoman --password-stdin
|
||||||
|
- docker build -t gitea.earthmanrpg.me/discoman/gamearray:latest .
|
||||||
|
- docker push gitea.earthmanrpg.me/discoman/gamearray:latest
|
||||||
|
when:
|
||||||
|
- branch: main
|
||||||
|
- event: push
|
||||||
|
|
||||||
|
- name: deploy
|
||||||
|
image: alpine
|
||||||
|
environment:
|
||||||
|
SSH_KEY:
|
||||||
|
from_secret: deploy_ssh_key
|
||||||
|
commands:
|
||||||
|
- apk add --no-cache openssh-client
|
||||||
|
- mkdir -p ~/.ssh
|
||||||
|
- printf '%s\n' "$SSH_KEY" > ~/.ssh/id_ed25519
|
||||||
|
- chmod 600 ~/.ssh/id_ed25519
|
||||||
|
- ssh -o StrictHostKeyChecking=no discoman@staging.earthmanrpg.me /opt/gamearray/deploy.sh
|
||||||
|
when:
|
||||||
|
- branch: main
|
||||||
|
- event: push
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why `docker:cli` instead of a Docker plugin?** Using plain Docker CLI with the socket pass-through is more transparent than a third-party plugin. You can see exactly what's happening.
|
||||||
|
|
||||||
|
**Why `alpine` + manual SSH instead of `appleboy/drone-ssh`?** Same reason -- fewer moving parts, easier to debug. The `printf` + `ssh` pattern is dead simple.
|
||||||
|
|
||||||
|
**Branch gating:** Both steps only run on pushes to `main`. Feature branch pushes still run tests but don't deploy.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Stage 5: Test end-to-end
|
||||||
|
|
||||||
|
1. Push a small visible change (e.g., tweak a template's page title) to `main` on Gitea
|
||||||
|
2. Watch the Woodpecker pipeline at `https://ci.earthmanrpg.me`:
|
||||||
|
- `test-UTs` passes
|
||||||
|
- `test-FTs` passes
|
||||||
|
- `build-and-push` builds the image and pushes to the registry
|
||||||
|
- `deploy` SSHes to staging and runs the deploy script
|
||||||
|
3. Visit `https://staging.earthmanrpg.me` and verify the change is live
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Files modified
|
||||||
|
|
||||||
|
| File | Action |
|
||||||
|
|------|--------|
|
||||||
|
| `infra/cicd/docker-compose.yaml` | Add `WOODPECKER_BACKEND_DOCKER_VOLUMES` to agent |
|
||||||
|
| `infra/gamearray.env.j2` | **New** -- container env file template |
|
||||||
|
| `infra/deploy.sh.j2` | **New** -- deploy script template |
|
||||||
|
| `infra/deploy-playbook.yaml` | Add tasks for env file, deploy script, registry login |
|
||||||
|
| `infra/group_vars/staging/vault.yaml` | Add `gitea_registry_token` |
|
||||||
|
| `.woodpecker.yaml` | Add `build-and-push` and `deploy` steps |
|
||||||
|
|
||||||
|
## Known limitation
|
||||||
|
|
||||||
|
**Ephemeral database:** The SQLite database still lives inside the container (deferred issue from memory). Every deploy wipes it. This is fine for staging right now but will need a volume mount or PostgreSQL before production CD.
|
||||||
114
infra/cicd-playbook.yaml
Normal file
114
infra/cicd-playbook.yaml
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
- hosts: cicd
|
||||||
|
|
||||||
|
tasks:
|
||||||
|
- name: Install Docker
|
||||||
|
ansible.builtin.apt:
|
||||||
|
name: docker.io
|
||||||
|
state: latest
|
||||||
|
update_cache: true
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Install Nginx
|
||||||
|
ansible.builtin.apt:
|
||||||
|
name: nginx
|
||||||
|
state: latest
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Add out user to the docker group, so we don't need sudo/become
|
||||||
|
ansible.builtin.user:
|
||||||
|
name: '{{ ansible_user }}'
|
||||||
|
groups: docker
|
||||||
|
append: true # don't remove any existing groups
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Reset ssh connection to allow the user/group change to take effect
|
||||||
|
ansible.builtin.meta: reset_connection
|
||||||
|
|
||||||
|
- name: Install docker-compose-plugin & certbot
|
||||||
|
ansible.builtin.apt:
|
||||||
|
name:
|
||||||
|
- docker-compose-v2
|
||||||
|
- certbot
|
||||||
|
- python3-certbot-nginx
|
||||||
|
state: latest
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Create /opt/cicd/ directory tree
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: "/opt/cicd/nginx"
|
||||||
|
state: directory
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Cp docker-compose.yaml to server
|
||||||
|
ansible.builtin.copy:
|
||||||
|
src: cicd/docker-compose.yaml
|
||||||
|
dest: /opt/cicd/docker-compose.yaml
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Template .env to /opt/cicd/
|
||||||
|
ansible.builtin.template:
|
||||||
|
src: cicd/.env.j2
|
||||||
|
dest: /opt/cicd/.env
|
||||||
|
mode: "0600"
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Deploy nginx config (Gitea)
|
||||||
|
ansible.builtin.copy:
|
||||||
|
src: cicd/nginx/gitea.conf
|
||||||
|
dest: /etc/nginx/sites-available/gitea
|
||||||
|
become: true
|
||||||
|
notify: Restart nginx
|
||||||
|
|
||||||
|
- name: Deploy nginx config (Woodpecker)
|
||||||
|
ansible.builtin.copy:
|
||||||
|
src: cicd/nginx/woodpecker.conf
|
||||||
|
dest: /etc/nginx/sites-available/woodpecker
|
||||||
|
become: true
|
||||||
|
notify: Restart nginx
|
||||||
|
|
||||||
|
- name: Enable nginx site (Gitea)
|
||||||
|
ansible.builtin.file:
|
||||||
|
src: /etc/nginx/sites-available/gitea
|
||||||
|
dest: /etc/nginx/sites-enabled/gitea
|
||||||
|
state: link
|
||||||
|
become: true
|
||||||
|
notify: Restart nginx
|
||||||
|
|
||||||
|
- name: Enable nginx site (Woodpecker)
|
||||||
|
ansible.builtin.file:
|
||||||
|
src: /etc/nginx/sites-available/woodpecker
|
||||||
|
dest: /etc/nginx/sites-enabled/woodpecker
|
||||||
|
state: link
|
||||||
|
become: true
|
||||||
|
notify: Restart nginx
|
||||||
|
|
||||||
|
- name: Remove default nginx site
|
||||||
|
ansible.builtin.file:
|
||||||
|
path: /etc/nginx/sites-enabled/default
|
||||||
|
state: absent
|
||||||
|
become: true
|
||||||
|
notify: Restart nginx
|
||||||
|
|
||||||
|
- name: Obtain SSL certs via certbot
|
||||||
|
ansible.builtin.command:
|
||||||
|
cmd: >
|
||||||
|
certbot --nginx
|
||||||
|
-d gitea.earthmanrpg.me
|
||||||
|
-d ci.earthmanrpg.me
|
||||||
|
--non-interactive
|
||||||
|
--agree-tos
|
||||||
|
-m discodedisco@outlook.com
|
||||||
|
creates: /etc/letsencrypt/live/gitea.earthmanrpg.me/fullchain.pem
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Run docker compose -f /opt/cicd/docker-compose.yaml up -d
|
||||||
|
ansible.builtin.command:
|
||||||
|
cmd: docker compose -f /opt/cicd/docker-compose.yaml up -d
|
||||||
|
become: true
|
||||||
|
|
||||||
|
handlers:
|
||||||
|
- name: Restart nginx
|
||||||
|
ansible.builtin.service:
|
||||||
|
name: nginx
|
||||||
|
state: restarted
|
||||||
|
become: true
|
||||||
4
infra/cicd/.env.j2
Normal file
4
infra/cicd/.env.j2
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
WOODPECKER_ADMIN={{ woodpecker_admin }}
|
||||||
|
WOODPECKER_AGENT_SECRET={{ woodpecker_agent_secret }}
|
||||||
|
WOODPECKER_GITEA_CLIENT={{ woodpecker_gitea_client }}
|
||||||
|
WOODPECKER_GITEA_SECRET={{ woodpecker_gitea_secret }}
|
||||||
59
infra/cicd/docker-compose.yaml
Normal file
59
infra/cicd/docker-compose.yaml
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
services:
|
||||||
|
gitea:
|
||||||
|
image: docker.gitea.com/gitea:1.24
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
- USER_UID=1000
|
||||||
|
- USER_GID=1000
|
||||||
|
- GITEA__server__ROOT_URL=https://gitea.earthmanrpg.me/
|
||||||
|
- GITEA__server__DOMAIN=gitea.earthmanrpg.me
|
||||||
|
- GITEA__server__SSH_DOMAIN=gitea.earthmanrpg.me
|
||||||
|
- GITEA__webhook__ALLOWED_HOST_LIST=external,loopback
|
||||||
|
volumes:
|
||||||
|
- ./data/gitea:/data # Gitea stores repos, db, config here
|
||||||
|
- /etc/timezone:/etc/timezone:ro
|
||||||
|
- /etc/localtime:/etc/localtime:ro
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:3000:3000" # http (only localhost, nginx proxies)
|
||||||
|
- "222:22" # ssh (public, for git push)
|
||||||
|
networks:
|
||||||
|
- cicd
|
||||||
|
|
||||||
|
woodpecker-server:
|
||||||
|
image: woodpeckerci/woodpecker-server:v3
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
- gitea
|
||||||
|
environment:
|
||||||
|
- WOODPECKER_HOST=https://ci.earthmanrpg.me
|
||||||
|
- WOODPECKER_OPEN=false
|
||||||
|
- WOODPECKER_ADMIN=${WOODPECKER_ADMIN}
|
||||||
|
- WOODPECKER_GITEA=true
|
||||||
|
- WOODPECKER_GITEA_URL=https://gitea.earthmanrpg.me
|
||||||
|
- WOODPECKER_GITEA_CLIENT=${WOODPECKER_GITEA_CLIENT}
|
||||||
|
- WOODPECKER_GITEA_SECRET=${WOODPECKER_GITEA_SECRET}
|
||||||
|
- WOODPECKER_AGENT_SECRET=${WOODPECKER_AGENT_SECRET}
|
||||||
|
volumes:
|
||||||
|
- ./data/woodpecker-server:/var/lib/woodpecker
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8000:8000" # (only nginx proxies)
|
||||||
|
networks:
|
||||||
|
- cicd
|
||||||
|
|
||||||
|
woodpecker-agent:
|
||||||
|
image: woodpeckerci/woodpecker-agent:v3
|
||||||
|
restart: unless-stopped
|
||||||
|
depends_on:
|
||||||
|
- woodpecker-server
|
||||||
|
environment:
|
||||||
|
- WOODPECKER_SERVER=woodpecker-server:9000
|
||||||
|
- WOODPECKER_AGENT_SECRET=${WOODPECKER_AGENT_SECRET}
|
||||||
|
- WOODPECKER_MAX_WORKFLOWS=2
|
||||||
|
- WOODPECKER_BACKEND_DOCKER_VOLUMES=/var/run/docker.sock:/var/run/docker.sock
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
networks:
|
||||||
|
- cicd
|
||||||
|
|
||||||
|
networks:
|
||||||
|
cicd:
|
||||||
14
infra/cicd/nginx/gitea.conf
Normal file
14
infra/cicd/nginx/gitea.conf
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name gitea.earthmanrpg.me;
|
||||||
|
|
||||||
|
client_max_body_size 100m;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:3000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
}
|
||||||
16
infra/cicd/nginx/woodpecker.conf
Normal file
16
infra/cicd/nginx/woodpecker.conf
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name ci.earthmanrpg.me;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:8000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
|
# WebSocket support (Woodpecker live log streaming)
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
}
|
||||||
|
}
|
||||||
5
infra/debug-ci.py
Normal file
5
infra/debug-ci.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
from selenium import webdriver
|
||||||
|
|
||||||
|
options = webdriver.FirefoxOptions()
|
||||||
|
options.add_argument("--headless")
|
||||||
|
webdriver.Firefox(options=options).quit()
|
||||||
@@ -50,37 +50,6 @@
|
|||||||
- name: Reset ssh connection to allow the user/group change to take effect
|
- name: Reset ssh connection to allow the user/group change to take effect
|
||||||
ansible.builtin.meta: reset_connection
|
ansible.builtin.meta: reset_connection
|
||||||
|
|
||||||
- name: Build container image locally
|
|
||||||
community.docker.docker_image:
|
|
||||||
name: gamearray
|
|
||||||
source: build
|
|
||||||
state: present
|
|
||||||
build:
|
|
||||||
path: /mnt/d/cosmovault/latticework/oreilly/percival/python-tdd
|
|
||||||
platform: linux/amd64
|
|
||||||
force_source: true
|
|
||||||
delegate_to: 127.0.0.1
|
|
||||||
|
|
||||||
- name: Export container image locally
|
|
||||||
community.docker.docker_image:
|
|
||||||
name: gamearray
|
|
||||||
archive_path: /tmp/gamearray-img.tar
|
|
||||||
source: local
|
|
||||||
delegate_to: 127.0.0.1
|
|
||||||
|
|
||||||
- name: Upload image to server
|
|
||||||
ansible.builtin.copy:
|
|
||||||
src: /tmp/gamearray-img.tar
|
|
||||||
dest: /tmp/gamearray-img.tar
|
|
||||||
|
|
||||||
- name: Import container image on server
|
|
||||||
community.docker.docker_image:
|
|
||||||
name: gamearray
|
|
||||||
load_path: /tmp/gamearray-img.tar
|
|
||||||
source: load
|
|
||||||
force_source: true
|
|
||||||
state: present
|
|
||||||
|
|
||||||
- name: Ensure .secret-key files exists
|
- name: Ensure .secret-key files exists
|
||||||
# the intention is that this only happens once per server
|
# the intention is that this only happens once per server
|
||||||
ansible.builtin.copy:
|
ansible.builtin.copy:
|
||||||
@@ -94,30 +63,108 @@
|
|||||||
src: ~/.secret-key
|
src: ~/.secret-key
|
||||||
register: secret_key
|
register: secret_key
|
||||||
|
|
||||||
- name: Ensure db.sqlite3 file exists outside container
|
- name: Create /opt/gamearray/ directory
|
||||||
ansible.builtin.file:
|
ansible.builtin.file:
|
||||||
path: "{{ ansible_env.HOME }}/db.sqlite3"
|
path: /opt/gamearray
|
||||||
state: touch
|
state: directory
|
||||||
owner: 1234 # so nonroot user can access it in container
|
become: true
|
||||||
become: true # needed for ownership change
|
|
||||||
|
- name: Template gamearray.env to server
|
||||||
|
ansible.builtin.template:
|
||||||
|
src: gamearray.env.j2
|
||||||
|
dest: /opt/gamearray/gamearray.env
|
||||||
|
owner: "{{ ansible_user }}"
|
||||||
|
mode: "0600"
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Template deploy script to server
|
||||||
|
ansible.builtin.template:
|
||||||
|
src: deploy.sh.j2
|
||||||
|
dest: /opt/gamearray/deploy.sh
|
||||||
|
mode: "0755"
|
||||||
|
become: true
|
||||||
|
|
||||||
|
- name: Login to Gitea container registry
|
||||||
|
ansible.builtin.command:
|
||||||
|
cmd: docker login gitea.earthmanrpg.me -u discoman -p {{ gitea_registry_token }}
|
||||||
|
no_log: true
|
||||||
|
|
||||||
|
- name: Create Docker network
|
||||||
|
community.docker.docker_network:
|
||||||
|
name: gamearray_net
|
||||||
|
state: present
|
||||||
|
|
||||||
|
- name: Create Postgres data volume
|
||||||
|
community.docker.docker_volume:
|
||||||
|
name: gamearray_postgres_data
|
||||||
|
state: present
|
||||||
|
|
||||||
|
- name: Start Postgres container
|
||||||
|
community.docker.docker_container:
|
||||||
|
name: gamearray_postgres
|
||||||
|
image: postgres:16
|
||||||
|
state: started
|
||||||
|
restart_policy: unless-stopped
|
||||||
|
networks:
|
||||||
|
- name: gamearray_net
|
||||||
|
volumes:
|
||||||
|
- gamearray_postgres_data:/var/lib/postgresql/data
|
||||||
|
env:
|
||||||
|
POSTGRES_DB: gamearray
|
||||||
|
POSTGRES_USER: gamearray
|
||||||
|
POSTGRES_PASSWORD: "{{ postgres_password }}"
|
||||||
|
|
||||||
|
- name: Start Redis container
|
||||||
|
community.docker.docker_container:
|
||||||
|
name: gamearray_redis
|
||||||
|
image: redis:7
|
||||||
|
state: started
|
||||||
|
restart_policy: unless-stopped
|
||||||
|
networks:
|
||||||
|
- name: gamearray_net
|
||||||
|
|
||||||
- name: Run container
|
- name: Run container
|
||||||
community.docker.docker_container:
|
community.docker.docker_container:
|
||||||
name: gamearray
|
name: gamearray
|
||||||
image: gamearray
|
image: gitea.earthmanrpg.me/discoman/gamearray:latest
|
||||||
state: started
|
state: started
|
||||||
recreate: true
|
recreate: true
|
||||||
|
restart_policy: unless-stopped
|
||||||
env:
|
env:
|
||||||
DJANGO_DEBUG_FALSE: "1"
|
DJANGO_DEBUG_FALSE: "1"
|
||||||
DJANGO_SECRET_KEY: "{{ secret_key.content | b64decode }}"
|
DJANGO_SECRET_KEY: "{{ secret_key.content | b64decode }}"
|
||||||
DJANGO_ALLOWED_HOST: "{{ django_allowed_host }}"
|
DJANGO_ALLOWED_HOST: "{{ django_allowed_host }}"
|
||||||
DJANGO_DB_PATH: "/home/nonroot/db.sqlite3"
|
DJANGO_SUPERUSER_EMAIL: "{{ django_superuser_email }}"
|
||||||
EMAIL_HOST_USER: "{{ email_host_user }}"
|
DJANGO_SUPERUSER_PASSWORD: "{{ django_superuser_password }}"
|
||||||
EMAIL_HOST_PASSWORD: "{{ email_host_password }}"
|
DATABASE_URL: "postgresql://gamearray:{{ postgres_password }}@gamearray_postgres/gamearray"
|
||||||
MAILGUN_API_KEY: "{{ mailgun_api_key }}"
|
MAILGUN_API_KEY: "{{ mailgun_api_key }}"
|
||||||
|
CELERY_BROKER_URL: "redis://gamearray_redis:6379/0"
|
||||||
|
REDIS_URL: "redis://gamearray_redis:6379/1"
|
||||||
|
networks:
|
||||||
|
- name: gamearray_net
|
||||||
ports:
|
ports:
|
||||||
127.0.0.1:8888:8888
|
127.0.0.1:8888:8888
|
||||||
|
|
||||||
|
- name: Start Celery worker container
|
||||||
|
community.docker.docker_container:
|
||||||
|
name: gamearray_celery
|
||||||
|
image: gitea.earthmanrpg.me/discoman/gamearray:latest
|
||||||
|
state: started
|
||||||
|
recreate: true
|
||||||
|
restart_policy: unless-stopped
|
||||||
|
env:
|
||||||
|
DJANGO_DEBUG_FALSE: "1"
|
||||||
|
DJANGO_SECRET_KEY: "{{ secret_key.content | b64decode }}"
|
||||||
|
DJANGO_ALLOWED_HOST: "{{ django_allowed_host }}"
|
||||||
|
DATABASE_URL: "postgresql://gamearray:{{ postgres_password }}@gamearray_postgres/gamearray"
|
||||||
|
MAILGUN_API_KEY: "{{ mailgun_api_key }}"
|
||||||
|
CELERY_BROKER_URL: "redis://gamearray_redis:6379/0"
|
||||||
|
REDIS_URL: "redis://gamearray_redis:6379/1"
|
||||||
|
networks:
|
||||||
|
- name: gamearray_net
|
||||||
|
command: "python -m celery -A core worker -l info"
|
||||||
|
|
||||||
|
|
||||||
- name: Create static files directory
|
- name: Create static files directory
|
||||||
ansible.builtin.file:
|
ansible.builtin.file:
|
||||||
path: /var/www/gamearray/static
|
path: /var/www/gamearray/static
|
||||||
@@ -134,7 +181,12 @@
|
|||||||
- name: Run migration inside container
|
- name: Run migration inside container
|
||||||
community.docker.docker_container_exec:
|
community.docker.docker_container_exec:
|
||||||
container: gamearray
|
container: gamearray
|
||||||
command: ./manage.py migrate
|
command: python manage.py migrate
|
||||||
|
|
||||||
|
- name: Ensure superuser exists
|
||||||
|
community.docker.docker_container_exec:
|
||||||
|
container: gamearray
|
||||||
|
command: python manage.py ensure_superuser
|
||||||
|
|
||||||
handlers:
|
handlers:
|
||||||
- name: Restart nginx
|
- name: Restart nginx
|
||||||
|
|||||||
41
infra/deploy.sh.j2
Normal file
41
infra/deploy.sh.j2
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
IMAGE=gitea.earthmanrpg.me/discoman/gamearray:latest
|
||||||
|
|
||||||
|
echo "==> Pulling latest image..."
|
||||||
|
docker pull "$IMAGE"
|
||||||
|
|
||||||
|
echo "==> Stopping old container..."
|
||||||
|
docker stop gamearray 2>/dev/null || true
|
||||||
|
docker rm gamearray 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "==> Starting new container..."
|
||||||
|
docker run -d --name gamearray \
|
||||||
|
--restart unless-stopped \
|
||||||
|
--env-file /opt/gamearray/gamearray.env \
|
||||||
|
--network gamearray_net \
|
||||||
|
-p 127.0.0.1:8888:8888 \
|
||||||
|
"$IMAGE"
|
||||||
|
|
||||||
|
echo "==> Stopping old celery worker..."
|
||||||
|
docker stop gamearray_celery 2>/dev/null || true
|
||||||
|
docker rm gamearray_celery 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "==> Starting new celery worker..."
|
||||||
|
docker run -d --name gamearray_celery \
|
||||||
|
--restart unless-stopped \
|
||||||
|
--env-file /opt/gamearray/gamearray.env \
|
||||||
|
--network gamearray_net \
|
||||||
|
"$IMAGE" python -m celery -A core worker -l info
|
||||||
|
|
||||||
|
echo "==> Running migrations..."
|
||||||
|
docker exec gamearray python ./manage.py migrate
|
||||||
|
|
||||||
|
echo "==> Ensuring superuser exists..."
|
||||||
|
docker exec gamearray python manage.py ensure_superuser
|
||||||
|
|
||||||
|
echo "==> Copying static files..."
|
||||||
|
sudo docker cp gamearray:/src/static/. /var/www/gamearray/static/
|
||||||
|
|
||||||
|
echo "==> Deploy complete."
|
||||||
12
infra/gamearray.env.j2
Normal file
12
infra/gamearray.env.j2
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
DJANGO_DEBUG_FALSE=1
|
||||||
|
DJANGO_SECRET_KEY={{ secret_key.content | b64decode }}
|
||||||
|
DJANGO_ALLOWED_HOST={{ django_allowed_host }}
|
||||||
|
DJANGO_SUPERUSER_EMAIL={{ django_superuser_email }}
|
||||||
|
DJANGO_SUPERUSER_PASSWORD={{ django_superuser_password }}
|
||||||
|
DATABASE_URL=postgresql://gamearray:{{ postgres_password }}@gamearray_postgres/gamearray
|
||||||
|
MAILGUN_API_KEY={{ mailgun_api_key }}
|
||||||
|
STRIPE_PUBLISHABLE_KEY={{ stripe_publishable_key }}
|
||||||
|
STRIPE_SECRET_KEY={{ stripe_secret_key }}
|
||||||
|
CELERY_BROKER_URL=redis://gamearray_redis:6379/0
|
||||||
|
REDIS_URL=redis://gamearray_redis:6379/1
|
||||||
|
|
||||||
18
infra/group_vars/cicd/vault.yaml
Normal file
18
infra/group_vars/cicd/vault.yaml
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
$ANSIBLE_VAULT;1.1;AES256
|
||||||
|
32353432336330376365646535626462343239653737383565353163623230393338633536653231
|
||||||
|
3536303839613765643136366535333962376665306662620a383634393561653139306139366631
|
||||||
|
34663365316264656235396538653035366437663030383962373936336464306632333662623737
|
||||||
|
3834366363383135330a643064383065653565636334636336366138383464663562363030313636
|
||||||
|
30356332663332613565313339633036653463636264643531383231613739653061333134333337
|
||||||
|
36643365303637653635613838626466353163386331383864623936326636303734326566626561
|
||||||
|
32633562336663303866376335363935343031363465353834303133376363376665333363343535
|
||||||
|
35616532616264663631626135353134623965613539336562353963363534336261663530343331
|
||||||
|
30636332633538313838363434386331323837376663666463393736383830363966373662316539
|
||||||
|
39343466626633313734363732386135333636663735646430616130353765616133393165366231
|
||||||
|
62613130306164323938373964313938613634396665363161646264323332316664656265643231
|
||||||
|
35393032343263316464333530623365303430623235363862393435646433616566336136353236
|
||||||
|
34636630373530393464663839656661313364333830383966353739346335643635393030396335
|
||||||
|
30653332306163346431353535613338323163333032333435613139383366336338326635363165
|
||||||
|
34353033346362646131353339666561353766366239643661313334646365666236616232623865
|
||||||
|
37636162613334353632346664343034303861393833363535343063623831613735303762643064
|
||||||
|
31303161306364356436393665363939643736353238333037393936303136336566
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
$ANSIBLE_VAULT;1.1;AES256
|
|
||||||
33333861646565323863616363316265346132643135656533613763336462656361353562396163
|
|
||||||
6461313530323231383264373737323934346239316232340a356130646163636436663162386438
|
|
||||||
30636530373663643166616665313738303437636562643035303138613861656165663939613433
|
|
||||||
3465316130343732660a376536373136636162316665386536363536306130383033623735396634
|
|
||||||
66383262643630356536633366373933313637646539643137356330316463356139613738386661
|
|
||||||
34663231656232666630653162653732363431613461396464623133303965636432626536306634
|
|
||||||
64373530313532353531633263383335653239386530343330326237343862386436633666646235
|
|
||||||
31613530383834656462366535643030356562313237363735386337356165663564336564623862
|
|
||||||
34623863623738653735393734336635616135383036306231623464653432616265626233306230
|
|
||||||
63646466323135363466393832636466646434303564653032323366346430306336363435653761
|
|
||||||
30336437373231376261326264616131653833616236623365393334303834626162343761623037
|
|
||||||
36666665663866643263383835626336353030626337303461396665343731666465653662396164
|
|
||||||
34306261356130363037643637303632663830383331346334313336663163303730306265393031
|
|
||||||
39653231373139616465326561313633306433653461653931663164363565363636316433323933
|
|
||||||
61333536323936306538343336663966633161633565666231393261643062636239323264623364
|
|
||||||
38376266393937376133366561663931356236396131376137653536636539613738356466363334
|
|
||||||
32326165316434636631613366376235633337356135333531623861343039346261656239613036
|
|
||||||
65303836323538373832646531343234666330363161343337623539633464303161343765363331
|
|
||||||
35386233303563346662633239346363373931333764383233623161313965623266656364383037
|
|
||||||
32393738356532346665613031346338363738666265303765363438663062663237353033393262
|
|
||||||
6137
|
|
||||||
@@ -1,22 +1,42 @@
|
|||||||
$ANSIBLE_VAULT;1.1;AES256
|
$ANSIBLE_VAULT;1.1;AES256
|
||||||
33333861646565323863616363316265346132643135656533613763336462656361353562396163
|
38383061343764656262613934313230656462366163363263653462333338333863326338343838
|
||||||
6461313530323231383264373737323934346239316232340a356130646163636436663162386438
|
3664646437643462346636623231633639396239333532340a363338313839353734326238643735
|
||||||
30636530373663643166616665313738303437636562643035303138613861656165663939613433
|
39343237396433336436366430626332343666666461613636656433363838613432393539386266
|
||||||
3465316130343732660a376536373136636162316665386536363536306130383033623735396634
|
3237336434346333350a663530623334633438616135376437666631313064333735653633396461
|
||||||
66383262643630356536633366373933313637646539643137356330316463356139613738386661
|
31306163343838336465626663373661343839653037333235313361633335646337353339616333
|
||||||
34663231656232666630653162653732363431613461396464623133303965636432626536306634
|
35343233346562346236636364316265313936646235373866636333353866623161663935626637
|
||||||
64373530313532353531633263383335653239386530343330326237343862386436633666646235
|
31633864366339653930626365373237326531366632626337636163333266656434323063333365
|
||||||
31613530383834656462366535643030356562313237363735386337356165663564336564623862
|
38373437383261613439306666373764633737623466626235356465636365646337306534326535
|
||||||
34623863623738653735393734336635616135383036306231623464653432616265626233306230
|
36633866663161613632613434666134343465383663633165663330376535653537333763376232
|
||||||
63646466323135363466393832636466646434303564653032323366346430306336363435653761
|
61653265303134656338393033303834663630653064666134633638393235346631346461633030
|
||||||
30336437373231376261326264616131653833616236623365393334303834626162343761623037
|
35343332393961363361613661633633613262663231366236396663636239326534373134623762
|
||||||
36666665663866643263383835626336353030626337303461396665343731666465653662396164
|
30653139333134616236666238616466633733656633326331386138363839653566333434346534
|
||||||
34306261356130363037643637303632663830383331346334313336663163303730306265393031
|
63326539333461383265316332336333656365386531393630663537363365643061363263313738
|
||||||
39653231373139616465326561313633306433653461653931663164363565363636316433323933
|
37633564363533633762393736636333306433306534393539636231656162343562383232663932
|
||||||
61333536323936306538343336663966633161633565666231393261643062636239323264623364
|
62646339363266303564383438636636373661656465666663613863396639633732636635326166
|
||||||
38376266393937376133366561663931356236396131376137653536636539613738356466363334
|
39323738303338373466366236623665633538363134616565326665386564613735393638656630
|
||||||
32326165316434636631613366376235633337356135333531623861343039346261656239613036
|
31326431316163376132623064376634643737313864336464623431333834663361336133353838
|
||||||
65303836323538373832646531343234666330363161343337623539633464303161343765363331
|
32303635663261333732306137383133623134373363613837306637663566303634653863343766
|
||||||
35386233303563346662633239346363373931333764383233623161313965623266656364383037
|
33613936626362653466333537666462373633313038376565623363666631353162643634653730
|
||||||
32393738356532346665613031346338363738666265303765363438663062663237353033393262
|
30323532623261643136666237316561353038323265303930336364633731333533386563623133
|
||||||
6137
|
31343965643336613933663431626435333235366639363334653065303434386165333739336632
|
||||||
|
61363030376664643638653365626365623936623864666663326534343863613962616431376666
|
||||||
|
39363837386639393235316339323932326466616330303165613032663637616232656162653335
|
||||||
|
61613266376262626234383135306238313366346330656333383465383861663962653638303362
|
||||||
|
34353833646461383839386238626661346263363131643438343461393739336132386466373665
|
||||||
|
32646238633161363064666335626639653335306236613866333934646366323564306133396131
|
||||||
|
36343032623964316138386538333863363530396330646431373466646538663063326330663639
|
||||||
|
32323762356632336364333162336133336335623865323861663131626232633066643238333237
|
||||||
|
32343938353166353037316162653832663433343534626331633936633866356666653932656665
|
||||||
|
38396533356131326262633431653435306362633966383531356236396639376437396333616130
|
||||||
|
35666435393461316232323234653865346338326330623065373461323961393663306262313066
|
||||||
|
30313430353065616230356135333565333338373663643434353561363438656233383739663233
|
||||||
|
35653832353062396634613832353837333835636461616234343462626239636634613430373931
|
||||||
|
31656534343764643065643733326637343631356633653531313062633362663461313732633331
|
||||||
|
35626364393563373339636466346339383032383635303865306636623737343237333863353238
|
||||||
|
63306132396262656365323833323635633563653735366630313363386236613231346339643430
|
||||||
|
63396230353566633830383932666335373665356434656438336338633035653465613665613862
|
||||||
|
31663565653338376662323866613538363566306635333735646363363730646331306234353839
|
||||||
|
30346363393231623563646439623261643634663831313338393761343865303930373133633733
|
||||||
|
31656466303365316164396463373335396464643130643337656361333339653238333633373662
|
||||||
|
6539
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
[staging]
|
[staging]
|
||||||
staging.earthmanrpg.me
|
staging.earthmanrpg.me ansible_user=discoman ansible_ssh_private_key_file=~/.ssh/id_ed25519_wsl_python-tdd letsencrypt_domain=staging.earthmanrpg.me
|
||||||
|
|
||||||
[production]
|
[production]
|
||||||
www.earthmanrpg.me
|
www.earthmanrpg.me ansible_user=discoman ansible_ssh_private_key_file=~/.ssh/id_ed25519_wsl_python-tdd
|
||||||
earthmanrpg.me
|
earthmanrpg.me ansible_user=discoman ansible_ssh_private_key_file=~/.ssh/id_ed25519_wsl_python-tdd
|
||||||
dashboard.earthmanrpg.me
|
dashboard.earthmanrpg.me ansible_user=discoman ansible_ssh_private_key_file=~/.ssh/id_ed25519_wsl_python-tdd
|
||||||
|
|
||||||
|
[cicd]
|
||||||
|
gitea.earthmanrpg.me ansible_user=root ansible_ssh_private_key_file=~/.ssh/id_ed25519_wsl_python-tdd
|
||||||
|
|||||||
@@ -1,6 +1,15 @@
|
|||||||
server {
|
server {
|
||||||
listen 80;
|
listen 80;
|
||||||
server_name {{ django_allowed_host }};
|
server_name {{ django_allowed_host | replace(',', ' ')}};
|
||||||
|
return 301 https://$host$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name {{ django_allowed_host | replace(',', ' ') }};
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/{{ letsencrypt_domain }}/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/{{ letsencrypt_domain }}/privkey.pem;
|
||||||
|
|
||||||
location /static/ {
|
location /static/ {
|
||||||
alias /var/www/gamearray/static/;
|
alias /var/www/gamearray/static/;
|
||||||
@@ -8,9 +17,12 @@ server {
|
|||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://127.0.0.1:8888;
|
proxy_pass http://127.0.0.1:8888;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
proxy_set_header X-Forwarded-Proto https;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,11 +2,21 @@ asgiref==3.11.0
|
|||||||
attrs==25.4.0
|
attrs==25.4.0
|
||||||
certifi==2025.11.12
|
certifi==2025.11.12
|
||||||
cffi==2.0.0
|
cffi==2.0.0
|
||||||
|
channels
|
||||||
|
channels-redis
|
||||||
charset-normalizer==3.4.4
|
charset-normalizer==3.4.4
|
||||||
|
coverage
|
||||||
|
cryptography
|
||||||
cssselect==1.3.0
|
cssselect==1.3.0
|
||||||
|
daphne
|
||||||
|
dj-database-url
|
||||||
Django==6.0
|
Django==6.0
|
||||||
|
django-compressor
|
||||||
|
django-htmx
|
||||||
|
django-libsass
|
||||||
django-stubs==5.2.8
|
django-stubs==5.2.8
|
||||||
django-stubs-ext==5.2.8
|
django-stubs-ext==5.2.8
|
||||||
|
djangorestframework
|
||||||
gunicorn==23.0.0
|
gunicorn==23.0.0
|
||||||
h11==0.16.0
|
h11==0.16.0
|
||||||
idna==3.11
|
idna==3.11
|
||||||
@@ -15,17 +25,21 @@ outcome==1.3.0.post0
|
|||||||
packaging==25.0
|
packaging==25.0
|
||||||
pycparser==2.23
|
pycparser==2.23
|
||||||
PySocks==1.7.1
|
PySocks==1.7.1
|
||||||
|
python-dotenv
|
||||||
requests==2.32.5
|
requests==2.32.5
|
||||||
|
scipy
|
||||||
selenium==4.39.0
|
selenium==4.39.0
|
||||||
sniffio==1.3.1
|
sniffio==1.3.1
|
||||||
sortedcontainers==2.4.0
|
sortedcontainers==2.4.0
|
||||||
sqlparse==0.5.5
|
sqlparse==0.5.5
|
||||||
|
stripe
|
||||||
trio==0.32.0
|
trio==0.32.0
|
||||||
trio-websocket==0.12.2
|
trio-websocket==0.12.2
|
||||||
types-PyYAML==6.0.12.20250915
|
types-PyYAML==6.0.12.20250915
|
||||||
typing_extensions==4.15.0
|
typing_extensions==4.15.0
|
||||||
tzdata==2025.3
|
tzdata==2025.3
|
||||||
urllib3==2.6.2
|
urllib3==2.6.2
|
||||||
|
uvicorn[standard]
|
||||||
websocket-client==1.9.0
|
websocket-client==1.9.0
|
||||||
whitenoise==6.11.0
|
whitenoise==6.11.0
|
||||||
wsproto==1.3.2
|
wsproto==1.3.2
|
||||||
|
|||||||
@@ -1,6 +1,23 @@
|
|||||||
|
celery
|
||||||
|
cryptography
|
||||||
|
channels
|
||||||
|
channels-redis
|
||||||
|
cssselect==1.3.0
|
||||||
|
daphne
|
||||||
Django==6.0
|
Django==6.0
|
||||||
|
dj-database-url
|
||||||
|
django-compressor
|
||||||
|
django-htmx
|
||||||
|
django-libsass
|
||||||
django-stubs==5.2.8
|
django-stubs==5.2.8
|
||||||
django-stubs-ext==5.2.8
|
django-stubs-ext==5.2.8
|
||||||
|
djangorestframework
|
||||||
gunicorn==23.0.0
|
gunicorn==23.0.0
|
||||||
|
lxml==6.0.2
|
||||||
|
psycopg2-binary
|
||||||
|
redis
|
||||||
requests==2.31.0
|
requests==2.31.0
|
||||||
|
scipy
|
||||||
|
stripe
|
||||||
whitenoise==6.11.0
|
whitenoise==6.11.0
|
||||||
|
uvicorn[standard]
|
||||||
|
|||||||
9
src/.coveragerc
Normal file
9
src/.coveragerc
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
[run]
|
||||||
|
source = apps
|
||||||
|
omit =
|
||||||
|
*/migrations/*
|
||||||
|
*/tests/*
|
||||||
|
*/routing.py
|
||||||
|
|
||||||
|
[report]
|
||||||
|
show_missing = true
|
||||||
0
src/apps/ap/__init__.py
Normal file
0
src/apps/ap/__init__.py
Normal file
7
src/apps/ap/apps.py
Normal file
7
src/apps/ap/apps.py
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class ApConfig(AppConfig):
|
||||||
|
default_auto_field = "django.db.models.BigAutoField"
|
||||||
|
name = "apps.ap"
|
||||||
|
label = "ap"
|
||||||
0
src/apps/ap/tests/__init__.py
Normal file
0
src/apps/ap/tests/__init__.py
Normal file
0
src/apps/ap/tests/integrated/__init__.py
Normal file
0
src/apps/ap/tests/integrated/__init__.py
Normal file
119
src/apps/ap/tests/integrated/test_ap_views.py
Normal file
119
src/apps/ap/tests/integrated/test_ap_views.py
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from apps.drama.models import GameEvent, record
|
||||||
|
from apps.epic.models import Room
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class WebFingerTest(TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="actor@test.io", username="actor")
|
||||||
|
|
||||||
|
def test_returns_jrd_for_known_user(self):
|
||||||
|
response = self.client.get(
|
||||||
|
"/.well-known/webfinger",
|
||||||
|
{"resource": "acct:actor@earthmanrpg.me"},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response["Content-Type"], "application/jrd+json")
|
||||||
|
|
||||||
|
def test_jrd_links_to_actor_url(self):
|
||||||
|
response = self.client.get(
|
||||||
|
"/.well-known/webfinger",
|
||||||
|
{"resource": "acct:actor@earthmanrpg.me"},
|
||||||
|
)
|
||||||
|
data = json.loads(response.content)
|
||||||
|
hrefs = [link["href"] for link in data["links"]]
|
||||||
|
self.assertTrue(any("/ap/users/actor/" in href for href in hrefs))
|
||||||
|
|
||||||
|
def test_returns_404_for_unknown_user(self):
|
||||||
|
response = self.client.get(
|
||||||
|
"/.well-known/webfinger",
|
||||||
|
{"resource": "acct:nobody@earthmanrpg.me"},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 404)
|
||||||
|
|
||||||
|
def test_returns_400_for_missing_resource(self):
|
||||||
|
response = self.client.get("/.well-known/webfinger")
|
||||||
|
self.assertEqual(response.status_code, 400)
|
||||||
|
|
||||||
|
|
||||||
|
class ActorViewTest(TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="actor@test.io", username="actor")
|
||||||
|
|
||||||
|
def test_returns_200_for_known_user(self):
|
||||||
|
response = self.client.get("/ap/users/actor/")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
def test_returns_activity_json_content_type(self):
|
||||||
|
response = self.client.get("/ap/users/actor/")
|
||||||
|
self.assertEqual(response["Content-Type"], "application/activity+json")
|
||||||
|
|
||||||
|
def test_actor_has_required_fields(self):
|
||||||
|
response = self.client.get("/ap/users/actor/")
|
||||||
|
data = json.loads(response.content)
|
||||||
|
self.assertEqual(data["type"], "Person")
|
||||||
|
self.assertIn("id", data)
|
||||||
|
self.assertIn("outbox", data)
|
||||||
|
self.assertIn("publicKey", data)
|
||||||
|
|
||||||
|
def test_requires_no_authentication(self):
|
||||||
|
# AP Actor endpoints must be publicly accessible
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.get("/ap/users/actor/")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
def test_returns_404_for_unknown_user(self):
|
||||||
|
response = self.client.get("/ap/users/nobody/")
|
||||||
|
self.assertEqual(response.status_code, 404)
|
||||||
|
|
||||||
|
|
||||||
|
class OutboxViewTest(TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="actor@test.io", username="actor")
|
||||||
|
self.room = Room.objects.create(name="Test Room", owner=self.user)
|
||||||
|
record(
|
||||||
|
self.room, GameEvent.SLOT_FILLED, actor=self.user,
|
||||||
|
slot_number=1, token_type="coin",
|
||||||
|
token_display="Coin", renewal_days=7,
|
||||||
|
)
|
||||||
|
record(
|
||||||
|
self.room, GameEvent.ROLE_SELECTED, actor=self.user,
|
||||||
|
role="PC", slot_number=1, role_display="Player",
|
||||||
|
)
|
||||||
|
# INVITE_SENT is unsupported — should be excluded from outbox
|
||||||
|
record(self.room, GameEvent.INVITE_SENT, actor=self.user)
|
||||||
|
|
||||||
|
def test_returns_200(self):
|
||||||
|
response = self.client.get("/ap/users/actor/outbox/")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
def test_returns_activity_json_content_type(self):
|
||||||
|
response = self.client.get("/ap/users/actor/outbox/")
|
||||||
|
self.assertEqual(response["Content-Type"], "application/activity+json")
|
||||||
|
|
||||||
|
def test_outbox_is_ordered_collection(self):
|
||||||
|
response = self.client.get("/ap/users/actor/outbox/")
|
||||||
|
data = json.loads(response.content)
|
||||||
|
self.assertEqual(data["type"], "OrderedCollection")
|
||||||
|
|
||||||
|
def test_total_items_excludes_unsupported_verbs(self):
|
||||||
|
response = self.client.get("/ap/users/actor/outbox/")
|
||||||
|
data = json.loads(response.content)
|
||||||
|
# 2 supported events (SLOT_FILLED + ROLE_SELECTED); INVITE_SENT excluded
|
||||||
|
self.assertEqual(data["totalItems"], 2)
|
||||||
|
|
||||||
|
def test_requires_no_authentication(self):
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.get("/ap/users/actor/outbox/")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
def test_returns_404_for_unknown_user(self):
|
||||||
|
response = self.client.get("/ap/users/nobody/outbox/")
|
||||||
|
self.assertEqual(response.status_code, 404)
|
||||||
0
src/apps/ap/tests/unit/__init__.py
Normal file
0
src/apps/ap/tests/unit/__init__.py
Normal file
88
src/apps/ap/tests/unit/test_activity.py
Normal file
88
src/apps/ap/tests/unit/test_activity.py
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from apps.drama.models import GameEvent, record
|
||||||
|
from apps.epic.models import Room
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
BASE = "https://earthmanrpg.me"
|
||||||
|
|
||||||
|
|
||||||
|
class ToActivityTest(TestCase):
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="actor@test.io", username="testactor")
|
||||||
|
self.room = Room.objects.create(name="Test Room", owner=self.user)
|
||||||
|
|
||||||
|
def _record(self, verb, **data):
|
||||||
|
return record(self.room, verb, actor=self.user, **data)
|
||||||
|
|
||||||
|
def test_slot_filled_returns_join_gate_activity(self):
|
||||||
|
event = self._record(
|
||||||
|
GameEvent.SLOT_FILLED,
|
||||||
|
slot_number=1, token_type="coin",
|
||||||
|
token_display="Coin", renewal_days=7,
|
||||||
|
)
|
||||||
|
activity = event.to_activity(BASE)
|
||||||
|
self.assertIsNotNone(activity)
|
||||||
|
self.assertEqual(activity["type"], "earthman:JoinGate")
|
||||||
|
|
||||||
|
def test_role_selected_returns_select_role_activity(self):
|
||||||
|
event = self._record(
|
||||||
|
GameEvent.ROLE_SELECTED,
|
||||||
|
role="PC", slot_number=1, role_display="Player",
|
||||||
|
)
|
||||||
|
activity = event.to_activity(BASE)
|
||||||
|
self.assertIsNotNone(activity)
|
||||||
|
self.assertEqual(activity["type"], "earthman:SelectRole")
|
||||||
|
|
||||||
|
def test_room_created_returns_create_activity(self):
|
||||||
|
event = self._record(GameEvent.ROOM_CREATED)
|
||||||
|
activity = event.to_activity(BASE)
|
||||||
|
self.assertIsNotNone(activity)
|
||||||
|
self.assertEqual(activity["type"], "Create")
|
||||||
|
|
||||||
|
def test_unsupported_verb_returns_none(self):
|
||||||
|
event = self._record(GameEvent.INVITE_SENT)
|
||||||
|
self.assertIsNone(event.to_activity(BASE))
|
||||||
|
|
||||||
|
def test_activity_contains_actor_url(self):
|
||||||
|
event = self._record(
|
||||||
|
GameEvent.ROLE_SELECTED,
|
||||||
|
role="PC", slot_number=1, role_display="Player",
|
||||||
|
)
|
||||||
|
activity = event.to_activity(BASE)
|
||||||
|
self.assertIn(BASE, activity["actor"])
|
||||||
|
|
||||||
|
def test_activity_contains_object_url(self):
|
||||||
|
event = self._record(
|
||||||
|
GameEvent.SLOT_FILLED,
|
||||||
|
slot_number=1, token_type="coin",
|
||||||
|
token_display="Coin", renewal_days=7,
|
||||||
|
)
|
||||||
|
activity = event.to_activity(BASE)
|
||||||
|
self.assertIn(str(self.room.id), activity["object"])
|
||||||
|
|
||||||
|
|
||||||
|
class EnsureKeypairTest(TestCase):
|
||||||
|
|
||||||
|
def test_ensure_keypair_populates_both_fields(self):
|
||||||
|
user = User.objects.create(email="keys@test.io")
|
||||||
|
self.assertEqual(user.ap_public_key, "")
|
||||||
|
self.assertEqual(user.ap_private_key, "")
|
||||||
|
user.ensure_keypair()
|
||||||
|
self.assertTrue(user.ap_public_key.startswith("-----BEGIN PUBLIC KEY-----"))
|
||||||
|
self.assertTrue(user.ap_private_key.startswith("-----BEGIN PRIVATE KEY-----"))
|
||||||
|
|
||||||
|
def test_ensure_keypair_persists_to_db(self):
|
||||||
|
user = User.objects.create(email="persist@test.io")
|
||||||
|
user.ensure_keypair()
|
||||||
|
refreshed = User.objects.get(pk=user.pk)
|
||||||
|
self.assertTrue(refreshed.ap_public_key.startswith("-----BEGIN PUBLIC KEY-----"))
|
||||||
|
|
||||||
|
def test_ensure_keypair_is_idempotent(self):
|
||||||
|
user = User.objects.create(email="idem@test.io")
|
||||||
|
user.ensure_keypair()
|
||||||
|
original_pub = user.ap_public_key
|
||||||
|
user.ensure_keypair()
|
||||||
|
self.assertEqual(user.ap_public_key, original_pub)
|
||||||
10
src/apps/ap/urls.py
Normal file
10
src/apps/ap/urls.py
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from . import views
|
||||||
|
|
||||||
|
app_name = "ap"
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("users/<str:username>/", views.actor, name="actor"),
|
||||||
|
path("users/<str:username>/outbox/", views.outbox, name="outbox"),
|
||||||
|
]
|
||||||
83
src/apps/ap/views.py
Normal file
83
src/apps/ap/views.py
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
|
from django.http import HttpResponse, JsonResponse
|
||||||
|
from django.shortcuts import get_object_or_404
|
||||||
|
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
AP_CONTEXT = [
|
||||||
|
"https://www.w3.org/ns/activitystreams",
|
||||||
|
{"earthman": "https://earthmanrpg.me/ns#"},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _base_url(request):
|
||||||
|
return f"{request.scheme}://{request.get_host()}"
|
||||||
|
|
||||||
|
|
||||||
|
def _ap_response(data):
|
||||||
|
return HttpResponse(
|
||||||
|
json.dumps(data),
|
||||||
|
content_type="application/activity+json",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def webfinger(request):
|
||||||
|
resource = request.GET.get("resource", "")
|
||||||
|
if not resource:
|
||||||
|
return HttpResponse(status=400)
|
||||||
|
# Expect acct:username@host
|
||||||
|
if not resource.startswith("acct:"):
|
||||||
|
return HttpResponse(status=400)
|
||||||
|
username = resource[len("acct:"):].split("@")[0]
|
||||||
|
user = get_object_or_404(User, username=username)
|
||||||
|
base = _base_url(request)
|
||||||
|
data = {
|
||||||
|
"subject": resource,
|
||||||
|
"links": [
|
||||||
|
{
|
||||||
|
"rel": "self",
|
||||||
|
"type": "application/activity+json",
|
||||||
|
"href": f"{base}/ap/users/{user.username}/",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
return HttpResponse(json.dumps(data), content_type="application/jrd+json")
|
||||||
|
|
||||||
|
|
||||||
|
def actor(request, username):
|
||||||
|
user = get_object_or_404(User, username=username)
|
||||||
|
user.ensure_keypair()
|
||||||
|
base = _base_url(request)
|
||||||
|
actor_url = f"{base}/ap/users/{username}/"
|
||||||
|
data = {
|
||||||
|
"@context": AP_CONTEXT,
|
||||||
|
"id": actor_url,
|
||||||
|
"type": "Person",
|
||||||
|
"preferredUsername": username,
|
||||||
|
"inbox": f"{actor_url}inbox/",
|
||||||
|
"outbox": f"{actor_url}outbox/",
|
||||||
|
"publicKey": {
|
||||||
|
"id": f"{actor_url}#main-key",
|
||||||
|
"owner": actor_url,
|
||||||
|
"publicKeyPem": user.ap_public_key,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return _ap_response(data)
|
||||||
|
|
||||||
|
|
||||||
|
def outbox(request, username):
|
||||||
|
user = get_object_or_404(User, username=username)
|
||||||
|
base = _base_url(request)
|
||||||
|
events = user.game_events.select_related("room").order_by("timestamp")
|
||||||
|
activities = [a for e in events if (a := e.to_activity(base)) is not None]
|
||||||
|
actor_url = f"{base}/ap/users/{username}/"
|
||||||
|
data = {
|
||||||
|
"@context": AP_CONTEXT,
|
||||||
|
"id": f"{actor_url}outbox/",
|
||||||
|
"type": "OrderedCollection",
|
||||||
|
"totalItems": len(activities),
|
||||||
|
"orderedItems": activities,
|
||||||
|
}
|
||||||
|
return _ap_response(data)
|
||||||
0
src/apps/api/__init__.py
Normal file
0
src/apps/api/__init__.py
Normal file
32
src/apps/api/serializers.py
Normal file
32
src/apps/api/serializers.py
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from apps.dashboard.models import Item, Note
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class ItemSerializer(serializers.ModelSerializer):
|
||||||
|
text = serializers.CharField()
|
||||||
|
|
||||||
|
def validate_text(self, value):
|
||||||
|
note = self.context["note"]
|
||||||
|
if note.item_set.filter(text=value).exists():
|
||||||
|
raise serializers.ValidationError("duplicate")
|
||||||
|
return value
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Item
|
||||||
|
fields = ["id", "text"]
|
||||||
|
|
||||||
|
class NoteSerializer(serializers.ModelSerializer):
|
||||||
|
name = serializers.ReadOnlyField()
|
||||||
|
url = serializers.CharField(source="get_absolute_url", read_only=True)
|
||||||
|
items = ItemSerializer(many=True, read_only=True, source="item_set")
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = Note
|
||||||
|
fields = ["id", "name", "url", "items"]
|
||||||
|
|
||||||
|
class UserSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ["id", "username"]
|
||||||
0
src/apps/api/tests/__init__.py
Normal file
0
src/apps/api/tests/__init__.py
Normal file
0
src/apps/api/tests/integrated/__init__.py
Normal file
0
src/apps/api/tests/integrated/__init__.py
Normal file
115
src/apps/api/tests/integrated/test_views.py
Normal file
115
src/apps/api/tests/integrated/test_views.py
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
from django.test import TestCase
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
from apps.dashboard.models import Item, Note
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
class BaseAPITest(TestCase):
|
||||||
|
# Helper fns
|
||||||
|
def setUp(self):
|
||||||
|
self.client = APIClient()
|
||||||
|
self.user = User.objects.create_user("test@example.com")
|
||||||
|
self.client.force_authenticate(user=self.user)
|
||||||
|
|
||||||
|
class NoteDetailAPITest(BaseAPITest):
|
||||||
|
def test_returns_note_with_items(self):
|
||||||
|
note = Note.objects.create(owner=self.user)
|
||||||
|
Item.objects.create(text="item 1", note=note)
|
||||||
|
Item.objects.create(text="item 2", note=note)
|
||||||
|
|
||||||
|
response = self.client.get(f"/api/notes/{note.id}/")
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response.data["id"], str(note.id))
|
||||||
|
self.assertEqual(len(response.data["items"]), 2)
|
||||||
|
|
||||||
|
class NoteItemsAPITest(BaseAPITest):
|
||||||
|
def test_can_add_item_to_note(self):
|
||||||
|
note = Note.objects.create(owner=self.user)
|
||||||
|
|
||||||
|
response = self.client.post(
|
||||||
|
f"/api/notes/{note.id}/items/",
|
||||||
|
{"text": "a new item"},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
self.assertEqual(Item.objects.count(), 1)
|
||||||
|
self.assertEqual(Item.objects.first().text, "a new item")
|
||||||
|
|
||||||
|
def test_cannot_add_empty_item_to_note(self):
|
||||||
|
note = Note.objects.create(owner=self.user)
|
||||||
|
|
||||||
|
response = self.client.post(
|
||||||
|
f"/api/notes/{note.id}/items/",
|
||||||
|
{"text": ""},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 400)
|
||||||
|
self.assertEqual(Item.objects.count(), 0)
|
||||||
|
|
||||||
|
def test_cannot_add_duplicate_item_to_note(self):
|
||||||
|
note = Note.objects.create(owner=self.user)
|
||||||
|
Item.objects.create(text="note item", note=note)
|
||||||
|
duplicate_response = self.client.post(
|
||||||
|
f"/api/notes/{note.id}/items/",
|
||||||
|
{"text": "note item"},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(duplicate_response.status_code, 400)
|
||||||
|
self.assertEqual(Item.objects.count(), 1)
|
||||||
|
|
||||||
|
class NotesAPITest(BaseAPITest):
|
||||||
|
def test_get_returns_only_users_notes(self):
|
||||||
|
note1 = Note.objects.create(owner=self.user)
|
||||||
|
Item.objects.create(text="item 1", note=note1)
|
||||||
|
other_user = User.objects.create_user("other@example.com")
|
||||||
|
Note.objects.create(owner=other_user)
|
||||||
|
|
||||||
|
response = self.client.get("/api/notes/")
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(len(response.data), 1)
|
||||||
|
self.assertEqual(response.data[0]["id"], str(note1.id))
|
||||||
|
|
||||||
|
def test_post_creates_note_with_item(self):
|
||||||
|
response = self.client.post(
|
||||||
|
"/api/notes/",
|
||||||
|
{"text": "first item"},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
self.assertEqual(Note.objects.count(), 1)
|
||||||
|
self.assertEqual(Note.objects.first().owner, self.user)
|
||||||
|
self.assertEqual(Item.objects.first().text, "first item")
|
||||||
|
|
||||||
|
class UserSearchAPITest(BaseAPITest):
|
||||||
|
def test_returns_users_matching_username(self):
|
||||||
|
disco = User.objects.create_user("disco@example.com")
|
||||||
|
disco.username = "discoman"
|
||||||
|
disco.searchable = True
|
||||||
|
disco.save()
|
||||||
|
|
||||||
|
response = self.client.get("/api/users/?q=disc")
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(len(response.data), 1)
|
||||||
|
self.assertEqual(response.data[0]["username"], "discoman")
|
||||||
|
|
||||||
|
def test_non_searchable_users_are_excluded(self):
|
||||||
|
alice = User.objects.create_user("alice@example.com")
|
||||||
|
alice.username = "princessAli"
|
||||||
|
alice.save() # searchable defaults to False
|
||||||
|
|
||||||
|
response = self.client.get("/api/users/?q=prin")
|
||||||
|
|
||||||
|
self.assertEqual(response.data, [])
|
||||||
|
|
||||||
|
def test_response_does_not_include_email(self):
|
||||||
|
alice = User.objects.create_user("alice@example.com")
|
||||||
|
alice.username = "princessAli"
|
||||||
|
alice.searchable = True
|
||||||
|
alice.save()
|
||||||
|
|
||||||
|
response = self.client.get("/api/users/?q=prin")
|
||||||
|
|
||||||
|
self.assertNotIn("email", response.data[0])
|
||||||
0
src/apps/api/tests/unit/__init__.py
Normal file
0
src/apps/api/tests/unit/__init__.py
Normal file
19
src/apps/api/tests/unit/test_serializers.py
Normal file
19
src/apps/api/tests/unit/test_serializers.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from django.test import SimpleTestCase
|
||||||
|
from apps.api.serializers import ItemSerializer, NoteSerializer
|
||||||
|
|
||||||
|
|
||||||
|
class ItemSerializerTest(SimpleTestCase):
|
||||||
|
def test_fields(self):
|
||||||
|
serializer = ItemSerializer()
|
||||||
|
self.assertEqual(
|
||||||
|
set(serializer.fields.keys()),
|
||||||
|
{"id", "text"},
|
||||||
|
)
|
||||||
|
|
||||||
|
class NoteSerializerTest(SimpleTestCase):
|
||||||
|
def test_fields(self):
|
||||||
|
serializer = NoteSerializer()
|
||||||
|
self.assertEqual(
|
||||||
|
set(serializer.fields.keys()),
|
||||||
|
{"id", "name", "url", "items"},
|
||||||
|
)
|
||||||
11
src/apps/api/urls.py
Normal file
11
src/apps/api/urls.py
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from . import views
|
||||||
|
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path('notes/', views.NotesAPI.as_view(), name='api_notes'),
|
||||||
|
path('notes/<uuid:note_id>/', views.NoteDetailAPI.as_view(), name='api_note_detail'),
|
||||||
|
path('notes/<uuid:note_id>/items/', views.NoteItemsAPI.as_view(), name='api_note_items'),
|
||||||
|
path('users/', views.UserSearchAPI.as_view(), name='api_users'),
|
||||||
|
]
|
||||||
45
src/apps/api/views.py
Normal file
45
src/apps/api/views.py
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
from django.shortcuts import get_object_or_404
|
||||||
|
from rest_framework.views import APIView
|
||||||
|
from rest_framework.response import Response
|
||||||
|
|
||||||
|
from apps.api.serializers import ItemSerializer, NoteSerializer, UserSerializer
|
||||||
|
from apps.dashboard.models import Item, Note
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class NoteDetailAPI(APIView):
|
||||||
|
def get(self, request, note_id):
|
||||||
|
note = get_object_or_404(Note, id=note_id)
|
||||||
|
serializer = NoteSerializer(note)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
class NoteItemsAPI(APIView):
|
||||||
|
def post(self, request, note_id):
|
||||||
|
note = get_object_or_404(Note, id=note_id)
|
||||||
|
serializer = ItemSerializer(data=request.data, context={"note": note})
|
||||||
|
if serializer.is_valid():
|
||||||
|
serializer.save(note=note)
|
||||||
|
return Response(serializer.data, status=201)
|
||||||
|
return Response(serializer.errors, status=400)
|
||||||
|
|
||||||
|
class NotesAPI(APIView):
|
||||||
|
def get(self, request):
|
||||||
|
notes = Note.objects.filter(owner=request.user)
|
||||||
|
serializer = NoteSerializer(notes, many=True)
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
def post(self, request):
|
||||||
|
note = Note.objects.create(owner=request.user)
|
||||||
|
item = Item.objects.create(text=request.data.get("text", ""), note=note)
|
||||||
|
serializer = NoteSerializer(note)
|
||||||
|
return Response(serializer.data, status=201)
|
||||||
|
|
||||||
|
class UserSearchAPI(APIView):
|
||||||
|
def get(self, request):
|
||||||
|
q = request.query_params.get("q", "")
|
||||||
|
users = User.objects.filter(
|
||||||
|
username__icontains=q,
|
||||||
|
searchable=True,
|
||||||
|
)
|
||||||
|
serializer = UserSerializer(users, many=True)
|
||||||
|
return Response(serializer.data)
|
||||||
0
src/apps/applets/__init__.py
Normal file
0
src/apps/applets/__init__.py
Normal file
11
src/apps/applets/admin.py
Normal file
11
src/apps/applets/admin.py
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
from apps.applets.models import Applet, UserApplet
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(Applet)
|
||||||
|
class AppletAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ['slug', 'name', 'default_visible', 'grid_cols', 'grid_rows']
|
||||||
|
list_editable = ['grid_cols', 'grid_rows']
|
||||||
|
|
||||||
|
admin.site.register(UserApplet)
|
||||||
5
src/apps/applets/apps.py
Normal file
5
src/apps/applets/apps.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class AppletsConfig(AppConfig):
|
||||||
|
name = 'apps.applets'
|
||||||
36
src/apps/applets/migrations/0001_initial.py
Normal file
36
src/apps/applets/migrations/0001_initial.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
initial = True
|
||||||
|
dependencies = [
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='Applet',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('slug', models.SlugField(unique=True)),
|
||||||
|
('name', models.CharField(max_length=100)),
|
||||||
|
('context', models.CharField(choices=[('dashboard', 'Dashboard'), ('gameboard', 'Gameboard')], default='dashboard', max_length=20)),
|
||||||
|
('default_visible', models.BooleanField(default=True)),
|
||||||
|
('grid_cols', models.PositiveSmallIntegerField(default=12)),
|
||||||
|
('grid_rows', models.PositiveSmallIntegerField(default=3)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='UserApplet',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('visible', models.BooleanField(default=True)),
|
||||||
|
('applet', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='applets.applet')),
|
||||||
|
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_applets', to=settings.AUTH_USER_MODEL)),
|
||||||
|
],
|
||||||
|
options={'unique_together': {('user', 'applet')}},
|
||||||
|
),
|
||||||
|
]
|
||||||
29
src/apps/applets/migrations/0002_seed_applets.py
Normal file
29
src/apps/applets/migrations/0002_seed_applets.py
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
def seed_applets(apps, schema_editor):
|
||||||
|
Applet = apps.get_model('applets', 'Applet')
|
||||||
|
for slug, name, cols, rows, context in [
|
||||||
|
('wallet', 'Wallet', 12, 3, 'dashboard'),
|
||||||
|
('new-list', 'New List', 9, 3, 'dashboard'),
|
||||||
|
('my-lists', 'My Lists', 3, 3, 'dashboard'),
|
||||||
|
('username', 'Username', 6, 3, 'dashboard'),
|
||||||
|
('palette', 'Palette', 6, 3, 'dashboard'),
|
||||||
|
('new-game', 'New Game', 4, 2, 'gameboard'),
|
||||||
|
('my-games', 'My Games', 4, 4, 'gameboard'),
|
||||||
|
('game-kit', 'Game Kit', 4, 2, 'gameboard'),
|
||||||
|
]:
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug=slug,
|
||||||
|
defaults={'name': name, 'grid_cols': cols, 'grid_rows': rows, 'context': context},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
('applets', '0001_initial')
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(seed_applets, migrations.RunPython.noop)
|
||||||
|
]
|
||||||
37
src/apps/applets/migrations/0003_wallet_applets.py
Normal file
37
src/apps/applets/migrations/0003_wallet_applets.py
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
def seed_wallet_applets(apps, schema_editor):
|
||||||
|
Applet = apps.get_model('applets', 'Applet')
|
||||||
|
for slug, name, cols, rows in [
|
||||||
|
('wallet-balances', 'Wallet Balances', 3, 3),
|
||||||
|
('wallet-tokens', 'Wallet Tokens', 3, 3),
|
||||||
|
('wallet-payment', 'Payment Methods', 6, 2),
|
||||||
|
]:
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug=slug,
|
||||||
|
defaults={'name': name, 'grid_cols': cols, 'grid_rows': rows, 'context': 'wallet'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
('applets', '0002_seed_applets'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='applet',
|
||||||
|
name='context',
|
||||||
|
field=models.CharField(
|
||||||
|
choices=[
|
||||||
|
('dashboard', 'Dashboard'),
|
||||||
|
('gameboard', 'Gameboard'),
|
||||||
|
('wallet', 'Wallet'),
|
||||||
|
],
|
||||||
|
default='dashboard',
|
||||||
|
max_length=20,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.RunPython(seed_wallet_applets, migrations.RunPython.noop),
|
||||||
|
]
|
||||||
24
src/apps/applets/migrations/0004_rename_list_applet_slugs.py
Normal file
24
src/apps/applets/migrations/0004_rename_list_applet_slugs.py
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
def rename_list_slugs(apps, schema_editor):
|
||||||
|
Applet = apps.get_model('applets', 'Applet')
|
||||||
|
Applet.objects.filter(slug='new-list').update(slug='new-note', name='New Note')
|
||||||
|
Applet.objects.filter(slug='my-lists').update(slug='my-notes', name='My Notes')
|
||||||
|
|
||||||
|
|
||||||
|
def reverse_rename_list_slugs(apps, schema_editor):
|
||||||
|
Applet = apps.get_model('applets', 'Applet')
|
||||||
|
Applet.objects.filter(slug='new-note').update(slug='new-list', name='New List')
|
||||||
|
Applet.objects.filter(slug='my-notes').update(slug='my-lists', name='My Lists')
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('applets', '0003_wallet_applets'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(rename_list_slugs, reverse_rename_list_slugs),
|
||||||
|
]
|
||||||
24
src/apps/applets/migrations/0005_gameboard_applet_heights.py
Normal file
24
src/apps/applets/migrations/0005_gameboard_applet_heights.py
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
def increase_gameboard_applet_heights(apps, schema_editor):
|
||||||
|
Applet = apps.get_model('applets', 'Applet')
|
||||||
|
Applet.objects.filter(slug__in=['new-game', 'game-kit', 'wallet-payment']).update(grid_rows=3)
|
||||||
|
|
||||||
|
|
||||||
|
def revert_gameboard_applet_heights(apps, schema_editor):
|
||||||
|
Applet = apps.get_model('applets', 'Applet')
|
||||||
|
Applet.objects.filter(slug__in=['new-game', 'game-kit', 'wallet-payment']).update(grid_rows=2)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
('applets', '0004_rename_list_applet_slugs')
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(
|
||||||
|
increase_gameboard_applet_heights,
|
||||||
|
revert_gameboard_applet_heights,
|
||||||
|
)
|
||||||
|
]
|
||||||
48
src/apps/applets/migrations/0006_billboard_applets.py
Normal file
48
src/apps/applets/migrations/0006_billboard_applets.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
def seed_billboard_applets(apps, schema_editor):
|
||||||
|
Applet = apps.get_model("applets", "Applet")
|
||||||
|
for slug, name, cols, rows in [
|
||||||
|
("billboard-my-scrolls", "My Scrolls", 4, 3),
|
||||||
|
("billboard-my-contacts", "Contacts", 4, 3),
|
||||||
|
("billboard-most-recent", "Most Recent", 8, 6),
|
||||||
|
]:
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug=slug,
|
||||||
|
defaults={"name": name, "grid_cols": cols, "grid_rows": rows, "context": "billboard"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_billboard_applets(apps, schema_editor):
|
||||||
|
Applet = apps.get_model("applets", "Applet")
|
||||||
|
Applet.objects.filter(slug__in=[
|
||||||
|
"billboard-my-scrolls",
|
||||||
|
"billboard-my-contacts",
|
||||||
|
"billboard-most-recent",
|
||||||
|
]).delete()
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("applets", "0005_gameboard_applet_heights"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name="applet",
|
||||||
|
name="context",
|
||||||
|
field=models.CharField(
|
||||||
|
choices=[
|
||||||
|
("dashboard", "Dashboard"),
|
||||||
|
("gameboard", "Gameboard"),
|
||||||
|
("wallet", "Wallet"),
|
||||||
|
("billboard", "Billboard"),
|
||||||
|
],
|
||||||
|
default="dashboard",
|
||||||
|
max_length=20,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
migrations.RunPython(seed_billboard_applets, remove_billboard_applets),
|
||||||
|
]
|
||||||
29
src/apps/applets/migrations/0007_fix_billboard_applets.py
Normal file
29
src/apps/applets/migrations/0007_fix_billboard_applets.py
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
def fix_billboard_applets(apps, schema_editor):
|
||||||
|
Applet = apps.get_model("applets", "Applet")
|
||||||
|
# billboard-scroll belongs only to the billscroll page template, not the grid
|
||||||
|
Applet.objects.filter(slug="billboard-scroll").delete()
|
||||||
|
# Rename "My Contacts" → "Contacts"
|
||||||
|
Applet.objects.filter(slug="billboard-my-contacts").update(name="Contacts")
|
||||||
|
|
||||||
|
|
||||||
|
def reverse_fix_billboard_applets(apps, schema_editor):
|
||||||
|
Applet = apps.get_model("applets", "Applet")
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug="billboard-scroll",
|
||||||
|
defaults={"name": "Billscroll", "grid_cols": 12, "grid_rows": 6, "context": "billboard"},
|
||||||
|
)
|
||||||
|
Applet.objects.filter(slug="billboard-my-contacts").update(name="My Contacts")
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
("applets", "0006_billboard_applets"),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(fix_billboard_applets, reverse_fix_billboard_applets),
|
||||||
|
]
|
||||||
25
src/apps/applets/migrations/0008_game_kit_applets.py
Normal file
25
src/apps/applets/migrations/0008_game_kit_applets.py
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
def seed_game_kit_applets(apps, schema_editor):
|
||||||
|
Applet = apps.get_model('applets', 'Applet')
|
||||||
|
for slug, name in [
|
||||||
|
('gk-trinkets', 'Trinkets'),
|
||||||
|
('gk-tokens', 'Tokens'),
|
||||||
|
('gk-decks', 'Card Decks'),
|
||||||
|
('gk-dice', 'Dice Sets'),
|
||||||
|
]:
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug=slug,
|
||||||
|
defaults={'name': name, 'grid_cols': 3, 'grid_rows': 3, 'context': 'game-kit'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
('applets', '0007_fix_billboard_applets'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RunPython(seed_game_kit_applets, migrations.RunPython.noop)
|
||||||
|
]
|
||||||
0
src/apps/applets/migrations/__init__.py
Normal file
0
src/apps/applets/migrations/__init__.py
Normal file
38
src/apps/applets/models.py
Normal file
38
src/apps/applets/models.py
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
from django.db import models
|
||||||
|
|
||||||
|
class Applet(models.Model):
|
||||||
|
DASHBOARD = "dashboard"
|
||||||
|
GAMEBOARD = "gameboard"
|
||||||
|
WALLET = "wallet"
|
||||||
|
BILLBOARD = "billboard"
|
||||||
|
CONTEXT_CHOICES = [
|
||||||
|
(DASHBOARD, "Dashboard"),
|
||||||
|
(GAMEBOARD, "Gameboard"),
|
||||||
|
(WALLET, "Wallet"),
|
||||||
|
(BILLBOARD, "Billboard"),
|
||||||
|
]
|
||||||
|
|
||||||
|
slug = models.SlugField(unique=True)
|
||||||
|
name = models.CharField(max_length=100)
|
||||||
|
context = models.CharField(max_length=20, choices=CONTEXT_CHOICES, default=DASHBOARD)
|
||||||
|
default_visible = models.BooleanField(default=True)
|
||||||
|
grid_cols = models.PositiveSmallIntegerField(default=12)
|
||||||
|
grid_rows = models.PositiveSmallIntegerField(default=3)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.name
|
||||||
|
|
||||||
|
class UserApplet(models.Model):
|
||||||
|
user = models.ForeignKey(
|
||||||
|
"lyric.User",
|
||||||
|
related_name="user_applets",
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
)
|
||||||
|
applet = models.ForeignKey(
|
||||||
|
Applet,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
)
|
||||||
|
visible = models.BooleanField(default=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
unique_together = ("user", "applet")
|
||||||
42
src/apps/applets/static/apps/applets/applets.js
Normal file
42
src/apps/applets/static/apps/applets/applets.js
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
const initGearMenus = () => {
|
||||||
|
document.querySelectorAll('.gear-btn').forEach(gear => {
|
||||||
|
const menuId = gear.dataset.menuTarget;
|
||||||
|
|
||||||
|
gear.addEventListener('click', (e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
const menu = document.getElementById(menuId);
|
||||||
|
if (!menu) return;
|
||||||
|
const opening = menu.style.display === 'none' || menu.style.display === '';
|
||||||
|
menu.style.display = opening ? 'block' : 'none';
|
||||||
|
gear.classList.toggle('active', opening);
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('click', (e) => {
|
||||||
|
const menu = document.getElementById(menuId);
|
||||||
|
if (!menu || menu.style.display === 'none') return;
|
||||||
|
if (e.target.closest('.applet-menu-cancel') || !menu.contains(e.target)) {
|
||||||
|
menu.style.display = 'none';
|
||||||
|
gear.classList.remove('active');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
})
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', initGearMenus);
|
||||||
|
|
||||||
|
const appletContainerIds = new Set([
|
||||||
|
'id_applets_container',
|
||||||
|
'id_game_applets_container',
|
||||||
|
'id_gk_sections_container',
|
||||||
|
'id_wallet_applets_container',
|
||||||
|
]);
|
||||||
|
|
||||||
|
document.body.addEventListener('htmx:afterSwap', (e) => {
|
||||||
|
if (!e.detail.target || !appletContainerIds.has(e.detail.target.id)) return;
|
||||||
|
document.querySelectorAll('.gear-btn').forEach(gear => {
|
||||||
|
const menu = document.getElementById(gear.dataset.menuTarget);
|
||||||
|
if (menu) menu.style.display = 'none';
|
||||||
|
gear.classList.remove('active');
|
||||||
|
});
|
||||||
|
});
|
||||||
0
src/apps/applets/tests/__init__.py
Normal file
0
src/apps/applets/tests/__init__.py
Normal file
0
src/apps/applets/tests/integrated/__init__.py
Normal file
0
src/apps/applets/tests/integrated/__init__.py
Normal file
65
src/apps/applets/tests/integrated/test_models.py
Normal file
65
src/apps/applets/tests/integrated/test_models.py
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
from django.db.utils import IntegrityError
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from apps.applets.models import Applet, UserApplet
|
||||||
|
from apps.applets.utils import applet_context
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class AppletModelTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.applet = Applet.objects.create(
|
||||||
|
slug="my-applet", name="My Applet", default_visible=True
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_applet_can_be_created(self):
|
||||||
|
self.assertEqual(Applet.objects.get(slug="my-applet"), self.applet)
|
||||||
|
|
||||||
|
def test_applet_slug_is_unique(self):
|
||||||
|
with self.assertRaises(IntegrityError):
|
||||||
|
Applet.objects.create(slug="my-applet", name="Second")
|
||||||
|
|
||||||
|
def test_applet_str(self):
|
||||||
|
self.assertEqual(str(self.applet), "My Applet")
|
||||||
|
|
||||||
|
def test_applet_grid_defaults(self):
|
||||||
|
self.assertEqual(self.applet.grid_cols, 12)
|
||||||
|
self.assertEqual(self.applet.grid_rows, 3)
|
||||||
|
|
||||||
|
|
||||||
|
class UserAppletModelTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="a@b.cde")
|
||||||
|
self.applet, _ = Applet.objects.get_or_create(slug="username", defaults={"name": "Username"})
|
||||||
|
|
||||||
|
def test_user_applet_links_user_to_applet(self):
|
||||||
|
ua = UserApplet.objects.create(user=self.user, applet=self.applet, visible=True)
|
||||||
|
self.assertIn(ua, self.user.user_applets.all())
|
||||||
|
|
||||||
|
def test_user_applet_unique_per_user_and_applet(self):
|
||||||
|
UserApplet.objects.create(user=self.user, applet=self.applet, visible=True)
|
||||||
|
with self.assertRaises(IntegrityError):
|
||||||
|
UserApplet.objects.create(user=self.user, applet=self.applet, visible=False)
|
||||||
|
|
||||||
|
class AppletContextTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="a@b.cde")
|
||||||
|
self.dash_applet, _ = Applet.objects.get_or_create(slug="username", defaults={"name": "Username", "context": "dashboard"})
|
||||||
|
self.game_applet, _ = Applet.objects.get_or_create(slug="new-game", defaults={"name": "New Game", "context": "gameboard"})
|
||||||
|
|
||||||
|
def test_filters_by_context(self):
|
||||||
|
result = applet_context(self.user, "dashboard")
|
||||||
|
slugs = [e["applet"].slug for e in result]
|
||||||
|
self.assertIn("username", slugs)
|
||||||
|
self.assertNotIn("new-game", slugs)
|
||||||
|
|
||||||
|
def test_defaults_to_applet_default_visible(self):
|
||||||
|
result = applet_context(self.user, "dashboard")
|
||||||
|
[entry] = [e for e in result if e["applet"].slug == "username"]
|
||||||
|
self.assertTrue(entry["visible"])
|
||||||
|
|
||||||
|
def test_respects_user_applet_visible_false(self):
|
||||||
|
UserApplet.objects.create(user=self.user, applet=self.dash_applet, visible=False)
|
||||||
|
result = applet_context(self.user, "dashboard")
|
||||||
|
[entry] = [e for e in result if e["applet"].slug == "username"]
|
||||||
|
self.assertFalse(entry["visible"])
|
||||||
11
src/apps/applets/utils.py
Normal file
11
src/apps/applets/utils.py
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
from apps.applets.models import Applet, UserApplet
|
||||||
|
|
||||||
|
|
||||||
|
def applet_context(user, context):
|
||||||
|
ua_map = {ua.applet_id: ua.visible for ua in user.user_applets.all()}
|
||||||
|
applets = {a.slug: a for a in Applet.objects.filter(context=context)}
|
||||||
|
return [
|
||||||
|
{"applet": applets[slug], "visible": ua_map.get(applets[slug].pk, applets[slug].default_visible)}
|
||||||
|
for slug in applets
|
||||||
|
if slug in applets
|
||||||
|
]
|
||||||
0
src/apps/billboard/__init__.py
Normal file
0
src/apps/billboard/__init__.py
Normal file
6
src/apps/billboard/apps.py
Normal file
6
src/apps/billboard/apps.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class BillboardConfig(AppConfig):
|
||||||
|
default_auto_field = 'django.db.models.BigAutoField'
|
||||||
|
name = 'apps.billboard'
|
||||||
0
src/apps/billboard/tests/__init__.py
Normal file
0
src/apps/billboard/tests/__init__.py
Normal file
0
src/apps/billboard/tests/integrated/__init__.py
Normal file
0
src/apps/billboard/tests/integrated/__init__.py
Normal file
189
src/apps/billboard/tests/integrated/test_views.py
Normal file
189
src/apps/billboard/tests/integrated/test_views.py
Normal file
@@ -0,0 +1,189 @@
|
|||||||
|
from django.test import TestCase
|
||||||
|
from django.urls import reverse
|
||||||
|
|
||||||
|
from apps.applets.models import Applet
|
||||||
|
from apps.drama.models import GameEvent, ScrollPosition, record
|
||||||
|
from apps.epic.models import Room
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_billboard_applets():
|
||||||
|
for slug, name, cols, rows in [
|
||||||
|
("billboard-my-scrolls", "My Scrolls", 4, 3),
|
||||||
|
("billboard-my-contacts", "Contacts", 4, 3),
|
||||||
|
("billboard-most-recent", "Most Recent", 8, 6),
|
||||||
|
]:
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug=slug,
|
||||||
|
defaults={"name": name, "grid_cols": cols, "grid_rows": rows, "context": "billboard"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class BillboardViewTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="test@billboard.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
_seed_billboard_applets()
|
||||||
|
|
||||||
|
def test_uses_billboard_template(self):
|
||||||
|
response = self.client.get("/billboard/")
|
||||||
|
self.assertTemplateUsed(response, "apps/billboard/billboard.html")
|
||||||
|
|
||||||
|
def test_passes_applets_context(self):
|
||||||
|
response = self.client.get("/billboard/")
|
||||||
|
self.assertIn("applets", response.context)
|
||||||
|
slugs = [e["applet"].slug for e in response.context["applets"]]
|
||||||
|
self.assertIn("billboard-my-scrolls", slugs)
|
||||||
|
self.assertIn("billboard-my-contacts", slugs)
|
||||||
|
self.assertIn("billboard-most-recent", slugs)
|
||||||
|
|
||||||
|
def test_passes_my_rooms_context(self):
|
||||||
|
room = Room.objects.create(name="Test Room", owner=self.user)
|
||||||
|
response = self.client.get("/billboard/")
|
||||||
|
self.assertIn(room, response.context["my_rooms"])
|
||||||
|
|
||||||
|
def test_passes_recent_room_and_events(self):
|
||||||
|
room = Room.objects.create(name="Test Room", owner=self.user)
|
||||||
|
record(
|
||||||
|
room, GameEvent.SLOT_FILLED, actor=self.user,
|
||||||
|
slot_number=1, token_type="coin",
|
||||||
|
token_display="Coin-on-a-String", renewal_days=7,
|
||||||
|
)
|
||||||
|
response = self.client.get("/billboard/")
|
||||||
|
self.assertEqual(response.context["recent_room"], room)
|
||||||
|
self.assertEqual(len(response.context["recent_events"]), 1)
|
||||||
|
|
||||||
|
def test_recent_events_capped_at_36(self):
|
||||||
|
room = Room.objects.create(name="Test Room", owner=self.user)
|
||||||
|
for i in range(40):
|
||||||
|
record(
|
||||||
|
room, GameEvent.SLOT_FILLED, actor=self.user,
|
||||||
|
slot_number=1, token_type="coin",
|
||||||
|
token_display="Coin-on-a-String", renewal_days=7,
|
||||||
|
)
|
||||||
|
response = self.client.get("/billboard/")
|
||||||
|
self.assertEqual(len(response.context["recent_events"]), 36)
|
||||||
|
|
||||||
|
def test_recent_events_in_chronological_order(self):
|
||||||
|
room = Room.objects.create(name="Test Room", owner=self.user)
|
||||||
|
for _ in range(3):
|
||||||
|
record(
|
||||||
|
room, GameEvent.SLOT_FILLED, actor=self.user,
|
||||||
|
slot_number=1, token_type="coin",
|
||||||
|
token_display="Coin-on-a-String", renewal_days=7,
|
||||||
|
)
|
||||||
|
response = self.client.get("/billboard/")
|
||||||
|
events = response.context["recent_events"]
|
||||||
|
timestamps = [e.timestamp for e in events]
|
||||||
|
self.assertEqual(timestamps, sorted(timestamps))
|
||||||
|
|
||||||
|
def test_recent_room_is_none_when_no_events(self):
|
||||||
|
response = self.client.get("/billboard/")
|
||||||
|
self.assertIsNone(response.context["recent_room"])
|
||||||
|
self.assertEqual(list(response.context["recent_events"]), [])
|
||||||
|
|
||||||
|
|
||||||
|
class ToggleBillboardAppletsTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="test@toggle.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
_seed_billboard_applets()
|
||||||
|
|
||||||
|
def test_toggle_hides_unchecked_applets(self):
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("billboard:toggle_applets"),
|
||||||
|
{"applets": ["billboard-my-scrolls"]},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 302)
|
||||||
|
from apps.applets.models import UserApplet
|
||||||
|
contacts = Applet.objects.get(slug="billboard-my-contacts")
|
||||||
|
ua = UserApplet.objects.get(user=self.user, applet=contacts)
|
||||||
|
self.assertFalse(ua.visible)
|
||||||
|
|
||||||
|
def test_toggle_returns_partial_on_htmx(self):
|
||||||
|
response = self.client.post(
|
||||||
|
reverse("billboard:toggle_applets"),
|
||||||
|
{"applets": ["billboard-my-scrolls"]},
|
||||||
|
HTTP_HX_REQUEST="true",
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertTemplateUsed(response, "apps/billboard/_partials/_applets.html")
|
||||||
|
|
||||||
|
|
||||||
|
class BillscrollViewTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="test@billscroll.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
self.room = Room.objects.create(name="Test Room", owner=self.user)
|
||||||
|
record(
|
||||||
|
self.room, GameEvent.SLOT_FILLED, actor=self.user,
|
||||||
|
slot_number=1, token_type="coin",
|
||||||
|
token_display="Coin-on-a-String", renewal_days=7,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_uses_room_scroll_template(self):
|
||||||
|
response = self.client.get(f"/billboard/room/{self.room.id}/scroll/")
|
||||||
|
self.assertTemplateUsed(response, "apps/billboard/room_scroll.html")
|
||||||
|
|
||||||
|
def test_passes_events_context(self):
|
||||||
|
response = self.client.get(f"/billboard/room/{self.room.id}/scroll/")
|
||||||
|
self.assertIn("events", response.context)
|
||||||
|
self.assertEqual(response.context["events"].count(), 1)
|
||||||
|
|
||||||
|
def test_passes_page_class_billscroll(self):
|
||||||
|
response = self.client.get(f"/billboard/room/{self.room.id}/scroll/")
|
||||||
|
self.assertEqual(response.context["page_class"], "page-billscroll")
|
||||||
|
|
||||||
|
def test_passes_scroll_position_zero_when_none_saved(self):
|
||||||
|
response = self.client.get(f"/billboard/room/{self.room.id}/scroll/")
|
||||||
|
self.assertEqual(response.context["scroll_position"], 0)
|
||||||
|
|
||||||
|
def test_passes_saved_scroll_position_in_context(self):
|
||||||
|
ScrollPosition.objects.create(user=self.user, room=self.room, position=250)
|
||||||
|
response = self.client.get(f"/billboard/room/{self.room.id}/scroll/")
|
||||||
|
self.assertEqual(response.context["scroll_position"], 250)
|
||||||
|
|
||||||
|
def test_scroll_renders_event_body_and_time_columns(self):
|
||||||
|
response = self.client.get(f"/billboard/room/{self.room.id}/scroll/")
|
||||||
|
self.assertContains(response, 'class="drama-event-body"')
|
||||||
|
self.assertContains(response, 'class="drama-event-time"')
|
||||||
|
|
||||||
|
|
||||||
|
class SaveScrollPositionTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="test@savescroll.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
self.room = Room.objects.create(name="Test Room", owner=self.user)
|
||||||
|
|
||||||
|
def test_post_saves_scroll_position(self):
|
||||||
|
self.client.post(
|
||||||
|
f"/billboard/room/{self.room.id}/scroll-position/",
|
||||||
|
{"position": 300},
|
||||||
|
)
|
||||||
|
sp = ScrollPosition.objects.get(user=self.user, room=self.room)
|
||||||
|
self.assertEqual(sp.position, 300)
|
||||||
|
|
||||||
|
def test_post_updates_existing_position(self):
|
||||||
|
ScrollPosition.objects.create(user=self.user, room=self.room, position=100)
|
||||||
|
self.client.post(
|
||||||
|
f"/billboard/room/{self.room.id}/scroll-position/",
|
||||||
|
{"position": 450},
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
ScrollPosition.objects.get(user=self.user, room=self.room).position, 450
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_post_returns_204(self):
|
||||||
|
response = self.client.post(
|
||||||
|
f"/billboard/room/{self.room.id}/scroll-position/",
|
||||||
|
{"position": 100},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 204)
|
||||||
|
|
||||||
|
def test_post_requires_login(self):
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.post(
|
||||||
|
f"/billboard/room/{self.room.id}/scroll-position/",
|
||||||
|
{"position": 100},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 302)
|
||||||
12
src/apps/billboard/urls.py
Normal file
12
src/apps/billboard/urls.py
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
from django.urls import path
|
||||||
|
|
||||||
|
from apps.billboard import views
|
||||||
|
|
||||||
|
app_name = "billboard"
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("", views.billboard, name="billboard"),
|
||||||
|
path("toggle-applets", views.toggle_billboard_applets, name="toggle_applets"),
|
||||||
|
path("room/<uuid:room_id>/scroll/", views.room_scroll, name="scroll"),
|
||||||
|
path("room/<uuid:room_id>/scroll-position/", views.save_scroll_position, name="save_scroll_position"),
|
||||||
|
]
|
||||||
86
src/apps/billboard/views.py
Normal file
86
src/apps/billboard/views.py
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
from django.contrib.auth.decorators import login_required
|
||||||
|
from django.db.models import Max, Q
|
||||||
|
from django.shortcuts import redirect, render
|
||||||
|
|
||||||
|
from apps.applets.models import Applet, UserApplet
|
||||||
|
from apps.applets.utils import applet_context
|
||||||
|
from apps.drama.models import GameEvent, ScrollPosition
|
||||||
|
from apps.epic.models import GateSlot, Room, RoomInvite
|
||||||
|
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def billboard(request):
|
||||||
|
my_rooms = Room.objects.filter(
|
||||||
|
Q(owner=request.user) |
|
||||||
|
Q(gate_slots__gamer=request.user) |
|
||||||
|
Q(invites__invitee_email=request.user.email, invites__status=RoomInvite.PENDING)
|
||||||
|
).distinct().order_by("-created_at")
|
||||||
|
|
||||||
|
recent_room = (
|
||||||
|
Room.objects.filter(
|
||||||
|
Q(owner=request.user) | Q(gate_slots__gamer=request.user)
|
||||||
|
)
|
||||||
|
.annotate(last_event=Max("events__timestamp"))
|
||||||
|
.filter(last_event__isnull=False)
|
||||||
|
.order_by("-last_event")
|
||||||
|
.distinct()
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
recent_events = (
|
||||||
|
list(recent_room.events.select_related("actor").order_by("-timestamp")[:36])[::-1]
|
||||||
|
if recent_room else []
|
||||||
|
)
|
||||||
|
|
||||||
|
return render(request, "apps/billboard/billboard.html", {
|
||||||
|
"my_rooms": my_rooms,
|
||||||
|
"recent_room": recent_room,
|
||||||
|
"recent_events": recent_events,
|
||||||
|
"viewer": request.user,
|
||||||
|
"applets": applet_context(request.user, "billboard"),
|
||||||
|
"page_class": "page-billboard",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def toggle_billboard_applets(request):
|
||||||
|
checked = request.POST.getlist("applets")
|
||||||
|
for applet in Applet.objects.filter(context="billboard"):
|
||||||
|
UserApplet.objects.update_or_create(
|
||||||
|
user=request.user,
|
||||||
|
applet=applet,
|
||||||
|
defaults={"visible": applet.slug in checked},
|
||||||
|
)
|
||||||
|
if request.headers.get("HX-Request"):
|
||||||
|
return render(request, "apps/billboard/_partials/_applets.html", {
|
||||||
|
"applets": applet_context(request.user, "billboard"),
|
||||||
|
})
|
||||||
|
return redirect("billboard:billboard")
|
||||||
|
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def room_scroll(request, room_id):
|
||||||
|
room = Room.objects.get(id=room_id)
|
||||||
|
events = room.events.select_related("actor").all()
|
||||||
|
sp = ScrollPosition.objects.filter(user=request.user, room=room).first()
|
||||||
|
return render(request, "apps/billboard/room_scroll.html", {
|
||||||
|
"room": room,
|
||||||
|
"events": events,
|
||||||
|
"viewer": request.user,
|
||||||
|
"scroll_position": sp.position if sp else 0,
|
||||||
|
"page_class": "page-billscroll",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def save_scroll_position(request, room_id):
|
||||||
|
if request.method != "POST":
|
||||||
|
from django.http import HttpResponseNotAllowed
|
||||||
|
return HttpResponseNotAllowed(["POST"])
|
||||||
|
room = Room.objects.get(id=room_id)
|
||||||
|
position = int(request.POST.get("position", 0))
|
||||||
|
ScrollPosition.objects.update_or_create(
|
||||||
|
user=request.user, room=room,
|
||||||
|
defaults={"position": position},
|
||||||
|
)
|
||||||
|
from django.http import HttpResponse
|
||||||
|
return HttpResponse(status=204)
|
||||||
@@ -1,3 +1 @@
|
|||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
|
||||||
# Register your models here.
|
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ from django import forms
|
|||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
from .models import Item
|
from .models import Item
|
||||||
|
|
||||||
DUPLICATE_ITEM_ERROR = "You've already logged this to your list"
|
DUPLICATE_ITEM_ERROR = "You've already logged this to your note"
|
||||||
EMPTY_ITEM_ERROR = "You can't have an empty list item"
|
EMPTY_ITEM_ERROR = "You can't have an empty note item"
|
||||||
|
|
||||||
class ItemForm(forms.Form):
|
class ItemForm(forms.Form):
|
||||||
text = forms.CharField(
|
text = forms.CharField(
|
||||||
@@ -11,22 +11,22 @@ class ItemForm(forms.Form):
|
|||||||
required=True,
|
required=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
def save(self, for_list):
|
def save(self, for_note):
|
||||||
return Item.objects.create(
|
return Item.objects.create(
|
||||||
list=for_list,
|
note=for_note,
|
||||||
text=self.cleaned_data["text"],
|
text=self.cleaned_data["text"],
|
||||||
)
|
)
|
||||||
|
|
||||||
class ExistingListItemForm(ItemForm):
|
class ExistingNoteItemForm(ItemForm):
|
||||||
def __init__(self, for_list, *args, **kwargs):
|
def __init__(self, for_note, *args, **kwargs):
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
self._for_list = for_list
|
self._for_note = for_note
|
||||||
|
|
||||||
def clean_text(self):
|
def clean_text(self):
|
||||||
text = self.cleaned_data["text"]
|
text = self.cleaned_data["text"]
|
||||||
if self._for_list.item_set.filter(text=text).exists():
|
if self._for_note.item_set.filter(text=text).exists():
|
||||||
raise forms.ValidationError(DUPLICATE_ITEM_ERROR)
|
raise forms.ValidationError(DUPLICATE_ITEM_ERROR)
|
||||||
return text
|
return text
|
||||||
|
|
||||||
def save(self):
|
def save(self):
|
||||||
return super().save(for_list=self._for_list)
|
return super().save(for_note=self._for_note)
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
# Generated by Django 6.0 on 2026-02-08 01:19
|
# Generated by Django 6.0 on 2026-02-23 04:30
|
||||||
|
|
||||||
import django.db.models.deletion
|
import django.db.models.deletion
|
||||||
|
import uuid
|
||||||
|
from django.conf import settings
|
||||||
from django.db import migrations, models
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
@@ -9,13 +11,16 @@ class Migration(migrations.Migration):
|
|||||||
initial = True
|
initial = True
|
||||||
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
]
|
]
|
||||||
|
|
||||||
operations = [
|
operations = [
|
||||||
migrations.CreateModel(
|
migrations.CreateModel(
|
||||||
name='List',
|
name='List',
|
||||||
fields=[
|
fields=[
|
||||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||||
|
('owner', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='lists', to=settings.AUTH_USER_MODEL)),
|
||||||
|
('shared_with', models.ManyToManyField(blank=True, related_name='shared_lists', to=settings.AUTH_USER_MODEL)),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
migrations.CreateModel(
|
migrations.CreateModel(
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
# Generated by Django 6.0 on 2026-02-09 03:29
|
|
||||||
|
|
||||||
import django.db.models.deletion
|
|
||||||
from django.conf import settings
|
|
||||||
from django.db import migrations, models
|
|
||||||
|
|
||||||
|
|
||||||
class Migration(migrations.Migration):
|
|
||||||
|
|
||||||
dependencies = [
|
|
||||||
('dashboard', '0001_initial'),
|
|
||||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
||||||
]
|
|
||||||
|
|
||||||
operations = [
|
|
||||||
migrations.AddField(
|
|
||||||
model_name='list',
|
|
||||||
name='owner',
|
|
||||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='lists', to=settings.AUTH_USER_MODEL),
|
|
||||||
),
|
|
||||||
]
|
|
||||||
20
src/apps/dashboard/migrations/0002_rename_list_to_note.py
Normal file
20
src/apps/dashboard/migrations/0002_rename_list_to_note.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
from django.db import migrations
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('dashboard', '0001_initial'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.RenameModel(
|
||||||
|
old_name='List',
|
||||||
|
new_name='Note',
|
||||||
|
),
|
||||||
|
migrations.RenameField(
|
||||||
|
model_name='Item',
|
||||||
|
old_name='list',
|
||||||
|
new_name='note',
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Generated by Django 6.0 on 2026-03-12 19:30
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('dashboard', '0002_rename_list_to_note'),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='note',
|
||||||
|
name='owner',
|
||||||
|
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='notes', to=settings.AUTH_USER_MODEL),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='note',
|
||||||
|
name='shared_with',
|
||||||
|
field=models.ManyToManyField(blank=True, related_name='shared_notes', to=settings.AUTH_USER_MODEL),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1,30 +1,39 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
from django.db import models
|
from django.db import models
|
||||||
from django.urls import reverse
|
from django.urls import reverse
|
||||||
|
|
||||||
class List(models.Model):
|
|
||||||
|
class Note(models.Model):
|
||||||
|
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||||
owner = models.ForeignKey(
|
owner = models.ForeignKey(
|
||||||
"lyric.User",
|
"lyric.User",
|
||||||
related_name="lists",
|
related_name="notes",
|
||||||
blank=True,
|
blank=True,
|
||||||
null=True,
|
null=True,
|
||||||
on_delete=models.CASCADE,
|
on_delete=models.CASCADE,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
shared_with = models.ManyToManyField(
|
||||||
|
"lyric.User",
|
||||||
|
related_name="shared_notes",
|
||||||
|
blank=True,
|
||||||
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
return self.item_set.first().text
|
return self.item_set.first().text
|
||||||
|
|
||||||
def get_absolute_url(self):
|
def get_absolute_url(self):
|
||||||
return reverse("view_list", args=[self.id])
|
return reverse("view_note", args=[self.id])
|
||||||
|
|
||||||
class Item(models.Model):
|
class Item(models.Model):
|
||||||
text = models.TextField(default="")
|
text = models.TextField(default="")
|
||||||
list = models.ForeignKey(List, default=None, on_delete=models.CASCADE)
|
note = models.ForeignKey(Note, default=None, on_delete=models.CASCADE)
|
||||||
|
|
||||||
class Meta:
|
class Meta:
|
||||||
ordering = ("id",)
|
ordering = ("id",)
|
||||||
unique_together = ("list", "text")
|
unique_together = ("note", "text")
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return self.text
|
return self.text
|
||||||
|
|
||||||
|
|||||||
43
src/apps/dashboard/static/apps/dashboard/dashboard.js
Normal file
43
src/apps/dashboard/static/apps/dashboard/dashboard.js
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
// console.log("apps/scripts/dashboard.js loading");
|
||||||
|
const initialize = (inputSelector) => {
|
||||||
|
// console.log("initialize called!");
|
||||||
|
const textInput = document.querySelector(inputSelector);
|
||||||
|
if (!textInput) return;
|
||||||
|
textInput.oninput = () => {
|
||||||
|
// console.log("oninput triggered");
|
||||||
|
textInput.classList.remove("is-invalid");
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const bindPaletteWheel = () => {
|
||||||
|
document.querySelectorAll('.palette-scroll').forEach(el => {
|
||||||
|
el.addEventListener('wheel', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
el.scrollLeft += e.deltaY;
|
||||||
|
}, { passive: false });
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const bindPaletteForms = () => {
|
||||||
|
document.querySelectorAll('form[action*="set_palette"]').forEach(form => {
|
||||||
|
form.addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const resp = await fetch(form.action, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Accept": "application/json" },
|
||||||
|
body: new FormData(form, e.submitter),
|
||||||
|
});
|
||||||
|
if (!resp.ok) return;
|
||||||
|
const { palette } = await resp.json();
|
||||||
|
// Swap body palette class
|
||||||
|
[...document.body.classList]
|
||||||
|
.filter(c => c.startsWith("palette-"))
|
||||||
|
.forEach(c => document.body.classList.remove(c));
|
||||||
|
document.body.classList.add(palette);
|
||||||
|
// Update active swatch indicator
|
||||||
|
document.querySelectorAll(".swatch").forEach(sw => {
|
||||||
|
sw.classList.toggle("active", sw.classList.contains(palette));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
95
src/apps/dashboard/static/apps/dashboard/game-kit.js
Normal file
95
src/apps/dashboard/static/apps/dashboard/game-kit.js
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
(function () {
|
||||||
|
var btn = document.getElementById('id_kit_btn');
|
||||||
|
var dialog = document.getElementById('id_kit_bag_dialog');
|
||||||
|
if (!btn || !dialog) return;
|
||||||
|
|
||||||
|
btn.addEventListener('click', function () {
|
||||||
|
if (dialog.hasAttribute('open')) {
|
||||||
|
dialog.removeAttribute('open');
|
||||||
|
btn.classList.remove('active');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
fetch(btn.dataset.kitUrl, {
|
||||||
|
headers: { 'X-Requested-With': 'XMLHttpRequest' },
|
||||||
|
})
|
||||||
|
.then(function (r) { return r.text(); })
|
||||||
|
.then(function (html) {
|
||||||
|
dialog.innerHTML = html;
|
||||||
|
attachCardListeners();
|
||||||
|
btn.classList.add('active');
|
||||||
|
dialog.setAttribute('open', '');
|
||||||
|
})
|
||||||
|
.catch(function () {
|
||||||
|
btn.classList.remove('active');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Escape key
|
||||||
|
document.addEventListener('keydown', function (e) {
|
||||||
|
if (e.key === 'Escape' && dialog.hasAttribute('open')) {
|
||||||
|
dialog.removeAttribute('open');
|
||||||
|
btn.classList.remove('active');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Click outside (but not on the rails button — let that flow through)
|
||||||
|
document.addEventListener('click', function (e) {
|
||||||
|
if (!dialog.hasAttribute('open')) return;
|
||||||
|
if (dialog.contains(e.target)) return;
|
||||||
|
if (e.target === btn || btn.contains(e.target)) return;
|
||||||
|
if (e.target.closest('button.token-rails')) return;
|
||||||
|
dialog.removeAttribute('open');
|
||||||
|
btn.classList.remove('active');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Inject token_id before token-rails form submits
|
||||||
|
document.addEventListener('click', function (e) {
|
||||||
|
var rails = e.target.closest('button.token-rails');
|
||||||
|
if (!rails || !window._kitTokenId) return;
|
||||||
|
var form = rails.closest('form');
|
||||||
|
if (!form) return;
|
||||||
|
var existing = form.querySelector('input[name="token_id"]');
|
||||||
|
if (existing) existing.remove();
|
||||||
|
var hidden = document.createElement('input');
|
||||||
|
hidden.type = 'hidden';
|
||||||
|
hidden.name = 'token_id';
|
||||||
|
hidden.value = window._kitTokenId;
|
||||||
|
form.appendChild(hidden);
|
||||||
|
if (dialog.hasAttribute('open')) dialog.removeAttribute('open');
|
||||||
|
});
|
||||||
|
|
||||||
|
function attachTooltip(el) {
|
||||||
|
el.addEventListener('mouseenter', function () {
|
||||||
|
var tooltip = el.querySelector('.token-tooltip');
|
||||||
|
if (!tooltip) return;
|
||||||
|
var rect = el.getBoundingClientRect();
|
||||||
|
tooltip.style.position = 'fixed';
|
||||||
|
tooltip.style.bottom = (window.innerHeight - rect.top + 8) + 'px';
|
||||||
|
tooltip.style.left = rect.left + 'px';
|
||||||
|
tooltip.style.display = 'block';
|
||||||
|
});
|
||||||
|
el.addEventListener('mouseleave', function () {
|
||||||
|
var tooltip = el.querySelector('.token-tooltip');
|
||||||
|
if (tooltip) tooltip.style.display = '';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function attachCardListeners() {
|
||||||
|
dialog.querySelectorAll('.token[data-token-id]').forEach(function (card) {
|
||||||
|
card.addEventListener('click', function () {
|
||||||
|
dialog.querySelectorAll('.token[data-token-id].selected').forEach(function (c) {
|
||||||
|
c.classList.remove('selected');
|
||||||
|
});
|
||||||
|
card.classList.add('selected');
|
||||||
|
window._kitTokenId = card.dataset.tokenId;
|
||||||
|
var slot = document.querySelector('.token-slot');
|
||||||
|
if (slot) slot.classList.add('ready');
|
||||||
|
});
|
||||||
|
attachTooltip(card);
|
||||||
|
});
|
||||||
|
|
||||||
|
dialog.querySelectorAll('.kit-bag-deck').forEach(attachTooltip);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}());
|
||||||
94
src/apps/dashboard/static/apps/dashboard/wallet.js
Normal file
94
src/apps/dashboard/static/apps/dashboard/wallet.js
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
const initWallet = () => {
|
||||||
|
let stripe, elements;
|
||||||
|
|
||||||
|
const addBtn = document.getElementById('id_add_payment_method');
|
||||||
|
const saveBtn = document.getElementById('id_save_payment_method');
|
||||||
|
const cancelBtn = document.getElementById('id_cancel_payment_method');
|
||||||
|
if (!addBtn) return;
|
||||||
|
|
||||||
|
const getCsrf = () => document.cookie.match(/csrftoken=([^;]+)/)[1];
|
||||||
|
|
||||||
|
addBtn.addEventListener('click', async () => {
|
||||||
|
const res = await fetch('/dashboard/wallet/setup-intent', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {'X-CSRFToken': getCsrf()},
|
||||||
|
});
|
||||||
|
const {client_secret, publishable_key} = await res.json();
|
||||||
|
stripe = Stripe(publishable_key);
|
||||||
|
elements = stripe.elements({clientSecret: client_secret});
|
||||||
|
const paymentEl = elements.create('payment');
|
||||||
|
paymentEl.mount('#id_stripe_payment_element');
|
||||||
|
saveBtn.hidden = false;
|
||||||
|
cancelBtn.hidden = false;
|
||||||
|
const section = addBtn.closest('section');
|
||||||
|
section.style.setProperty('--applet-rows', '15');
|
||||||
|
});
|
||||||
|
|
||||||
|
saveBtn.addEventListener('click', async () => {
|
||||||
|
const {error, setupIntent} = await stripe.confirmSetup({
|
||||||
|
elements,
|
||||||
|
redirect: 'if_required',
|
||||||
|
});
|
||||||
|
if (error) { console.error(error); return; }
|
||||||
|
const res = await fetch('/dashboard/wallet/save-payment-method', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'X-CSRFToken': getCsrf(),
|
||||||
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
},
|
||||||
|
body: `payment_method_id=${setupIntent.payment_method}`,
|
||||||
|
});
|
||||||
|
const {last4, brand} = await res.json();
|
||||||
|
const pm = document.createElement('div');
|
||||||
|
pm.textContent = `${brand} ····${last4}`;
|
||||||
|
document.getElementById('id_payment_methods').appendChild(pm);
|
||||||
|
elements.getElement('payment').unmount();
|
||||||
|
elements = null;
|
||||||
|
stripe = null;
|
||||||
|
saveBtn.hidden = true;
|
||||||
|
cancelBtn.hidden = true;
|
||||||
|
const section = cancelBtn.closest('section');
|
||||||
|
section.style.setProperty('--applet-rows', '3');
|
||||||
|
});
|
||||||
|
|
||||||
|
cancelBtn.addEventListener('click', () => {
|
||||||
|
if (elements) {
|
||||||
|
elements.getElement('payment').unmount();
|
||||||
|
elements = null;
|
||||||
|
stripe = null;
|
||||||
|
}
|
||||||
|
saveBtn.hidden = true;
|
||||||
|
cancelBtn.hidden = true;
|
||||||
|
const section = cancelBtn.closest('section');
|
||||||
|
section.style.setProperty('--applet-rows', '3');
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
function initWalletTooltips() {
|
||||||
|
const portal = document.getElementById('id_tooltip_portal');
|
||||||
|
if (!portal) return;
|
||||||
|
|
||||||
|
document.querySelectorAll('.wallet-tokens .token').forEach(token => {
|
||||||
|
const tooltip = token.querySelector('.token-tooltip');
|
||||||
|
if (!tooltip) return;
|
||||||
|
|
||||||
|
token.addEventListener('mouseenter', () => {
|
||||||
|
const rect = token.getBoundingClientRect();
|
||||||
|
portal.innerHTML = tooltip.innerHTML;
|
||||||
|
portal.classList.add('active');
|
||||||
|
const halfW = portal.offsetWidth / 2;
|
||||||
|
const rawLeft = rect.left + rect.width / 2;
|
||||||
|
const clampedLeft = Math.max(halfW + 8, Math.min(rawLeft, window.innerWidth - halfW - 8));
|
||||||
|
portal.style.left = Math.round(clampedLeft) + 'px';
|
||||||
|
portal.style.top = Math.round(rect.top) + 'px';
|
||||||
|
portal.style.transform = 'translate(-50%, calc(-100% - 0.5rem))';
|
||||||
|
});
|
||||||
|
|
||||||
|
token.addEventListener('mouseleave', () => {
|
||||||
|
portal.classList.remove('active');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', initWallet);
|
||||||
|
document.addEventListener('DOMContentLoaded', initWalletTooltips);
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
// console.log("apps/scripts/dashboard.js loading");
|
|
||||||
const initialize = (inputSelector) => {
|
|
||||||
// console.log("initialize called!");
|
|
||||||
const textInput = document.querySelector(inputSelector);
|
|
||||||
textInput.oninput = () => {
|
|
||||||
// console.log("oninput triggered");
|
|
||||||
textInput.classList.remove("is-invalid");
|
|
||||||
};
|
|
||||||
};
|
|
||||||
0
src/apps/dashboard/tests/integrated/__init__.py
Normal file
0
src/apps/dashboard/tests/integrated/__init__.py
Normal file
41
src/apps/dashboard/tests/integrated/test_forms.py
Normal file
41
src/apps/dashboard/tests/integrated/test_forms.py
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from apps.dashboard.forms import (
|
||||||
|
DUPLICATE_ITEM_ERROR,
|
||||||
|
EMPTY_ITEM_ERROR,
|
||||||
|
ExistingNoteItemForm,
|
||||||
|
ItemForm,
|
||||||
|
)
|
||||||
|
from apps.dashboard.models import Item, Note
|
||||||
|
|
||||||
|
|
||||||
|
class ItemFormTest(TestCase):
|
||||||
|
def test_form_save_handles_saving_to_a_note(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
form = ItemForm(data={"text": "do re mi"})
|
||||||
|
self.assertTrue(form.is_valid())
|
||||||
|
new_item = form.save(for_note=mynote)
|
||||||
|
self.assertEqual(new_item, Item.objects.get())
|
||||||
|
self.assertEqual(new_item.text, "do re mi")
|
||||||
|
self.assertEqual(new_item.note, mynote)
|
||||||
|
|
||||||
|
class ExistingNoteItemFormTest(TestCase):
|
||||||
|
def test_form_validation_for_blank_items(self):
|
||||||
|
note = Note.objects.create()
|
||||||
|
form = ExistingNoteItemForm(for_note=note, data={"text": ""})
|
||||||
|
self.assertFalse(form.is_valid())
|
||||||
|
self.assertEqual(form.errors["text"], [EMPTY_ITEM_ERROR])
|
||||||
|
|
||||||
|
def test_form_validation_for_duplicate_items(self):
|
||||||
|
note = Note.objects.create()
|
||||||
|
Item.objects.create(note=note, text="twins, basil")
|
||||||
|
form = ExistingNoteItemForm(for_note=note, data={"text": "twins, basil"})
|
||||||
|
self.assertFalse(form.is_valid())
|
||||||
|
self.assertEqual(form.errors["text"], [DUPLICATE_ITEM_ERROR])
|
||||||
|
|
||||||
|
def test_form_save(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
form = ExistingNoteItemForm(for_note=mynote, data={"text": "howdy"})
|
||||||
|
self.assertTrue(form.is_valid())
|
||||||
|
new_item = form.save()
|
||||||
|
self.assertEqual(new_item, Item.objects.get())
|
||||||
70
src/apps/dashboard/tests/integrated/test_models.py
Normal file
70
src/apps/dashboard/tests/integrated/test_models.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
from django.core.exceptions import ValidationError
|
||||||
|
from django.db.utils import IntegrityError
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from apps.dashboard.models import Item, Note
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class ItemModelTest(TestCase):
|
||||||
|
def test_item_is_related_to_note(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
item = Item()
|
||||||
|
item.note = mynote
|
||||||
|
item.save()
|
||||||
|
self.assertIn(item, mynote.item_set.all())
|
||||||
|
|
||||||
|
def test_cannot_save_null_note_items(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
item = Item(note=mynote, text=None)
|
||||||
|
with self.assertRaises(IntegrityError):
|
||||||
|
item.save()
|
||||||
|
|
||||||
|
def test_cannot_save_empty_note_items(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
item = Item(note=mynote, text="")
|
||||||
|
with self.assertRaises(ValidationError):
|
||||||
|
item.full_clean()
|
||||||
|
|
||||||
|
def test_duplicate_items_are_invalid(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
Item.objects.create(note=mynote, text="jklol")
|
||||||
|
with self.assertRaises(ValidationError):
|
||||||
|
item = Item(note=mynote, text="jklol")
|
||||||
|
item.full_clean()
|
||||||
|
|
||||||
|
def test_still_can_save_same_item_to_different_notes(self):
|
||||||
|
note1 = Note.objects.create()
|
||||||
|
note2 = Note.objects.create()
|
||||||
|
Item.objects.create(note=note1, text="nojk")
|
||||||
|
item = Item(note=note2, text="nojk")
|
||||||
|
item.full_clean() # should not raise
|
||||||
|
|
||||||
|
class NoteModelTest(TestCase):
|
||||||
|
def test_get_absolute_url(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
self.assertEqual(mynote.get_absolute_url(), f"/dashboard/note/{mynote.id}/")
|
||||||
|
|
||||||
|
def test_note_items_order(self):
|
||||||
|
note1 = Note.objects.create()
|
||||||
|
item1 = Item.objects.create(note=note1, text="i1")
|
||||||
|
item2 = Item.objects.create(note=note1, text="item 2")
|
||||||
|
item3 = Item.objects.create(note=note1, text="3")
|
||||||
|
self.assertEqual(
|
||||||
|
list(note1.item_set.all()),
|
||||||
|
[item1, item2, item3],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_notes_can_have_owners(self):
|
||||||
|
user = User.objects.create(email="a@b.cde")
|
||||||
|
mynote = Note.objects.create(owner=user)
|
||||||
|
self.assertIn(mynote, user.notes.all())
|
||||||
|
|
||||||
|
def test_note_owner_is_optional(self):
|
||||||
|
Note.objects.create()
|
||||||
|
|
||||||
|
def test_note_name_is_first_item_text(self):
|
||||||
|
note = Note.objects.create()
|
||||||
|
Item.objects.create(note=note, text="first item")
|
||||||
|
Item.objects.create(note=note, text="second item")
|
||||||
|
self.assertEqual(note.name, "first item")
|
||||||
79
src/apps/dashboard/tests/integrated/test_stripe_views.py
Normal file
79
src/apps/dashboard/tests/integrated/test_stripe_views.py
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
from unittest import mock
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from apps.lyric.models import PaymentMethod, User
|
||||||
|
|
||||||
|
|
||||||
|
class SetupIntentViewTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="capman@test.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
|
def test_setup_intent_requires_login(self):
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.post("/dashboard/wallet/setup-intent")
|
||||||
|
self.assertRedirects(
|
||||||
|
response, "/?next=/dashboard/wallet/setup-intent",
|
||||||
|
fetch_redirect_response=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
@mock.patch("apps.dashboard.views.stripe")
|
||||||
|
def test_returns_client_secret(self, mock_stripe):
|
||||||
|
mock_stripe.Customer.create.return_value = mock.Mock(id="cus_test123")
|
||||||
|
mock_stripe.SetupIntent.create.return_value = mock.Mock(client_secret="seti_secret")
|
||||||
|
response = self.client.post("/dashboard/wallet/setup-intent")
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response.json()["client_secret"], "seti_secret")
|
||||||
|
self.assertIn("publishable_key", response.json())
|
||||||
|
|
||||||
|
@mock.patch("apps.dashboard.views.stripe")
|
||||||
|
def test_reuses_existing_stripe_customer(self, mock_stripe):
|
||||||
|
self.user.stripe_customer_id = "cus_existing"
|
||||||
|
self.user.save()
|
||||||
|
mock_stripe.SetupIntent.create.return_value = mock.Mock(client_secret="seti_secret")
|
||||||
|
self.client.post("/dashboard/wallet/setup-intent")
|
||||||
|
mock_stripe.Customer.create.assert_not_called()
|
||||||
|
mock_stripe.SetupIntent.create.assert_called_once_with(customer="cus_existing")
|
||||||
|
|
||||||
|
class SavePaymentMethodViewTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="capman@test.io")
|
||||||
|
self.user.stripe_customer_id = "cus_test123"
|
||||||
|
self.user.save()
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
|
def test_save_payment_method_requires_login(self):
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.post(
|
||||||
|
"/dashboard/wallet/save-payment-method", {"payment_method_id": "pm_test"}
|
||||||
|
)
|
||||||
|
self.assertRedirects(
|
||||||
|
response, "/?next=/dashboard/wallet/save-payment-method",
|
||||||
|
fetch_redirect_response=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
@mock.patch("apps.dashboard.views.stripe")
|
||||||
|
def test_creates_payment_method_record(self, mock_stripe):
|
||||||
|
mock_stripe.PaymentMethod.retrieve.return_value = mock.Mock(
|
||||||
|
card=mock.Mock(last4="4242", brand="visa")
|
||||||
|
)
|
||||||
|
self.client.post(
|
||||||
|
"/dashboard/wallet/save-payment-method",
|
||||||
|
{"payment_method_id": "pm_test123"},
|
||||||
|
)
|
||||||
|
pm = PaymentMethod.objects.get(user=self.user)
|
||||||
|
self.assertEqual(pm.last4, "4242")
|
||||||
|
self.assertEqual(pm.brand, "visa")
|
||||||
|
|
||||||
|
@mock.patch("apps.dashboard.views.stripe")
|
||||||
|
def test_returns_json_with_last4_and_brand(self, mock_stripe):
|
||||||
|
mock_stripe.PaymentMethod.retrieve.return_value = mock.Mock(
|
||||||
|
card=mock.Mock(last4="4242", brand="visa")
|
||||||
|
)
|
||||||
|
response = self.client.post(
|
||||||
|
"/dashboard/wallet/save-payment-method",
|
||||||
|
{"payment_method_id": "pm_test123"},
|
||||||
|
)
|
||||||
|
data = response.json()
|
||||||
|
self.assertEqual(data["last4"], "4242")
|
||||||
|
self.assertEqual(data["brand"], "visa")
|
||||||
484
src/apps/dashboard/tests/integrated/test_views.py
Normal file
484
src/apps/dashboard/tests/integrated/test_views.py
Normal file
@@ -0,0 +1,484 @@
|
|||||||
|
import lxml.html
|
||||||
|
|
||||||
|
from django.contrib.messages import get_messages
|
||||||
|
from django.test import override_settings, TestCase
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils import html
|
||||||
|
|
||||||
|
from apps.applets.models import Applet, UserApplet
|
||||||
|
from apps.dashboard.forms import (
|
||||||
|
DUPLICATE_ITEM_ERROR,
|
||||||
|
EMPTY_ITEM_ERROR,
|
||||||
|
)
|
||||||
|
from apps.dashboard.models import Item, Note
|
||||||
|
from apps.lyric.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class HomePageTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="disco@test.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
Applet.objects.get_or_create(slug="new-note", defaults={"name": "New Note"})
|
||||||
|
|
||||||
|
def test_uses_home_template(self):
|
||||||
|
response = self.client.get('/')
|
||||||
|
self.assertTemplateUsed(response, 'apps/dashboard/home.html')
|
||||||
|
|
||||||
|
def test_renders_input_form(self):
|
||||||
|
response = self.client.get('/')
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
forms = parsed.cssselect('form[method=POST]')
|
||||||
|
self.assertIn("/dashboard/new_note", [form.get("action") for form in forms])
|
||||||
|
[form] = [form for form in forms if form.get("action") == "/dashboard/new_note"]
|
||||||
|
inputs = form.cssselect("input")
|
||||||
|
self.assertIn("text", [input.get("name") for input in inputs])
|
||||||
|
|
||||||
|
class NewNoteTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
user = User.objects.create(email="disco@test.io")
|
||||||
|
self.client.force_login(user)
|
||||||
|
|
||||||
|
def test_can_save_a_POST_request(self):
|
||||||
|
self.client.post("/dashboard/new_note", data={"text": "A new note item"})
|
||||||
|
self.assertEqual(Item.objects.count(), 1)
|
||||||
|
new_item = Item.objects.get()
|
||||||
|
self.assertEqual(new_item.text, "A new note item")
|
||||||
|
|
||||||
|
def test_redirects_after_POST(self):
|
||||||
|
response = self.client.post("/dashboard/new_note", data={"text": "A new note item"})
|
||||||
|
new_note = Note.objects.get()
|
||||||
|
self.assertRedirects(response, f"/dashboard/note/{new_note.id}/")
|
||||||
|
|
||||||
|
# Post invalid input helper
|
||||||
|
def post_invalid_input(self):
|
||||||
|
return self.client.post("/dashboard/new_note", data={"text": ""})
|
||||||
|
|
||||||
|
def test_for_invalid_input_nothing_saved_to_db(self):
|
||||||
|
self.post_invalid_input()
|
||||||
|
self.assertEqual(Item.objects.count(), 0)
|
||||||
|
|
||||||
|
def test_for_invalid_input_renders_home_template(self):
|
||||||
|
response = self.post_invalid_input()
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertTemplateUsed(response, "apps/dashboard/home.html")
|
||||||
|
|
||||||
|
def test_for_invalid_input_shows_error_on_page(self):
|
||||||
|
response = self.post_invalid_input()
|
||||||
|
self.assertContains(response, html.escape(EMPTY_ITEM_ERROR))
|
||||||
|
|
||||||
|
@override_settings(COMPRESS_ENABLED=False)
|
||||||
|
class NoteViewTest(TestCase):
|
||||||
|
def test_uses_note_template(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
response = self.client.get(f"/dashboard/note/{mynote.id}/")
|
||||||
|
self.assertTemplateUsed(response, "apps/dashboard/note.html")
|
||||||
|
|
||||||
|
def test_renders_input_form(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
url = f"/dashboard/note/{mynote.id}/"
|
||||||
|
response = self.client.get(url)
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
forms = parsed.cssselect("form[method=POST]")
|
||||||
|
self.assertIn(url, [form.get("action") for form in forms])
|
||||||
|
[form] = [form for form in forms if form.get("action") == url]
|
||||||
|
inputs = form.cssselect("input")
|
||||||
|
self.assertIn("text", [input.get("name") for input in inputs])
|
||||||
|
|
||||||
|
def test_displays_only_items_for_that_note(self):
|
||||||
|
# Given/Arrange
|
||||||
|
correct_note = Note.objects.create()
|
||||||
|
Item.objects.create(text="itemey 1", note=correct_note)
|
||||||
|
Item.objects.create(text="itemey 2", note=correct_note)
|
||||||
|
other_note = Note.objects.create()
|
||||||
|
Item.objects.create(text="other note item", note=other_note)
|
||||||
|
# When/Act
|
||||||
|
response = self.client.get(f"/dashboard/note/{correct_note.id}/")
|
||||||
|
# Then/Assert
|
||||||
|
self.assertContains(response, "itemey 1")
|
||||||
|
self.assertContains(response, "itemey 2")
|
||||||
|
self.assertNotContains(response, "other note item")
|
||||||
|
|
||||||
|
def test_can_save_a_POST_request_to_an_existing_note(self):
|
||||||
|
other_note = Note.objects.create()
|
||||||
|
correct_note = Note.objects.create()
|
||||||
|
|
||||||
|
self.client.post(
|
||||||
|
f"/dashboard/note/{correct_note.id}/",
|
||||||
|
data={"text": "A new item for an existing note"},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(Item.objects.count(), 1)
|
||||||
|
new_item = Item.objects.get()
|
||||||
|
self.assertEqual(new_item.text, "A new item for an existing note")
|
||||||
|
self.assertEqual(new_item.note, correct_note)
|
||||||
|
|
||||||
|
def test_POST_redirects_to_note_view(self):
|
||||||
|
other_note = Note.objects.create()
|
||||||
|
correct_note = Note.objects.create()
|
||||||
|
|
||||||
|
response = self.client.post(
|
||||||
|
f"/dashboard/note/{correct_note.id}/",
|
||||||
|
data={"text": "A new item for an existing note"},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertRedirects(response, f"/dashboard/note/{correct_note.id}/")
|
||||||
|
|
||||||
|
# Post invalid input helper
|
||||||
|
def post_invalid_input(self):
|
||||||
|
mynote = Note.objects.create()
|
||||||
|
return self.client.post(f"/dashboard/note/{mynote.id}/", data={"text": ""})
|
||||||
|
|
||||||
|
def test_for_invalid_input_nothing_saved_to_db(self):
|
||||||
|
self.post_invalid_input()
|
||||||
|
self.assertEqual(Item.objects.count(), 0)
|
||||||
|
|
||||||
|
def test_for_invalid_input_renders_note_template(self):
|
||||||
|
response = self.post_invalid_input()
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertTemplateUsed(response, "apps/dashboard/note.html")
|
||||||
|
|
||||||
|
def test_for_invalid_input_shows_error_on_page(self):
|
||||||
|
response = self.post_invalid_input()
|
||||||
|
self.assertContains(response, html.escape(EMPTY_ITEM_ERROR))
|
||||||
|
|
||||||
|
def test_for_invalid_input_sets_is_invalid_class(self):
|
||||||
|
response = self.post_invalid_input()
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[input] = parsed.cssselect("input[name=text]")
|
||||||
|
self.assertIn("is-invalid", set(input.classes))
|
||||||
|
|
||||||
|
def test_duplicate_item_validation_errors_end_up_on_note_page(self):
|
||||||
|
note1 = Note.objects.create()
|
||||||
|
Item.objects.create(note=note1, text="lorem ipsum")
|
||||||
|
|
||||||
|
response = self.client.post(
|
||||||
|
f"/dashboard/note/{note1.id}/",
|
||||||
|
data={"text": "lorem ipsum"},
|
||||||
|
)
|
||||||
|
|
||||||
|
expected_error = html.escape(DUPLICATE_ITEM_ERROR)
|
||||||
|
self.assertContains(response, expected_error)
|
||||||
|
self.assertTemplateUsed(response, "apps/dashboard/note.html")
|
||||||
|
self.assertEqual(Item.objects.all().count(), 1)
|
||||||
|
|
||||||
|
class MyNotesTest(TestCase):
|
||||||
|
def test_my_notes_url_renders_my_notes_template(self):
|
||||||
|
user = User.objects.create(email="a@b.cde")
|
||||||
|
self.client.force_login(user)
|
||||||
|
response = self.client.get(f"/dashboard/users/{user.id}/")
|
||||||
|
self.assertTemplateUsed(response, "apps/dashboard/my_notes.html")
|
||||||
|
|
||||||
|
def test_passes_correct_owner_to_template(self):
|
||||||
|
User.objects.create(email="wrongowner@example.com")
|
||||||
|
correct_user = User.objects.create(email="a@b.cde")
|
||||||
|
self.client.force_login(correct_user)
|
||||||
|
response = self.client.get(f"/dashboard/users/{correct_user.id}/")
|
||||||
|
self.assertEqual(response.context["owner"], correct_user)
|
||||||
|
|
||||||
|
def test_note_owner_is_saved_if_user_is_authenticated(self):
|
||||||
|
user = User.objects.create(email="a@b.cde")
|
||||||
|
self.client.force_login(user)
|
||||||
|
self.client.post("/dashboard/new_note", data={"text": "new item"})
|
||||||
|
new_note = Note.objects.get()
|
||||||
|
self.assertEqual(new_note.owner, user)
|
||||||
|
|
||||||
|
def test_my_notes_redirects_if_not_logged_in(self):
|
||||||
|
user = User.objects.create(email="a@b.cde")
|
||||||
|
response = self.client.get(f"/dashboard/users/{user.id}/")
|
||||||
|
self.assertRedirects(response, "/")
|
||||||
|
|
||||||
|
def test_my_notes_returns_403_for_wrong_user(self):
|
||||||
|
# create two users, login as user_a, request user_b's my_notes url
|
||||||
|
user1 = User.objects.create(email="a@b.cde")
|
||||||
|
user2 = User.objects.create(email="wrongowner@example.com")
|
||||||
|
self.client.force_login(user2)
|
||||||
|
response = self.client.get(f"/dashboard/users/{user1.id}/")
|
||||||
|
# assert 403
|
||||||
|
self.assertEqual(response.status_code, 403)
|
||||||
|
|
||||||
|
class ShareNoteTest(TestCase):
|
||||||
|
def test_post_to_share_note_url_redirects_to_note(self):
|
||||||
|
our_note = Note.objects.create()
|
||||||
|
alice = User.objects.create(email="alice@example.com")
|
||||||
|
response = self.client.post(
|
||||||
|
f"/dashboard/note/{our_note.id}/share_note",
|
||||||
|
data={"recipient": "alice@example.com"},
|
||||||
|
)
|
||||||
|
self.assertRedirects(response, f"/dashboard/note/{our_note.id}/")
|
||||||
|
|
||||||
|
def test_post_with_email_adds_user_to_shared_with(self):
|
||||||
|
our_note = Note.objects.create()
|
||||||
|
alice = User.objects.create(email="alice@example.com")
|
||||||
|
self.client.post(
|
||||||
|
f"/dashboard/note/{our_note.id}/share_note",
|
||||||
|
data={"recipient": "alice@example.com"},
|
||||||
|
)
|
||||||
|
self.assertIn(alice, our_note.shared_with.all())
|
||||||
|
|
||||||
|
def test_post_with_nonexistent_email_redirects_to_note(self):
|
||||||
|
our_note = Note.objects.create()
|
||||||
|
response = self.client.post(
|
||||||
|
f"/dashboard/note/{our_note.id}/share_note",
|
||||||
|
data={"recipient": "nobody@example.com"},
|
||||||
|
)
|
||||||
|
self.assertRedirects(
|
||||||
|
response,
|
||||||
|
f"/dashboard/note/{our_note.id}/",
|
||||||
|
fetch_redirect_response=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_share_note_does_not_add_owner_as_recipient(self):
|
||||||
|
owner = User.objects.create(email="owner@example.com")
|
||||||
|
our_note = Note.objects.create(owner=owner)
|
||||||
|
self.client.force_login(owner)
|
||||||
|
self.client.post(reverse("share_note", args=[our_note.id]),
|
||||||
|
data={"recipient": "owner@example.com"})
|
||||||
|
self.assertNotIn(owner, our_note.shared_with.all())
|
||||||
|
|
||||||
|
@override_settings(MESSAGE_STORAGE='django.contrib.messages.storage.session.SessionStorage')
|
||||||
|
def test_share_note_shows_privacy_safe_message(self):
|
||||||
|
our_note = Note.objects.create()
|
||||||
|
response = self.client.post(
|
||||||
|
f"/dashboard/note/{our_note.id}/share_note",
|
||||||
|
data={"recipient": "nobody@example.com"},
|
||||||
|
follow=True,
|
||||||
|
)
|
||||||
|
messages = list(get_messages(response.wsgi_request))
|
||||||
|
self.assertEqual(
|
||||||
|
str(messages[0]),
|
||||||
|
"An invite has been sent if that address is registered.",
|
||||||
|
)
|
||||||
|
|
||||||
|
class ViewAuthNoteTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.owner = User.objects.create(email="disco@example.com")
|
||||||
|
self.our_note = Note.objects.create(owner=self.owner)
|
||||||
|
|
||||||
|
def test_anonymous_user_is_redirected(self):
|
||||||
|
response = self.client.get(reverse("view_note", args=[self.our_note.id]))
|
||||||
|
self.assertRedirects(response, "/", fetch_redirect_response=False)
|
||||||
|
|
||||||
|
def test_non_owner_non_shared_user_gets_403(self):
|
||||||
|
stranger = User.objects.create(email="stranger@example.com")
|
||||||
|
self.client.force_login(stranger)
|
||||||
|
response = self.client.get(reverse("view_note", args=[self.our_note.id]))
|
||||||
|
self.assertEqual(response.status_code, 403)
|
||||||
|
|
||||||
|
def test_shared_with_user_can_access_note(self):
|
||||||
|
guest = User.objects.create(email="guest@example.com")
|
||||||
|
self.our_note.shared_with.add(guest)
|
||||||
|
self.client.force_login(guest)
|
||||||
|
response = self.client.get(reverse("view_note", args=[self.our_note.id]))
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
@override_settings(COMPRESS_ENABLED=False)
|
||||||
|
class SetPaletteTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="a@b.cde")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
self.url = reverse("home")
|
||||||
|
Applet.objects.get_or_create(slug="palette", defaults={"name": "Palette"})
|
||||||
|
|
||||||
|
def test_anonymous_user_is_redirected_home(self):
|
||||||
|
response = self.client.post("/dashboard/set_palette")
|
||||||
|
self.assertRedirects(response, "/", fetch_redirect_response=False)
|
||||||
|
|
||||||
|
def test_set_palette_updates_user_palette(self):
|
||||||
|
User.objects.filter(pk=self.user.pk).update(palette="palette-sheol")
|
||||||
|
self.client.post("/dashboard/set_palette", data={"palette": "palette-default"})
|
||||||
|
self.user.refresh_from_db()
|
||||||
|
self.assertEqual(self.user.palette, "palette-default")
|
||||||
|
|
||||||
|
def test_locked_palette_is_rejected(self):
|
||||||
|
response = self.client.post("/dashboard/set_palette", data={"palette": "palette-nirvana"})
|
||||||
|
self.user.refresh_from_db()
|
||||||
|
self.assertEqual(self.user.palette, "palette-default")
|
||||||
|
self.assertRedirects(response, "/", fetch_redirect_response=False)
|
||||||
|
|
||||||
|
def test_set_palette_redirects_home(self):
|
||||||
|
response = self.client.post("/dashboard/set_palette", data={"palette": "palette-default"})
|
||||||
|
self.assertRedirects(response, "/", fetch_redirect_response=False)
|
||||||
|
|
||||||
|
def test_set_palette_returns_json_when_requested(self):
|
||||||
|
response = self.client.post(
|
||||||
|
"/dashboard/set_palette",
|
||||||
|
data={"palette": "palette-sepia"},
|
||||||
|
headers={"Accept": "application/json"},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response.json(), {"palette": "palette-sepia"})
|
||||||
|
|
||||||
|
def test_locked_palette_returns_unchanged_json(self):
|
||||||
|
response = self.client.post(
|
||||||
|
"/dashboard/set_palette",
|
||||||
|
data={"palette": "palette-nirvana"},
|
||||||
|
headers={"Accept": "application/json"},
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertEqual(response.json(), {"palette": "palette-default"})
|
||||||
|
|
||||||
|
def test_dashboard_contains_set_palette_form(self):
|
||||||
|
response = self.client.get(self.url)
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
forms = parsed.cssselect('form[action="/dashboard/set_palette"]')
|
||||||
|
unlocked = [p for p in response.context["palettes"] if not p["locked"]]
|
||||||
|
self.assertEqual(len(forms), len(unlocked))
|
||||||
|
|
||||||
|
def test_active_palette_swatch_has_active_class(self):
|
||||||
|
response = self.client.get(self.url)
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[active] = parsed.cssselect(".swatch.active")
|
||||||
|
self.assertIn("palette-default", active.classes)
|
||||||
|
|
||||||
|
def test_locked_palettes_are_not_forms(self):
|
||||||
|
response = self.client.get(self.url)
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
locked = parsed.cssselect(".swatch.locked")
|
||||||
|
expected_locked = [p for p in response.context["palettes"] if p["locked"]]
|
||||||
|
self.assertEqual(len(locked), len(expected_locked))
|
||||||
|
# they mustn't be button els
|
||||||
|
for swatch in locked:
|
||||||
|
self.assertNotEqual(swatch.tag, "button")
|
||||||
|
|
||||||
|
def test_palette_picker_count_matches_context(self):
|
||||||
|
response = self.client.get(self.url)
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
swatches = parsed.cssselect(".swatch")
|
||||||
|
self.assertEqual(len(swatches), len(response.context["palettes"]))
|
||||||
|
|
||||||
|
@override_settings(COMPRESS_ENABLED=False)
|
||||||
|
class ProfileViewTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="discoman@example.com")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
|
def test_post_username_saves_to_user(self):
|
||||||
|
self.client.post("/dashboard/set_profile", data={"username": "discoman"})
|
||||||
|
self.user.refresh_from_db()
|
||||||
|
self.assertEqual(self.user.username, "discoman")
|
||||||
|
|
||||||
|
def test_post_username_requires_login(self):
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.post("/dashboard/set_profile", data={"username": "somnambulist"})
|
||||||
|
self.assertRedirects(response, "/?next=/dashboard/set_profile", fetch_redirect_response=False)
|
||||||
|
|
||||||
|
def test_dash_renders_username_applet(self):
|
||||||
|
response = self.client.get("/")
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[applet] = parsed.cssselect("#id_applet_username")
|
||||||
|
self.assertIn("@", applet.text_content())
|
||||||
|
[input_el] = parsed.cssselect("#id_new_username")
|
||||||
|
self.assertEqual("", input_el.get("value"))
|
||||||
|
|
||||||
|
def test_dash_shows_display_name_in_applet(self):
|
||||||
|
self.user.username = "discoman"
|
||||||
|
self.user.save()
|
||||||
|
response = self.client.get("/")
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[username_input] = parsed.cssselect("#id_new_username")
|
||||||
|
self.assertEqual("discoman", username_input.get("value"))
|
||||||
|
|
||||||
|
class ToggleDashAppletsViewTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="disco@test.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
self.username_applet, _ = Applet.objects.get_or_create(slug="username", defaults={"name": "Username"})
|
||||||
|
self.palette_applet, _ = Applet.objects.get_or_create(slug="palette", defaults={"name": "Palette"})
|
||||||
|
self.url = reverse("toggle_applets")
|
||||||
|
|
||||||
|
def test_unauthenticated_user_is_redirected(self):
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.post(self.url)
|
||||||
|
self.assertRedirects(
|
||||||
|
response, f"/?next={self.url}", fetch_redirect_response=False
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_unchecked_applet_gets_user_applet_with_visible_false(self):
|
||||||
|
self.client.post(self.url, {"applets": ["username"]})
|
||||||
|
ua = UserApplet.objects.get(user=self.user, applet=self.palette_applet)
|
||||||
|
self.assertFalse(ua.visible)
|
||||||
|
|
||||||
|
def test_redirects_on_normal_post(self):
|
||||||
|
response = self.client.post(
|
||||||
|
self.url, {"applets": ["username", "palette"]}
|
||||||
|
)
|
||||||
|
self.assertRedirects(response, reverse("home"), fetch_redirect_response=False)
|
||||||
|
|
||||||
|
def test_returns_200_on_htmx_post(self):
|
||||||
|
response = self.client.post(
|
||||||
|
self.url,
|
||||||
|
{"applets": ["username", "palette"]},
|
||||||
|
HTTP_HX_REQUEST="true",
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
|
||||||
|
def test_htmx_post_renders_visible_applets_only(self):
|
||||||
|
response = self.client.post(
|
||||||
|
self.url,
|
||||||
|
{"applets": ["username"]},
|
||||||
|
HTTP_HX_REQUEST="true",
|
||||||
|
)
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
self.assertEqual(len(parsed.cssselect("#id_applet_username")), 1)
|
||||||
|
self.assertEqual(len(parsed.cssselect("#id_applet_palette")), 0)
|
||||||
|
|
||||||
|
def test_toggle_applets_does_not_affect_gameboard_applets(self):
|
||||||
|
game_applet, _ = Applet.objects.get_or_create(
|
||||||
|
slug="new-game", defaults={"name": "New Game", "context": "gameboard"}
|
||||||
|
)
|
||||||
|
self.client.post(self.url, {"applets": ["username", "palette"]})
|
||||||
|
self.assertFalse(UserApplet.objects.filter(user=self.user, applet=game_applet). exists())
|
||||||
|
|
||||||
|
class AppletVisibilityContextTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="disco@test.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
self.username_applet, _ = Applet.objects.get_or_create(slug="username", defaults={"name": "Username"})
|
||||||
|
self.palette_applet, _ = Applet.objects.get_or_create(slug="palette", defaults={"name": "Palette"})
|
||||||
|
UserApplet.objects.create(user=self.user, applet=self.palette_applet, visible=False)
|
||||||
|
|
||||||
|
def test_dash_reflects_user_applet_visibility(self):
|
||||||
|
response = self.client.get("/")
|
||||||
|
applet_map = {entry["applet"].slug: entry["visible"] for entry in response.context["applets"]}
|
||||||
|
self.assertFalse(applet_map["palette"])
|
||||||
|
self.assertTrue(applet_map["username"])
|
||||||
|
|
||||||
|
class FooterNavTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="disco@test.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
|
def test_footer_nav_present_on_dashboard(self):
|
||||||
|
response = self.client.get("/")
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[nav] = parsed.cssselect("#id_footer_nav")
|
||||||
|
self.assertIsNotNone(nav)
|
||||||
|
|
||||||
|
def test_footer_nav_has_dashboard_link(self):
|
||||||
|
response = self.client.get("/")
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[nav] = parsed.cssselect("#id_footer_nav")
|
||||||
|
links = [a.get("href") for a in nav.cssselect("a")]
|
||||||
|
self.assertIn("/", links)
|
||||||
|
|
||||||
|
def test_footer_nav_has_gameboard_link(self):
|
||||||
|
response = self.client.get("/")
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[nav] = parsed.cssselect("#id_footer_nav")
|
||||||
|
links = [a.get("href") for a in nav.cssselect("a")]
|
||||||
|
self.assertIn("/gameboard/", links)
|
||||||
|
|
||||||
|
class WalletAppletTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="disco@test.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
Applet.objects.get_or_create(slug="wallet", defaults={"name": "Wallet"})
|
||||||
|
response = self.client.get("/")
|
||||||
|
self.parsed = lxml.html.fromstring(response.content)
|
||||||
|
|
||||||
|
def test_wallet_applet_present_on_dash(self):
|
||||||
|
[_] = self.parsed.cssselect("#id_applet_wallet")
|
||||||
|
|
||||||
|
def test_wallet_applet_has_manage_link(self):
|
||||||
|
[link] = self.parsed.cssselect("#id_applet_wallet a.wallet-manage-link")
|
||||||
|
self.assertEqual(link.get("href"), "/dashboard/wallet/")
|
||||||
139
src/apps/dashboard/tests/integrated/test_wallet_views.py
Normal file
139
src/apps/dashboard/tests/integrated/test_wallet_views.py
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
import lxml.html
|
||||||
|
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
from apps.applets.models import Applet, UserApplet
|
||||||
|
from apps.lyric.models import Token, User, Wallet
|
||||||
|
|
||||||
|
|
||||||
|
class WalletViewTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="capman@test.io")
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
response = self.client.get("/dashboard/wallet/")
|
||||||
|
self.parsed = lxml.html.fromstring(response.content)
|
||||||
|
|
||||||
|
def test_wallet_page_requires_login(self):
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.get("/dashboard/wallet/")
|
||||||
|
self.assertRedirects(
|
||||||
|
response, "/?next=/dashboard/wallet/", fetch_redirect_response=False
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_wallet_page_renders(self):
|
||||||
|
[el] = self.parsed.cssselect("#id_writs_balance")
|
||||||
|
self.assertEqual(el.text_content().strip(), "144")
|
||||||
|
|
||||||
|
def test_wallet_page_shows_esteem_balance(self):
|
||||||
|
[el] = self.parsed.cssselect("#id_esteem_balance")
|
||||||
|
self.assertEqual(el.text_content().strip(), "0")
|
||||||
|
|
||||||
|
def test_wallet_page_shows_coin_on_a_string(self):
|
||||||
|
[_] = self.parsed.cssselect("#id_coin_on_a_string")
|
||||||
|
|
||||||
|
def test_wallet_page_shows_free_token(self):
|
||||||
|
[_] = self.parsed.cssselect("#id_free_token")
|
||||||
|
|
||||||
|
def test_wallet_page_shows_payment_methods_section(self):
|
||||||
|
[_] = self.parsed.cssselect("#id_add_payment_method")
|
||||||
|
|
||||||
|
def test_wallet_page_shows_stripe_payment_element(self):
|
||||||
|
[_] = self.parsed.cssselect("#id_stripe_payment_element")
|
||||||
|
|
||||||
|
def test_wallet_page_shows_tithe_token_shop(self):
|
||||||
|
[_] = self.parsed.cssselect("#id_tithe_token_shop")
|
||||||
|
|
||||||
|
def test_tithe_token_shop_shows_bundle(self):
|
||||||
|
bundles = self.parsed.cssselect("#id_tithe_token_shop .token-bundle")
|
||||||
|
self.assertGreater(len(bundles), 0)
|
||||||
|
|
||||||
|
|
||||||
|
class WalletViewAppletContextTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="walletctx@test.io")
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug="wallet-balances",
|
||||||
|
defaults={"name": "Wallet Balances", "grid_cols": 3, "grid_rows": 3, "context": "wallet"},
|
||||||
|
)
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug="wallet-tokens",
|
||||||
|
defaults={"name": "Wallet Tokens", "grid_cols": 3, "grid_rows": 3, "context": "wallet"},
|
||||||
|
)
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug="wallet-payment",
|
||||||
|
defaults={"name": "Payment Methods", "grid_cols": 6, "grid_rows": 3, "context": "wallet"},
|
||||||
|
)
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
|
def test_wallet_view_passes_applets_context(self):
|
||||||
|
response = self.client.get("/dashboard/wallet/")
|
||||||
|
slugs = [e["applet"].slug for e in response.context["applets"]]
|
||||||
|
self.assertIn("wallet-balances", slugs)
|
||||||
|
self.assertIn("wallet-tokens", slugs)
|
||||||
|
self.assertIn("wallet-payment", slugs)
|
||||||
|
|
||||||
|
def test_wallet_page_renders_applets_container(self):
|
||||||
|
response = self.client.get("/dashboard/wallet/")
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[_] = parsed.cssselect("#id_wallet_applets_container")
|
||||||
|
|
||||||
|
def test_wallet_page_renders_gear_button(self):
|
||||||
|
response = self.client.get("/dashboard/wallet/")
|
||||||
|
parsed = lxml.html.fromstring(response.content)
|
||||||
|
[_] = parsed.cssselect(".gear-btn")
|
||||||
|
|
||||||
|
|
||||||
|
class ToggleWalletAppletsTest(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.user = User.objects.create(email="wallettoggle@test.io")
|
||||||
|
self.balances = Applet.objects.get_or_create(
|
||||||
|
slug="wallet-balances",
|
||||||
|
defaults={"name": "Wallet Balances", "grid_cols": 3, "grid_rows": 3, "context": "wallet"},
|
||||||
|
)[0]
|
||||||
|
self.tokens = Applet.objects.get_or_create(
|
||||||
|
slug="wallet-tokens",
|
||||||
|
defaults={"name": "Wallet Tokens", "grid_cols": 3, "grid_rows": 3, "context": "wallet"},
|
||||||
|
)[0]
|
||||||
|
Applet.objects.get_or_create(
|
||||||
|
slug="wallet-payment",
|
||||||
|
defaults={"name": "Payment Methods", "grid_cols": 6, "grid_rows": 3, "context": "wallet"},
|
||||||
|
)
|
||||||
|
self.client.force_login(self.user)
|
||||||
|
|
||||||
|
def test_toggle_requires_login(self):
|
||||||
|
self.client.logout()
|
||||||
|
response = self.client.post("/dashboard/wallet/toggle-applets", {})
|
||||||
|
self.assertRedirects(
|
||||||
|
response, "/?next=/dashboard/wallet/toggle-applets",
|
||||||
|
fetch_redirect_response=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_toggle_redirects_to_wallet(self):
|
||||||
|
response = self.client.post(
|
||||||
|
"/dashboard/wallet/toggle-applets", {"applets": ["wallet-balances"]}
|
||||||
|
)
|
||||||
|
self.assertRedirects(response, "/dashboard/wallet/", fetch_redirect_response=False)
|
||||||
|
|
||||||
|
def test_toggle_hides_unchecked_applet(self):
|
||||||
|
self.client.post(
|
||||||
|
"/dashboard/wallet/toggle-applets", {"applets": ["wallet-balances"]}
|
||||||
|
)
|
||||||
|
ua = UserApplet.objects.get(user=self.user, applet=self.tokens)
|
||||||
|
self.assertFalse(ua.visible)
|
||||||
|
|
||||||
|
def test_toggle_shows_checked_applet(self):
|
||||||
|
UserApplet.objects.create(user=self.user, applet=self.balances, visible=False)
|
||||||
|
self.client.post(
|
||||||
|
"/dashboard/wallet/toggle-applets", {"applets": ["wallet-balances"]}
|
||||||
|
)
|
||||||
|
ua = UserApplet.objects.get(user=self.user, applet=self.balances)
|
||||||
|
self.assertTrue(ua.visible)
|
||||||
|
|
||||||
|
def test_toggle_htmx_returns_container_partial(self):
|
||||||
|
response = self.client.post(
|
||||||
|
"/dashboard/wallet/toggle-applets",
|
||||||
|
{"applets": ["wallet-balances"]},
|
||||||
|
HTTP_HX_REQUEST="true",
|
||||||
|
)
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
self.assertContains(response, "id_wallet_applets_container")
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
from django.test import TestCase
|
|
||||||
from ..forms import (
|
|
||||||
DUPLICATE_ITEM_ERROR,
|
|
||||||
EMPTY_ITEM_ERROR,
|
|
||||||
ExistingListItemForm,
|
|
||||||
ItemForm,
|
|
||||||
)
|
|
||||||
from ..models import Item, List
|
|
||||||
|
|
||||||
class ItemFormTest(TestCase):
|
|
||||||
def test_form_validation_for_blank_items(self):
|
|
||||||
form = ItemForm(data={"text": ""})
|
|
||||||
self.assertFalse(form.is_valid())
|
|
||||||
self.assertEqual(form.errors["text"], [EMPTY_ITEM_ERROR])
|
|
||||||
|
|
||||||
def test_form_save_handles_saving_to_a_list(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
form = ItemForm(data={"text": "do re mi"})
|
|
||||||
self.assertTrue(form.is_valid())
|
|
||||||
new_item = form.save(for_list=mylist)
|
|
||||||
self.assertEqual(new_item, Item.objects.get())
|
|
||||||
self.assertEqual(new_item.text, "do re mi")
|
|
||||||
self.assertEqual(new_item.list, mylist)
|
|
||||||
|
|
||||||
class ExistingListItemFormTest(TestCase):
|
|
||||||
def test_form_validation_for_blank_items(self):
|
|
||||||
list_ = List.objects.create()
|
|
||||||
form = ExistingListItemForm(for_list=list_, data={"text": ""})
|
|
||||||
self.assertFalse(form.is_valid())
|
|
||||||
self.assertEqual(form.errors["text"], [EMPTY_ITEM_ERROR])
|
|
||||||
|
|
||||||
def test_form_validation_for_duplicate_items(self):
|
|
||||||
list_ = List.objects.create()
|
|
||||||
Item.objects.create(list=list_, text="twins, basil")
|
|
||||||
form = ExistingListItemForm(for_list=list_, data={"text": "twins, basil"})
|
|
||||||
self.assertFalse(form.is_valid())
|
|
||||||
self.assertEqual(form.errors["text"], [DUPLICATE_ITEM_ERROR])
|
|
||||||
|
|
||||||
def test_form_save(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
form = ExistingListItemForm(for_list=mylist, data={"text": "howdy"})
|
|
||||||
self.assertTrue(form.is_valid())
|
|
||||||
new_item = form.save()
|
|
||||||
self.assertEqual(new_item, Item.objects.get())
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
from django.core.exceptions import ValidationError
|
|
||||||
from django.db.utils import IntegrityError
|
|
||||||
from django.test import TestCase
|
|
||||||
from ..models import Item, List
|
|
||||||
from apps.lyric.models import User
|
|
||||||
|
|
||||||
class ItemModelTest(TestCase):
|
|
||||||
def test_default_text(self):
|
|
||||||
item = Item()
|
|
||||||
self.assertEqual(item.text, "")
|
|
||||||
|
|
||||||
def test_item_is_related_to_list(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
item = Item()
|
|
||||||
item.list = mylist
|
|
||||||
item.save()
|
|
||||||
self.assertIn(item, mylist.item_set.all())
|
|
||||||
|
|
||||||
def test_cannot_save_null_list_items(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
item = Item(list=mylist, text=None)
|
|
||||||
with self.assertRaises(IntegrityError):
|
|
||||||
item.save()
|
|
||||||
|
|
||||||
def test_cannot_save_empty_list_items(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
item = Item(list=mylist, text="")
|
|
||||||
with self.assertRaises(ValidationError):
|
|
||||||
item.full_clean()
|
|
||||||
|
|
||||||
def test_duplicate_items_are_invalid(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
Item.objects.create(list=mylist, text="jklol")
|
|
||||||
with self.assertRaises(ValidationError):
|
|
||||||
item = Item(list=mylist, text="jklol")
|
|
||||||
item.full_clean()
|
|
||||||
|
|
||||||
def test_still_can_save_same_item_to_different_lists(self):
|
|
||||||
list1 = List.objects.create()
|
|
||||||
list2 = List.objects.create()
|
|
||||||
Item.objects.create(list=list1, text="nojk")
|
|
||||||
item = Item(list=list2, text="nojk")
|
|
||||||
item.full_clean() # should not raise
|
|
||||||
|
|
||||||
def test_string_representation(self):
|
|
||||||
item = Item(text="sample text")
|
|
||||||
self.assertEqual(str(item), "sample text")
|
|
||||||
|
|
||||||
class ListModelTest(TestCase):
|
|
||||||
def test_get_absolute_url(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
self.assertEqual(mylist.get_absolute_url(), f"/apps/dashboard/{mylist.id}/")
|
|
||||||
|
|
||||||
def test_list_items_order(self):
|
|
||||||
list1 = List.objects.create()
|
|
||||||
item1 = Item.objects.create(list=list1, text="i1")
|
|
||||||
item2 = Item.objects.create(list=list1, text="item 2")
|
|
||||||
item3 = Item.objects.create(list=list1, text="3")
|
|
||||||
self.assertEqual(
|
|
||||||
list(list1.item_set.all()),
|
|
||||||
[item1, item2, item3],
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_lists_can_have_owners(self):
|
|
||||||
user = User.objects.create(email="a@b.cde")
|
|
||||||
mylist = List.objects.create(owner=user)
|
|
||||||
self.assertIn(mylist, user.lists.all())
|
|
||||||
|
|
||||||
def test_list_owner_is_optional(self):
|
|
||||||
List.objects.create()
|
|
||||||
|
|
||||||
def test_list_name_is_first_item_text(self):
|
|
||||||
list_ = List.objects.create()
|
|
||||||
Item.objects.create(list=list_, text="first item")
|
|
||||||
Item.objects.create(list=list_, text="second item")
|
|
||||||
self.assertEqual(list_.name, "first item")
|
|
||||||
@@ -1,166 +0,0 @@
|
|||||||
import lxml.html
|
|
||||||
from django.test import TestCase
|
|
||||||
from django.utils import html
|
|
||||||
from unittest import skip
|
|
||||||
from ..forms import (
|
|
||||||
DUPLICATE_ITEM_ERROR,
|
|
||||||
EMPTY_ITEM_ERROR,
|
|
||||||
)
|
|
||||||
from ..models import Item, List
|
|
||||||
from apps.lyric.models import User
|
|
||||||
|
|
||||||
class HomePageTest(TestCase):
|
|
||||||
def test_uses_home_template(self):
|
|
||||||
response = self.client.get('/')
|
|
||||||
self.assertTemplateUsed(response, 'apps/dashboard/home.html')
|
|
||||||
|
|
||||||
def test_renders_input_form(self):
|
|
||||||
response = self.client.get('/')
|
|
||||||
parsed = lxml.html.fromstring(response.content)
|
|
||||||
forms = parsed.cssselect('form[method=POST]')
|
|
||||||
self.assertIn("/apps/dashboard/new_list", [form.get("action") for form in forms])
|
|
||||||
[form] = [form for form in forms if form.get("action") == "/apps/dashboard/new_list"]
|
|
||||||
inputs = form.cssselect("input")
|
|
||||||
self.assertIn("text", [input.get("name") for input in inputs])
|
|
||||||
|
|
||||||
class NewListTest(TestCase):
|
|
||||||
def test_can_save_a_POST_request(self):
|
|
||||||
self. client.post("/apps/dashboard/new_list", data={"text": "A new list item"})
|
|
||||||
self.assertEqual(Item.objects.count(), 1)
|
|
||||||
new_item = Item.objects.get()
|
|
||||||
self.assertEqual(new_item.text, "A new list item")
|
|
||||||
|
|
||||||
def test_redirects_after_POST(self):
|
|
||||||
response = self.client.post("/apps/dashboard/new_list", data={"text": "A new list item"})
|
|
||||||
new_list = List.objects.get()
|
|
||||||
self.assertRedirects(response, f"/apps/dashboard/{new_list.id}/")
|
|
||||||
|
|
||||||
# Post invalid input helper
|
|
||||||
def post_invalid_input(self):
|
|
||||||
return self.client.post("/apps/dashboard/new_list", data={"text": ""})
|
|
||||||
|
|
||||||
def test_for_invalid_input_nothing_saved_to_db(self):
|
|
||||||
self.post_invalid_input()
|
|
||||||
self.assertEqual(Item.objects.count(), 0)
|
|
||||||
|
|
||||||
def test_for_invalid_input_renders_list_template(self):
|
|
||||||
response = self.post_invalid_input()
|
|
||||||
self.assertEqual(response.status_code, 200)
|
|
||||||
self.assertTemplateUsed(response, "apps/dashboard/home.html")
|
|
||||||
|
|
||||||
def test_for_invalid_input_shows_error_on_page(self):
|
|
||||||
response = self.post_invalid_input()
|
|
||||||
self.assertContains(response, html.escape(EMPTY_ITEM_ERROR))
|
|
||||||
|
|
||||||
class ListViewTest(TestCase):
|
|
||||||
def test_uses_list_template(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
response = self.client.get(f"/apps/dashboard/{mylist.id}/")
|
|
||||||
self.assertTemplateUsed(response, "apps/dashboard/list.html")
|
|
||||||
|
|
||||||
def test_renders_input_form(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
url = f"/apps/dashboard/{mylist.id}/"
|
|
||||||
response = self.client.get(url)
|
|
||||||
parsed = lxml.html.fromstring(response.content)
|
|
||||||
forms = parsed.cssselect("form[method=POST]")
|
|
||||||
self.assertIn(url, [form.get("action") for form in forms])
|
|
||||||
[form] = [form for form in forms if form.get("action") == url]
|
|
||||||
inputs = form.cssselect("input")
|
|
||||||
self.assertIn("text", [input.get("name") for input in inputs])
|
|
||||||
|
|
||||||
def test_displays_only_items_for_that_list(self):
|
|
||||||
# Given/Arrange
|
|
||||||
correct_list = List.objects.create()
|
|
||||||
Item.objects.create(text="itemey 1", list=correct_list)
|
|
||||||
Item.objects.create(text="itemey 2", list=correct_list)
|
|
||||||
other_list = List.objects.create()
|
|
||||||
Item.objects.create(text="other list item", list=other_list)
|
|
||||||
# When/Act
|
|
||||||
response = self.client.get(f"/apps/dashboard/{correct_list.id}/")
|
|
||||||
# Then/Assert
|
|
||||||
self.assertContains(response, "itemey 1")
|
|
||||||
self.assertContains(response, "itemey 2")
|
|
||||||
self.assertNotContains(response, "other list item")
|
|
||||||
|
|
||||||
def test_can_save_a_POST_request_to_an_existing_list(self):
|
|
||||||
other_list = List.objects.create()
|
|
||||||
correct_list = List.objects.create()
|
|
||||||
|
|
||||||
self.client.post(
|
|
||||||
f"/apps/dashboard/{correct_list.id}/",
|
|
||||||
data={"text": "A new item for an existing list"},
|
|
||||||
)
|
|
||||||
|
|
||||||
self.assertEqual(Item.objects.count(), 1)
|
|
||||||
new_item = Item.objects.get()
|
|
||||||
self.assertEqual(new_item.text, "A new item for an existing list")
|
|
||||||
self.assertEqual(new_item.list, correct_list)
|
|
||||||
|
|
||||||
def test_POST_redirects_to_list_view(self):
|
|
||||||
other_list = List.objects.create()
|
|
||||||
correct_list = List.objects.create()
|
|
||||||
|
|
||||||
response = self.client.post(
|
|
||||||
f"/apps/dashboard/{correct_list.id}/",
|
|
||||||
data={"text": "A new item for an existing list"},
|
|
||||||
)
|
|
||||||
|
|
||||||
self.assertRedirects(response, f"/apps/dashboard/{correct_list.id}/")
|
|
||||||
|
|
||||||
# Post invalid input helper
|
|
||||||
def post_invalid_input(self):
|
|
||||||
mylist = List.objects.create()
|
|
||||||
return self.client.post(f"/apps/dashboard/{mylist.id}/", data={"text": ""})
|
|
||||||
|
|
||||||
def test_for_invalid_input_nothing_saved_to_db(self):
|
|
||||||
self.post_invalid_input()
|
|
||||||
self.assertEqual(Item.objects.count(), 0)
|
|
||||||
|
|
||||||
def test_for_invalid_input_renders_list_template(self):
|
|
||||||
response = self.post_invalid_input()
|
|
||||||
self.assertEqual(response.status_code, 200)
|
|
||||||
self.assertTemplateUsed(response, "apps/dashboard/list.html")
|
|
||||||
|
|
||||||
def test_for_invalid_input_shows_error_on_page(self):
|
|
||||||
response = self.post_invalid_input()
|
|
||||||
self.assertContains(response, html.escape(EMPTY_ITEM_ERROR))
|
|
||||||
|
|
||||||
def test_for_invalid_input_sets_is_invalid_class(self):
|
|
||||||
response = self.post_invalid_input()
|
|
||||||
parsed = lxml.html.fromstring(response.content)
|
|
||||||
[input] = parsed.cssselect("input[name=text]")
|
|
||||||
self.assertIn("is-invalid", set(input.classes))
|
|
||||||
|
|
||||||
def test_duplicate_item_validation_errors_end_up_on_lists_page(self):
|
|
||||||
list1 = List.objects.create()
|
|
||||||
Item.objects.create(list=list1, text="lorem ipsum")
|
|
||||||
|
|
||||||
response = self.client.post(
|
|
||||||
f"/apps/dashboard/{list1.id}/",
|
|
||||||
data={"text": "lorem ipsum"},
|
|
||||||
)
|
|
||||||
|
|
||||||
expected_error = html.escape(DUPLICATE_ITEM_ERROR)
|
|
||||||
self.assertContains(response, expected_error)
|
|
||||||
self.assertTemplateUsed(response, "apps/dashboard/list.html")
|
|
||||||
self.assertEqual(Item.objects.all().count(), 1)
|
|
||||||
|
|
||||||
class MyListsTest(TestCase):
|
|
||||||
def test_my_lists_url_renders_my_lists_template(self):
|
|
||||||
user = User.objects.create(email="a@b.cde")
|
|
||||||
response = self.client.get(f"/apps/dashboard/users/{user.id}/")
|
|
||||||
self.assertTemplateUsed(response, "apps/dashboard/my_lists.html")
|
|
||||||
|
|
||||||
def test_passes_correct_owner_to_template(self):
|
|
||||||
User.objects.create(email="wrong@owner.com")
|
|
||||||
correct_user = User.objects.create(email="a@b.cde")
|
|
||||||
response = self.client.get(f"/apps/dashboard/users/{correct_user.id}/")
|
|
||||||
self.assertEqual(response.context["owner"], correct_user)
|
|
||||||
|
|
||||||
def test_list_owner_is_saved_if_user_is_authenticated(self):
|
|
||||||
user = User.objects.create(email="a@b.cde")
|
|
||||||
self.client.force_login(user)
|
|
||||||
self.client.post("/apps/dashboard/new_list", data={"text": "new item"})
|
|
||||||
new_list = List.objects.get()
|
|
||||||
self.assertEqual(new_list.owner, user)
|
|
||||||
0
src/apps/dashboard/tests/unit/__init__.py
Normal file
0
src/apps/dashboard/tests/unit/__init__.py
Normal file
13
src/apps/dashboard/tests/unit/test_forms.py
Normal file
13
src/apps/dashboard/tests/unit/test_forms.py
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
from django.test import SimpleTestCase
|
||||||
|
|
||||||
|
from apps.dashboard.forms import (
|
||||||
|
EMPTY_ITEM_ERROR,
|
||||||
|
ItemForm,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleItemFormTest(SimpleTestCase):
|
||||||
|
def test_form_validation_for_blank_items(self):
|
||||||
|
form = ItemForm(data={"text": ""})
|
||||||
|
self.assertFalse(form.is_valid())
|
||||||
|
self.assertEqual(form.errors["text"], [EMPTY_ITEM_ERROR])
|
||||||
13
src/apps/dashboard/tests/unit/test_models.py
Normal file
13
src/apps/dashboard/tests/unit/test_models.py
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
from django.test import SimpleTestCase
|
||||||
|
|
||||||
|
from apps.dashboard.models import Item
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleItemModelTest(SimpleTestCase):
|
||||||
|
def test_default_text(self):
|
||||||
|
item = Item()
|
||||||
|
self.assertEqual(item.text, "")
|
||||||
|
|
||||||
|
def test_string_representation(self):
|
||||||
|
item = Item(text="sample text")
|
||||||
|
self.assertEqual(str(item), "sample text")
|
||||||
9
src/apps/dashboard/tests/unit/test_templates.py
Normal file
9
src/apps/dashboard/tests/unit/test_templates.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
from datetime import date
|
||||||
|
from django.test import SimpleTestCase
|
||||||
|
from django.template.loader import render_to_string
|
||||||
|
|
||||||
|
|
||||||
|
class FooterTemplateTest(SimpleTestCase):
|
||||||
|
def test_footer_shows_current_year(self):
|
||||||
|
rendered = render_to_string("core/_partials/_footer.html")
|
||||||
|
self.assertIn(str(date.today().year), rendered)
|
||||||
@@ -2,7 +2,16 @@ from django.urls import path
|
|||||||
from . import views
|
from . import views
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('new_list', views.new_list, name='new_list'),
|
path('new_note', views.new_note, name='new_note'),
|
||||||
path('<int:list_id>/', views.view_list, name='view_list'),
|
path('note/<uuid:note_id>/', views.view_note, name='view_note'),
|
||||||
path('users/<uuid:user_id>/', views.my_lists, name='my_lists'),
|
path('note/<uuid:note_id>/share_note', views.share_note, name="share_note"),
|
||||||
|
path('set_palette', views.set_palette, name='set_palette'),
|
||||||
|
path('set_profile', views.set_profile, name='set_profile'),
|
||||||
|
path('users/<uuid:user_id>/', views.my_notes, name='my_notes'),
|
||||||
|
path('toggle_applets', views.toggle_applets, name="toggle_applets"),
|
||||||
|
path('wallet/', views.wallet, name='wallet'),
|
||||||
|
path('wallet/toggle-applets', views.toggle_wallet_applets, name='toggle_wallet_applets'),
|
||||||
|
path('wallet/setup-intent', views.setup_intent, name='setup_intent'),
|
||||||
|
path('wallet/save-payment-method', views.save_payment_method, name='save_payment_method'),
|
||||||
|
path('kit-bag/', views.kit_bag, name='kit_bag'),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,34 +1,238 @@
|
|||||||
|
import stripe
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.contrib import messages
|
||||||
|
from django.contrib.auth.decorators import login_required
|
||||||
|
from django.db.models import Max, Q
|
||||||
|
from django.http import HttpResponse, HttpResponseForbidden, JsonResponse
|
||||||
from django.shortcuts import redirect, render
|
from django.shortcuts import redirect, render
|
||||||
from .forms import ExistingListItemForm, ItemForm
|
from django.utils import timezone
|
||||||
from .models import Item, List
|
from django.views.decorators.csrf import ensure_csrf_cookie
|
||||||
from apps.lyric.models import User
|
|
||||||
|
from apps.applets.models import Applet, UserApplet
|
||||||
|
from apps.applets.utils import applet_context
|
||||||
|
from apps.dashboard.forms import ExistingNoteItemForm, ItemForm
|
||||||
|
from apps.dashboard.models import Item, Note
|
||||||
|
from apps.lyric.models import PaymentMethod, Token, User, Wallet
|
||||||
|
|
||||||
|
|
||||||
|
APPLET_ORDER = ["wallet", "new-note", "my-notes", "username", "palette"]
|
||||||
|
UNLOCKED_PALETTES = frozenset([
|
||||||
|
"palette-default",
|
||||||
|
"palette-sepia",
|
||||||
|
"palette-oblivion-light",
|
||||||
|
"palette-monochrome-dark",
|
||||||
|
])
|
||||||
|
PALETTES = [
|
||||||
|
{"name": "palette-default", "label": "Earthman", "locked": False},
|
||||||
|
{"name": "palette-sepia", "label": "Sepia", "locked": False},
|
||||||
|
{"name": "palette-oblivion-light", "label": "Oblivion (Light)", "locked": False},
|
||||||
|
{"name": "palette-monochrome-dark", "label": "Monochrome (Dark)", "locked": False},
|
||||||
|
{"name": "palette-nirvana", "label": "Nirvana", "locked": True},
|
||||||
|
{"name": "palette-sheol", "label": "Sheol", "locked": True},
|
||||||
|
{"name": "palette-inferno", "label": "Inferno", "locked": True},
|
||||||
|
{"name": "palette-terrestre", "label": "Terrestre", "locked": True},
|
||||||
|
{"name": "palette-celestia", "label": "Celestia", "locked": True},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _recent_notes(user, limit=3):
|
||||||
|
return (
|
||||||
|
Note
|
||||||
|
.objects
|
||||||
|
.filter(Q(owner=user) | Q(shared_with=user))
|
||||||
|
.annotate(last_item=Max('item__id'))
|
||||||
|
.order_by('-last_item')
|
||||||
|
.distinct()[:limit]
|
||||||
|
)
|
||||||
|
|
||||||
def home_page(request):
|
def home_page(request):
|
||||||
return render(request, "apps/dashboard/home.html", {"form": ItemForm()})
|
context = {
|
||||||
|
"form": ItemForm(),
|
||||||
|
"palettes": PALETTES,
|
||||||
|
"page_class": "page-dashboard",
|
||||||
|
}
|
||||||
|
if request.user.is_authenticated:
|
||||||
|
context["applets"] = applet_context(request.user, "dashboard")
|
||||||
|
context["recent_notes"] = _recent_notes(request.user)
|
||||||
|
return render(request, "apps/dashboard/home.html", context)
|
||||||
|
|
||||||
def new_list(request):
|
def new_note(request):
|
||||||
form = ItemForm(data=request.POST)
|
form = ItemForm(data=request.POST)
|
||||||
if form.is_valid():
|
if form.is_valid():
|
||||||
nulist = List.objects.create()
|
nunote = Note.objects.create()
|
||||||
if request.user.is_authenticated:
|
if request.user.is_authenticated:
|
||||||
nulist.owner = request.user
|
nunote.owner = request.user
|
||||||
nulist.save()
|
nunote.save()
|
||||||
form.save(for_list=nulist)
|
form.save(for_note=nunote)
|
||||||
return redirect(nulist)
|
return redirect(nunote)
|
||||||
else:
|
else:
|
||||||
return render(request, "apps/dashboard/home.html", {"form": form})
|
context = {
|
||||||
|
"form": form,
|
||||||
|
"palettes": PALETTES,
|
||||||
|
"page_class": "page-dashboard",
|
||||||
|
}
|
||||||
|
if request.user.is_authenticated:
|
||||||
|
context["applets"] = applet_context(request.user, "dashboard")
|
||||||
|
context["recent_notes"] = _recent_notes(request.user)
|
||||||
|
return render(request, "apps/dashboard/home.html", context)
|
||||||
|
|
||||||
def view_list(request, list_id):
|
def view_note(request, note_id):
|
||||||
our_list = List.objects.get(id=list_id)
|
our_note = Note.objects.get(id=note_id)
|
||||||
form = ExistingListItemForm(for_list=our_list)
|
|
||||||
|
if our_note.owner:
|
||||||
|
if not request.user.is_authenticated:
|
||||||
|
return redirect("/")
|
||||||
|
if request.user != our_note.owner and request.user not in our_note.shared_with.all():
|
||||||
|
return HttpResponseForbidden()
|
||||||
|
|
||||||
|
form = ExistingNoteItemForm(for_note=our_note)
|
||||||
|
|
||||||
if request.method == "POST":
|
if request.method == "POST":
|
||||||
form = ExistingListItemForm(for_list=our_list, data=request.POST)
|
form = ExistingNoteItemForm(for_note=our_note, data=request.POST)
|
||||||
if form.is_valid():
|
if form.is_valid():
|
||||||
form.save()
|
form.save()
|
||||||
return redirect(our_list)
|
return redirect(our_note)
|
||||||
return render(request, "apps/dashboard/list.html", {"list": our_list, "form": form})
|
return render(request, "apps/dashboard/note.html", {"note": our_note, "form": form})
|
||||||
|
|
||||||
def my_lists(request, user_id):
|
def my_notes(request, user_id):
|
||||||
owner = User.objects.get(id=user_id)
|
owner = User.objects.get(id=user_id)
|
||||||
return render(request, "apps/dashboard/my_lists.html", {"owner": owner})
|
if not request.user.is_authenticated:
|
||||||
|
return redirect("/")
|
||||||
|
if request.user.id != owner.id:
|
||||||
|
return HttpResponseForbidden()
|
||||||
|
return render(request, "apps/dashboard/my_notes.html", {"owner": owner})
|
||||||
|
|
||||||
|
def share_note(request, note_id):
|
||||||
|
our_note = Note.objects.get(id=note_id)
|
||||||
|
try:
|
||||||
|
recipient = User.objects.get(email=request.POST["recipient"])
|
||||||
|
if recipient == request.user:
|
||||||
|
return redirect(our_note)
|
||||||
|
our_note.shared_with.add(recipient)
|
||||||
|
except User.DoesNotExist:
|
||||||
|
pass
|
||||||
|
messages.success(request, "An invite has been sent if that address is registered.")
|
||||||
|
return redirect(our_note)
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def set_palette(request):
|
||||||
|
if request.method == "POST":
|
||||||
|
palette = request.POST.get("palette", "")
|
||||||
|
if palette in UNLOCKED_PALETTES:
|
||||||
|
request.user.palette = palette
|
||||||
|
request.user.save(update_fields=["palette"])
|
||||||
|
if "application/json" in request.headers.get("Accept", ""):
|
||||||
|
return JsonResponse({"palette": request.user.palette})
|
||||||
|
return redirect("home")
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def set_profile(request):
|
||||||
|
if request.method == "POST":
|
||||||
|
username = request.POST.get("username", "")
|
||||||
|
request.user.username = username
|
||||||
|
request.user.save(update_fields=["username"])
|
||||||
|
return redirect("/")
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def toggle_applets(request):
|
||||||
|
checked = request.POST.getlist("applets")
|
||||||
|
for applet in Applet.objects.filter(context="dashboard"):
|
||||||
|
UserApplet.objects.update_or_create(
|
||||||
|
user=request.user,
|
||||||
|
applet=applet,
|
||||||
|
defaults={"visible": applet.slug in checked},
|
||||||
|
)
|
||||||
|
if request.headers.get("HX-Request"):
|
||||||
|
return render(request, "apps/dashboard/_partials/_applets.html", {
|
||||||
|
"applets": applet_context(request.user, "dashboard"),
|
||||||
|
"palettes": PALETTES,
|
||||||
|
"form": ItemForm(),
|
||||||
|
"recent_notes": _recent_notes(request.user),
|
||||||
|
})
|
||||||
|
return redirect("home")
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
@ensure_csrf_cookie
|
||||||
|
def wallet(request):
|
||||||
|
return render(request, "apps/dashboard/wallet.html", {
|
||||||
|
"wallet": request.user.wallet,
|
||||||
|
"pass_token": request.user.tokens.filter(token_type=Token.PASS).first(),
|
||||||
|
"coin": request.user.tokens.filter(token_type=Token.COIN).first(),
|
||||||
|
"free_tokens": list(request.user.tokens.filter(
|
||||||
|
token_type=Token.FREE, expires_at__gt=timezone.now()
|
||||||
|
).order_by("expires_at")),
|
||||||
|
"tithe_tokens": list(request.user.tokens.filter(token_type=Token.TITHE)),
|
||||||
|
"free_count": request.user.tokens.filter(
|
||||||
|
token_type=Token.FREE, expires_at__gt=timezone.now()
|
||||||
|
).count(),
|
||||||
|
"tithe_count": request.user.tokens.filter(token_type=Token.TITHE).count(),
|
||||||
|
"applets": applet_context(request.user, "wallet"),
|
||||||
|
"page_class": "page-wallet",
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def kit_bag(request):
|
||||||
|
tokens = list(request.user.tokens.all())
|
||||||
|
free_tokens = sorted(
|
||||||
|
[t for t in tokens if t.token_type == Token.FREE and t.expires_at and t.expires_at > timezone.now()],
|
||||||
|
key=lambda t: t.expires_at,
|
||||||
|
)
|
||||||
|
tithe_tokens = [t for t in tokens if t.token_type == Token.TITHE]
|
||||||
|
return render(request, "core/_partials/_kit_bag_panel.html", {
|
||||||
|
"equipped_deck": request.user.equipped_deck,
|
||||||
|
"equipped_trinket": request.user.equipped_trinket,
|
||||||
|
"free_token": free_tokens[0] if free_tokens else None,
|
||||||
|
"free_count": len(free_tokens),
|
||||||
|
"tithe_token": tithe_tokens[0] if tithe_tokens else None,
|
||||||
|
"tithe_count": len(tithe_tokens),
|
||||||
|
})
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def toggle_wallet_applets(request):
|
||||||
|
checked = request.POST.getlist("applets")
|
||||||
|
for applet in Applet.objects.filter(context="wallet"):
|
||||||
|
UserApplet.objects.update_or_create(
|
||||||
|
user=request.user,
|
||||||
|
applet=applet,
|
||||||
|
defaults={"visible": applet.slug in checked},
|
||||||
|
)
|
||||||
|
if request.headers.get("HX-Request"):
|
||||||
|
return render(request, "apps/wallet/_partials/_applets.html", {
|
||||||
|
"applets": applet_context(request.user, "wallet"),
|
||||||
|
"wallet": request.user.wallet,
|
||||||
|
"pass_token": request.user.tokens.filter(token_type=Token.PASS).first(),
|
||||||
|
"coin": request.user.tokens.filter(token_type=Token.COIN).first(),
|
||||||
|
"free_tokens": list(request.user.tokens.filter(token_type=Token.FREE)),
|
||||||
|
"tithe_tokens": list(request.user.tokens.filter(token_type=Token.TITHE)),
|
||||||
|
})
|
||||||
|
return redirect("wallet")
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def setup_intent(request):
|
||||||
|
stripe.api_key = settings.STRIPE_SECRET_KEY
|
||||||
|
user = request.user
|
||||||
|
if not user.stripe_customer_id:
|
||||||
|
customer = stripe.Customer.create(email=user.email)
|
||||||
|
user.stripe_customer_id = customer.id
|
||||||
|
user.save(update_fields=["stripe_customer_id"])
|
||||||
|
intent = stripe.SetupIntent.create(customer=user.stripe_customer_id)
|
||||||
|
return JsonResponse({
|
||||||
|
"client_secret": intent.client_secret,
|
||||||
|
"publishable_key": settings.STRIPE_PUBLISHABLE_KEY,
|
||||||
|
})
|
||||||
|
|
||||||
|
@login_required(login_url="/")
|
||||||
|
def save_payment_method(request):
|
||||||
|
stripe.api_key = settings.STRIPE_SECRET_KEY
|
||||||
|
pm_id = request.POST.get("payment_method_id")
|
||||||
|
pm = stripe.PaymentMethod.retrieve(pm_id)
|
||||||
|
stripe.PaymentMethod.attach(pm_id, customer=request.user.stripe_customer_id)
|
||||||
|
PaymentMethod.objects.create(
|
||||||
|
user=request.user,
|
||||||
|
stripe_pm_id=pm_id,
|
||||||
|
last4=pm.card.last4,
|
||||||
|
brand=pm.card.brand,
|
||||||
|
)
|
||||||
|
return JsonResponse({"last4": pm.card.last4, "brand": pm.card.brand})
|
||||||
|
|||||||
0
src/apps/drama/__init__.py
Normal file
0
src/apps/drama/__init__.py
Normal file
19
src/apps/drama/admin.py
Normal file
19
src/apps/drama/admin.py
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
from apps.drama.models import GameEvent
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(GameEvent)
|
||||||
|
class GameEventAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ("timestamp", "room", "actor", "verb")
|
||||||
|
list_filter = ("verb",)
|
||||||
|
readonly_fields = ("room", "actor", "verb", "data", "timestamp")
|
||||||
|
|
||||||
|
def has_add_permission(self, request):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def has_delete_permission(self, request, obj=None):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def has_change_permission(self, request, obj=None):
|
||||||
|
return False
|
||||||
6
src/apps/drama/apps.py
Normal file
6
src/apps/drama/apps.py
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class DramaConfig(AppConfig):
|
||||||
|
default_auto_field = 'django.db.models.BigAutoField'
|
||||||
|
name = 'apps.drama'
|
||||||
32
src/apps/drama/migrations/0001_initial.py
Normal file
32
src/apps/drama/migrations/0001_initial.py
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
# Generated by Django 6.0 on 2026-03-19 18:34
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('epic', '0006_table_status_and_table_seat'),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='GameEvent',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('verb', models.CharField(choices=[('room_created', 'Room created'), ('slot_reserved', 'Gate slot reserved'), ('slot_filled', 'Gate slot filled'), ('slot_returned', 'Gate slot returned'), ('slot_released', 'Gate slot released'), ('invite_sent', 'Invite sent'), ('role_select_started', 'Role select started'), ('role_selected', 'Role selected'), ('roles_revealed', 'Roles revealed')], max_length=30)),
|
||||||
|
('data', models.JSONField(default=dict)),
|
||||||
|
('timestamp', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('actor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='game_events', to=settings.AUTH_USER_MODEL)),
|
||||||
|
('room', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='events', to='epic.room')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'ordering': ['timestamp'],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
30
src/apps/drama/migrations/0002_scrollposition.py
Normal file
30
src/apps/drama/migrations/0002_scrollposition.py
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
# Generated by Django 6.0 on 2026-03-24 21:36
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('drama', '0001_initial'),
|
||||||
|
('epic', '0006_table_status_and_table_seat'),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='ScrollPosition',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('position', models.PositiveIntegerField(default=0)),
|
||||||
|
('updated_at', models.DateTimeField(auto_now=True)),
|
||||||
|
('room', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scroll_positions', to='epic.room')),
|
||||||
|
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='scroll_positions', to=settings.AUTH_USER_MODEL)),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'unique_together': {('user', 'room')},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user