first commit
This commit is contained in:
+61
@@ -0,0 +1,61 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
|
||||
# Virtual environments
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
|
||||
# Environment / secrets
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Django
|
||||
*.log
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
local_settings.py
|
||||
|
||||
# User-uploaded media
|
||||
media/
|
||||
|
||||
# Collected static files
|
||||
staticfiles/
|
||||
|
||||
# Python tooling / caches
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.coverage
|
||||
coverage.xml
|
||||
htmlcov/
|
||||
|
||||
# Packaging
|
||||
build/
|
||||
dist/
|
||||
*.egg-info/
|
||||
.eggs/
|
||||
|
||||
# Node / frontend tooling
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# IDEs / editors
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# OS junk
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Local development
|
||||
*.sqlite3
|
||||
@@ -0,0 +1,18 @@
|
||||
# Tasknest development notes
|
||||
|
||||
## Weather scheduling
|
||||
|
||||
The server gets a finite 16-day daily forecast from Open-Meteo and caches each user's normalized forecast for twelve hours. No browser code, template, or model calls Open-Meteo directly.
|
||||
|
||||
- **Dry** rejects a day with precipitation probability of 40% or more, or 0.5 mm or more precipitation.
|
||||
- **Sunny / mostly sunny** also requires a clear/partly-cloudy condition and at least four hours of sunshine.
|
||||
- **Warm** requires a maximum temperature of at least 15 °C.
|
||||
- **Dry and warm** requires both of the corresponding rules.
|
||||
|
||||
If no forecast is available, a weather-dependent task remains visible rather than being treated as unsuitable. If a forecast finds an unsuitable natural occurrence, Tasknest creates a weather-owned occurrence shift to the first suitable vacancy in the finite forecast horizon. Natural recurrences and existing weather shifts are skipped, so an occurrence is never duplicated. The original recurrence anchor is not changed.
|
||||
|
||||
Deferral precedence is: manual, missed, and Sick Day state are evaluated before weather movement. Weather never overwrites those sources. Weather shifts are stored separately in `TaskWeatherShift`, so they can be recalculated without modifying user-owned deferrals.
|
||||
|
||||
## Legacy ownership migration
|
||||
|
||||
Migration `0006` assigns old unowned tasks only when the database has exactly one active user. This local development database met that condition and its two existing tasks were assigned to that account. In a multi-user deployment the migration deliberately leaves legacy rows unowned instead of guessing; claim them explicitly before making ownership non-null at the database level.
|
||||
@@ -0,0 +1 @@
|
||||
node_modules/
|
||||
@@ -0,0 +1,51 @@
|
||||
# Tasknest frontend
|
||||
|
||||
This directory owns browser assets. Vite compiles `src/main.js`, its SCSS import,
|
||||
and the local `htmx.org` dependency. Django renders those assets through the
|
||||
`{% vite_asset 'src/main.js' %}` template tag in `planner/base.html`.
|
||||
|
||||
## First-time setup
|
||||
|
||||
Install Node.js 20.19+ (or a newer current LTS), then run:
|
||||
|
||||
```sh
|
||||
cd main/frontend
|
||||
npm install
|
||||
```
|
||||
|
||||
This installs Vite, Sass, HTMX, and Concurrently.
|
||||
|
||||
## Development
|
||||
|
||||
From `main/frontend`, start the normal CORS-free development workflow with one command:
|
||||
|
||||
```sh
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Concurrent output is labeled and color-coded: `assets` is cyan and `django` is green. Vite rebuilds SCSS and JavaScript whenever source files change; Django serves the generated assets from its own origin, so there is no request to port `5173`. Refresh the browser after an asset change. The command stops the other process if either process fails. The Django server listens on port `1234`; change the `dev:django` script in `package.json` if you need another port.
|
||||
|
||||
For environments where the browser can reach Vite directly on port `5173`, use optional HMR instead:
|
||||
|
||||
```sh
|
||||
npm run dev:hmr
|
||||
```
|
||||
|
||||
The HMR mode loads Vite's HMR client and `src/main.js` from the Vite server. If Django is served on a different host or port, set `VITE_DEV_SERVER` to the browser-reachable Vite URL. The development server uses `cors: true` deliberately; do not expose it as a production asset server.
|
||||
|
||||
## Production build
|
||||
|
||||
```sh
|
||||
cd main/frontend
|
||||
npm ci
|
||||
npm run build
|
||||
cd /home/jorenmartijn/django
|
||||
VITE_USE_DEV_SERVER=false tasksnest/bin/python main/manage.py collectstatic
|
||||
```
|
||||
|
||||
`npm run build` writes hashed assets and `.vite/manifest.json` to
|
||||
`planner/static/planner/dist/`. With `VITE_USE_DEV_SERVER=false`, Django's
|
||||
`vite_asset` tag reads that manifest and emits the correct hashed JavaScript and
|
||||
CSS URLs. Build before `collectstatic`; do not commit `node_modules` or the
|
||||
compiled `dist` output unless your deployment intentionally stores built assets
|
||||
in source control.
|
||||
Generated
+1837
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "tasknest-frontend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"scripts": {
|
||||
"dev": "concurrently --kill-others-on-fail --names assets,django --prefix-colors cyan,green \"npm run dev:assets\" \"npm run dev:django\"",
|
||||
"dev:assets": "vite build --watch",
|
||||
"dev:django": "VITE_USE_DEV_SERVER=false ../../tasksnest/bin/python ../manage.py runserver 0.0.0.0:1234",
|
||||
"dev:hmr": "concurrently --kill-others-on-fail --names vite,django --prefix-colors cyan,green \"npm run dev:vite\" \"npm run dev:django:hmr\"",
|
||||
"dev:vite": "vite",
|
||||
"dev:django:hmr": "../../tasksnest/bin/python ../manage.py runserver 0.0.0.0:1234",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"devDependencies": {
|
||||
"sass": "^1.93.2",
|
||||
"vite": "^7.1.7",
|
||||
"concurrently": "^9.2.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"htmx.org": "^2.0.7"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import htmx from 'htmx.org';
|
||||
import './styles/main.scss';
|
||||
|
||||
window.htmx = htmx;
|
||||
|
||||
function getCookie(name) {
|
||||
const value = `; ${document.cookie}`;
|
||||
const parts = value.split(`; ${name}=`);
|
||||
return parts.length === 2 ? parts.pop().split(';').shift() : '';
|
||||
}
|
||||
|
||||
htmx.on('htmx:configRequest', (event) => {
|
||||
event.detail.headers['X-CSRFToken'] = getCookie('csrftoken');
|
||||
});
|
||||
|
||||
|
||||
let fastingTimerInterval;
|
||||
|
||||
function formatElapsed(milliseconds) {
|
||||
const totalSeconds = Math.max(0, Math.floor(milliseconds / 1000));
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return [hours, minutes, seconds].map((value) => String(value).padStart(2, '0')).join(':');
|
||||
}
|
||||
|
||||
function updateFastingTimers() {
|
||||
document.querySelectorAll('[data-fasting-timer]').forEach((timer) => {
|
||||
const cycleStart = Date.parse(timer.dataset.cycleStart);
|
||||
const cycleEnd = Date.parse(timer.dataset.cycleEnd);
|
||||
if (!Number.isFinite(cycleStart) || !Number.isFinite(cycleEnd) || cycleEnd <= cycleStart) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const progress = Math.max(0, Math.min(100, ((now - cycleStart) / (cycleEnd - cycleStart)) * 100));
|
||||
const elapsed = timer.querySelector('[data-fasting-elapsed]');
|
||||
const ring = timer.querySelector('[data-fasting-progress]');
|
||||
if (elapsed) elapsed.textContent = formatElapsed(now - cycleStart);
|
||||
if (ring) ring.style.strokeDashoffset = String(100 - progress);
|
||||
timer.setAttribute('aria-label', `${timer.dataset.phase} progress: ${Math.floor(progress)} percent`);
|
||||
|
||||
// A server refresh switches to the next phase and synchronizes completion history.
|
||||
if (now >= cycleEnd && !timer.dataset.refreshing) {
|
||||
timer.dataset.refreshing = 'true';
|
||||
htmx.ajax('GET', timer.dataset.refreshUrl, {target: '#fasting-widget', swap: 'outerHTML'});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initialiseFastingTimers() {
|
||||
window.clearInterval(fastingTimerInterval);
|
||||
updateFastingTimers();
|
||||
if (document.querySelector('[data-fasting-timer]')) {
|
||||
fastingTimerInterval = window.setInterval(updateFastingTimers, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialiseFastingTimers);
|
||||
htmx.on('htmx:afterSwap', initialiseFastingTimers);
|
||||
|
||||
|
||||
function initialiseGeolocation() {
|
||||
const button = document.querySelector('[data-use-location]');
|
||||
if (!button || button.dataset.ready) return;
|
||||
button.dataset.ready = 'true';
|
||||
button.addEventListener('click', () => {
|
||||
const status = document.querySelector('[data-location-status]');
|
||||
const latitude = document.querySelector('[name="latitude"]');
|
||||
const longitude = document.querySelector('[name="longitude"]');
|
||||
if (!navigator.geolocation) {
|
||||
if (status) status.textContent = 'Location is unavailable in this browser. You can enter coordinates manually.';
|
||||
return;
|
||||
}
|
||||
if (status) status.textContent = 'Requesting your location…';
|
||||
navigator.geolocation.getCurrentPosition((position) => {
|
||||
if (latitude) latitude.value = position.coords.latitude.toFixed(5);
|
||||
if (longitude) longitude.value = position.coords.longitude.toFixed(5);
|
||||
if (status) status.textContent = 'Location added. Save settings to confirm it.';
|
||||
}, () => {
|
||||
if (status) status.textContent = 'Location was unavailable. You can enter coordinates manually.';
|
||||
}, {enableHighAccuracy: false, timeout: 10000, maximumAge: 0});
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', initialiseGeolocation);
|
||||
htmx.on('htmx:afterSwap', initialiseGeolocation);
|
||||
|
||||
|
||||
function initialiseCategoryPickers() {
|
||||
document.querySelectorAll("[data-category-picker]").forEach((picker) => {
|
||||
if (picker.dataset.ready) return;
|
||||
picker.dataset.ready = "true";
|
||||
|
||||
const input = picker.querySelector("[data-category-input]");
|
||||
const clearButton = picker.querySelector("[data-category-clear]");
|
||||
const suggestions = picker.querySelector("[role=listbox]");
|
||||
const suggestionUrl = input?.dataset.suggestionsUrl;
|
||||
if (!input || !clearButton || !suggestions || !suggestionUrl) return;
|
||||
|
||||
let activeIndex = -1;
|
||||
let requestSequence = 0;
|
||||
|
||||
const options = () => Array.from(suggestions.querySelectorAll("[role=option]"));
|
||||
const updateClearButton = () => { clearButton.hidden = !input.value; };
|
||||
const closeSuggestions = () => {
|
||||
activeIndex = -1;
|
||||
suggestions.hidden = true;
|
||||
suggestions.replaceChildren();
|
||||
input.setAttribute("aria-expanded", "false");
|
||||
input.removeAttribute("aria-activedescendant");
|
||||
};
|
||||
const setActiveOption = (index) => {
|
||||
const availableOptions = options();
|
||||
if (!availableOptions.length) return;
|
||||
activeIndex = (index + availableOptions.length) % availableOptions.length;
|
||||
availableOptions.forEach((option, optionIndex) => {
|
||||
option.setAttribute("aria-selected", String(optionIndex === activeIndex));
|
||||
});
|
||||
const activeOption = availableOptions[activeIndex];
|
||||
input.setAttribute("aria-activedescendant", activeOption.id);
|
||||
activeOption.scrollIntoView({ block: "nearest" });
|
||||
};
|
||||
const choose = (category) => {
|
||||
input.value = category;
|
||||
updateClearButton();
|
||||
closeSuggestions();
|
||||
input.focus();
|
||||
};
|
||||
const showSuggestions = (categories) => {
|
||||
suggestions.replaceChildren();
|
||||
activeIndex = -1;
|
||||
input.removeAttribute("aria-activedescendant");
|
||||
categories.forEach((category, index) => {
|
||||
const option = document.createElement("li");
|
||||
option.id = input.id + "-option-" + index;
|
||||
option.setAttribute("role", "option");
|
||||
option.setAttribute("aria-selected", "false");
|
||||
option.dataset.categoryValue = category;
|
||||
option.textContent = category;
|
||||
suggestions.append(option);
|
||||
});
|
||||
suggestions.hidden = categories.length === 0;
|
||||
input.setAttribute("aria-expanded", String(categories.length > 0));
|
||||
};
|
||||
const loadSuggestions = async () => {
|
||||
const requestId = ++requestSequence;
|
||||
const url = new URL(suggestionUrl, window.location.origin);
|
||||
url.searchParams.set("q", input.value);
|
||||
try {
|
||||
const response = await fetch(url, { headers: { Accept: "application/json" } });
|
||||
if (!response.ok || requestId !== requestSequence) return;
|
||||
const payload = await response.json();
|
||||
showSuggestions(payload.categories || []);
|
||||
} catch {
|
||||
if (requestId === requestSequence) closeSuggestions();
|
||||
}
|
||||
};
|
||||
|
||||
input.addEventListener("input", () => {
|
||||
updateClearButton();
|
||||
loadSuggestions();
|
||||
});
|
||||
input.addEventListener("focus", () => {
|
||||
if (input.value) loadSuggestions();
|
||||
});
|
||||
input.addEventListener("keydown", (event) => {
|
||||
const availableOptions = options();
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
if (suggestions.hidden) loadSuggestions();
|
||||
else setActiveOption(activeIndex + 1);
|
||||
} else if (event.key === "ArrowUp" && !suggestions.hidden) {
|
||||
event.preventDefault();
|
||||
setActiveOption(activeIndex - 1);
|
||||
} else if (event.key === "Enter" && activeIndex >= 0 && availableOptions[activeIndex]) {
|
||||
event.preventDefault();
|
||||
choose(availableOptions[activeIndex].dataset.categoryValue);
|
||||
} else if (event.key === "Escape") {
|
||||
closeSuggestions();
|
||||
}
|
||||
});
|
||||
suggestions.addEventListener("click", (event) => {
|
||||
const option = event.target.closest("[role=option]");
|
||||
if (option) choose(option.dataset.categoryValue);
|
||||
});
|
||||
clearButton.addEventListener("click", () => {
|
||||
input.value = "";
|
||||
updateClearButton();
|
||||
closeSuggestions();
|
||||
input.focus();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", initialiseCategoryPickers);
|
||||
htmx.on("htmx:afterSwap", initialiseCategoryPickers);
|
||||
@@ -0,0 +1,144 @@
|
||||
@use 'sass:color';
|
||||
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Fraunces:opsz,wght@9..144,600;9..144,700&display=swap');
|
||||
|
||||
$ink: #25292e;
|
||||
$muted: #6d737a;
|
||||
$line: #e6e8e3;
|
||||
$surface: #ffffff;
|
||||
$canvas: #f7f7f3;
|
||||
$forest: #235943;
|
||||
$forest-dark: #174333;
|
||||
$mint: #e0f0e5;
|
||||
$coral: #d95d4e;
|
||||
$shadow: 0 18px 45px rgba(29, 43, 37, .08);
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html { min-height: 100%; background: $canvas; }
|
||||
body {
|
||||
min-width: 320px;
|
||||
margin: 0;
|
||||
color: $ink;
|
||||
background: $canvas;
|
||||
font-family: 'DM Sans', system-ui, sans-serif;
|
||||
font-size: 1rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
a { color: inherit; }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button { cursor: pointer; }
|
||||
|
||||
.site-header {
|
||||
border-bottom: 1px solid rgba($ink, .08);
|
||||
background: rgba($canvas, .9);
|
||||
backdrop-filter: blur(14px);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 5;
|
||||
|
||||
&__inner {
|
||||
max-width: 1180px;
|
||||
min-height: 72px;
|
||||
margin: 0 auto;
|
||||
padding: 0 28px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
}
|
||||
}
|
||||
.brand {
|
||||
display: inline-flex;
|
||||
gap: 9px;
|
||||
align-items: center;
|
||||
color: $ink;
|
||||
text-decoration: none;
|
||||
font-family: Fraunces, Georgia, serif;
|
||||
font-size: 1.35rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -.04em;
|
||||
&__mark { display: grid; place-items: center; width: 27px; height: 27px; border-radius: 9px; color: white; background: $forest; font: 700 17px/1 'DM Sans', sans-serif; }
|
||||
}
|
||||
.primary-nav { display: flex; align-items: center; gap: 25px; font-size: .93rem; font-weight: 600; }
|
||||
.primary-nav > a:not(.button) { text-decoration: none; color: $muted; &:hover { color: $forest; } }
|
||||
.page-content { max-width: 1180px; margin: 0 auto; padding: 64px 28px 88px; }
|
||||
|
||||
.hero { display: flex; align-items: end; justify-content: space-between; gap: 32px; margin: 0 0 42px; }
|
||||
.eyebrow { margin: 0 0 9px; color: $forest; font-size: .74rem; font-weight: 700; letter-spacing: .1em; text-transform: uppercase; }
|
||||
h1, h2, p { margin-top: 0; }
|
||||
h1 { max-width: 740px; margin-bottom: 13px; font-family: Fraunces, Georgia, serif; font-size: clamp(2.25rem, 5vw, 4.25rem); font-weight: 700; line-height: 1.04; letter-spacing: -.055em; }
|
||||
h2 { font-family: Fraunces, Georgia, serif; letter-spacing: -.03em; }
|
||||
.hero__copy { max-width: 500px; margin-bottom: 0; color: $muted; font-size: 1.08rem; }
|
||||
|
||||
.button {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
|
||||
min-height: 46px; padding: 0 19px; border: 1px solid $forest; border-radius: 999px;
|
||||
color: white; background: $forest; text-decoration: none; font-size: .9rem; font-weight: 700;
|
||||
transition: transform .16s ease, background .16s ease, box-shadow .16s ease;
|
||||
&:hover { background: $forest-dark; box-shadow: 0 7px 18px rgba($forest, .2); transform: translateY(-1px); }
|
||||
&:focus-visible { outline: 3px solid rgba($forest, .3); outline-offset: 3px; }
|
||||
&--compact { min-height: 38px; padding: 0 14px; }
|
||||
&--secondary { color: $forest; border-color: rgba($forest, .28); background: transparent; &:hover { color: white; background: $forest; } }
|
||||
&--danger { border-color: $coral; background: $coral; &:hover { background: color.adjust($coral, $lightness: -8%); } }
|
||||
}
|
||||
.text-link, .back-link a { color: $forest; font-weight: 700; text-underline-offset: 3px; }
|
||||
|
||||
.home-layout { display: grid; grid-template-columns: minmax(0, 1fr) 285px; gap: 24px; align-items: start; }.home-main { min-width: 0; }.homepage-sidebar { position: sticky; top: 96px; }.fasting-widget { padding: 23px; border: 1px solid $line; border-radius: 18px; background: $surface; box-shadow: $shadow; }.fasting-widget__topline { display: flex; align-items: start; justify-content: space-between; gap: 12px; }.fasting-widget h2 { margin: 0 0 8px; font-size: 1.38rem; }.fasting-widget__copy { margin: 0 0 18px; color: $muted; font-size: .9rem; }.fasting-state { flex: 0 0 auto; padding: 4px 8px; border-radius: 999px; font-size: .67rem; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; }.fasting-state--fasting { color: #316e58; background: $mint; }.fasting-state--eating { color: #87651f; background: #fff5d9; }.fasting-timer { --timer-color: #2e8b67; position: relative; display: grid; place-items: center; width: min(100%, 215px); aspect-ratio: 1; margin: 19px auto 13px; }.fasting-timer--eating { --timer-color: #dc9a30; }.fasting-timer__ring { width: 100%; height: 100%; transform: rotate(-90deg); }.fasting-timer__track, .fasting-timer__progress { fill: none; stroke-width: 9; }.fasting-timer__track { stroke: #e9ece7; }.fasting-timer__progress { stroke: var(--timer-color); stroke-linecap: round; stroke-dasharray: 100; stroke-dashoffset: 100; transition: stroke-dashoffset .75s linear; }.fasting-timer__content { position: absolute; display: grid; justify-items: center; gap: 2px; padding: 20px; text-align: center; }.fasting-timer__content strong { font-size: clamp(1.6rem, 3.1vw, 2.25rem); font-variant-numeric: tabular-nums; letter-spacing: -.055em; line-height: 1; }.fasting-timer__content span { color: $muted; font-size: .72rem; font-weight: 700; }.fasting-widget__cycle-copy { text-align: center; font-size: .82rem; }.fasting-widget__cycle-copy time { color: $ink; font-weight: 700; }
|
||||
.fasting-widget__schedule { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; padding: 13px 0; margin: 0 0 16px; border-top: 1px solid $line; border-bottom: 1px solid $line; }.fasting-widget__schedule dt { color: $muted; font-size: .68rem; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }.fasting-widget__schedule dd { margin: 3px 0 0; font-size: .86rem; font-weight: 700; }.fasting-widget__actions { display: flex; align-items: center; gap: 14px; }.fasting-widget__actions form { margin: 0; }.fasting-history { margin-top: 22px; }.fasting-history h3 { margin: 0 0 8px; color: $muted; font-family: 'DM Sans', system-ui, sans-serif; font-size: .68rem; letter-spacing: .06em; text-transform: uppercase; }.fasting-history ul { display: grid; gap: 6px; padding: 0; margin: 0; list-style: none; }.fasting-history li { display: flex; justify-content: space-between; gap: 8px; color: $muted; font-size: .78rem; }.fasting-history time { color: $ink; font-weight: 700; }.fasting-form { display: grid; gap: 14px; }.fasting-form .field label:not(.checkbox-field) { display: block; margin-bottom: 6px; color: #444b4b; font-size: .82rem; font-weight: 700; }.fasting-form .field input:not([type='checkbox']) { width: 100%; padding: 9px 10px; border: 1px solid #cfd4cb; border-radius: 8px; color: $ink; }.fasting-form .field small { display: block; margin-top: 4px; color: $muted; font-size: .75rem; }
|
||||
.task-panel, .detail-card, .task-form, .confirmation-card { border: 1px solid $line; border-radius: 20px; background: $surface; box-shadow: $shadow; }
|
||||
.task-filters { display: flex; align-items: end; gap: 14px; padding: 21px 24px; border-bottom: 1px solid $line; background: #fcfcfa; border-radius: 20px 20px 0 0; }
|
||||
.task-filters label { display: block; margin-bottom: 5px; color: $muted; font-size: .77rem; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; }
|
||||
.task-filters select { min-width: 160px; padding: 8px 34px 8px 11px; border: 1px solid #cfd4cb; border-radius: 8px; background: white; color: $ink; }
|
||||
.task-filters__actions { display: flex; align-items: center; gap: 12px; margin-left: auto; }
|
||||
.loading-indicator { color: $muted; font-size: .85rem; }
|
||||
.htmx-indicator { opacity: 0; transition: opacity .18s ease; }
|
||||
.htmx-request .htmx-indicator, .htmx-request.htmx-indicator { opacity: 1; }
|
||||
.task-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 18px; padding: 24px; }
|
||||
.task-card { display: flex; flex-direction: column; min-height: 253px; padding: 20px; border: 1px solid $line; border-radius: 15px; background: white; transition: transform .18s ease, box-shadow .18s ease; &:hover { box-shadow: 0 12px 24px rgba(25, 37, 31, .08); transform: translateY(-2px); } }
|
||||
.task-card--inactive { background: #fbfbf9; opacity: .72; }
|
||||
.task-card__topline, .task-card__footer, .task-card__meta { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.task-card__topline { color: $muted; font-size: .78rem; }
|
||||
.priority { display: inline-flex; padding: 3px 8px; border-radius: 999px; font-size: .68rem; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; }
|
||||
.priority--low { color: #537363; background: #edf5ef; }
|
||||
.priority--medium { color: #87651f; background: #fff5d9; }
|
||||
.priority--high { color: #9f4034; background: #fff0ed; }
|
||||
.task-card h2 { margin: 19px 0 7px; font-size: 1.35rem; line-height: 1.18; }.task-card h2 a { text-decoration: none; &:hover { color: $forest; } }
|
||||
.task-card__description { margin-bottom: 14px; color: $muted; font-size: .9rem; }.task-card__meta { justify-content: flex-start; flex-wrap: wrap; color: $muted; font-size: .77rem; }.task-card__meta span { padding: 3px 7px; border-radius: 5px; background: #f2f3ef; }
|
||||
.subtask-count { margin: auto 0 12px; color: $muted; font-size: .78rem; }.task-card__footer { padding-top: 13px; border-top: 1px solid $line; }.task-card__footer form { margin: 0; }
|
||||
.status-button { display: inline-flex; align-items: center; gap: 6px; padding: 0; border: 0; color: $muted; background: none; font-size: .79rem; font-weight: 700; }.status-button__dot { width: 8px; height: 8px; border-radius: 50%; background: $forest; }.task-card--inactive .status-button__dot { background: #aeb4ae; }
|
||||
.empty-state { padding: 70px 24px; text-align: center; }.empty-state h2 { margin: 11px 0 4px; font-size: 1.5rem; }.empty-state p { color: $muted; }.empty-state__icon { display: grid; place-items: center; width: 45px; height: 45px; margin: auto; border-radius: 14px; color: $forest; background: $mint; font-weight: 700; }
|
||||
|
||||
.planner-hero { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 38px; align-items: end; margin-bottom: 38px; }.planner-hero > div > p:last-child { max-width: 540px; margin-bottom: 0; color: $muted; font-size: 1.05rem; }.planner-controls { display: flex; align-items: end; gap: 12px; padding: 18px; border: 1px solid $line; border-radius: 16px; background: $surface; box-shadow: $shadow; }.planner-controls label { display: block; margin-bottom: 5px; color: $muted; font-size: .75rem; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }.planner-controls input, .planner-controls select { min-height: 39px; padding: 7px 9px; border: 1px solid #cfd4cb; border-radius: 8px; background: white; color: $ink; }.planner-controls .button { min-height: 39px; padding: 0 14px; }.recommendations-panel { border: 1px solid $line; border-radius: 20px; background: $surface; box-shadow: $shadow; overflow: hidden; }.recommendations-panel__header { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 25px 28px; border-bottom: 1px solid $line; background: #fcfcfa; }.recommendations-panel__header h2 { margin: 0; font-size: 1.65rem; }.budget-note { margin: 0; color: $muted; font-size: .9rem; }.budget-note strong { color: $forest; }.recommendation-list { padding: 16px 24px 24px; }.recommendation-card { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 16px; padding: 23px 4px; border-bottom: 1px solid $line; }.recommendation-card:last-child { border-bottom: 0; }.recommendation-card h3 { margin: 11px 0 4px; font-family: Fraunces, Georgia, serif; font-size: 1.32rem; letter-spacing: -.025em; }.recommendation-card h3 a { text-decoration: none; &:hover { color: $forest; } }.recommendation-card__main > p { margin: 0; color: $muted; font-size: .88rem; }.recommendation-card__subtasks { grid-column: 1 / -1; margin-top: 5px; padding: 15px 17px; border-radius: 10px; background: #f6f8f4; }.recommendation-card__subtasks h4 { margin: 0 0 8px; color: $muted; font-size: .72rem; letter-spacing: .06em; text-transform: uppercase; }.recommendation-card__subtasks ul { display: grid; gap: 7px; padding: 0; margin: 0; list-style: none; }.recommendation-card__subtasks li { display: flex; justify-content: space-between; gap: 12px; font-size: .9rem; }.recommendation-card__subtasks a { color: $ink; font-weight: 700; }.recommendation-card__subtasks span { color: $muted; font-size: .82rem; }
|
||||
.back-link { margin-bottom: 25px; font-size: .9rem; }.detail-card { overflow: hidden; }.detail-card__header { display: flex; justify-content: space-between; gap: 28px; padding: 42px 44px; color: white; background: $forest; }.detail-card__header .eyebrow { color: #b7d9c2; }.detail-card__header h1 { margin-bottom: 10px; }.detail-card__date { margin: 0; color: #d6e8da; }.detail-card__actions { display: flex; align-items: start; gap: 13px; }.detail-card__actions .button--secondary { color: white; border-color: rgba(white, .5); }.detail-card__actions .button--secondary:hover { color: $forest; background: white; }.icon-link { color: #d6e8da; font-size: .86rem; }.detail-card__body { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(190px, .7fr); gap: 40px; padding: 38px 44px; }.prose { color: #3e4549; }.prose p:last-child { margin-bottom: 0; }.muted { color: $muted; }.task-facts { margin: 0; }.task-facts > div { padding: 13px 0; border-bottom: 1px solid $line; }.task-facts > div:first-child { padding-top: 0; }.task-facts dt { color: $muted; font-size: .75rem; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; }.task-facts dd { margin: 3px 0 0; font-weight: 600; }.task-facts a { color: $forest; }.subtasks-section { margin: 42px 0 0; }.subtasks-section h2 { margin-bottom: 14px; font-size: 2rem; }.subtasks-list { max-width: 760px; padding: 0; margin: 0; list-style: none; border-top: 1px solid $line; }.subtasks-list li { display: flex; justify-content: space-between; gap: 20px; padding: 15px 4px; border-bottom: 1px solid $line; }.subtasks-list a { color: $ink; font-weight: 700; }.subtasks-list span { color: $muted; font-size: .86rem; }
|
||||
|
||||
.inline-form-panel { padding: 32px; }.inline-form-panel__header { display: flex; align-items: start; justify-content: space-between; gap: 24px; margin-bottom: 27px; }.inline-form-panel__header h2 { margin: 0 0 5px; font-size: 2rem; }.inline-form-panel__header p:last-child { margin: 0; color: $muted; }.task-form--inline { padding: 0; border: 0; border-radius: 0; box-shadow: none; }
|
||||
.form-layout { display: grid; grid-template-columns: minmax(250px, .7fr) minmax(0, 1.3fr); gap: clamp(32px, 7vw, 100px); align-items: start; }.form-layout__intro { padding-top: 25px; }.form-layout__intro h1 { font-size: clamp(2.4rem, 4vw, 3.5rem); }.form-layout__intro p:last-child { color: $muted; font-size: 1.05rem; }.task-form { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; padding: 30px; }.field { min-width: 0; }.field--title, .field--description, .field--parent_task, .form-actions { grid-column: 1 / -1; }.field label:not(.checkbox-field) { display: block; margin-bottom: 7px; color: #444b4b; font-size: .85rem; font-weight: 700; }.field input:not([type='checkbox']), .field select, .field textarea { width: 100%; padding: 10px 11px; border: 1px solid #cfd4cb; border-radius: 9px; color: $ink; background: white; outline: none; transition: border .15s, box-shadow .15s; &:focus { border-color: $forest; box-shadow: 0 0 0 3px rgba($forest, .12); } }.field textarea { resize: vertical; }.checkbox-field { display: inline-flex; align-items: center; gap: 8px; min-height: 42px; color: #444b4b; font-size: .9rem; font-weight: 600; }.checkbox-field input { width: 17px; height: 17px; accent-color: $forest; }.field small { display: block; margin-top: 4px; color: $muted; }.field--error input, .field--error select, .field--error textarea { border-color: $coral; }.field-error, .form-errors { margin: 5px 0 0; color: #aa382d; font-size: .84rem; }.form-errors { grid-column: 1 / -1; padding: 11px; border-radius: 8px; background: #fff0ed; }.form-actions { display: flex; align-items: center; gap: 18px; margin-top: 4px; }.confirmation-card { max-width: 660px; padding: 46px; }.confirmation-card h1 { font-size: clamp(2.2rem, 4vw, 3.4rem); }.confirmation-card > p:not(.eyebrow) { max-width: 500px; color: $muted; font-size: 1.05rem; }
|
||||
.visually-hidden { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }
|
||||
|
||||
@media (max-width: 820px) { .home-layout { grid-template-columns: 1fr; }.homepage-sidebar { position: static; }.planner-hero { grid-template-columns: 1fr; align-items: start; }.planner-controls { justify-content: start; }.task-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }.form-layout { grid-template-columns: 1fr; }.form-layout__intro { padding-top: 0; }.detail-card__header, .detail-card__body { padding: 30px; }.detail-card__header { display: block; }.detail-card__actions { margin-top: 24px; }.detail-card__body { grid-template-columns: 1fr; gap: 30px; } }
|
||||
@media (max-width: 560px) { .planner-controls { display: grid; grid-template-columns: 1fr; }.planner-controls input, .planner-controls select { width: 100%; }.recommendations-panel__header { display: block; padding: 20px; }.budget-note { margin-top: 10px; }.recommendation-list { padding: 8px 20px 20px; }.recommendation-card { grid-template-columns: 1fr; }.recommendation-card > .text-link { justify-self: start; }.site-header__inner, .page-content { padding-left: 18px; padding-right: 18px; }.site-header__inner { min-height: 62px; }.primary-nav { gap: 12px; }.primary-nav > a:not(.button) { display: none; }.page-content { padding-top: 40px; }.hero { display: block; margin-bottom: 30px; }.hero .button { margin-top: 21px; }.task-filters { flex-wrap: wrap; padding: 17px; }.task-filters > div { flex: 1; }.task-filters__actions { width: 100%; margin-left: 0; }.task-filters select { width: 100%; }.task-grid { grid-template-columns: 1fr; padding: 15px; }.task-form { grid-template-columns: 1fr; padding: 22px; }.field--title, .field--description, .field--parent_task, .form-actions { grid-column: auto; }.detail-card__header, .detail-card__body, .confirmation-card, .inline-form-panel { padding: 25px; }.detail-card__actions { align-items: center; }.subtasks-list li { padding-left: 0; padding-right: 0; } }
|
||||
|
||||
|
||||
.nav-logout { margin: 0; }.nav-logout button { padding: 0; border: 0; color: $muted; background: transparent; font-weight: 600; &:hover { color: $forest; } }.flash-message { max-width: 760px; margin: 0 auto 24px; padding: 12px 15px; border-radius: 10px; color: $forest-dark; background: $mint; font-weight: 600; }.weather-widget { margin-bottom: 18px; padding: 20px 23px; border: 1px solid $line; border-radius: 18px; background: linear-gradient(145deg, #f7fbf8, $surface); box-shadow: $shadow; }.weather-widget__topline { display: flex; align-items: start; justify-content: space-between; }.weather-widget h2 { margin: 0; font-size: 1.38rem; }.weather-widget__icon { font-size: 2rem; }.weather-widget__reading { margin: 14px 0 3px; color: $ink; }.weather-widget__reading strong { font-size: 1.7rem; letter-spacing: -.05em; }.weather-widget__detail { margin: 0 0 10px; color: $muted; font-size: .84rem; }.auth-panel, .settings-page { max-width: 680px; margin: 0 auto; }.auth-panel { padding: 36px; border: 1px solid $line; border-radius: 20px; background: $surface; box-shadow: $shadow; }.auth-panel h1, .settings-page > h1 { font-size: clamp(2.3rem, 4vw, 3.5rem); }.auth-panel form, .settings-card form { display: grid; gap: 16px; }.form-field { display: grid; gap: 6px; }.form-field label { color: #444b4b; font-size: .85rem; font-weight: 700; }.form-field input, .form-field select { min-height: 42px; padding: 9px 10px; border: 1px solid #cfd4cb; border-radius: 9px; }.form-field small { color: $muted; }.settings-card { margin-top: 24px; padding: 28px; border: 1px solid $line; border-radius: 18px; background: $surface; box-shadow: $shadow; }.settings-card h2 { margin-bottom: 7px; }.settings-card > p { color: $muted; }.settings-card [data-location-status] { min-height: 1.5em; color: $muted; font-size: .85rem; }
|
||||
|
||||
.task-weather-forecast { display: flex; align-items: center; gap: 7px; margin: 13px 0 0; padding: 9px 10px; border-radius: 8px; color: #3d5750; background: #f1f7f2; font-size: .78rem; font-weight: 600; }.task-weather-forecast > span:first-child { font-size: 1.05rem; }
|
||||
|
||||
|
||||
.workout-panel { margin-top: 30px; padding: 27px 29px; border: 1px solid $line; border-radius: 20px; background: $surface; box-shadow: $shadow; }.workout-panel__header { display: flex; align-items: center; gap: 20px; }.workout-panel__header h2 { margin: 0; font-size: 1.7rem; }.workout-panel__header p:last-child { margin: 4px 0 0; color: $muted; font-size: .86rem; }.workout-panel__summary { display: grid; margin-left: auto; text-align: right; }.workout-panel__summary strong { color: $forest; font-size: 1.3rem; }.workout-panel__summary span, .workout-panel__note { color: $muted; font-size: .78rem; }.workout-panel__note { margin: 17px 0 -3px; }.workout-list { margin-top: 23px; border-top: 1px solid $line; }.workout-entry { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 17px 2px; border-bottom: 1px solid $line; }.workout-entry--completed { opacity: .62; }.workout-entry--completed h3 { text-decoration: line-through; }.workout-entry h3 { margin: 0 0 3px; font-family: Fraunces, Georgia, serif; font-size: 1.16rem; }.workout-entry p { margin: 0; color: $muted; font-size: .84rem; }.workout-entry__actions { display: flex; align-items: center; gap: 13px; }.workout-entry__actions form { margin: 0; }.workout-entry__remove { padding: 0; border: 0; background: transparent; color: $coral; }.workout-empty { margin-top: 22px; color: $muted; }.workout-form { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; }.workout-form .field--error, .workout-form .form-actions { grid-column: 1 / -1; }
|
||||
@media (max-width: 560px) { .workout-panel { padding: 22px; }.workout-panel__header, .workout-entry { align-items: flex-start; flex-wrap: wrap; }.workout-panel__summary { margin-left: 0; text-align: left; }.workout-entry__actions { width: 100%; }.workout-form { grid-template-columns: 1fr; } }
|
||||
.checkin-panel { margin-top: 30px; padding: 27px 29px; border: 1px solid $line; border-radius: 20px; background: $surface; box-shadow: $shadow; }
|
||||
.checkin-panel__header { display: flex; justify-content: space-between; gap: 24px; align-items: start; }.checkin-panel__header h2 { margin: 0; font-size: 1.7rem; }.checkin-panel__header > div > p:last-child { margin: 4px 0 0; color: $muted; font-size: .86rem; }.checkin-streaks { display: flex; flex-wrap: wrap; justify-content: end; gap: 12px 18px; margin: 0; }.checkin-streaks > div { min-width: 74px; }.checkin-streaks dt { color: $muted; font-size: .66rem; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }.checkin-streaks dd { margin: 2px 0 0; color: $forest; font-size: .92rem; font-weight: 700; }.checkin-streaks__note { min-width: 115px; }.checkin-streaks__note dd { color: $muted; font-size: .75rem; }
|
||||
.checkin-form { display: grid; grid-template-columns: 120px repeat(2, minmax(110px, 1fr)); gap: 15px; align-items: end; margin-top: 24px; padding: 19px 0; border-top: 1px solid $line; border-bottom: 1px solid $line; }.checkin-form .field label:not(.checkbox-field) { display: block; margin-bottom: 6px; color: #444b4b; font-size: .8rem; font-weight: 700; }.checkin-form .field input:not([type='checkbox']) { width: 100%; min-height: 39px; padding: 8px 9px; border: 1px solid #cfd4cb; border-radius: 8px; color: $ink; background: white; }.checkin-form .field small { display: block; margin-top: 3px; color: $muted; font-size: .7rem; }.checkin-form__note { grid-column: 1 / 3; }.checkin-form__physio { grid-column: 3 / -1; }.checkin-form .form-actions { grid-column: 1 / -1; margin: -2px 0 0; }
|
||||
.checkin-calendar { margin-top: 23px; }.checkin-calendar__header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }.checkin-calendar__header h3 { margin: 0; font-family: Fraunces, Georgia, serif; font-size: 1.16rem; }.checkin-calendar__header .text-link { width: 28px; text-align: center; text-decoration: none; }.checkin-calendar__weekdays, .checkin-calendar__grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 5px; }.checkin-calendar__weekdays { margin-bottom: 5px; color: $muted; font-size: .66rem; font-weight: 700; text-align: center; text-transform: uppercase; }.checkin-day { position: relative; display: grid; min-height: 47px; padding: 5px; border: 1px solid transparent; border-radius: 8px; color: $ink; background: #f4f5f1; text-decoration: none; }.checkin-day:hover { border-color: rgba($forest, .45); }.checkin-day:focus-visible { outline: 3px solid rgba($forest, .3); outline-offset: 2px; }.checkin-day--unrecorded { color: #89908a; background: #f3f4f1; border-style: dashed; border-color: #d9ddd5; }.checkin-day--zero { color: #35664d; background: #dff0e4; }.checkin-day--low { color: #5d6a2a; background: #eef2d7; }.checkin-day--moderate { color: #815d1d; background: #fff0c8; }.checkin-day--high { color: #99412f; background: #ffe0d8; }.checkin-day--severe { color: white; background: #be4c40; }.checkin-day--outside { opacity: .48; }.checkin-day--today { border-color: $forest; }.checkin-day--selected { box-shadow: inset 0 0 0 2px $ink; }.checkin-day__number { font-size: .7rem; font-weight: 700; }.checkin-day__score { align-self: end; justify-self: end; font-size: 1rem; line-height: 1; }.checkin-day__empty { align-self: end; justify-self: end; font-size: .8rem; }.checkin-day__physio { position: absolute; right: 5px; bottom: 4px; font-size: .62rem; font-weight: 700; }.checkin-calendar__legend { display: flex; flex-wrap: wrap; gap: 8px 14px; margin: 12px 0 0; color: $muted; font-size: .72rem; }.checkin-calendar__legend span { display: inline-flex; align-items: center; gap: 5px; }.checkin-legend { display: inline-block; width: 9px; height: 9px; border-radius: 2px; }.checkin-legend--unrecorded { border: 1px dashed #aeb4ae; background: #f3f4f1; }.checkin-legend--zero { background: #dff0e4; }
|
||||
@media (max-width: 700px) { .checkin-panel__header { display: block; }.checkin-streaks { justify-content: start; margin-top: 17px; }.checkin-form { grid-template-columns: 1fr 1fr; }.checkin-form__note, .checkin-form__physio { grid-column: 1 / -1; } } @media (max-width: 420px) { .checkin-panel { padding: 22px; }.checkin-day { min-height: 42px; padding: 4px; }.checkin-calendar__grid { gap: 3px; }.checkin-day__score { font-size: .88rem; } }
|
||||
.checkin-physio-total { margin: 10px 0 0; color: $muted; font-size: .83rem; }.checkin-physio-total strong { color: $forest; font-size: 1rem; }
|
||||
.checkin-streaks { display: grid; grid-template-columns: repeat(3, minmax(100px, 1fr)); align-items: start; width: min(100%, 410px); gap: 18px; }.checkin-streaks > div { min-width: 0; }.checkin-streaks dt { display: flex; align-items: center; gap: 4px; min-height: 1.2em; }.checkin-streaks dd { white-space: nowrap; }.checkin-tooltip { position: relative; display: inline-grid; place-items: center; width: 15px; height: 15px; padding: 0; border: 0; border-radius: 50%; color: $forest; background: $mint; font: 700 10px/1 sans-serif; cursor: help; }.checkin-tooltip:focus-visible { outline: 2px solid $forest; outline-offset: 2px; }.checkin-tooltip__content { position: absolute; z-index: 2; bottom: calc(100% + 8px); left: 50%; width: 190px; padding: 8px 9px; border-radius: 7px; color: white; background: $ink; font: 500 .72rem/1.35 'DM Sans', system-ui, sans-serif; letter-spacing: normal; text-transform: none; text-align: left; visibility: hidden; opacity: 0; pointer-events: none; transform: translateX(-50%) translateY(3px); transition: opacity .15s ease, transform .15s ease, visibility .15s; }.checkin-tooltip:hover .checkin-tooltip__content, .checkin-tooltip:focus .checkin-tooltip__content { visibility: visible; opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
@media (max-width: 700px) { .checkin-streaks { grid-template-columns: repeat(3, minmax(0, 1fr)); width: 100%; gap: 12px; } } @media (max-width: 420px) { .checkin-streaks { grid-template-columns: 1fr 1fr; }.checkin-streaks > div:last-child { grid-column: 1 / -1; } }
|
||||
.task-card--completed { background: #f5f8f4; }.task-card--completed h2 { text-decoration: line-through; }.task-card--completed .task-completion-button { color: $forest; }.task-card--completed .task-completion-button .status-button__dot { background: $forest; }.task-card__footer { flex-wrap: wrap; justify-content: flex-start; }.task-card__footer .text-link { margin-left: auto; }.task-completion-button.button { min-height: 38px; }.recommendation-card__actions { display: flex; align-items: center; justify-content: end; gap: 14px; }.recommendation-card__actions form { margin: 0; }.recommendation-card__actions .button { min-height: 38px; }
|
||||
@media (max-width: 560px) { .recommendation-card__actions { justify-self: start; } }
|
||||
|
||||
.category-picker { position: relative; }.category-picker input { padding-right: 40px !important; }.category-picker__clear { position: absolute; top: 50%; right: 7px; display: grid; place-items: center; width: 27px; height: 27px; padding: 0; border: 0; border-radius: 50%; color: $muted; background: transparent; font-size: 1.25rem; line-height: 1; transform: translateY(-50%); }.category-picker__clear:hover { color: $ink; background: #edf0eb; }.category-picker__clear:focus-visible { outline: 2px solid $forest; outline-offset: 1px; }.category-picker__suggestions { position: absolute; z-index: 5; top: calc(100% + 5px); right: 0; left: 0; max-height: 180px; padding: 5px; margin: 0; overflow-y: auto; border: 1px solid $line; border-radius: 9px; background: $surface; box-shadow: $shadow; list-style: none; }.category-picker__suggestions [role="option"] { padding: 8px 9px; border-radius: 6px; cursor: pointer; font-size: .9rem; }.category-picker__suggestions [role="option"][aria-selected="true"], .category-picker__suggestions [role="option"]:hover { color: $forest-dark; background: $mint; }
|
||||
|
||||
.checkin-form__heading { grid-column: 1 / -1; margin: 0 0 -2px; font-family: Fraunces, Georgia, serif; font-size: 1.08rem; }.checkin-form--sleep { margin-top: -1px; border-top: 0; }.checkin-form--sleep .checkin-form__note { grid-column: 1 / -1; }.checkin-day__sleep { position: absolute; top: 4px; right: 5px; color: currentColor; font-size: .82rem; font-weight: 700; }.checkin-day__physio { left: 5px; right: auto; }.checkin-legend--sleep { width: auto; height: auto; color: $forest; background: transparent; font-style: normal; }.sleep-trend { margin-top: 24px; padding-top: 20px; border-top: 1px solid $line; }.sleep-trend header { display: flex; align-items: baseline; justify-content: space-between; gap: 18px; }.sleep-trend h3 { margin: 0; font-family: Fraunces, Georgia, serif; font-size: 1.16rem; }.sleep-trend header p, .sleep-trend__empty { margin: 0; color: $muted; font-size: .78rem; }.sleep-trend header p { max-width: 420px; text-align: right; }.sleep-trend__table-wrap { margin-top: 12px; overflow-x: auto; }.sleep-trend table { width: 100%; border-collapse: collapse; font-size: .82rem; }.sleep-trend th, .sleep-trend td { padding: 8px 5px; border-bottom: 1px solid $line; text-align: left; }.sleep-trend thead th { color: $muted; font-size: .7rem; letter-spacing: .04em; text-transform: uppercase; }.sleep-trend tbody th { font-weight: 600; }.sleep-trend__empty { margin-top: 10px; }
|
||||
@media (max-width: 700px) { .sleep-trend header { display: block; }.sleep-trend header p { margin-top: 5px; text-align: left; } }
|
||||
|
||||
.checkin-tabs { display: flex; gap: 6px; margin-top: 22px; padding-bottom: 1px; border-bottom: 1px solid $line; }.checkin-tabs__tab { padding: 9px 12px 10px; border-bottom: 2px solid transparent; color: $muted; font-size: .84rem; font-weight: 700; text-decoration: none; }.checkin-tabs__tab:hover { color: $forest; }.checkin-tabs__tab:focus-visible { outline: 2px solid $forest; outline-offset: -2px; }.checkin-tabs__tab.is-active { border-color: $forest; color: $forest; }
|
||||
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import { fileURLToPath, URL } from 'node:url';
|
||||
|
||||
const root = fileURLToPath(new URL('.', import.meta.url));
|
||||
|
||||
export default defineConfig({
|
||||
root,
|
||||
base: '/static/planner/dist/',
|
||||
publicDir: false,
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
// The Vite server is development-only; accept the Django origin in use.
|
||||
cors: false,
|
||||
},
|
||||
build: {
|
||||
outDir: fileURLToPath(new URL('../planner/static/planner/dist', import.meta.url)),
|
||||
emptyOutDir: true,
|
||||
manifest: true,
|
||||
rollupOptions: {
|
||||
input: fileURLToPath(new URL('./src/main.js', import.meta.url)),
|
||||
},
|
||||
},
|
||||
});
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run administrative tasks."""
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tasksnest.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Couldn't import Django. Are you sure it's installed and "
|
||||
"available on your PYTHONPATH environment variable? Did you "
|
||||
"forget to activate a virtual environment?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,74 @@
|
||||
from django.contrib import admin
|
||||
|
||||
from .models import FastingPause, FastingPeriod, FastingSettings, SickDaySettings, Task, TaskWeatherShift, UserSettings, Workout, WorkoutCompletion
|
||||
|
||||
|
||||
@admin.register(Task)
|
||||
class TaskAdmin(admin.ModelAdmin):
|
||||
list_display = ('title', 'owner', 'priority', 'category', 'scheduled_for', 'deferred_until', 'deferral_source', 'is_recurring', 'is_active', 'is_completed', 'parent_task')
|
||||
list_filter = ('priority', 'category', 'scheduled_for', 'weather_profile', 'deferral_source', 'is_recurring', 'is_active', 'is_completed', 'parent_task')
|
||||
search_fields = ('title', 'description', 'category')
|
||||
list_select_related = ('owner', 'parent_task')
|
||||
autocomplete_fields = ('owner', 'parent_task')
|
||||
|
||||
|
||||
@admin.register(SickDaySettings)
|
||||
class SickDaySettingsAdmin(admin.ModelAdmin):
|
||||
list_display = ('user', 'enabled', 'recovery_date')
|
||||
list_filter = ('enabled',)
|
||||
search_fields = ('user__username',)
|
||||
autocomplete_fields = ('user',)
|
||||
|
||||
|
||||
@admin.register(FastingSettings)
|
||||
class FastingSettingsAdmin(admin.ModelAdmin):
|
||||
list_display = ('user', 'enabled', 'fasting_start_time', 'fasting_duration_minutes', 'updated_at')
|
||||
list_filter = ('enabled',)
|
||||
search_fields = ('user__username',)
|
||||
autocomplete_fields = ('user',)
|
||||
|
||||
|
||||
@admin.register(FastingPeriod)
|
||||
class FastingPeriodAdmin(admin.ModelAdmin):
|
||||
list_display = ('user', 'scheduled_start', 'scheduled_end', 'completed_at', 'status')
|
||||
list_filter = ('status',)
|
||||
search_fields = ('user__username',)
|
||||
autocomplete_fields = ('user',)
|
||||
|
||||
|
||||
@admin.register(FastingPause)
|
||||
class FastingPauseAdmin(admin.ModelAdmin):
|
||||
list_display = ('user', 'paused_at', 'resumed_at')
|
||||
search_fields = ('user__username',)
|
||||
autocomplete_fields = ('user',)
|
||||
|
||||
|
||||
@admin.register(UserSettings)
|
||||
class UserSettingsAdmin(admin.ModelAdmin):
|
||||
list_display = ('user', 'latitude', 'longitude', 'updated_at')
|
||||
search_fields = ('user__username',)
|
||||
autocomplete_fields = ('user',)
|
||||
|
||||
|
||||
@admin.register(TaskWeatherShift)
|
||||
class TaskWeatherShiftAdmin(admin.ModelAdmin):
|
||||
list_display = ('task', 'owner', 'original_date', 'shifted_to', 'reason')
|
||||
list_filter = ('original_date', 'shifted_to')
|
||||
search_fields = ('task__title', 'owner__username', 'reason')
|
||||
autocomplete_fields = ('task', 'owner')
|
||||
|
||||
|
||||
@admin.register(Workout)
|
||||
class WorkoutAdmin(admin.ModelAdmin):
|
||||
list_display = ('name', 'owner', 'scheduled_for', 'is_daily_recurring', 'is_completed', 'duration_minutes', 'calories_burned')
|
||||
list_filter = ('is_daily_recurring', 'is_completed', 'scheduled_for')
|
||||
search_fields = ('name', 'owner__username')
|
||||
autocomplete_fields = ('owner',)
|
||||
|
||||
|
||||
@admin.register(WorkoutCompletion)
|
||||
class WorkoutCompletionAdmin(admin.ModelAdmin):
|
||||
list_display = ('workout', 'completed_on', 'completed_at')
|
||||
list_filter = ('completed_on',)
|
||||
search_fields = ('workout__name', 'workout__owner__username')
|
||||
autocomplete_fields = ('workout',)
|
||||
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class PlannerConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'planner'
|
||||
@@ -0,0 +1,236 @@
|
||||
from django import forms
|
||||
from django.contrib.auth.forms import UserCreationForm
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
from zoneinfo import available_timezones
|
||||
|
||||
from .models import FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, UserSettings, Workout
|
||||
from .timezones import localdate_for_user
|
||||
|
||||
|
||||
class TaskForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Task
|
||||
fields = (
|
||||
'title', 'description', 'estimated_duration_minutes', 'priority', 'category',
|
||||
'scheduled_for', 'is_recurring', 'recurrence_interval', 'recurrence_unit',
|
||||
'defer_days', 'is_active', 'is_outdoor', 'weather_profile', 'required_on_sick_day', 'parent_task',
|
||||
)
|
||||
widgets = {
|
||||
'description': forms.Textarea(attrs={'rows': 5}),
|
||||
'scheduled_for': forms.DateInput(attrs={'type': 'date'}),
|
||||
}
|
||||
|
||||
def __init__(self, *args, owner=None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.owner = owner
|
||||
parents = Task.objects.filter(parent_task__isnull=True)
|
||||
if owner is not None:
|
||||
parents = parents.filter(owner=owner)
|
||||
if self.instance.pk:
|
||||
# Keeping choices top-level prevents accidental deep nesting in the UI.
|
||||
parents = parents.exclude(pk=self.instance.pk)
|
||||
self.fields['parent_task'].queryset = parents
|
||||
self.fields['defer_days'].help_text = 'Days to defer this one-time task after it is missed.'
|
||||
category_id = self['category'].id_for_label
|
||||
self.fields['category'].widget.attrs.update({
|
||||
'autocomplete': 'off',
|
||||
'role': 'combobox',
|
||||
'aria-autocomplete': 'list',
|
||||
'aria-expanded': 'false',
|
||||
'aria-controls': f'{category_id}-suggestions',
|
||||
'aria-haspopup': 'listbox',
|
||||
'data-category-input': '',
|
||||
'data-suggestions-url': reverse('planner:category-suggestions'),
|
||||
})
|
||||
|
||||
def clean_category(self):
|
||||
category = self.cleaned_data['category'].strip()
|
||||
if not category or self.owner is None:
|
||||
return category
|
||||
|
||||
for existing_category in Task.objects.filter(owner=self.owner).exclude(category='').order_by('pk').values_list('category', flat=True):
|
||||
normalized = existing_category.strip()
|
||||
if normalized.casefold() == category.casefold():
|
||||
return normalized
|
||||
return category
|
||||
|
||||
|
||||
class DailyPlannerForm(forms.Form):
|
||||
selected_date = forms.DateField(
|
||||
label='Plan for',
|
||||
widget=forms.DateInput(attrs={'type': 'date'}),
|
||||
)
|
||||
energy_level = forms.TypedChoiceField(
|
||||
label='Energy level',
|
||||
coerce=int,
|
||||
choices=(
|
||||
(1, '1 — Very low (15 min)'),
|
||||
(2, '2 — Low (30 min)'),
|
||||
(3, '3 — Steady (60 min)'),
|
||||
(4, '4 — High (90 min)'),
|
||||
(5, '5 — Fully charged (180 min)'),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
DAILY_FASTING_DURATION_CHOICES = (
|
||||
('Beginner', (
|
||||
(12 * 60, '12:12 — Fast 12 hours, eat within 12 hours'),
|
||||
(13 * 60, '13:11 — Fast 13 hours, eat within 11 hours'),
|
||||
(14 * 60, '14:10 — Fast 14 hours, eat within 10 hours'),
|
||||
(15 * 60, '15:9 — Fast 15 hours, eat within 9 hours'),
|
||||
)),
|
||||
('Experienced', (
|
||||
(16 * 60, '16:8 — Fast 16 hours, eat within 8 hours'),
|
||||
(17 * 60, '17:7 — Fast 17 hours, eat within 7 hours'),
|
||||
(18 * 60, '18:6 — Fast 18 hours, eat within 6 hours'),
|
||||
)),
|
||||
('Professional', (
|
||||
(19 * 60, '19:5 — Fast 19 hours, eat within 5 hours'),
|
||||
(20 * 60, '20:4 — Fast 20 hours, eat within 4 hours'),
|
||||
(21 * 60, '21:3 — Fast 21 hours, eat within 3 hours'),
|
||||
(22 * 60, '22:2 — Fast 22 hours, eat within 2 hours'),
|
||||
)),
|
||||
)
|
||||
|
||||
|
||||
class FastingSettingsForm(forms.ModelForm):
|
||||
fasting_duration_minutes = forms.TypedChoiceField(
|
||||
label='Daily fasting schedule',
|
||||
choices=DAILY_FASTING_DURATION_CHOICES,
|
||||
coerce=int,
|
||||
help_text='Choose a daily fasting and eating-window rhythm.',
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = FastingSettings
|
||||
fields = ('enabled', 'fasting_start_time', 'fasting_duration_minutes')
|
||||
widgets = {
|
||||
'fasting_start_time': forms.TimeInput(attrs={'type': 'time'}),
|
||||
}
|
||||
labels = {
|
||||
'fasting_start_time': 'Fasting starts at',
|
||||
}
|
||||
help_texts = {
|
||||
}
|
||||
|
||||
|
||||
TIME_ZONE_CHOICES = tuple((name, name) for name in sorted(available_timezones()))
|
||||
|
||||
|
||||
class TimeZoneSettingsForm(forms.ModelForm):
|
||||
time_zone = forms.ChoiceField(label='Time zone', choices=TIME_ZONE_CHOICES)
|
||||
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ('time_zone',)
|
||||
help_texts = {
|
||||
'time_zone': 'Used for dates and displayed times, including fasting.',
|
||||
}
|
||||
|
||||
|
||||
class UserSettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ('latitude', 'longitude')
|
||||
widgets = {
|
||||
'latitude': forms.TextInput(attrs={'inputmode': 'decimal', 'autocomplete': 'off', 'placeholder': 'e.g. 52.36760'}),
|
||||
'longitude': forms.TextInput(attrs={'inputmode': 'decimal', 'autocomplete': 'off', 'placeholder': 'e.g. 4.90410'}),
|
||||
}
|
||||
help_texts = {
|
||||
'latitude': 'Between -90 and 90.',
|
||||
'longitude': 'Between -180 and 180.',
|
||||
}
|
||||
|
||||
|
||||
class SickDaySettingsForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = SickDaySettings
|
||||
fields = ('enabled', 'recovery_date')
|
||||
widgets = {'recovery_date': forms.DateInput(attrs={'type': 'date'})}
|
||||
help_texts = {'recovery_date': 'Optional. Tasks resume the day after this date.'}
|
||||
|
||||
|
||||
class RegistrationForm(UserCreationForm):
|
||||
class Meta(UserCreationForm.Meta):
|
||||
model = get_user_model()
|
||||
fields = ('username',)
|
||||
|
||||
|
||||
class WorkoutForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Workout
|
||||
fields = ('name', 'scheduled_for', 'is_daily_recurring', 'duration_minutes', 'calories_burned')
|
||||
widgets = {'scheduled_for': forms.DateInput(attrs={'type': 'date'})}
|
||||
help_texts = {
|
||||
'is_daily_recurring': 'Show this workout every day from its start date.',
|
||||
'calories_burned': 'Optional; only completed workouts with a value contribute to today’s total.',
|
||||
}
|
||||
|
||||
|
||||
class SleepCheckInForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = SleepCheckIn
|
||||
fields = ('wake_up_date', 'rested_score', 'watch_sleep_score', 'note')
|
||||
widgets = {
|
||||
'wake_up_date': forms.DateInput(attrs={'type': 'date'}),
|
||||
'rested_score': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
|
||||
'watch_sleep_score': forms.NumberInput(attrs={'min': 0, 'max': 100, 'inputmode': 'numeric'}),
|
||||
'note': forms.TextInput(attrs={'maxlength': 500, 'placeholder': 'Anything useful to remember?'}),
|
||||
}
|
||||
labels = {
|
||||
'wake_up_date': 'Wake-up date',
|
||||
'rested_score': 'How rested (0–10)',
|
||||
'watch_sleep_score': 'Watch sleep score (0–100%, optional)',
|
||||
'note': 'Note (optional)',
|
||||
}
|
||||
|
||||
def __init__(self, *args, user=None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.user = user
|
||||
|
||||
def clean_wake_up_date(self):
|
||||
wake_up_date = self.cleaned_data['wake_up_date']
|
||||
today = localdate_for_user(self.user) if self.user else timezone.localdate()
|
||||
if wake_up_date > today:
|
||||
raise forms.ValidationError('Sleep can only be recorded for today or earlier.')
|
||||
return wake_up_date
|
||||
|
||||
|
||||
class NeckHeadacheCheckInForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = NeckHeadacheCheckIn
|
||||
fields = (
|
||||
'check_in_date', 'neck_pain_severity', 'headache_severity', 'note',
|
||||
'had_physiotherapy',
|
||||
)
|
||||
widgets = {
|
||||
'check_in_date': forms.DateInput(attrs={'type': 'date'}),
|
||||
'neck_pain_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
|
||||
'headache_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
|
||||
'note': forms.TextInput(attrs={'maxlength': 500, 'placeholder': 'Anything useful to remember?'}),
|
||||
}
|
||||
labels = {
|
||||
'check_in_date': 'Date',
|
||||
'neck_pain_severity': 'Neck pain (0–10)',
|
||||
'headache_severity': 'Headache (0–10)',
|
||||
'note': 'Note (optional)',
|
||||
'had_physiotherapy': 'I had a physiotherapy session',
|
||||
}
|
||||
help_texts = {
|
||||
'neck_pain_severity': '0 means no pain.',
|
||||
'headache_severity': '0 means no headache.',
|
||||
}
|
||||
|
||||
def __init__(self, *args, user=None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.user = user
|
||||
|
||||
def clean_check_in_date(self):
|
||||
check_in_date = self.cleaned_data['check_in_date']
|
||||
today = localdate_for_user(self.user) if self.user else timezone.localdate()
|
||||
if check_in_date > today:
|
||||
raise forms.ValidationError('Check-ins can only be recorded for today or earlier.')
|
||||
return check_in_date
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Activate each signed-in user's preferred timezone for the request."""
|
||||
from django.utils import timezone
|
||||
|
||||
from .timezones import timezone_for_user
|
||||
|
||||
|
||||
class UserTimezoneMiddleware:
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
timezone.activate(timezone_for_user(request.user))
|
||||
try:
|
||||
return self.get_response(request)
|
||||
finally:
|
||||
timezone.deactivate()
|
||||
@@ -0,0 +1,43 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 13:16
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Task',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=255)),
|
||||
('description', models.TextField(blank=True)),
|
||||
('estimated_duration_minutes', models.PositiveIntegerField(blank=True, null=True)),
|
||||
('priority', models.CharField(choices=[('low', 'Low'), ('medium', 'Medium'), ('high', 'High')], default='medium', max_length=6)),
|
||||
('category', models.CharField(blank=True, max_length=100)),
|
||||
('is_recurring', models.BooleanField(default=False)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
('scheduled_for', models.DateField()),
|
||||
('recurrence_interval', models.PositiveIntegerField(blank=True, default=1)),
|
||||
('recurrence_unit', models.CharField(blank=True, choices=[('day', 'Day'), ('week', 'Week'), ('month', 'Month')], max_length=5)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('is_outdoor', models.BooleanField(default=False)),
|
||||
('weather_profile', models.CharField(default='none', max_length=50)),
|
||||
('required_on_sick_day', models.BooleanField(default=False)),
|
||||
('defer_days', models.PositiveIntegerField(blank=True, null=True)),
|
||||
('deferred_until', models.DateField(blank=True, null=True)),
|
||||
('deferral_source', models.CharField(blank=True, max_length=255)),
|
||||
('parent_task', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='subtasks', to='planner.task')),
|
||||
],
|
||||
options={
|
||||
'ordering': ('scheduled_for', 'title'),
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 13:17
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='task',
|
||||
name='recurrence_interval',
|
||||
field=models.PositiveIntegerField(blank=True, default=1, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,30 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 17:48
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0002_alter_task_recurrence_interval'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='task',
|
||||
name='deferral_source',
|
||||
field=models.CharField(blank=True, choices=[('manual', 'Manual'), ('missed', 'Missed'), ('sick_day', 'Sick day')], max_length=20),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SickDaySettings',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('enabled', models.BooleanField(default=False)),
|
||||
('recovery_date', models.DateField(blank=True, null=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='sick_day_settings', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,58 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 18:04
|
||||
|
||||
import datetime
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0003_alter_task_deferral_source_sickdaysettings'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='FastingPause',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('paused_at', models.DateTimeField()),
|
||||
('resumed_at', models.DateTimeField(blank=True, null=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='fasting_pauses', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('-paused_at',),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='FastingSettings',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('enabled', models.BooleanField(default=False)),
|
||||
('fasting_start_time', models.TimeField(default=datetime.time(20, 0))),
|
||||
('fasting_duration_minutes', models.PositiveIntegerField(default=960, validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(1439)])),
|
||||
('tracking_started_at', models.DateTimeField(blank=True, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='fasting_settings', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='FastingPeriod',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('scheduled_start', models.DateTimeField()),
|
||||
('scheduled_end', models.DateTimeField()),
|
||||
('completed_at', models.DateTimeField()),
|
||||
('status', models.CharField(choices=[('completed', 'Completed')], default='completed', max_length=16)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='fasting_periods', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('-scheduled_start',),
|
||||
'constraints': [models.UniqueConstraint(fields=('user', 'scheduled_start'), name='unique_user_fasting_scheduled_start')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,69 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 18:26
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def assign_tasks_when_single_active_user(apps, schema_editor):
|
||||
"""Claim legacy tasks only when ownership is unambiguous."""
|
||||
User = apps.get_model(*settings.AUTH_USER_MODEL.split('.'))
|
||||
Task = apps.get_model('planner', 'Task')
|
||||
users = list(User.objects.filter(is_active=True).values_list('pk', flat=True)[:2])
|
||||
if len(users) == 1:
|
||||
Task.objects.filter(owner__isnull=True).update(owner_id=users[0])
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0004_fastingpause_fastingsettings_fastingperiod'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='task',
|
||||
name='owner',
|
||||
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='tasks', to=settings.AUTH_USER_MODEL),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='task',
|
||||
name='deferral_source',
|
||||
field=models.CharField(blank=True, choices=[('manual', 'Manual'), ('missed', 'Missed'), ('sick_day', 'Sick day'), ('weather', 'Weather')], max_length=20),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='task',
|
||||
name='weather_profile',
|
||||
field=models.CharField(choices=[('none', 'Any weather'), ('dry', 'Dry'), ('sunny', 'Sunny / mostly sunny'), ('warm', 'Warm'), ('dry_warm', 'Dry and warm')], default='none', max_length=50),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UserSettings',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('latitude', models.DecimalField(blank=True, decimal_places=5, max_digits=8, null=True, validators=[django.core.validators.MinValueValidator(-90), django.core.validators.MaxValueValidator(90)])),
|
||||
('longitude', models.DecimalField(blank=True, decimal_places=5, max_digits=9, null=True, validators=[django.core.validators.MinValueValidator(-180), django.core.validators.MaxValueValidator(180)])),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='planner_settings', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='TaskWeatherShift',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('original_date', models.DateField()),
|
||||
('shifted_to', models.DateField(blank=True, null=True)),
|
||||
('reason', models.CharField(blank=True, max_length=255)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='task_weather_shifts', to=settings.AUTH_USER_MODEL)),
|
||||
('task', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='weather_shifts', to='planner.task')),
|
||||
],
|
||||
options={
|
||||
'ordering': ('original_date',),
|
||||
'constraints': [models.UniqueConstraint(fields=('task', 'original_date'), name='unique_weather_shift_per_task_occurrence')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
from django.conf import settings
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
def assign_tasks_when_single_active_user(apps, schema_editor):
|
||||
"""Claim only unambiguous legacy data; never guess in a multi-user database."""
|
||||
app_label, model_name = settings.AUTH_USER_MODEL.split('.')
|
||||
User = apps.get_model(app_label, model_name)
|
||||
Task = apps.get_model('planner', 'Task')
|
||||
users = list(User.objects.filter(is_active=True).values_list('pk', flat=True)[:2])
|
||||
if len(users) == 1:
|
||||
Task.objects.filter(owner__isnull=True).update(owner_id=users[0])
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('planner', '0005_task_owner_alter_task_deferral_source_and_more')]
|
||||
operations = [migrations.RunPython(assign_tasks_when_single_active_user, migrations.RunPython.noop)]
|
||||
@@ -0,0 +1,24 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 18:42
|
||||
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0006_assign_unambiguous_legacy_task_owners'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='usersettings',
|
||||
name='latitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=9, null=True, validators=[django.core.validators.MinValueValidator(-90), django.core.validators.MaxValueValidator(90)]),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='usersettings',
|
||||
name='longitude',
|
||||
field=models.DecimalField(blank=True, decimal_places=6, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(-180), django.core.validators.MaxValueValidator(180)]),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,47 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-29 18:51
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0007_alter_usersettings_latitude_and_more'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Workout',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=255)),
|
||||
('scheduled_for', models.DateField()),
|
||||
('is_completed', models.BooleanField(default=False)),
|
||||
('duration_minutes', models.PositiveIntegerField(blank=True, null=True)),
|
||||
('calories_burned', models.PositiveIntegerField(blank=True, null=True)),
|
||||
('is_daily_recurring', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='workouts', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('scheduled_for', 'name'),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='WorkoutCompletion',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('completed_on', models.DateField()),
|
||||
('completed_at', models.DateTimeField(auto_now_add=True)),
|
||||
('workout', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='completions', to='planner.workout')),
|
||||
],
|
||||
options={
|
||||
'ordering': ('-completed_on',),
|
||||
'constraints': [models.UniqueConstraint(fields=('workout', 'completed_on'), name='unique_workout_completion_per_day')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-30
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [
|
||||
('planner', '0008_workout_workoutcompletion'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='NeckHeadacheCheckIn',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('check_in_date', models.DateField()),
|
||||
('neck_pain_severity', models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(10)])),
|
||||
('headache_severity', models.PositiveSmallIntegerField(validators=[MinValueValidator(0), MaxValueValidator(10)])),
|
||||
('note', models.CharField(blank=True, max_length=500)),
|
||||
('had_physiotherapy', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='neck_headache_check_ins', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={'ordering': ('-check_in_date',)},
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='neckheadachecheckin',
|
||||
constraint=models.UniqueConstraint(fields=('user', 'check_in_date'), name='unique_neck_headache_check_in_per_day'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-30 11:50
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0009_neckheadachecheckin'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='task',
|
||||
name='is_completed',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,39 @@
|
||||
# Generated by Django 6.1.1 on 2026-09-30 15:00
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('planner', '0010_task_is_completed'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='usersettings',
|
||||
name='time_zone',
|
||||
field=models.CharField(default='Europe/Amsterdam', max_length=64),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='SleepCheckIn',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('wake_up_date', models.DateField()),
|
||||
('rested_score', models.PositiveSmallIntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
|
||||
('watch_sleep_score', models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
|
||||
('note', models.CharField(blank=True, max_length=500)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sleep_check_ins', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('-wake_up_date',),
|
||||
'constraints': [models.UniqueConstraint(fields=('user', 'wake_up_date'), name='unique_sleep_check_in_per_wake_up_date')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,336 @@
|
||||
from datetime import time
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from django.urls import reverse
|
||||
|
||||
|
||||
class Task(models.Model):
|
||||
class Priority(models.TextChoices):
|
||||
LOW = 'low', 'Low'
|
||||
MEDIUM = 'medium', 'Medium'
|
||||
HIGH = 'high', 'High'
|
||||
|
||||
class RecurrenceUnit(models.TextChoices):
|
||||
DAY = 'day', 'Day'
|
||||
WEEK = 'week', 'Week'
|
||||
MONTH = 'month', 'Month'
|
||||
|
||||
class DeferralSource(models.TextChoices):
|
||||
MANUAL = 'manual', 'Manual'
|
||||
MISSED = 'missed', 'Missed'
|
||||
SICK_DAY = 'sick_day', 'Sick day'
|
||||
WEATHER = 'weather', 'Weather'
|
||||
|
||||
class WeatherProfile(models.TextChoices):
|
||||
ANY = 'none', 'Any weather'
|
||||
DRY = 'dry', 'Dry'
|
||||
SUNNY = 'sunny', 'Sunny / mostly sunny'
|
||||
WARM = 'warm', 'Warm'
|
||||
DRY_AND_WARM = 'dry_warm', 'Dry and warm'
|
||||
|
||||
owner = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tasks', null=True, blank=True
|
||||
)
|
||||
title = models.CharField(max_length=255)
|
||||
description = models.TextField(blank=True)
|
||||
estimated_duration_minutes = models.PositiveIntegerField(blank=True, null=True)
|
||||
priority = models.CharField(max_length=6, choices=Priority.choices, default=Priority.MEDIUM)
|
||||
category = models.CharField(max_length=100, blank=True)
|
||||
is_recurring = models.BooleanField(default=False)
|
||||
is_active = models.BooleanField(default=True)
|
||||
is_completed = models.BooleanField(default=False)
|
||||
scheduled_for = models.DateField()
|
||||
recurrence_interval = models.PositiveIntegerField(default=1, blank=True, null=True)
|
||||
recurrence_unit = models.CharField(max_length=5, choices=RecurrenceUnit.choices, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
is_outdoor = models.BooleanField(default=False)
|
||||
weather_profile = models.CharField(
|
||||
max_length=50, choices=WeatherProfile.choices, default=WeatherProfile.ANY
|
||||
)
|
||||
required_on_sick_day = models.BooleanField(default=False)
|
||||
defer_days = models.PositiveIntegerField(blank=True, null=True)
|
||||
deferred_until = models.DateField(blank=True, null=True)
|
||||
deferral_source = models.CharField(max_length=20, choices=DeferralSource.choices, blank=True)
|
||||
parent_task = models.ForeignKey(
|
||||
'self', blank=True, null=True, on_delete=models.SET_NULL, related_name='subtasks'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
ordering = ('scheduled_for', 'title')
|
||||
|
||||
def __str__(self):
|
||||
return self.title
|
||||
|
||||
def get_absolute_url(self):
|
||||
return reverse('planner:task-detail', kwargs={'pk': self.pk})
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if not self.parent_task_id:
|
||||
return
|
||||
if self.owner_id and self.parent_task.owner_id and self.owner_id != self.parent_task.owner_id:
|
||||
raise ValidationError({'parent_task': 'A parent task must belong to the same user.'})
|
||||
if self.pk and self.parent_task_id == self.pk:
|
||||
raise ValidationError({'parent_task': 'A task cannot be its own parent.'})
|
||||
|
||||
# Follow the proposed parent's ancestors. Finding this task means the
|
||||
# assignment would create a circular hierarchy.
|
||||
ancestor = self.parent_task
|
||||
visited_ids = set()
|
||||
while ancestor is not None:
|
||||
if ancestor.pk in visited_ids:
|
||||
break
|
||||
visited_ids.add(ancestor.pk)
|
||||
if self.pk and ancestor.pk == self.pk:
|
||||
raise ValidationError(
|
||||
{'parent_task': 'A task cannot have one of its descendants as its parent.'}
|
||||
)
|
||||
ancestor = ancestor.parent_task
|
||||
|
||||
|
||||
class UserSettings(models.Model):
|
||||
"""Private, per-user preferences that do not belong on Django's User model."""
|
||||
|
||||
user = models.OneToOneField(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='planner_settings'
|
||||
)
|
||||
latitude = models.DecimalField(
|
||||
max_digits=9, decimal_places=6, blank=True, null=True,
|
||||
validators=[MinValueValidator(-90), MaxValueValidator(90)],
|
||||
)
|
||||
longitude = models.DecimalField(
|
||||
max_digits=10, decimal_places=6, blank=True, null=True,
|
||||
validators=[MinValueValidator(-180), MaxValueValidator(180)],
|
||||
)
|
||||
time_zone = models.CharField(max_length=64, default='Europe/Amsterdam')
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if (self.latitude is None) != (self.longitude is None):
|
||||
raise ValidationError('Enter both latitude and longitude, or leave both empty.')
|
||||
|
||||
def __str__(self):
|
||||
return f'Planner settings for {self.user}'
|
||||
|
||||
|
||||
class TaskWeatherShift(models.Model):
|
||||
"""A weather-owned move of a single scheduled task occurrence."""
|
||||
|
||||
task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='weather_shifts')
|
||||
owner = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='task_weather_shifts'
|
||||
)
|
||||
original_date = models.DateField()
|
||||
shifted_to = models.DateField(blank=True, null=True)
|
||||
reason = models.CharField(max_length=255, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=('task', 'original_date'), name='unique_weather_shift_per_task_occurrence'
|
||||
)
|
||||
]
|
||||
ordering = ('original_date',)
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.task_id and self.owner_id and self.task.owner_id != self.owner_id:
|
||||
raise ValidationError({'owner': 'A weather shift must belong to the task owner.'})
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.task} from {self.original_date}'
|
||||
|
||||
|
||||
class Workout(models.Model):
|
||||
"""A personal, non-task workout entry or repeating daily workout intention."""
|
||||
|
||||
owner = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='workouts'
|
||||
)
|
||||
name = models.CharField(max_length=255)
|
||||
scheduled_for = models.DateField()
|
||||
is_completed = models.BooleanField(default=False)
|
||||
duration_minutes = models.PositiveIntegerField(blank=True, null=True)
|
||||
calories_burned = models.PositiveIntegerField(blank=True, null=True)
|
||||
is_daily_recurring = models.BooleanField(default=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('scheduled_for', 'name')
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
|
||||
class WorkoutCompletion(models.Model):
|
||||
"""Completion state for one date of a repeating daily workout."""
|
||||
|
||||
workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='completions')
|
||||
completed_on = models.DateField()
|
||||
completed_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=('workout', 'completed_on'),
|
||||
name='unique_workout_completion_per_day',
|
||||
)
|
||||
]
|
||||
ordering = ('-completed_on',)
|
||||
|
||||
def __str__(self):
|
||||
return f'{self.workout} completed on {self.completed_on}'
|
||||
|
||||
|
||||
class NeckHeadacheCheckIn(models.Model):
|
||||
"""A private, once-per-local-day symptom check-in."""
|
||||
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name='neck_headache_check_ins',
|
||||
)
|
||||
check_in_date = models.DateField()
|
||||
neck_pain_severity = models.PositiveSmallIntegerField(
|
||||
validators=[MinValueValidator(0), MaxValueValidator(10)],
|
||||
)
|
||||
headache_severity = models.PositiveSmallIntegerField(
|
||||
validators=[MinValueValidator(0), MaxValueValidator(10)],
|
||||
)
|
||||
note = models.CharField(max_length=500, blank=True)
|
||||
had_physiotherapy = models.BooleanField(default=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=('user', 'check_in_date'), name='unique_neck_headache_check_in_per_day'
|
||||
)
|
||||
]
|
||||
ordering = ('-check_in_date',)
|
||||
|
||||
def __str__(self):
|
||||
return f'Neck and headache check-in for {self.user} on {self.check_in_date}'
|
||||
|
||||
|
||||
class SleepCheckIn(models.Model):
|
||||
"""A private, once-per-wake-up-date sleep check-in."""
|
||||
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name='sleep_check_ins',
|
||||
)
|
||||
wake_up_date = models.DateField()
|
||||
rested_score = models.PositiveSmallIntegerField(
|
||||
validators=[MinValueValidator(0), MaxValueValidator(10)],
|
||||
)
|
||||
watch_sleep_score = models.PositiveSmallIntegerField(
|
||||
blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(100)],
|
||||
)
|
||||
note = models.CharField(max_length=500, blank=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=('user', 'wake_up_date'), name='unique_sleep_check_in_per_wake_up_date'
|
||||
)
|
||||
]
|
||||
ordering = ('-wake_up_date',)
|
||||
|
||||
def __str__(self):
|
||||
return f'Sleep check-in for {self.user} on {self.wake_up_date}'
|
||||
|
||||
|
||||
class SickDaySettings(models.Model):
|
||||
"""Per-user preferences used by the Sick Day deferral policy."""
|
||||
|
||||
user = models.OneToOneField(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name='sick_day_settings',
|
||||
)
|
||||
enabled = models.BooleanField(default=False)
|
||||
recovery_date = models.DateField(blank=True, null=True)
|
||||
|
||||
def __str__(self):
|
||||
return f'Sick Day settings for {self.user}'
|
||||
|
||||
|
||||
class FastingSettings(models.Model):
|
||||
"""A user's repeating daily intermittent-fasting configuration."""
|
||||
|
||||
user = models.OneToOneField(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name='fasting_settings',
|
||||
)
|
||||
enabled = models.BooleanField(default=False)
|
||||
fasting_start_time = models.TimeField(default=time(20, 0))
|
||||
fasting_duration_minutes = models.PositiveIntegerField(
|
||||
default=16 * 60,
|
||||
validators=[MinValueValidator(1), MaxValueValidator((24 * 60) - 1)],
|
||||
)
|
||||
tracking_started_at = models.DateTimeField(blank=True, null=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
def __str__(self):
|
||||
return f'Fasting settings for {self.user}'
|
||||
|
||||
|
||||
class FastingPause(models.Model):
|
||||
"""An interval during which a user's automatic fasting tracking was paused."""
|
||||
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name='fasting_pauses',
|
||||
)
|
||||
paused_at = models.DateTimeField()
|
||||
resumed_at = models.DateTimeField(blank=True, null=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('-paused_at',)
|
||||
|
||||
def __str__(self):
|
||||
return f'Fasting pause for {self.user} at {self.paused_at}'
|
||||
|
||||
|
||||
class FastingPeriod(models.Model):
|
||||
class Status(models.TextChoices):
|
||||
COMPLETED = 'completed', 'Completed'
|
||||
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name='fasting_periods',
|
||||
)
|
||||
scheduled_start = models.DateTimeField()
|
||||
scheduled_end = models.DateTimeField()
|
||||
completed_at = models.DateTimeField()
|
||||
status = models.CharField(max_length=16, choices=Status.choices, default=Status.COMPLETED)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=('user', 'scheduled_start'),
|
||||
name='unique_user_fasting_scheduled_start',
|
||||
)
|
||||
]
|
||||
ordering = ('-scheduled_start',)
|
||||
|
||||
def __str__(self):
|
||||
return f'Fasting period for {self.user}: {self.scheduled_start}'
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Display and streak helpers for private daily symptom check-ins."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
|
||||
|
||||
# Keeping this policy value here makes it straightforward to tune later.
|
||||
LOW_PAIN_STREAK_THRESHOLD = 2
|
||||
ANNUAL_PHYSIOTHERAPY_SESSION_ALLOWANCE = 12
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CheckInStreaks:
|
||||
current: int
|
||||
longest: int
|
||||
|
||||
|
||||
def is_low_pain(check_in, threshold=LOW_PAIN_STREAK_THRESHOLD):
|
||||
return (
|
||||
check_in.neck_pain_severity <= threshold
|
||||
and check_in.headache_severity <= threshold
|
||||
)
|
||||
|
||||
|
||||
def calculate_check_in_streaks(check_ins, as_of_date, threshold=LOW_PAIN_STREAK_THRESHOLD):
|
||||
"""Return consecutive confirmed low-pain runs; absent dates always break a run."""
|
||||
by_date = {check_in.check_in_date: check_in for check_in in check_ins}
|
||||
if not by_date:
|
||||
return CheckInStreaks(current=0, longest=0)
|
||||
|
||||
first_date = min(by_date)
|
||||
longest = run = 0
|
||||
day = first_date
|
||||
while day <= as_of_date:
|
||||
check_in = by_date.get(day)
|
||||
if check_in is not None and is_low_pain(check_in, threshold):
|
||||
run += 1
|
||||
longest = max(longest, run)
|
||||
else:
|
||||
run = 0
|
||||
day += timedelta(days=1)
|
||||
|
||||
current = 0
|
||||
day = as_of_date
|
||||
while (check_in := by_date.get(day)) is not None and is_low_pain(check_in, threshold):
|
||||
current += 1
|
||||
day -= timedelta(days=1)
|
||||
return CheckInStreaks(current=current, longest=longest)
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Deferral policies, deliberately separate from HTTP views and model saves."""
|
||||
|
||||
from datetime import date, timedelta
|
||||
from typing import Iterable
|
||||
|
||||
from planner.models import SickDaySettings, Task
|
||||
from planner.services.scheduling import is_task_scheduled_on_date
|
||||
|
||||
|
||||
DEFERRAL_SOURCES = frozenset(Task.DeferralSource.values)
|
||||
|
||||
|
||||
def extend_task_deferral(task: Task, deferred_until: date, source: str) -> bool:
|
||||
"""Set a deferral only when it does not shorten an existing one.
|
||||
|
||||
The caller chooses the source when it extends a deferral. This is suitable
|
||||
for an intentional manual deferral; automatic policies use their narrower
|
||||
source-owning helpers below.
|
||||
"""
|
||||
if source not in DEFERRAL_SOURCES:
|
||||
raise ValueError(f'Unsupported deferral source: {source}')
|
||||
if not isinstance(deferred_until, date):
|
||||
raise ValueError('deferred_until must be a date')
|
||||
if task.deferred_until is not None and deferred_until <= task.deferred_until:
|
||||
return False
|
||||
|
||||
task.deferred_until = deferred_until
|
||||
task.deferral_source = source
|
||||
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
|
||||
return True
|
||||
|
||||
|
||||
def defer_task_manually(task: Task, deferred_until: date) -> bool:
|
||||
"""Apply a user-requested manual deferral without shortening an existing one."""
|
||||
return extend_task_deferral(task, deferred_until, Task.DeferralSource.MANUAL)
|
||||
|
||||
|
||||
def apply_missed_task_deferrals(tasks: Iterable[Task], selected_date: date) -> list[Task]:
|
||||
"""Create or extend missed deferrals for overdue one-time tasks.
|
||||
|
||||
Existing manual or Sick Day deferrals are left untouched. A missed deferral
|
||||
can only move later as the user views later dates.
|
||||
"""
|
||||
changed = []
|
||||
for task in tasks:
|
||||
if task.is_recurring or not task.defer_days or task.scheduled_for >= selected_date:
|
||||
continue
|
||||
if task.deferral_source not in ('', Task.DeferralSource.MISSED):
|
||||
continue
|
||||
|
||||
target_date = selected_date + timedelta(days=task.defer_days)
|
||||
if task.deferred_until is not None and target_date <= task.deferred_until:
|
||||
continue
|
||||
|
||||
task.deferred_until = target_date
|
||||
task.deferral_source = Task.DeferralSource.MISSED
|
||||
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
|
||||
changed.append(task)
|
||||
return changed
|
||||
|
||||
|
||||
def sick_day_applies(settings: SickDaySettings | None, selected_date: date) -> bool:
|
||||
"""Whether a user's Sick Day Mode applies to the selected calendar date."""
|
||||
return bool(
|
||||
settings
|
||||
and settings.enabled
|
||||
and (settings.recovery_date is None or selected_date <= settings.recovery_date)
|
||||
)
|
||||
|
||||
|
||||
def sick_day_target_date(settings: SickDaySettings, selected_date: date) -> date:
|
||||
"""Return the date to which Sick Day work should be deferred."""
|
||||
base_date = settings.recovery_date or selected_date
|
||||
return base_date + timedelta(days=1)
|
||||
|
||||
|
||||
def is_sick_day_suppressed(
|
||||
task: Task, settings: SickDaySettings | None, selected_date: date
|
||||
) -> bool:
|
||||
"""Hide normally scheduled non-essential work without touching other sources."""
|
||||
return (
|
||||
sick_day_applies(settings, selected_date)
|
||||
and not task.required_on_sick_day
|
||||
and task.deferral_source != Task.DeferralSource.SICK_DAY
|
||||
and is_task_scheduled_on_date(task, selected_date)
|
||||
)
|
||||
|
||||
|
||||
def sync_sick_day_deferrals(
|
||||
tasks: Iterable[Task], settings: SickDaySettings | None, selected_date: date
|
||||
) -> list[Task]:
|
||||
"""Synchronize only deferrals owned by Sick Day Mode.
|
||||
|
||||
Recovery-date changes can move Sick Day deferrals in either direction. When
|
||||
disabled, only Sick Day deferrals are removed; manual and missed deferrals
|
||||
are deliberately never changed by this function.
|
||||
"""
|
||||
changed = []
|
||||
task_list = list(tasks)
|
||||
if settings is None or not settings.enabled:
|
||||
for task in task_list:
|
||||
if task.deferral_source == Task.DeferralSource.SICK_DAY:
|
||||
task.deferred_until = None
|
||||
task.deferral_source = ''
|
||||
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
|
||||
changed.append(task)
|
||||
return changed
|
||||
|
||||
target_date = sick_day_target_date(settings, selected_date)
|
||||
applies = sick_day_applies(settings, selected_date)
|
||||
for task in task_list:
|
||||
if task.required_on_sick_day:
|
||||
if task.deferral_source == Task.DeferralSource.SICK_DAY:
|
||||
task.deferred_until = None
|
||||
task.deferral_source = ''
|
||||
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
|
||||
changed.append(task)
|
||||
continue
|
||||
|
||||
if task.deferral_source == Task.DeferralSource.SICK_DAY:
|
||||
if task.deferred_until != target_date:
|
||||
task.deferred_until = target_date
|
||||
task.save(update_fields=['deferred_until', 'updated_at'])
|
||||
changed.append(task)
|
||||
continue
|
||||
|
||||
if applies and task.deferral_source == '' and is_task_scheduled_on_date(task, selected_date):
|
||||
task.deferred_until = target_date
|
||||
task.deferral_source = Task.DeferralSource.SICK_DAY
|
||||
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
|
||||
changed.append(task)
|
||||
return changed
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Intermittent-fasting schedule and history synchronization policies."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from planner.models import FastingPause, FastingPeriod, FastingSettings
|
||||
from planner.timezones import timezone_for_user
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScheduledFastingPeriod:
|
||||
scheduled_start: datetime
|
||||
scheduled_end: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FastingPhase:
|
||||
name: str
|
||||
scheduled_start: datetime
|
||||
scheduled_end: datetime
|
||||
cycle_start: datetime
|
||||
cycle_end: datetime
|
||||
|
||||
@property
|
||||
def is_fasting(self) -> bool:
|
||||
return self.name == 'fasting'
|
||||
|
||||
|
||||
def current_timezone(user=None):
|
||||
"""Use the saved timezone when a user is known, otherwise Django's active zone."""
|
||||
return timezone_for_user(user) if user is not None else timezone.get_current_timezone()
|
||||
|
||||
|
||||
def scheduled_fasting_period(
|
||||
settings: FastingSettings, start_date: date, tz=None
|
||||
) -> ScheduledFastingPeriod:
|
||||
"""Build one scheduled daily fasting period in the active Django timezone."""
|
||||
tz = tz or current_timezone(settings.user)
|
||||
start = timezone.make_aware(
|
||||
datetime.combine(start_date, settings.fasting_start_time), timezone=tz
|
||||
)
|
||||
end = start + timedelta(minutes=settings.fasting_duration_minutes)
|
||||
return ScheduledFastingPeriod(start, end)
|
||||
|
||||
|
||||
def current_fasting_phase(
|
||||
settings: FastingSettings, now: datetime | None = None
|
||||
) -> FastingPhase:
|
||||
"""Return the current fasting/eating phase from the repeating daily schedule."""
|
||||
now = now or timezone.now()
|
||||
tz = current_timezone(settings.user)
|
||||
local_now = timezone.localtime(now, tz)
|
||||
local_time = local_now.timetz().replace(tzinfo=None)
|
||||
start_date = local_now.date()
|
||||
if local_time < settings.fasting_start_time:
|
||||
start_date -= timedelta(days=1)
|
||||
|
||||
period = scheduled_fasting_period(settings, start_date, tz)
|
||||
if period.scheduled_start <= now < period.scheduled_end:
|
||||
return FastingPhase(
|
||||
'fasting',
|
||||
period.scheduled_start,
|
||||
period.scheduled_end,
|
||||
period.scheduled_start,
|
||||
period.scheduled_end,
|
||||
)
|
||||
|
||||
# The eating cycle starts as the fast ends and resets at the next daily fast.
|
||||
next_fasting_start = period.scheduled_start + timedelta(days=1)
|
||||
return FastingPhase(
|
||||
'eating',
|
||||
period.scheduled_start,
|
||||
period.scheduled_end,
|
||||
period.scheduled_end,
|
||||
next_fasting_start,
|
||||
)
|
||||
|
||||
|
||||
def _period_overlaps_pause(
|
||||
user, period: ScheduledFastingPeriod, now: datetime
|
||||
) -> bool:
|
||||
pauses = FastingPause.objects.filter(user=user, paused_at__lt=period.scheduled_end)
|
||||
for pause in pauses:
|
||||
pause_end = pause.resumed_at or now
|
||||
if pause_end > period.scheduled_start:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def validate_fasting_duration(value: int) -> None:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value < 24 * 60:
|
||||
raise ValueError('Fasting duration must be between 1 and 1439 minutes.')
|
||||
|
||||
|
||||
def configure_fasting(
|
||||
user,
|
||||
*,
|
||||
enabled: bool,
|
||||
fasting_start_time,
|
||||
fasting_duration_minutes: int,
|
||||
now: datetime | None = None,
|
||||
) -> FastingSettings:
|
||||
"""Create or update configuration and record any transition into a pause."""
|
||||
validate_fasting_duration(fasting_duration_minutes)
|
||||
now = now or timezone.now()
|
||||
settings, created = FastingSettings.objects.get_or_create(
|
||||
user=user,
|
||||
defaults={
|
||||
'enabled': enabled,
|
||||
'fasting_start_time': fasting_start_time,
|
||||
'fasting_duration_minutes': fasting_duration_minutes,
|
||||
'tracking_started_at': now if enabled else None,
|
||||
},
|
||||
)
|
||||
if created:
|
||||
if not enabled:
|
||||
FastingPause.objects.create(user=user, paused_at=now)
|
||||
return settings
|
||||
|
||||
was_enabled = settings.enabled
|
||||
settings.fasting_start_time = fasting_start_time
|
||||
settings.fasting_duration_minutes = fasting_duration_minutes
|
||||
settings.enabled = enabled
|
||||
if enabled and settings.tracking_started_at is None:
|
||||
settings.tracking_started_at = now
|
||||
settings.save()
|
||||
|
||||
if was_enabled and not enabled:
|
||||
FastingPause.objects.get_or_create(user=user, resumed_at__isnull=True, defaults={'paused_at': now})
|
||||
elif not was_enabled and enabled:
|
||||
FastingPause.objects.filter(user=user, resumed_at__isnull=True).update(resumed_at=now)
|
||||
return settings
|
||||
|
||||
|
||||
def set_fasting_tracking_enabled(
|
||||
settings: FastingSettings, enabled: bool, now: datetime | None = None
|
||||
) -> FastingSettings:
|
||||
"""Pause or resume tracking while preserving the configured daily schedule."""
|
||||
return configure_fasting(
|
||||
settings.user,
|
||||
enabled=enabled,
|
||||
fasting_start_time=settings.fasting_start_time,
|
||||
fasting_duration_minutes=settings.fasting_duration_minutes,
|
||||
now=now,
|
||||
)
|
||||
|
||||
|
||||
def synchronize_fasting_periods(
|
||||
settings: FastingSettings | None, now: datetime | None = None
|
||||
) -> list[FastingPeriod]:
|
||||
"""Idempotently record completed scheduled periods that were fully tracked.
|
||||
|
||||
This function can be called from a request today and a background job later.
|
||||
It never creates records while paused or for any schedule period overlapping
|
||||
a recorded pause interval.
|
||||
"""
|
||||
if settings is None or not settings.enabled or settings.tracking_started_at is None:
|
||||
return []
|
||||
|
||||
now = now or timezone.now()
|
||||
tz = current_timezone(settings.user)
|
||||
started_local = timezone.localtime(settings.tracking_started_at, tz)
|
||||
current_local = timezone.localtime(now, tz)
|
||||
created_periods = []
|
||||
candidate_date = started_local.date()
|
||||
while candidate_date <= current_local.date():
|
||||
period = scheduled_fasting_period(settings, candidate_date, tz)
|
||||
candidate_date += timedelta(days=1)
|
||||
if period.scheduled_start < settings.tracking_started_at:
|
||||
continue
|
||||
if period.scheduled_end > now or _period_overlaps_pause(settings.user, period, now):
|
||||
continue
|
||||
|
||||
try:
|
||||
with transaction.atomic():
|
||||
history, created = FastingPeriod.objects.get_or_create(
|
||||
user=settings.user,
|
||||
scheduled_start=period.scheduled_start,
|
||||
defaults={
|
||||
'scheduled_end': period.scheduled_end,
|
||||
'completed_at': now,
|
||||
'status': FastingPeriod.Status.COMPLETED,
|
||||
},
|
||||
)
|
||||
except IntegrityError:
|
||||
# The uniqueness constraint makes concurrent synchronization safe.
|
||||
continue
|
||||
if created:
|
||||
created_periods.append(history)
|
||||
return created_periods
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Reusable scheduling and recommendation decisions for the task planner."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, timedelta
|
||||
from typing import TYPE_CHECKING, Iterable
|
||||
|
||||
from planner.models import Task, TaskWeatherShift
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from planner.models import SickDaySettings
|
||||
|
||||
ENERGY_BUDGETS = {1: 15, 2: 30, 3: 60, 4: 90, 5: 180}
|
||||
DEFAULT_ENERGY_LEVEL = 3
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RecommendedTaskGroup:
|
||||
"""One independently recommended top-level task and its eligible subtasks."""
|
||||
task: Task
|
||||
subtasks: tuple[Task, ...]
|
||||
|
||||
|
||||
def normalize_energy_level(value: object) -> int:
|
||||
try:
|
||||
level = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_ENERGY_LEVEL
|
||||
return max(min(level, max(ENERGY_BUDGETS)), min(ENERGY_BUDGETS))
|
||||
|
||||
|
||||
def duration_budget_for_energy(value: object) -> int:
|
||||
return ENERGY_BUDGETS[normalize_energy_level(value)]
|
||||
|
||||
|
||||
def is_task_scheduled_on_date(task: Task, selected_date: date) -> bool:
|
||||
anchor = task.scheduled_for
|
||||
if not isinstance(anchor, date) or not isinstance(selected_date, date):
|
||||
return False
|
||||
if not task.is_recurring:
|
||||
return selected_date == anchor
|
||||
interval = task.recurrence_interval
|
||||
if not isinstance(interval, int) or isinstance(interval, bool) or interval <= 0 or selected_date < anchor:
|
||||
return False
|
||||
if task.recurrence_unit == Task.RecurrenceUnit.DAY:
|
||||
return (selected_date - anchor).days % interval == 0
|
||||
if task.recurrence_unit == Task.RecurrenceUnit.WEEK:
|
||||
return (selected_date - anchor).days % (interval * 7) == 0
|
||||
if task.recurrence_unit == Task.RecurrenceUnit.MONTH:
|
||||
if selected_date.day != anchor.day:
|
||||
return False
|
||||
distance = (selected_date.year - anchor.year) * 12 + selected_date.month - anchor.month
|
||||
return distance >= 0 and distance % interval == 0
|
||||
return False
|
||||
|
||||
|
||||
def is_task_eligible(task: Task, selected_date: date) -> bool:
|
||||
if not isinstance(selected_date, date):
|
||||
return False
|
||||
if task.deferred_until is not None:
|
||||
if selected_date < task.deferred_until:
|
||||
return False
|
||||
if selected_date == task.deferred_until:
|
||||
return True
|
||||
return is_task_scheduled_on_date(task, selected_date)
|
||||
|
||||
|
||||
def task_recommendation_key(task: Task, energy_level: object) -> tuple:
|
||||
budget = duration_budget_for_energy(energy_level)
|
||||
duration = task.estimated_duration_minutes
|
||||
has_duration = duration is not None
|
||||
exceeds_budget = has_duration and duration > budget
|
||||
if not has_duration:
|
||||
preference = float('inf')
|
||||
elif normalize_energy_level(energy_level) <= 2:
|
||||
preference = duration
|
||||
elif duration <= budget:
|
||||
preference = budget - duration
|
||||
else:
|
||||
preference = duration - budget
|
||||
return (not task.is_active, not task.is_recurring, not has_duration,
|
||||
exceeds_budget if has_duration else True, preference, task.title.casefold())
|
||||
|
||||
|
||||
def _weather_shift_for_date(task: Task, selected_date: date):
|
||||
return task.weather_shifts.filter(shifted_to=selected_date).first()
|
||||
|
||||
|
||||
def _find_weather_target(task: Task, owner, original_date: date):
|
||||
"""Find the first forecast-supported vacancy for one weather-blocked occurrence."""
|
||||
from planner.services.weather import (
|
||||
FORECAST_SEARCH_HORIZON_DAYS, evaluate_weather_suitability, forecast_for_user_on_date,
|
||||
)
|
||||
for offset in range(1, FORECAST_SEARCH_HORIZON_DAYS + 1):
|
||||
candidate = original_date + timedelta(days=offset)
|
||||
# An occurrence may not be moved onto another natural or already moved occurrence.
|
||||
if is_task_scheduled_on_date(task, candidate):
|
||||
continue
|
||||
if task.weather_shifts.filter(shifted_to=candidate).exclude(original_date=original_date).exists():
|
||||
continue
|
||||
outcome = evaluate_weather_suitability(task, forecast_for_user_on_date(owner, candidate))
|
||||
if outcome.status == 'suitable':
|
||||
return candidate, outcome.reason
|
||||
return None, 'Waiting for a suitable weather forecast.'
|
||||
|
||||
|
||||
def is_weather_eligible(task: Task, selected_date: date, owner) -> bool:
|
||||
"""Apply weather-owned occurrence moves without changing recurrence anchors.
|
||||
|
||||
Manual, missed, and Sick Day deferrals are intentionally evaluated first and
|
||||
are never replaced by weather state. Unknown weather remains visible.
|
||||
"""
|
||||
if owner is None or task.weather_profile == Task.WeatherProfile.ANY:
|
||||
return is_task_eligible(task, selected_date)
|
||||
|
||||
moved = _weather_shift_for_date(task, selected_date)
|
||||
if moved is not None:
|
||||
task.weather_shift_reason = moved.reason
|
||||
task.weather_shifted_from = moved.original_date
|
||||
return True
|
||||
|
||||
if not is_task_eligible(task, selected_date):
|
||||
return False
|
||||
if task.deferred_until is not None and task.deferral_source != Task.DeferralSource.WEATHER:
|
||||
return True
|
||||
if not is_task_scheduled_on_date(task, selected_date):
|
||||
return True
|
||||
|
||||
existing = task.weather_shifts.filter(original_date=selected_date).first()
|
||||
if existing is not None:
|
||||
# The source is weather-owned, so it can be recalculated without touching other deferrals.
|
||||
target, reason = _find_weather_target(task, owner, selected_date)
|
||||
if existing.shifted_to != target or existing.reason != reason:
|
||||
existing.shifted_to, existing.reason = target, reason
|
||||
existing.save(update_fields=['shifted_to', 'reason', 'updated_at'])
|
||||
return False
|
||||
|
||||
from planner.services.weather import evaluate_weather_suitability, forecast_for_user_on_date
|
||||
outcome = evaluate_weather_suitability(task, forecast_for_user_on_date(owner, selected_date))
|
||||
if outcome.status != 'unsuitable':
|
||||
if outcome.status == 'unknown':
|
||||
task.weather_shift_reason = outcome.reason
|
||||
return True
|
||||
target, reason = _find_weather_target(task, owner, selected_date)
|
||||
TaskWeatherShift.objects.create(
|
||||
task=task, owner=owner, original_date=selected_date, shifted_to=target,
|
||||
reason=f'{outcome.reason} {reason}',
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def recommend_tasks(top_level_tasks: Iterable[Task], selected_date: date, energy_level: object,
|
||||
sick_day_settings: 'SickDaySettings | None' = None, *, user=None) -> list[RecommendedTaskGroup]:
|
||||
"""Recommend parent tasks first; completed parents unlock their subtasks."""
|
||||
from planner.services.deferrals import is_sick_day_suppressed
|
||||
|
||||
candidates = []
|
||||
for parent in top_level_tasks:
|
||||
if parent.is_completed:
|
||||
candidates.extend(
|
||||
subtask for subtask in parent.subtasks.all()
|
||||
if is_weather_eligible(subtask, selected_date, user)
|
||||
and not is_sick_day_suppressed(subtask, sick_day_settings, selected_date)
|
||||
)
|
||||
elif (
|
||||
is_weather_eligible(parent, selected_date, user)
|
||||
and not is_sick_day_suppressed(parent, sick_day_settings, selected_date)
|
||||
):
|
||||
candidates.append(parent)
|
||||
|
||||
candidates.sort(key=lambda task: task_recommendation_key(task, energy_level))
|
||||
return [RecommendedTaskGroup(task, ()) for task in candidates]
|
||||
|
||||
|
||||
def daily_recommendations(user, selected_date: date | object = None, energy_level: object = None,
|
||||
sick_day_settings: 'SickDaySettings | None' = None) -> list[RecommendedTaskGroup]:
|
||||
"""Load one user's tasks and apply deferral and weather policies.
|
||||
|
||||
The legacy three-argument shape remains temporarily supported for existing
|
||||
service callers; normal application code always passes the authenticated user.
|
||||
"""
|
||||
if isinstance(user, date):
|
||||
user, selected_date, energy_level, sick_day_settings = None, user, selected_date, energy_level
|
||||
from planner.services.deferrals import apply_missed_task_deferrals, sync_sick_day_deferrals
|
||||
|
||||
queryset = Task.objects.filter(parent_task__isnull=True)
|
||||
if user is not None:
|
||||
queryset = queryset.filter(owner=user)
|
||||
top_level_tasks = list(queryset.prefetch_related('subtasks', 'weather_shifts'))
|
||||
all_tasks = [task for parent in top_level_tasks for task in (parent, *parent.subtasks.all())]
|
||||
apply_missed_task_deferrals(all_tasks, selected_date)
|
||||
sync_sick_day_deferrals(all_tasks, sick_day_settings, selected_date)
|
||||
return recommend_tasks(top_level_tasks, selected_date, energy_level, sick_day_settings, user=user)
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Open-Meteo integration and weather suitability policy.
|
||||
|
||||
The rest of the planner only consumes DailyForecast instances, never Open-Meteo JSON.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
import json
|
||||
from typing import Iterable
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import urlopen
|
||||
|
||||
from django.core.cache import cache
|
||||
|
||||
from planner.models import Task, UserSettings
|
||||
|
||||
OPEN_METEO_URL = 'https://api.open-meteo.com/v1/forecast'
|
||||
FORECAST_SEARCH_HORIZON_DAYS = 16
|
||||
FORECAST_CACHE_SECONDS = 12 * 60 * 60
|
||||
MEANINGFUL_PRECIPITATION_PROBABILITY = 40
|
||||
MEANINGFUL_PRECIPITATION_MM = 0.5
|
||||
SUNNY_MINIMUM_SECONDS = 4 * 60 * 60
|
||||
WARM_MINIMUM_TEMPERATURE_C = 15.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DailyForecast:
|
||||
forecast_date: date
|
||||
condition: str
|
||||
precipitation_probability: float | None
|
||||
precipitation_mm: float | None
|
||||
temperature_min_c: float | None
|
||||
temperature_max_c: float | None
|
||||
wind_speed_max_kmh: float | None
|
||||
sunshine_seconds: float | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WeatherSuitability:
|
||||
status: str # suitable, unsuitable, unknown
|
||||
reason: str
|
||||
|
||||
@property
|
||||
def is_suitable(self) -> bool:
|
||||
return self.status == 'suitable'
|
||||
|
||||
|
||||
class WeatherServiceError(Exception):
|
||||
"""Open-Meteo could not provide a usable forecast."""
|
||||
|
||||
|
||||
def wmo_condition(code: int | None) -> str:
|
||||
"""Map Open-Meteo WMO codes into stable application-level conditions."""
|
||||
if code == 0:
|
||||
return 'clear'
|
||||
if code in (1, 2):
|
||||
return 'partly_cloudy'
|
||||
if code == 3:
|
||||
return 'cloudy'
|
||||
if code in (45, 48):
|
||||
return 'fog'
|
||||
if code in (51, 53, 55, 56, 57, 80, 81):
|
||||
return 'rain'
|
||||
if code in (61, 63, 66, 80):
|
||||
return 'rain'
|
||||
if code in (65, 67, 82):
|
||||
return 'heavy_rain'
|
||||
if code in (71, 73, 75, 77, 85, 86):
|
||||
return 'snow'
|
||||
if code in (95, 96, 99):
|
||||
return 'thunderstorm'
|
||||
return 'unknown'
|
||||
|
||||
|
||||
WEATHER_ICON_NAMES = {
|
||||
'clear': '☀', 'partly_cloudy': '⛅', 'cloudy': '☁', 'fog': '🌫',
|
||||
'rain': '🌦', 'heavy_rain': '🌧', 'thunderstorm': '⛈', 'snow': '❄', 'unknown': '◌',
|
||||
}
|
||||
WEATHER_LABELS = {
|
||||
'clear': 'Clear', 'partly_cloudy': 'Partly cloudy', 'cloudy': 'Cloudy', 'fog': 'Foggy',
|
||||
'rain': 'Rain', 'heavy_rain': 'Heavy rain', 'thunderstorm': 'Thunderstorms',
|
||||
'snow': 'Snow', 'unknown': 'Unknown conditions',
|
||||
}
|
||||
|
||||
|
||||
def _as_number(values: list, index: int) -> float | None:
|
||||
try:
|
||||
value = values[index]
|
||||
except (IndexError, TypeError):
|
||||
return None
|
||||
return float(value) if value is not None else None
|
||||
|
||||
|
||||
def normalize_open_meteo_response(payload: dict) -> list[DailyForecast]:
|
||||
"""Convert Open-Meteo's daily arrays into application forecast records."""
|
||||
daily = payload.get('daily') or {}
|
||||
dates = daily.get('time') or []
|
||||
forecasts = []
|
||||
for index, value in enumerate(dates):
|
||||
try:
|
||||
forecast_date = date.fromisoformat(value)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
code = _as_number(daily.get('weather_code', []), index)
|
||||
forecasts.append(DailyForecast(
|
||||
forecast_date=forecast_date,
|
||||
condition=wmo_condition(int(code) if code is not None else None),
|
||||
precipitation_probability=_as_number(daily.get('precipitation_probability_max', []), index),
|
||||
precipitation_mm=_as_number(daily.get('precipitation_sum', []), index),
|
||||
temperature_min_c=_as_number(daily.get('temperature_2m_min', []), index),
|
||||
temperature_max_c=_as_number(daily.get('temperature_2m_max', []), index),
|
||||
wind_speed_max_kmh=_as_number(daily.get('wind_speed_10m_max', []), index),
|
||||
sunshine_seconds=_as_number(daily.get('sunshine_duration', []), index),
|
||||
))
|
||||
return forecasts
|
||||
|
||||
|
||||
def fetch_open_meteo_forecasts(latitude: Decimal | float, longitude: Decimal | float) -> list[DailyForecast]:
|
||||
"""Fetch one normalized finite daily forecast from Open-Meteo."""
|
||||
params = urlencode({
|
||||
'latitude': str(latitude), 'longitude': str(longitude),
|
||||
'daily': 'weather_code,precipitation_probability_max,precipitation_sum,temperature_2m_min,temperature_2m_max,wind_speed_10m_max,sunshine_duration',
|
||||
'forecast_days': FORECAST_SEARCH_HORIZON_DAYS, 'timezone': 'auto',
|
||||
})
|
||||
try:
|
||||
with urlopen(f'{OPEN_METEO_URL}?{params}', timeout=5) as response: # nosec B310 - fixed HTTPS endpoint
|
||||
payload = json.loads(response.read().decode('utf-8'))
|
||||
except (OSError, ValueError, json.JSONDecodeError) as error:
|
||||
raise WeatherServiceError('Weather forecast is unavailable.') from error
|
||||
return normalize_open_meteo_response(payload)
|
||||
|
||||
|
||||
def _forecast_cache_key(user_id: int, latitude: Decimal, longitude: Decimal) -> str:
|
||||
return f'planner:weather:{user_id}:{latitude}:{longitude}'
|
||||
|
||||
|
||||
def forecasts_for_user(user) -> list[DailyForecast] | None:
|
||||
"""Return cached normalized forecasts, or None when location/API is unavailable."""
|
||||
settings = UserSettings.objects.filter(user=user).first()
|
||||
if settings is None or settings.latitude is None or settings.longitude is None:
|
||||
return None
|
||||
key = _forecast_cache_key(user.pk, settings.latitude, settings.longitude)
|
||||
cached = cache.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
forecasts = fetch_open_meteo_forecasts(settings.latitude, settings.longitude)
|
||||
except WeatherServiceError:
|
||||
return None
|
||||
cache.set(key, forecasts, FORECAST_CACHE_SECONDS)
|
||||
return forecasts
|
||||
|
||||
|
||||
def forecast_for_user_on_date(user, selected_date: date) -> DailyForecast | None:
|
||||
forecasts = forecasts_for_user(user)
|
||||
if forecasts is None:
|
||||
return None
|
||||
return next((forecast for forecast in forecasts if forecast.forecast_date == selected_date), None)
|
||||
|
||||
|
||||
def evaluate_weather_suitability(task: Task, forecast: DailyForecast | None) -> WeatherSuitability:
|
||||
"""Evaluate a task profile with centralized, explainable weather thresholds."""
|
||||
profile = task.weather_profile
|
||||
if profile == Task.WeatherProfile.ANY:
|
||||
return WeatherSuitability('suitable', 'Any weather is suitable.')
|
||||
if forecast is None:
|
||||
return WeatherSuitability('unknown', 'Weather forecast unavailable.')
|
||||
|
||||
rainy = (
|
||||
(forecast.precipitation_probability is not None and forecast.precipitation_probability >= MEANINGFUL_PRECIPITATION_PROBABILITY)
|
||||
or (forecast.precipitation_mm is not None and forecast.precipitation_mm >= MEANINGFUL_PRECIPITATION_MM)
|
||||
)
|
||||
dry = not rainy
|
||||
sunny = dry and forecast.condition in {'clear', 'partly_cloudy'} and (
|
||||
forecast.sunshine_seconds is not None and forecast.sunshine_seconds >= SUNNY_MINIMUM_SECONDS
|
||||
)
|
||||
warm = forecast.temperature_max_c is not None and forecast.temperature_max_c >= WARM_MINIMUM_TEMPERATURE_C
|
||||
|
||||
if profile == Task.WeatherProfile.DRY:
|
||||
return WeatherSuitability('suitable', f'Dry forecast.') if dry else WeatherSuitability('unsuitable', 'Rain expected.')
|
||||
if profile == Task.WeatherProfile.SUNNY:
|
||||
return WeatherSuitability('suitable', 'Sunny and dry forecast.') if sunny else WeatherSuitability('unsuitable', 'Not sunny and dry enough.')
|
||||
if profile == Task.WeatherProfile.WARM:
|
||||
return WeatherSuitability('suitable', f'Warm, up to {forecast.temperature_max_c:g} °C.') if warm else WeatherSuitability('unsuitable', f'Below {WARM_MINIMUM_TEMPERATURE_C:g} °C.')
|
||||
if profile == Task.WeatherProfile.DRY_AND_WARM:
|
||||
if not dry:
|
||||
return WeatherSuitability('unsuitable', 'Rain expected.')
|
||||
if not warm:
|
||||
return WeatherSuitability('unsuitable', f'Below {WARM_MINIMUM_TEMPERATURE_C:g} °C.')
|
||||
return WeatherSuitability('suitable', f'Dry and warm, up to {forecast.temperature_max_c:g} °C.')
|
||||
return WeatherSuitability('unknown', 'Unknown weather preference.')
|
||||
|
||||
|
||||
def weather_profile_label(task: Task) -> str:
|
||||
return task.get_weather_profile_display()
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Workout daily-occurrence policy, separate from task scheduling."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
|
||||
from django.db.models import Q
|
||||
|
||||
from planner.models import Workout, WorkoutCompletion
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DailyWorkoutSummary:
|
||||
workouts: tuple[Workout, ...]
|
||||
calories_total: int | None
|
||||
completed_without_calories: int
|
||||
|
||||
|
||||
def workouts_for_day(user, selected_date: date) -> DailyWorkoutSummary:
|
||||
"""Return this user's one-time and repeating workout occurrences for a day."""
|
||||
workouts = list(
|
||||
Workout.objects.filter(owner=user)
|
||||
.filter(Q(is_daily_recurring=True, scheduled_for__lte=selected_date) | Q(is_daily_recurring=False, scheduled_for=selected_date))
|
||||
.prefetch_related('completions')
|
||||
)
|
||||
total = 0
|
||||
completed_with_calories = 0
|
||||
completed_without_calories = 0
|
||||
for workout in workouts:
|
||||
completed = workout.completions.filter(completed_on=selected_date).exists() if workout.is_daily_recurring else workout.is_completed
|
||||
workout.completed_for_day = completed
|
||||
workout.occurrence_date = selected_date
|
||||
if completed:
|
||||
if workout.calories_burned is None:
|
||||
completed_without_calories += 1
|
||||
else:
|
||||
total += workout.calories_burned
|
||||
completed_with_calories += 1
|
||||
workouts.sort(key=lambda item: (item.completed_for_day, item.name.casefold()))
|
||||
return DailyWorkoutSummary(tuple(workouts), total if completed_with_calories else None, completed_without_calories)
|
||||
|
||||
|
||||
def toggle_workout_completion(workout: Workout, selected_date: date) -> bool:
|
||||
"""Toggle one displayed occurrence and return its new completion status."""
|
||||
if workout.is_daily_recurring:
|
||||
completion = WorkoutCompletion.objects.filter(workout=workout, completed_on=selected_date).first()
|
||||
if completion is not None:
|
||||
completion.delete()
|
||||
return False
|
||||
WorkoutCompletion.objects.create(workout=workout, completed_on=selected_date)
|
||||
return True
|
||||
workout.is_completed = not workout.is_completed
|
||||
workout.save(update_fields=['is_completed', 'updated_at'])
|
||||
return workout.is_completed
|
||||
@@ -0,0 +1,38 @@
|
||||
{% load vite %}
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="description" content="A calm, focused personal task planner.">
|
||||
<title>{% block title %}Tasknest{% endblock %}</title>
|
||||
{% vite_asset 'src/main.js' %}
|
||||
</head>
|
||||
<body>
|
||||
<div class="app-shell">
|
||||
<header class="site-header">
|
||||
<div class="site-header__inner">
|
||||
<a class="brand" href="{% url 'planner:task-list' %}" aria-label="Tasknest home">
|
||||
<span class="brand__mark" aria-hidden="true">✓</span>
|
||||
<span>tasknest</span>
|
||||
</a>
|
||||
<nav class="primary-nav" aria-label="Primary navigation">
|
||||
{% if user.is_authenticated %}
|
||||
<a href="{% url 'planner:task-list' %}">My tasks</a>
|
||||
<a href="{% url 'planner:daily-planner' %}">Daily planner</a>
|
||||
<a href="{% url 'planner:user-settings' %}">Settings</a>
|
||||
<form method="post" action="{% url 'planner:logout' %}" class="nav-logout">{% csrf_token %}<button type="submit">Log out</button></form>
|
||||
{% else %}
|
||||
<a href="{% url 'planner:login' %}">Log in</a>
|
||||
<a href="{% url 'planner:register' %}">Create account</a>
|
||||
{% endif %}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
<main class="page-content">
|
||||
{% if messages %}{% for message in messages %}<p class="flash-message" role="status">{{ message }}</p>{% endfor %}{% endif %}
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,88 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
|
||||
{% block title %}Daily planner · Tasknest{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="planner-hero" aria-labelledby="daily-planner-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Daily planner</p>
|
||||
<h1 id="daily-planner-heading">Choose your next best step.</h1>
|
||||
<p>Recommendations adapt to the date and the energy you have available.</p>
|
||||
</div>
|
||||
<form class="planner-controls" method="get">
|
||||
<div>
|
||||
{{ form.selected_date.label_tag }}
|
||||
{{ form.selected_date }}
|
||||
{% for error in form.selected_date.errors %}<p class="field-error" role="alert">{{ error }}</p>{% endfor %}
|
||||
</div>
|
||||
<div>
|
||||
{{ form.energy_level.label_tag }}
|
||||
{{ form.energy_level }}
|
||||
{% for error in form.energy_level.errors %}<p class="field-error" role="alert">{{ error }}</p>{% endfor %}
|
||||
</div>
|
||||
<button class="button" type="submit">Update plan</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{% if form.is_valid %}
|
||||
<section class="recommendations-panel" aria-labelledby="recommendations-heading">
|
||||
<header class="recommendations-panel__header">
|
||||
<div>
|
||||
<p class="eyebrow">{{ selected_date|date:"l, j F" }}</p>
|
||||
<h2 id="recommendations-heading">Recommended for you</h2>
|
||||
</div>
|
||||
<p class="budget-note">Your available time: <strong>{{ duration_budget }} minutes</strong></p>
|
||||
</header>
|
||||
{% if recommendations %}
|
||||
<div class="recommendation-list">
|
||||
{% for recommendation in recommendations %}
|
||||
<article class="recommendation-card">
|
||||
<div class="recommendation-card__main">
|
||||
<span class="priority priority--{{ recommendation.task.priority }}">{{ recommendation.task.get_priority_display }}</span>
|
||||
<h3><a href="{% url 'planner:task-detail' recommendation.task.pk %}">{{ recommendation.task.title }}</a></h3>
|
||||
<p>
|
||||
{% if recommendation.task.estimated_duration_minutes %}
|
||||
{{ recommendation.task.estimated_duration_minutes }} minutes
|
||||
{% else %}
|
||||
Duration flexible
|
||||
{% endif %}
|
||||
{% if recommendation.task.is_recurring %} · Recurring{% endif %}
|
||||
{% if not recommendation.task.is_active %} · Paused{% endif %}
|
||||
{% if recommendation.task.weather_profile != 'none' %} · {{ recommendation.task.get_weather_profile_display }}{% endif %}
|
||||
{% if recommendation.task.weather_shifted_from %} · Moved from {{ recommendation.task.weather_shifted_from|date:'l' }} — {{ recommendation.task.weather_shift_reason }}{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
<div class="recommendation-card__actions">
|
||||
<form method="post" action="{% url 'planner:task-toggle-completed' recommendation.task.pk %}" hx-post="{% url 'planner:task-toggle-completed' recommendation.task.pk %}">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="return_to_daily_planner" value="1">
|
||||
<input type="hidden" name="selected_date" value="{{ selected_date|date:'Y-m-d' }}">
|
||||
<input type="hidden" name="energy_level" value="{{ energy_level }}">
|
||||
<button class="button button--compact" type="submit">Mark complete</button>
|
||||
</form>
|
||||
<a class="text-link" href="{% url 'planner:task-update' recommendation.task.pk %}">Edit</a>
|
||||
</div>
|
||||
{% if recommendation.subtasks %}
|
||||
<section class="recommendation-card__subtasks" aria-labelledby="subtasks-{{ recommendation.task.pk }}">
|
||||
<h4 id="subtasks-{{ recommendation.task.pk }}">Eligible subtasks</h4>
|
||||
<ul>
|
||||
{% for subtask in recommendation.subtasks %}
|
||||
<li><a href="{% url 'planner:task-detail' subtask.pk %}">{{ subtask.title }}</a>{% if subtask.estimated_duration_minutes %}<span>{{ subtask.estimated_duration_minutes }} min</span>{% endif %}</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</section>
|
||||
{% endif %}
|
||||
</article>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<div class="empty-state__icon" aria-hidden="true">✓</div>
|
||||
<h2>Nothing scheduled for this day</h2>
|
||||
<p>Create a task or choose another date to make a plan.</p>
|
||||
<a class="button" href="{% url 'planner:task-list' %}">View tasks</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,23 @@
|
||||
<article class="fasting-widget fasting-widget--configuration" id="fasting-widget" aria-labelledby="fasting-configuration-heading">
|
||||
<p class="eyebrow">Intermittent fasting</p>
|
||||
<h2 id="fasting-configuration-heading">Set your daily schedule</h2>
|
||||
<p class="fasting-widget__copy">Your schedule repeats automatically; you do not need to start a timer each day.</p>
|
||||
<form class="fasting-form" method="post" action="{% url 'planner:fasting-configure' %}" hx-post="{% url 'planner:fasting-configure' %}" hx-target="#fasting-widget" hx-swap="outerHTML" novalidate>
|
||||
{% csrf_token %}
|
||||
{% for field in form %}
|
||||
<div class="field field--{{ field.name }}{% if field.errors %} field--error{% endif %}">
|
||||
{% if field.field.widget.input_type == 'checkbox' %}
|
||||
<label class="checkbox-field">{{ field }} <span>{{ field.label }}</span></label>
|
||||
{% else %}
|
||||
{{ field.label_tag }}{{ field }}
|
||||
{% endif %}
|
||||
{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}
|
||||
{% for error in field.errors %}<p class="field-error" role="alert">{{ error }}</p>{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div class="fasting-widget__actions">
|
||||
<button class="button button--compact" type="submit">Save schedule</button>
|
||||
<a class="text-link" href="{% url 'planner:task-list' %}" hx-get="{% url 'planner:fasting-widget' %}" hx-target="#fasting-widget" hx-swap="outerHTML">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</article>
|
||||
@@ -0,0 +1,69 @@
|
||||
<article class="fasting-widget" id="fasting-widget" aria-labelledby="fasting-heading">
|
||||
{% if not fasting_settings %}
|
||||
<p class="eyebrow">Optional routine</p>
|
||||
<h2 id="fasting-heading">Intermittent fasting</h2>
|
||||
<p class="fasting-widget__copy">Set a daily fasting window when it fits your routine.</p>
|
||||
<a class="button button--secondary button--compact" href="{% url 'planner:fasting-configure' %}" hx-get="{% url 'planner:fasting-configure' %}" hx-target="#fasting-widget" hx-swap="outerHTML">Set up fasting</a>
|
||||
{% elif fasting_settings.enabled %}
|
||||
<div class="fasting-widget__topline">
|
||||
<p class="eyebrow">Intermittent fasting</p>
|
||||
<span class="fasting-state fasting-state--{{ fasting_phase.name }}">{% if fasting_phase.is_fasting %}Fasting{% else %}Eating{% endif %}</span>
|
||||
</div>
|
||||
<h2 id="fasting-heading">{% if fasting_phase.is_fasting %}Fasting now{% else %}Eating window open{% endif %}</h2>
|
||||
<div
|
||||
class="fasting-timer fasting-timer--{{ fasting_phase.name }}"
|
||||
data-fasting-timer
|
||||
data-cycle-start="{{ fasting_phase.cycle_start|date:'c' }}"
|
||||
data-cycle-end="{{ fasting_phase.cycle_end|date:'c' }}"
|
||||
data-phase="{{ fasting_phase.name }}"
|
||||
data-refresh-url="{% url 'planner:fasting-widget' %}"
|
||||
role="timer"
|
||||
aria-live="off"
|
||||
aria-label="{% if fasting_phase.is_fasting %}Fasting{% else %}Eating window{% endif %} progress"
|
||||
>
|
||||
<svg class="fasting-timer__ring" viewBox="0 0 120 120" aria-hidden="true">
|
||||
<circle class="fasting-timer__track" cx="60" cy="60" r="53" pathLength="100"></circle>
|
||||
<circle class="fasting-timer__progress" cx="60" cy="60" r="53" pathLength="100" data-fasting-progress></circle>
|
||||
</svg>
|
||||
<div class="fasting-timer__content">
|
||||
<strong data-fasting-elapsed>00:00:00</strong>
|
||||
<span>{% if fasting_phase.is_fasting %}Fasting elapsed{% else %}Eating elapsed{% endif %}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="fasting-widget__copy fasting-widget__cycle-copy">
|
||||
{% if fasting_phase.is_fasting %}
|
||||
Fasting until <time datetime="{{ fasting_phase.cycle_end|date:'c' }}">{{ fasting_phase.cycle_end|time:"H:i" }}</time>
|
||||
{% else %}
|
||||
Next fast at <time datetime="{{ fasting_phase.cycle_end|date:'c' }}">{{ fasting_phase.cycle_end|time:"H:i" }}</time>
|
||||
{% endif %}
|
||||
</p>
|
||||
<dl class="fasting-widget__schedule">
|
||||
<div><dt>Fasting</dt><dd>{{ fasting_settings.fasting_start_time|time:"H:i" }} daily</dd></div>
|
||||
<div><dt>Schedule</dt><dd>{{ fasting_settings.fasting_duration_minutes }} min</dd></div>
|
||||
</dl>
|
||||
<div class="fasting-widget__actions">
|
||||
<form method="post" action="{% url 'planner:fasting-toggle' %}" hx-post="{% url 'planner:fasting-toggle' %}" hx-target="#fasting-widget" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<button class="button button--secondary button--compact" type="submit">Pause tracking</button>
|
||||
</form>
|
||||
<a class="text-link" href="{% url 'planner:fasting-configure' %}" hx-get="{% url 'planner:fasting-configure' %}" hx-target="#fasting-widget" hx-swap="outerHTML">Adjust</a>
|
||||
</div>
|
||||
{% if fasting_history %}
|
||||
<section class="fasting-history" aria-labelledby="fasting-history-heading">
|
||||
<h3 id="fasting-history-heading">Recent completed fasts</h3>
|
||||
<ul>{% for period in fasting_history %}<li><time datetime="{{ period.scheduled_start|date:'c' }}">{{ period.scheduled_start|date:"j M" }}</time><span>{{ period.scheduled_start|time:"H:i" }}–{{ period.scheduled_end|time:"H:i" }}</span></li>{% endfor %}</ul>
|
||||
</section>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
<p class="eyebrow">Intermittent fasting</p>
|
||||
<h2 id="fasting-heading">Tracking paused</h2>
|
||||
<p class="fasting-widget__copy">Your history is saved. Resume when you are ready to follow your normal schedule again.</p>
|
||||
<div class="fasting-widget__actions">
|
||||
<form method="post" action="{% url 'planner:fasting-toggle' %}" hx-post="{% url 'planner:fasting-toggle' %}" hx-target="#fasting-widget" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<button class="button button--compact" type="submit">Resume tracking</button>
|
||||
</form>
|
||||
<a class="text-link" href="{% url 'planner:fasting-configure' %}" hx-get="{% url 'planner:fasting-configure' %}" hx-target="#fasting-widget" hx-swap="outerHTML">Adjust schedule</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</article>
|
||||
@@ -0,0 +1,61 @@
|
||||
<section class="checkin-panel" id="neck-headache-checkin" aria-labelledby="checkin-heading">
|
||||
<header class="checkin-panel__header">
|
||||
<div>
|
||||
<p class="eyebrow">Daily wellbeing</p>
|
||||
<h2 id="checkin-heading">Pain & sleep check-ins</h2>
|
||||
<p>Record {{ check_in_selected_date|date:"l, j F" }}. Choose any day below to edit an entry.</p>
|
||||
</div>
|
||||
{% if check_in_active_tab == 'pain' %}
|
||||
<dl class="checkin-streaks" aria-label="Pain check-in summary">
|
||||
<div><dt>Current <span class="checkin-tooltip" tabindex="0" aria-label="A confirmed day has both pain scores at {{ check_in_streak_threshold }} or below">ⓘ<span class="checkin-tooltip__content" role="tooltip">A confirmed day has both scores at {{ check_in_streak_threshold }} or below.</span></span></dt><dd>{{ check_in_streaks.current }} day{{ check_in_streaks.current|pluralize }}</dd></div>
|
||||
<div><dt>Longest</dt><dd>{{ check_in_streaks.longest }} day{{ check_in_streaks.longest|pluralize }}</dd></div>
|
||||
<div><dt>Physio sessions this year</dt><dd>{{ physio_sessions_this_year }}/{{ annual_physio_session_allowance }}</dd></div>
|
||||
</dl>
|
||||
{% endif %}
|
||||
</header>
|
||||
|
||||
<nav class="checkin-tabs" role="tablist" aria-label="Wellbeing check-ins">
|
||||
<a class="checkin-tabs__tab{% if check_in_active_tab == 'pain' %} is-active{% endif %}" id="pain-checkin-tab" role="tab" aria-selected="{% if check_in_active_tab == 'pain' %}true{% else %}false{% endif %}" aria-controls="pain-checkin-panel" href="{% url 'planner:task-list' %}?check_in_date={{ check_in_selected_date|date:'Y-m-d' }}&wellbeing_tab=pain" hx-get="{% url 'planner:neck-headache-checkin-panel' %}?date={{ check_in_selected_date|date:'Y-m-d' }}&tab=pain" hx-target="#neck-headache-checkin" hx-swap="outerHTML">Neck & headache</a>
|
||||
<a class="checkin-tabs__tab{% if check_in_active_tab == 'sleep' %} is-active{% endif %}" id="sleep-checkin-tab" role="tab" aria-selected="{% if check_in_active_tab == 'sleep' %}true{% else %}false{% endif %}" aria-controls="sleep-checkin-panel" href="{% url 'planner:task-list' %}?check_in_date={{ check_in_selected_date|date:'Y-m-d' }}&wellbeing_tab=sleep" hx-get="{% url 'planner:neck-headache-checkin-panel' %}?date={{ check_in_selected_date|date:'Y-m-d' }}&tab=sleep" hx-target="#neck-headache-checkin" hx-swap="outerHTML">Sleep</a>
|
||||
</nav>
|
||||
|
||||
{% if check_in_active_tab == 'pain' %}
|
||||
<div id="pain-checkin-panel" role="tabpanel" aria-labelledby="pain-checkin-tab" tabindex="0">
|
||||
<form class="checkin-form" method="post" action="{% url 'planner:neck-headache-checkin-save' %}" hx-post="{% url 'planner:neck-headache-checkin-save' %}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" novalidate>
|
||||
{% csrf_token %}
|
||||
<h3 class="checkin-form__heading">Neck & headache</h3>
|
||||
{% if check_in_form.non_field_errors %}<div class="form-errors">{{ check_in_form.non_field_errors }}</div>{% endif %}
|
||||
<div class="field{% if check_in_form.check_in_date.errors %} field--error{% endif %}">{{ check_in_form.check_in_date.label_tag }}{{ check_in_form.check_in_date }}{% for error in check_in_form.check_in_date.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<div class="field{% if check_in_form.neck_pain_severity.errors %} field--error{% endif %}">{{ check_in_form.neck_pain_severity.label_tag }}{{ check_in_form.neck_pain_severity }}<small>{{ check_in_form.neck_pain_severity.help_text }}</small>{% for error in check_in_form.neck_pain_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<div class="field{% if check_in_form.headache_severity.errors %} field--error{% endif %}">{{ check_in_form.headache_severity.label_tag }}{{ check_in_form.headache_severity }}<small>{{ check_in_form.headache_severity.help_text }}</small>{% for error in check_in_form.headache_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<div class="field checkin-form__note{% if check_in_form.note.errors %} field--error{% endif %}">{{ check_in_form.note.label_tag }}{{ check_in_form.note }}{% for error in check_in_form.note.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<div class="field checkin-form__physio"><label class="checkbox-field">{{ check_in_form.had_physiotherapy }} <span>{{ check_in_form.had_physiotherapy.label }}</span></label></div>
|
||||
<div class="form-actions"><button class="button button--compact" type="submit">Save pain check-in</button></div>
|
||||
</form>
|
||||
</div>
|
||||
{% else %}
|
||||
<div id="sleep-checkin-panel" role="tabpanel" aria-labelledby="sleep-checkin-tab" tabindex="0">
|
||||
<form class="checkin-form checkin-form--sleep" method="post" action="{% url 'planner:sleep-checkin-save' %}" hx-post="{% url 'planner:sleep-checkin-save' %}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" novalidate>
|
||||
{% csrf_token %}
|
||||
<h3 class="checkin-form__heading">Sleep</h3>
|
||||
{% if sleep_check_in_form.non_field_errors %}<div class="form-errors">{{ sleep_check_in_form.non_field_errors }}</div>{% endif %}
|
||||
<div class="field{% if sleep_check_in_form.wake_up_date.errors %} field--error{% endif %}">{{ sleep_check_in_form.wake_up_date.label_tag }}{{ sleep_check_in_form.wake_up_date }}{% for error in sleep_check_in_form.wake_up_date.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<div class="field{% if sleep_check_in_form.rested_score.errors %} field--error{% endif %}">{{ sleep_check_in_form.rested_score.label_tag }}{{ sleep_check_in_form.rested_score }}{% for error in sleep_check_in_form.rested_score.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<div class="field{% if sleep_check_in_form.watch_sleep_score.errors %} field--error{% endif %}">{{ sleep_check_in_form.watch_sleep_score.label_tag }}{{ sleep_check_in_form.watch_sleep_score }}{% for error in sleep_check_in_form.watch_sleep_score.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<div class="field checkin-form__note{% if sleep_check_in_form.note.errors %} field--error{% endif %}">{{ sleep_check_in_form.note.label_tag }}{{ sleep_check_in_form.note }}{% for error in sleep_check_in_form.note.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
|
||||
<div class="form-actions"><button class="button button--compact" type="submit">Save sleep check-in</button></div>
|
||||
</form>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<section class="checkin-calendar" aria-labelledby="checkin-calendar-heading">
|
||||
<header class="checkin-calendar__header">
|
||||
<a class="text-link" href="{% url 'planner:task-list' %}?check_in_date={{ check_in_previous_month|date:'Y-m-d' }}&wellbeing_tab={{ check_in_active_tab }}" hx-get="{% url 'planner:neck-headache-checkin-panel' %}?date={{ check_in_previous_month|date:'Y-m-d' }}&tab={{ check_in_active_tab }}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" aria-label="Previous month">←</a><h3 id="checkin-calendar-heading">{{ check_in_selected_date|date:"F Y" }}</h3><a class="text-link" href="{% url 'planner:task-list' %}?check_in_date={{ check_in_next_month|date:'Y-m-d' }}&wellbeing_tab={{ check_in_active_tab }}" hx-get="{% url 'planner:neck-headache-checkin-panel' %}?date={{ check_in_next_month|date:'Y-m-d' }}&tab={{ check_in_active_tab }}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" aria-label="Next month">→</a>
|
||||
</header>
|
||||
<div class="checkin-calendar__weekdays" aria-hidden="true"><span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span><span>Sun</span></div>
|
||||
<div class="checkin-calendar__grid">{% for week in check_in_calendar_weeks %}{% for day in week %}<a class="checkin-day checkin-day--{{ day.level }}{% if day.is_today %} checkin-day--today{% endif %}{% if day.is_selected %} checkin-day--selected{% endif %}{% if day.is_outside_month %} checkin-day--outside{% endif %}" href="{% url 'planner:task-list' %}?check_in_date={{ day.date|date:'Y-m-d' }}&wellbeing_tab={{ check_in_active_tab }}" hx-get="{% url 'planner:neck-headache-checkin-panel' %}?date={{ day.date|date:'Y-m-d' }}&tab={{ check_in_active_tab }}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" aria-label="{{ day.label }}"><span class="checkin-day__number">{{ day.date|date:"j" }}</span>{% if day.check_in %}<strong class="checkin-day__score">{{ day.highest_score }}</strong>{% if day.check_in.had_physiotherapy %}<span class="checkin-day__physio" aria-hidden="true">✚</span>{% endif %}{% else %}<span class="checkin-day__empty" aria-hidden="true">—</span>{% endif %}{% if day.sleep_check_in %}<span class="checkin-day__sleep" aria-hidden="true">☾</span>{% endif %}</a>{% endfor %}{% endfor %}</div>
|
||||
<p class="checkin-calendar__legend"><span><i class="checkin-legend checkin-legend--unrecorded"></i> Pain unrecorded</span><span><i class="checkin-legend checkin-legend--zero"></i> Pain recorded: 0</span><span>Number = highest pain score</span><span><i class="checkin-legend checkin-legend--sleep">☾</i> Sleep check-in</span></p>
|
||||
</section>
|
||||
|
||||
{% if check_in_active_tab == 'sleep' %}<section class="sleep-trend" aria-labelledby="sleep-trend-heading"><header><h3 id="sleep-trend-heading">Sleep scores over time</h3><p>Rested and watch scores are shown together for comparison only; neither is presented as causing a change in the other.</p></header>{% if sleep_check_in_trend %}<div class="sleep-trend__table-wrap"><table><thead><tr><th scope="col">Wake-up date</th><th scope="col">Rested</th><th scope="col">Watch</th></tr></thead><tbody>{% for sleep in sleep_check_in_trend %}<tr><th scope="row"><time datetime="{{ sleep.wake_up_date|date:'Y-m-d' }}">{{ sleep.wake_up_date|date:"j M" }}</time></th><td>{{ sleep.rested_score }}/10</td><td>{% if sleep.watch_sleep_score is not None %}{{ sleep.watch_sleep_score }}%{% else %}—{% endif %}</td></tr>{% endfor %}</tbody></table></div>{% else %}<p class="sleep-trend__empty">Save a sleep check-in to start the comparison.</p>{% endif %}</section>{% endif %}
|
||||
</section>
|
||||
@@ -0,0 +1,36 @@
|
||||
<article class="task-card{% if not task.is_active %} task-card--inactive{% endif %}{% if task.is_completed %} task-card--completed{% endif %}" id="task-{{ task.pk }}">
|
||||
<div class="task-card__topline">
|
||||
<span class="priority priority--{{ task.priority }}">{{ task.get_priority_display }}</span>
|
||||
<time datetime="{{ task.scheduled_for|date:'Y-m-d' }}">{{ task.scheduled_for|date:"D, j M" }}</time>
|
||||
</div>
|
||||
<h2><a href="{% url 'planner:task-detail' task.pk %}">{{ task.title }}</a></h2>
|
||||
{% if task.description %}<p class="task-card__description">{{ task.description|truncatewords:20 }}</p>{% endif %}
|
||||
<div class="task-card__meta">
|
||||
{% if task.category %}<span>{{ task.category }}</span>{% endif %}
|
||||
{% if task.estimated_duration_minutes %}<span>{{ task.estimated_duration_minutes }} min</span>{% endif %}
|
||||
{% if task.is_recurring %}<span>Repeats</span>{% endif %}
|
||||
{% if task.weather_profile != 'none' %}<span>☀ {{ task.get_weather_profile_display }}</span>{% endif %}
|
||||
</div>
|
||||
{% if task.predicted_weather %}
|
||||
<p class="task-weather-forecast"><span aria-hidden="true">{{ task.predicted_weather_icon }}</span><span>Forecast for this task: {{ task.predicted_weather_label }}{% if task.predicted_weather.temperature_max_c is not None %}, {{ task.predicted_weather.temperature_max_c|floatformat:0 }} °C{% endif %}</span></p>
|
||||
{% endif %}
|
||||
{% if task.subtasks.all %}
|
||||
<p class="subtask-count"><span aria-hidden="true">↳</span> {{ task.subtasks.count }} subtask{{ task.subtasks.count|pluralize }}{% if task.is_completed %} unlocked{% else %} — complete this task to unlock{% endif %}</p>
|
||||
{% endif %}
|
||||
<footer class="task-card__footer">
|
||||
<form method="post" action="{% url 'planner:task-toggle-completed' task.pk %}" hx-post="{% url 'planner:task-toggle-completed' task.pk %}" hx-target="#task-{{ task.pk }}" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<button class="{% if task.is_completed %}status-button{% else %}button button--compact{% endif %} task-completion-button" type="submit">
|
||||
{% if task.is_completed %}<span class="status-button__dot" aria-hidden="true"></span>{% endif %}
|
||||
{% if task.is_completed %}Completed — reopen{% else %}Mark complete{% endif %}
|
||||
</button>
|
||||
</form>
|
||||
<form method="post" action="{% url 'planner:task-toggle-active' task.pk %}" hx-post="{% url 'planner:task-toggle-active' task.pk %}" hx-target="#task-{{ task.pk }}" hx-swap="outerHTML">
|
||||
{% csrf_token %}
|
||||
<button class="status-button" type="submit" aria-label="Mark {{ task.title }} as {% if task.is_active %}inactive{% else %}active{% endif %}">
|
||||
{% if task.is_active %}Active{% else %}Paused{% endif %}
|
||||
</button>
|
||||
</form>
|
||||
<a class="text-link" href="{% url 'planner:task-update' task.pk %}">Edit</a>
|
||||
</footer>
|
||||
</article>
|
||||
@@ -0,0 +1,18 @@
|
||||
<section class="inline-form-panel" aria-labelledby="new-task-heading">
|
||||
<header class="inline-form-panel__header">
|
||||
<div>
|
||||
<p class="eyebrow">Plan with intention</p>
|
||||
<h2 id="new-task-heading">Create a task</h2>
|
||||
<p>Give your future self a clear next step.</p>
|
||||
</div>
|
||||
<a class="icon-link" href="{% url 'planner:task-list' %}" hx-get="{% url 'planner:task-list' %}" hx-target="#task-list" hx-swap="innerHTML">Close<span class="visually-hidden"> task form</span></a>
|
||||
</header>
|
||||
<form class="task-form task-form--inline" method="post" action="{% url 'planner:task-create' %}" hx-post="{% url 'planner:task-create' %}" hx-target="#task-list" hx-swap="innerHTML" novalidate>
|
||||
{% csrf_token %}
|
||||
{% include 'planner/partials/task_form_fields.html' %}
|
||||
<div class="form-actions">
|
||||
<button class="button" type="submit">Save task</button>
|
||||
<a class="text-link" href="{% url 'planner:task-list' %}" hx-get="{% url 'planner:task-list' %}" hx-target="#task-list" hx-swap="innerHTML">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
@@ -0,0 +1,22 @@
|
||||
{% if form.non_field_errors %}<div class="form-errors" role="alert">{{ form.non_field_errors }}</div>{% endif %}
|
||||
{% for field in form %}
|
||||
<div class="field field--{{ field.name }}{% if field.errors %} field--error{% endif %}">
|
||||
{% if field.field.widget.input_type == "checkbox" %}
|
||||
<label class="checkbox-field">{{ field }} <span>{{ field.label }}</span></label>
|
||||
{% elif field.name == "category" %}
|
||||
{{ field.label_tag }}
|
||||
<div class="category-picker" data-category-picker>
|
||||
{{ field }}
|
||||
<button class="category-picker__clear" type="button" data-category-clear aria-label="Clear category"{% if not field.value %} hidden{% endif %}>
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
<ul class="category-picker__suggestions" id="{{ field.id_for_label }}-suggestions" role="listbox" aria-label="Category suggestions" hidden></ul>
|
||||
</div>
|
||||
{% else %}
|
||||
{{ field.label_tag }}
|
||||
{{ field }}
|
||||
{% endif %}
|
||||
{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}
|
||||
{% for error in field.errors %}<p class="field-error" role="alert">{{ error }}</p>{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,14 @@
|
||||
{% if tasks %}
|
||||
<div class="task-grid">
|
||||
{% for task in tasks %}
|
||||
{% include 'planner/partials/task_card.html' with task=task %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="empty-state">
|
||||
<div class="empty-state__icon" aria-hidden="true">✓</div>
|
||||
<h2>No tasks here</h2>
|
||||
<p>Try a different filter, or create a task to get started.</p>
|
||||
<a class="button" href="{% url 'planner:task-create' %}">Create task</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -0,0 +1,15 @@
|
||||
<article>
|
||||
<h2><a href="{% url 'planner:task-detail' task.pk %}">{{ task.title }}</a></h2>
|
||||
<p>
|
||||
<span>Scheduled for {{ task.scheduled_for }}</span>
|
||||
<span>Priority: {{ task.get_priority_display }}</span>
|
||||
{% if task.category %}<span>Category: {{ task.category }}</span>{% endif %}
|
||||
</p>
|
||||
{% if task.subtasks.all %}
|
||||
<ul aria-label="Subtasks for {{ task.title }}">
|
||||
{% for subtask in task.subtasks.all %}
|
||||
<li><a href="{% url 'planner:task-detail' subtask.pk %}">{{ subtask.title }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</article>
|
||||
@@ -0,0 +1,4 @@
|
||||
<section class="weather-widget" aria-labelledby="weather-heading">
|
||||
<div class="weather-widget__topline"><div><p class="eyebrow">Your forecast</p><h2 id="weather-heading">Weather</h2></div>{% if weather_forecast %}<span class="weather-widget__icon" aria-hidden="true">{{ weather_icon }}</span>{% endif %}</div>
|
||||
{% if weather_forecast %}<p class="weather-widget__reading"><strong>{% if weather_forecast.temperature_max_c is not None %}{{ weather_forecast.temperature_max_c|floatformat:0 }} °C{% else %}—{% endif %}</strong> {{ weather_label }}</p><p class="weather-widget__detail">{% if weather_forecast.precipitation_probability is not None %}{{ weather_forecast.precipitation_probability|floatformat:0 }}% chance of precipitation{% else %}Daily forecast{% endif %}</p>{% elif weather_location_configured %}<p class="weather-widget__detail">Forecast temporarily unavailable. Your tasks will continue as normal.</p>{% else %}<p class="weather-widget__detail">Add a location to see weather-aware plans.</p><a class="text-link" href="{% url 'planner:user-settings' %}">Set location</a>{% endif %}
|
||||
</section>
|
||||
@@ -0,0 +1 @@
|
||||
<section class="workout-panel" id="workout-section" aria-labelledby="workout-form-heading"><header class="inline-form-panel__header"><div><p class="eyebrow">Daily movement</p><h2 id="workout-form-heading">{% if form.instance.pk %}Edit workout{% else %}Add a workout{% endif %}</h2><p>Keep workouts separate from your regular task plan.</p></div><a class="icon-link" href="{% url 'planner:task-list' %}" hx-get="{% url 'planner:workout-today' %}" hx-target="#workout-section" hx-swap="outerHTML">Close</a></header><form class="workout-form" method="post" {% if form.instance.pk %}action="{% url 'planner:workout-update' form.instance.pk %}" hx-post="{% url 'planner:workout-update' form.instance.pk %}"{% else %}action="{% url 'planner:workout-create' %}" hx-post="{% url 'planner:workout-create' %}"{% endif %} hx-target="#workout-section" hx-swap="outerHTML" novalidate>{% csrf_token %}{% if form.non_field_errors %}<div class="form-errors">{{ form.non_field_errors }}</div>{% endif %}{% for field in form %}<div class="field{% if field.errors %} field--error{% endif %}">{% if field.field.widget.input_type == 'checkbox' %}<label class="checkbox-field">{{ field }} <span>{{ field.label }}</span></label>{% else %}{{ field.label_tag }}{{ field }}{% endif %}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{% for error in field.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>{% endfor %}<div class="form-actions"><button class="button" type="submit">Save workout</button><a class="text-link" href="{% url 'planner:task-list' %}" hx-get="{% url 'planner:workout-today' %}" hx-target="#workout-section" hx-swap="outerHTML">Cancel</a></div></form></section>
|
||||
@@ -0,0 +1,9 @@
|
||||
<section class="workout-panel" id="workout-section" aria-labelledby="workouts-heading">
|
||||
<header class="workout-panel__header">
|
||||
<div><p class="eyebrow">Daily movement</p><h2 id="workouts-heading">Daily Workout</h2><p>Today, {{ workout_date|date:"l, j F" }}</p></div>
|
||||
<div class="workout-panel__summary">{% if workout_calories_total is not None %}<strong>{{ workout_calories_total }} kcal</strong><span>Total burned today</span>{% else %}<strong>—</strong><span>No calorie data yet</span>{% endif %}</div>
|
||||
<a class="button button--compact" href="{% url 'planner:workout-create' %}" hx-get="{% url 'planner:workout-create' %}" hx-target="#workout-section" hx-swap="outerHTML">+ Add workout</a>
|
||||
</header>
|
||||
{% if completed_workouts_without_calories %}<p class="workout-panel__note">{{ completed_workouts_without_calories }} completed workout{{ completed_workouts_without_calories|pluralize }} without calorie data is not included in the total.</p>{% endif %}
|
||||
{% if workouts %}<div class="workout-list">{% for workout in workouts %}<article class="workout-entry{% if workout.completed_for_day %} workout-entry--completed{% endif %}"><div class="workout-entry__main"><h3>{{ workout.name }}</h3><p>{% if workout.is_daily_recurring %}Daily routine{% else %}One-time workout{% endif %}{% if workout.duration_minutes %} · {{ workout.duration_minutes }} min{% endif %}{% if workout.calories_burned is not None %} · {{ workout.calories_burned }} kcal{% endif %}</p></div><div class="workout-entry__actions"><form method="post" action="{% url 'planner:workout-toggle-completed' workout.pk %}" hx-post="{% url 'planner:workout-toggle-completed' workout.pk %}" hx-target="#workout-section" hx-swap="outerHTML">{% csrf_token %}<button class="status-button" type="submit">{% if workout.completed_for_day %}Completed{% else %}Mark complete{% endif %}</button></form><a class="text-link" href="{% url 'planner:workout-update' workout.pk %}" hx-get="{% url 'planner:workout-update' workout.pk %}" hx-target="#workout-section" hx-swap="outerHTML">Edit</a><form method="post" action="{% url 'planner:workout-delete' workout.pk %}" hx-post="{% url 'planner:workout-delete' workout.pk %}" hx-target="#workout-section" hx-swap="outerHTML">{% csrf_token %}<button class="text-link workout-entry__remove" type="submit">Remove</button></form></div></article>{% endfor %}</div>{% else %}<div class="workout-empty"><p>No workouts planned for today.</p><a class="text-link" href="{% url 'planner:workout-create' %}" hx-get="{% url 'planner:workout-create' %}" hx-target="#workout-section" hx-swap="outerHTML">Add your first workout</a></div>{% endif %}
|
||||
</section>
|
||||
@@ -0,0 +1,3 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
{% block title %}Create account · Tasknest{% endblock %}
|
||||
{% block content %}<section class="auth-panel"><p class="eyebrow">Get started</p><h1>Create your account</h1><form method="post">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Create account</button></form><p>Already have an account? <a href="{% url 'planner:login' %}">Log in</a>.</p></section>{% endblock %}
|
||||
@@ -0,0 +1,18 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
|
||||
{% block title %}Delete {{ task.title }} · Tasknest{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="confirmation-card">
|
||||
<p class="eyebrow">This cannot be undone</p>
|
||||
<h1>Delete “{{ task.title }}”?</h1>
|
||||
<p>Any subtasks will be kept and moved to your top-level task list.</p>
|
||||
<form method="post">
|
||||
{% csrf_token %}
|
||||
<div class="form-actions">
|
||||
<button class="button button--danger" type="submit">Delete task</button>
|
||||
<a class="text-link" href="{% url 'planner:task-detail' task.pk %}">Keep task</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,42 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
|
||||
{% block title %}{{ task.title }} · Tasknest{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<p class="back-link"><a href="{% url 'planner:task-list' %}">← Back to tasks</a></p>
|
||||
<article class="detail-card">
|
||||
<header class="detail-card__header">
|
||||
<div>
|
||||
<p class="eyebrow">{{ task.get_priority_display }} priority{% if task.category %} · {{ task.category }}{% endif %}</p>
|
||||
<h1>{{ task.title }}</h1>
|
||||
<p class="detail-card__date">Scheduled for <time datetime="{{ task.scheduled_for|date:'Y-m-d' }}">{{ task.scheduled_for|date:"l, j F Y" }}</time></p>
|
||||
</div>
|
||||
<div class="detail-card__actions">
|
||||
<a class="button button--secondary" href="{% url 'planner:task-update' task.pk %}">Edit task</a>
|
||||
<a class="icon-link" href="{% url 'planner:task-delete' task.pk %}">Delete<span class="visually-hidden"> {{ task.title }}</span></a>
|
||||
</div>
|
||||
</header>
|
||||
<div class="detail-card__body">
|
||||
{% if task.description %}<div class="prose">{{ task.description|linebreaks }}</div>{% else %}<p class="muted">No notes added yet.</p>{% endif %}
|
||||
<dl class="task-facts">
|
||||
{% if task.estimated_duration_minutes %}<div><dt>Time estimate</dt><dd>{{ task.estimated_duration_minutes }} minutes</dd></div>{% endif %}
|
||||
<div><dt>Status</dt><dd>{% if task.is_completed %}Completed{% elif task.is_active %}Active{% else %}Paused{% endif %}</dd></div>
|
||||
{% if task.is_recurring %}<div><dt>Repeats</dt><dd>Every {{ task.recurrence_interval }} {{ task.recurrence_unit }}</dd></div>{% endif %}
|
||||
{% if task.weather_profile != 'none' %}<div><dt>Weather requirement</dt><dd>{{ task.get_weather_profile_display }}</dd></div>{% endif %}
|
||||
{% if task.predicted_weather %}<div><dt>Predicted weather</dt><dd><span aria-hidden="true">{{ task.predicted_weather_icon }}</span> {{ task.predicted_weather_label }}{% if task.predicted_weather.temperature_max_c is not None %}, {{ task.predicted_weather.temperature_max_c|floatformat:0 }} °C{% endif %}</dd></div>{% endif %}
|
||||
{% if task.parent_task %}<div><dt>Parent task</dt><dd><a href="{% url 'planner:task-detail' task.parent_task.pk %}">{{ task.parent_task }}</a></dd></div>{% endif %}
|
||||
</dl>
|
||||
</div>
|
||||
</article>
|
||||
{% if task.subtasks.all %}
|
||||
<section class="subtasks-section" aria-labelledby="subtasks-heading">
|
||||
<p class="eyebrow">Break it down</p>
|
||||
<h2 id="subtasks-heading">Subtasks</h2>
|
||||
{% if task.is_completed %}
|
||||
<ul class="subtasks-list">{% for subtask in task.subtasks.all %}<li><a href="{% url 'planner:task-detail' subtask.pk %}">{{ subtask.title }}</a><span>{{ subtask.scheduled_for|date:"j M" }}</span></li>{% endfor %}</ul>
|
||||
{% else %}
|
||||
<p class="muted">Complete this task to unlock its {{ task.subtasks.count }} subtask{{ task.subtasks.count|pluralize }}.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,21 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
|
||||
{% block title %}{% if form.instance.pk %}Edit {{ form.instance.title }}{% else %}Create task{% endif %} · Tasknest{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="form-layout">
|
||||
<div class="form-layout__intro">
|
||||
<p class="eyebrow">{% if form.instance.pk %}Refine your plan{% else %}Plan with intention{% endif %}</p>
|
||||
<h1>{% if form.instance.pk %}Edit task{% else %}Create a task{% endif %}</h1>
|
||||
<p>{% if form.instance.pk %}Make this task fit the way you want to work.{% else %}Give your future self a clear next step.{% endif %}</p>
|
||||
</div>
|
||||
<form class="task-form" method="post" novalidate>
|
||||
{% csrf_token %}
|
||||
{% include 'planner/partials/task_form_fields.html' %}
|
||||
<div class="form-actions">
|
||||
<button class="button" type="submit">Save task</button>
|
||||
<a class="text-link" href="{% if form.instance.pk %}{% url 'planner:task-detail' form.instance.pk %}{% else %}{% url 'planner:task-list' %}{% endif %}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,49 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
|
||||
{% block title %}My tasks · Tasknest{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="hero" aria-labelledby="tasks-heading">
|
||||
<div>
|
||||
<p class="eyebrow">Personal planning</p>
|
||||
<h1 id="tasks-heading">Make space for what matters.</h1>
|
||||
<p class="hero__copy">A focused view of your tasks, plans, and next steps.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="home-layout">
|
||||
<div class="home-main">
|
||||
<section class="task-panel" aria-label="Task list">
|
||||
<form class="task-filters" method="get" hx-get="{% url 'planner:task-list' %}" hx-target="#task-list" hx-push-url="true" hx-trigger="change" hx-indicator="#loading-indicator">
|
||||
<div>
|
||||
<label for="status-filter">Show</label>
|
||||
<select id="status-filter" name="status">
|
||||
<option value="all" {% if current_filter == 'all' %}selected{% endif %}>All tasks</option>
|
||||
<option value="active" {% if current_filter == 'active' %}selected{% endif %}>Active tasks</option>
|
||||
<option value="inactive" {% if current_filter == 'inactive' %}selected{% endif %}>Inactive tasks</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="task-filters__actions">
|
||||
<span class="loading-indicator htmx-indicator" id="loading-indicator" role="status">Updating…</span>
|
||||
<button class="button button--secondary button--compact" type="submit">Apply filter</button>
|
||||
<a class="button button--compact" href="{% url 'planner:task-create' %}" hx-get="{% url 'planner:task-create' %}" hx-target="#task-list" hx-swap="innerHTML">
|
||||
<span aria-hidden="true">+</span> New task
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
<div id="task-list" aria-live="polite">
|
||||
{% include 'planner/partials/task_list_content.html' %}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% include 'planner/partials/workout_section.html' %}
|
||||
{% include 'planner/partials/neck_headache_checkin.html' %}
|
||||
</div>
|
||||
{% if user.is_authenticated %}
|
||||
<aside class="homepage-sidebar" aria-label="Personal routines">
|
||||
{% include 'planner/partials/weather_widget.html' %}
|
||||
{% include 'planner/partials/fasting_widget.html' %}
|
||||
</aside>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,11 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
{% block title %}Settings · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<section class="settings-page">
|
||||
<p class="eyebrow">Personal preferences</p><h1>Settings</h1>
|
||||
<section class="settings-card"><h2>Time zone</h2><p>Dates and displayed times, including fasting, use this time zone. Europe/Amsterdam is the default.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="time-zone">{% for field in time_zone_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save time zone</button></form></section>
|
||||
<section class="settings-card"><h2>Location & weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
|
||||
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
|
||||
<section class="settings-card"><h2>Fasting</h2><form method="post">{% csrf_token %}<input type="hidden" name="section" value="fasting">{% for field in fasting_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save fasting settings</button></form></section>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1 @@
|
||||
{% extends 'planner/base.html' %}{% block title %}{% if form.instance.pk %}Edit{% else %}Add{% endif %} workout · Tasknest{% endblock %}{% block content %}<div class="form-layout"><div class="form-layout__intro"><p class="eyebrow">Daily movement</p><h1>{% if form.instance.pk %}Edit workout{% else %}Add a workout{% endif %}</h1><p>Workouts are tracked separately from your task plan.</p></div>{% include 'planner/partials/workout_form_panel.html' %}</div>{% endblock %}
|
||||
@@ -0,0 +1,3 @@
|
||||
{% extends 'planner/base.html' %}
|
||||
{% block title %}Log in · Tasknest{% endblock %}
|
||||
{% block content %}<section class="auth-panel"><p class="eyebrow">Welcome back</p><h1>Log in to Tasknest</h1><form method="post">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Log in</button></form><p>New here? <a href="{% url 'planner:register' %}">Create an account</a>.</p></section>{% endblock %}
|
||||
@@ -0,0 +1,49 @@
|
||||
import json
|
||||
from functools import lru_cache
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib.staticfiles.storage import staticfiles_storage
|
||||
from django.template import TemplateSyntaxError
|
||||
from django.template import Library
|
||||
from django.utils.html import format_html
|
||||
from django.utils.safestring import mark_safe
|
||||
|
||||
register = Library()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _manifest():
|
||||
try:
|
||||
with settings.VITE_MANIFEST_PATH.open(encoding='utf-8') as manifest_file:
|
||||
return json.load(manifest_file)
|
||||
except FileNotFoundError as error:
|
||||
raise TemplateSyntaxError(
|
||||
'Vite manifest is missing. Run `npm run build` from main/frontend.'
|
||||
) from error
|
||||
|
||||
|
||||
@register.simple_tag
|
||||
def vite_asset(entry):
|
||||
"""Render Vite's development modules or production manifest assets."""
|
||||
if settings.VITE_USE_DEV_SERVER:
|
||||
server = settings.VITE_DEV_SERVER.rstrip('/')
|
||||
return format_html(
|
||||
'<script type="module" src="{}/@vite/client"></script>'
|
||||
'<script type="module" src="{}/{}"></script>',
|
||||
server,
|
||||
server,
|
||||
entry,
|
||||
)
|
||||
|
||||
asset = _manifest().get(entry)
|
||||
if asset is None:
|
||||
raise TemplateSyntaxError(f'Vite entry {entry!r} is not present in the manifest.')
|
||||
|
||||
tags = [
|
||||
format_html('<script type="module" src="{}"></script>', staticfiles_storage.url(f"planner/dist/{asset['file']}"))
|
||||
]
|
||||
for stylesheet in asset.get('css', []):
|
||||
tags.append(
|
||||
format_html('<link rel="stylesheet" href="{}">', staticfiles_storage.url(f'planner/dist/{stylesheet}'))
|
||||
)
|
||||
return mark_safe(''.join(tags))
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
"""Per-user timezone helpers for dates and displayed times."""
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
DEFAULT_TIME_ZONE = 'Europe/Amsterdam'
|
||||
|
||||
|
||||
def timezone_for_name(name):
|
||||
try:
|
||||
return ZoneInfo(name or DEFAULT_TIME_ZONE)
|
||||
except ZoneInfoNotFoundError:
|
||||
return ZoneInfo(DEFAULT_TIME_ZONE)
|
||||
|
||||
|
||||
def timezone_for_user(user):
|
||||
"""Return a user's saved IANA zone without requiring a settings row."""
|
||||
if not getattr(user, 'is_authenticated', False):
|
||||
return timezone_for_name(DEFAULT_TIME_ZONE)
|
||||
settings = getattr(user, 'planner_settings', None)
|
||||
if settings is None:
|
||||
from planner.models import UserSettings
|
||||
settings = UserSettings.objects.filter(user=user).only('time_zone').first()
|
||||
return timezone_for_name(getattr(settings, 'time_zone', DEFAULT_TIME_ZONE))
|
||||
|
||||
|
||||
def localdate_for_user(user, now=None):
|
||||
return timezone.localtime(now or timezone.now(), timezone_for_user(user)).date()
|
||||
@@ -0,0 +1,38 @@
|
||||
from django.contrib.auth import views as auth_views
|
||||
from django.urls import path
|
||||
|
||||
from .views import (
|
||||
DailyPlannerView, TaskCreateView, category_suggestions, TaskDeleteView, TaskDetailView, TaskListView,
|
||||
TaskUpdateView, WorkoutCreateView, WorkoutUpdateView, delete_workout, fasting_configure, neck_headache_checkin_panel,
|
||||
fasting_toggle_tracking, fasting_widget, logout_view, register, toggle_task_active, toggle_task_completed,
|
||||
save_neck_headache_checkin, save_sleep_checkin, toggle_workout_completed, user_settings, workout_today,
|
||||
)
|
||||
|
||||
app_name = 'planner'
|
||||
|
||||
urlpatterns = [
|
||||
path('', TaskListView.as_view(), name='task-list'),
|
||||
path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
|
||||
path('register/', register, name='register'),
|
||||
path('logout/', logout_view, name='logout'),
|
||||
path('settings/', user_settings, name='user-settings'),
|
||||
path('daily/', DailyPlannerView.as_view(), name='daily-planner'),
|
||||
path('fasting/widget/', fasting_widget, name='fasting-widget'),
|
||||
path('fasting/configure/', fasting_configure, name='fasting-configure'),
|
||||
path('fasting/toggle/', fasting_toggle_tracking, name='fasting-toggle'),
|
||||
path('check-ins/panel/', neck_headache_checkin_panel, name='neck-headache-checkin-panel'),
|
||||
path('check-ins/save/', save_neck_headache_checkin, name='neck-headache-checkin-save'),
|
||||
path('sleep-check-ins/save/', save_sleep_checkin, name='sleep-checkin-save'),
|
||||
path('workouts/today/', workout_today, name='workout-today'),
|
||||
path('workouts/new/', WorkoutCreateView.as_view(), name='workout-create'),
|
||||
path('workouts/<int:pk>/edit/', WorkoutUpdateView.as_view(), name='workout-update'),
|
||||
path('workouts/<int:pk>/toggle-completed/', toggle_workout_completed, name='workout-toggle-completed'),
|
||||
path('workouts/<int:pk>/delete/', delete_workout, name='workout-delete'),
|
||||
path('tasks/categories/', category_suggestions, name='category-suggestions'),
|
||||
path('tasks/new/', TaskCreateView.as_view(), name='task-create'),
|
||||
path('tasks/<int:pk>/', TaskDetailView.as_view(), name='task-detail'),
|
||||
path('tasks/<int:pk>/edit/', TaskUpdateView.as_view(), name='task-update'),
|
||||
path('tasks/<int:pk>/delete/', TaskDeleteView.as_view(), name='task-delete'),
|
||||
path('tasks/<int:pk>/toggle-active/', toggle_task_active, name='task-toggle-active'),
|
||||
path('tasks/<int:pk>/toggle-completed/', toggle_task_completed, name='task-toggle-completed'),
|
||||
]
|
||||
@@ -0,0 +1,594 @@
|
||||
import calendar
|
||||
from datetime import timedelta
|
||||
|
||||
from django.contrib import messages
|
||||
from django.contrib.auth import login, logout
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.http import Http404, HttpResponse, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.urls import reverse, reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.dateparse import parse_date
|
||||
from django.views.decorators.http import require_http_methods, require_POST
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView
|
||||
|
||||
from .forms import (
|
||||
DailyPlannerForm, FastingSettingsForm, RegistrationForm, SickDaySettingsForm, SleepCheckInForm, TimeZoneSettingsForm,
|
||||
NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm,
|
||||
)
|
||||
from .models import FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, UserSettings, Workout
|
||||
from .services.checkins import (
|
||||
ANNUAL_PHYSIOTHERAPY_SESSION_ALLOWANCE, LOW_PAIN_STREAK_THRESHOLD, calculate_check_in_streaks,
|
||||
)
|
||||
from .services.fasting import (
|
||||
configure_fasting, current_fasting_phase, set_fasting_tracking_enabled,
|
||||
synchronize_fasting_periods,
|
||||
)
|
||||
from .services.scheduling import daily_recommendations, duration_budget_for_energy
|
||||
from .services.workouts import toggle_workout_completion, workouts_for_day
|
||||
from .timezones import localdate_for_user
|
||||
from .services.weather import (
|
||||
WEATHER_ICON_NAMES, WEATHER_LABELS, forecast_for_user_on_date, forecasts_for_user,
|
||||
)
|
||||
|
||||
|
||||
def workout_context(user, selected_date=None):
|
||||
selected_date = selected_date or timezone.localdate()
|
||||
summary = workouts_for_day(user, selected_date)
|
||||
return {
|
||||
'workouts': summary.workouts,
|
||||
'workout_date': selected_date,
|
||||
'workout_calories_total': summary.calories_total,
|
||||
'completed_workouts_without_calories': summary.completed_without_calories,
|
||||
}
|
||||
|
||||
|
||||
def render_workout_section(request):
|
||||
return render(request, 'planner/partials/workout_section.html', workout_context(request.user))
|
||||
|
||||
|
||||
def selected_check_in_date(value, user=None):
|
||||
return parse_date(value) if value else (localdate_for_user(user) if user else timezone.localdate())
|
||||
|
||||
|
||||
def categories_for_user(user, query=""):
|
||||
"""Return each of a user's category names once, ignoring case and outer space."""
|
||||
needle = query.strip().casefold()
|
||||
categories = []
|
||||
seen = set()
|
||||
for category in Task.objects.filter(owner=user).exclude(category="").order_by("pk").values_list("category", flat=True):
|
||||
normalized = category.strip()
|
||||
key = normalized.casefold()
|
||||
if normalized and key not in seen and (not needle or key.startswith(needle)):
|
||||
seen.add(key)
|
||||
categories.append(normalized)
|
||||
return categories
|
||||
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(["GET"])
|
||||
def category_suggestions(request):
|
||||
query = request.GET.get("q", "")[:100]
|
||||
return JsonResponse({"categories": categories_for_user(request.user, query)})
|
||||
|
||||
|
||||
def pain_level(score):
|
||||
if score == 0:
|
||||
return 'zero'
|
||||
if score <= LOW_PAIN_STREAK_THRESHOLD:
|
||||
return 'low'
|
||||
if score <= 5:
|
||||
return 'moderate'
|
||||
if score <= 7:
|
||||
return 'high'
|
||||
return 'severe'
|
||||
|
||||
|
||||
def check_in_context(user, selected_date=None, form=None, sleep_form=None, active_tab='pain'):
|
||||
active_tab = active_tab if active_tab in {'pain', 'sleep'} else 'pain'
|
||||
today = localdate_for_user(user)
|
||||
selected_date = selected_date or today
|
||||
check_ins = list(
|
||||
NeckHeadacheCheckIn.objects.filter(user=user, check_in_date__lte=today)
|
||||
)
|
||||
sleep_check_ins = list(
|
||||
SleepCheckIn.objects.filter(user=user, wake_up_date__lte=today)
|
||||
)
|
||||
check_in_by_date = {check_in.check_in_date: check_in for check_in in check_ins}
|
||||
sleep_check_in_by_date = {check_in.wake_up_date: check_in for check_in in sleep_check_ins}
|
||||
selected_check_in = check_in_by_date.get(selected_date)
|
||||
selected_sleep_check_in = sleep_check_in_by_date.get(selected_date)
|
||||
|
||||
if form is None:
|
||||
initial = {'check_in_date': selected_date}
|
||||
if selected_check_in is None:
|
||||
initial.update(neck_pain_severity=0, headache_severity=0)
|
||||
form = NeckHeadacheCheckInForm(instance=selected_check_in, initial=initial, user=user)
|
||||
if sleep_form is None:
|
||||
sleep_form = SleepCheckInForm(
|
||||
instance=selected_sleep_check_in, initial={'wake_up_date': selected_date}, user=user
|
||||
)
|
||||
|
||||
calendar_weeks = []
|
||||
for week in calendar.Calendar(firstweekday=0).monthdatescalendar(
|
||||
selected_date.year, selected_date.month
|
||||
):
|
||||
calendar_week = []
|
||||
for day in week:
|
||||
check_in = check_in_by_date.get(day)
|
||||
sleep_check_in = sleep_check_in_by_date.get(day)
|
||||
if check_in is None:
|
||||
label = f'{day:%A, %d %B}: pain not recorded'
|
||||
highest_score = None
|
||||
level = 'unrecorded'
|
||||
else:
|
||||
highest_score = max(
|
||||
check_in.neck_pain_severity, check_in.headache_severity
|
||||
)
|
||||
level = pain_level(highest_score)
|
||||
label = (
|
||||
f'{day:%A, %d %B}: neck pain {check_in.neck_pain_severity} of 10; '
|
||||
f'headache {check_in.headache_severity} of 10'
|
||||
)
|
||||
if check_in.had_physiotherapy:
|
||||
label += '; physiotherapy session'
|
||||
if sleep_check_in is not None:
|
||||
label += f'; sleep rested {sleep_check_in.rested_score} of 10'
|
||||
if sleep_check_in.watch_sleep_score is not None:
|
||||
label += f'; watch sleep score {sleep_check_in.watch_sleep_score} percent'
|
||||
calendar_week.append({
|
||||
'date': day,
|
||||
'check_in': check_in,
|
||||
'sleep_check_in': sleep_check_in,
|
||||
'highest_score': highest_score,
|
||||
'level': level,
|
||||
'label': label,
|
||||
'is_today': day == today,
|
||||
'is_selected': day == selected_date,
|
||||
'is_outside_month': day.month != selected_date.month,
|
||||
})
|
||||
calendar_weeks.append(calendar_week)
|
||||
|
||||
month_start = selected_date.replace(day=1)
|
||||
return {
|
||||
'check_in_form': form,
|
||||
'sleep_check_in_form': sleep_form,
|
||||
'check_in_selected_date': selected_date,
|
||||
'check_in_today': today,
|
||||
'check_in_calendar_weeks': calendar_weeks,
|
||||
'check_in_previous_month': month_start - timedelta(days=1),
|
||||
'check_in_next_month': (month_start + timedelta(days=32)).replace(day=1),
|
||||
'check_in_streaks': calculate_check_in_streaks(check_ins, today),
|
||||
'check_in_streak_threshold': LOW_PAIN_STREAK_THRESHOLD,
|
||||
'physio_sessions_this_year': sum(
|
||||
check_in.had_physiotherapy and check_in.check_in_date.year == today.year
|
||||
for check_in in check_ins
|
||||
),
|
||||
'annual_physio_session_allowance': ANNUAL_PHYSIOTHERAPY_SESSION_ALLOWANCE,
|
||||
'sleep_check_in_trend': sleep_check_ins[:14],
|
||||
'check_in_active_tab': active_tab,
|
||||
}
|
||||
|
||||
|
||||
def render_check_in_panel(request, selected_date=None, form=None, sleep_form=None, active_tab='pain'):
|
||||
return render(
|
||||
request,
|
||||
'planner/partials/neck_headache_checkin.html',
|
||||
check_in_context(request.user, selected_date, form, sleep_form, active_tab),
|
||||
)
|
||||
|
||||
|
||||
def add_predicted_weather(user, tasks):
|
||||
"""Attach display-only normalized forecasts without adding per-task HTTP calls."""
|
||||
forecast_by_date = {forecast.forecast_date: forecast for forecast in (forecasts_for_user(user) or [])}
|
||||
today = timezone.localdate()
|
||||
for task in tasks:
|
||||
for item in (task, *task.subtasks.all()):
|
||||
if item.scheduled_for >= today:
|
||||
forecast = forecast_by_date.get(item.scheduled_for)
|
||||
if forecast is not None:
|
||||
item.predicted_weather = forecast
|
||||
item.predicted_weather_icon = WEATHER_ICON_NAMES[forecast.condition]
|
||||
item.predicted_weather_label = WEATHER_LABELS[forecast.condition]
|
||||
return tasks
|
||||
|
||||
|
||||
def dashboard_weather_context(user):
|
||||
forecast = forecast_for_user_on_date(user, timezone.localdate())
|
||||
profile = UserSettings.objects.filter(user=user).only('latitude').first()
|
||||
if forecast is None:
|
||||
return {'weather_forecast': None, 'weather_location_configured': bool(profile and profile.latitude is not None)}
|
||||
return {
|
||||
'weather_forecast': forecast,
|
||||
'weather_icon': WEATHER_ICON_NAMES[forecast.condition],
|
||||
'weather_label': WEATHER_LABELS[forecast.condition],
|
||||
'weather_location_configured': True,
|
||||
}
|
||||
|
||||
|
||||
def fasting_widget_context(user):
|
||||
"""Fetch widget state; schedule decisions remain in the fasting service."""
|
||||
fasting_settings = FastingSettings.objects.filter(user=user).first()
|
||||
if fasting_settings is None:
|
||||
return {'fasting_settings': None, 'fasting_history': []}
|
||||
synchronize_fasting_periods(fasting_settings)
|
||||
context = {
|
||||
'fasting_settings': fasting_settings,
|
||||
'fasting_history': FastingPeriod.objects.filter(user=user)[:3],
|
||||
}
|
||||
if fasting_settings.enabled:
|
||||
context['fasting_phase'] = current_fasting_phase(fasting_settings)
|
||||
return context
|
||||
|
||||
|
||||
def render_fasting_widget(request):
|
||||
return render(request, 'planner/partials/fasting_widget.html', fasting_widget_context(request.user))
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET'])
|
||||
def fasting_widget(request):
|
||||
return render_fasting_widget(request)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def fasting_configure(request):
|
||||
fasting_settings = FastingSettings.objects.filter(user=request.user).first()
|
||||
if request.method == 'POST':
|
||||
form = FastingSettingsForm(request.POST, instance=fasting_settings)
|
||||
if form.is_valid():
|
||||
configure_fasting(
|
||||
request.user,
|
||||
enabled=form.cleaned_data['enabled'],
|
||||
fasting_start_time=form.cleaned_data['fasting_start_time'],
|
||||
fasting_duration_minutes=form.cleaned_data['fasting_duration_minutes'],
|
||||
)
|
||||
return render_fasting_widget(request)
|
||||
else:
|
||||
form = FastingSettingsForm(instance=fasting_settings)
|
||||
return render(request, 'planner/partials/fasting_configuration.html', {'form': form})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def fasting_toggle_tracking(request):
|
||||
fasting_settings = FastingSettings.objects.filter(user=request.user).first()
|
||||
if fasting_settings is None:
|
||||
raise Http404('Fasting tracking has not been configured.')
|
||||
set_fasting_tracking_enabled(fasting_settings, not fasting_settings.enabled)
|
||||
return render_fasting_widget(request)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET'])
|
||||
def neck_headache_checkin_panel(request):
|
||||
selected_date = selected_check_in_date(request.GET.get('date'), request.user)
|
||||
return render_check_in_panel(request, selected_date, active_tab=request.GET.get('tab', 'pain'))
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def save_neck_headache_checkin(request):
|
||||
selected_date = selected_check_in_date(request.POST.get('check_in_date'), request.user)
|
||||
existing = NeckHeadacheCheckIn.objects.filter(
|
||||
user=request.user, check_in_date=selected_date
|
||||
).first()
|
||||
form = NeckHeadacheCheckInForm(request.POST, instance=existing, user=request.user)
|
||||
if form.is_valid():
|
||||
check_in = form.save(commit=False)
|
||||
check_in.user = request.user
|
||||
check_in.save()
|
||||
if request.headers.get('HX-Request') == 'true':
|
||||
return render_check_in_panel(request, check_in.check_in_date)
|
||||
return redirect(
|
||||
reverse('planner:task-list') + '?check_in_date=' + check_in.check_in_date.isoformat()
|
||||
)
|
||||
return render_check_in_panel(request, selected_date, form)
|
||||
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def save_sleep_checkin(request):
|
||||
selected_date = selected_check_in_date(request.POST.get('wake_up_date'), request.user)
|
||||
existing = SleepCheckIn.objects.filter(
|
||||
user=request.user, wake_up_date=selected_date
|
||||
).first()
|
||||
form = SleepCheckInForm(request.POST, instance=existing, user=request.user)
|
||||
if form.is_valid():
|
||||
check_in = form.save(commit=False)
|
||||
check_in.user = request.user
|
||||
check_in.save()
|
||||
if request.headers.get('HX-Request') == 'true':
|
||||
return render_check_in_panel(request, check_in.wake_up_date, active_tab='sleep')
|
||||
return redirect(
|
||||
reverse('planner:task-list') + '?check_in_date=' + check_in.wake_up_date.isoformat()
|
||||
)
|
||||
return render_check_in_panel(request, selected_date, sleep_form=form, active_tab='sleep')
|
||||
|
||||
|
||||
class OwnedTaskQuerysetMixin(LoginRequiredMixin):
|
||||
"""Constrain every normal task endpoint to the authenticated owner."""
|
||||
|
||||
def get_queryset(self):
|
||||
return Task.objects.filter(owner=self.request.user).prefetch_related('subtasks')
|
||||
|
||||
|
||||
class TaskListView(LoginRequiredMixin, ListView):
|
||||
model = Task
|
||||
context_object_name = 'tasks'
|
||||
template_name = 'planner/task_list.html'
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = Task.objects.filter(owner=self.request.user, parent_task__isnull=True).prefetch_related('subtasks')
|
||||
status = self.request.GET.get('status')
|
||||
if status == 'active':
|
||||
queryset = queryset.filter(is_active=True)
|
||||
elif status == 'inactive':
|
||||
queryset = queryset.filter(is_active=False)
|
||||
return queryset
|
||||
|
||||
def get_template_names(self):
|
||||
if self.request.headers.get('HX-Request') == 'true':
|
||||
return ['planner/partials/task_list_content.html']
|
||||
return [self.template_name]
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
context['tasks'] = add_predicted_weather(self.request.user, context['tasks'])
|
||||
context['current_filter'] = self.request.GET.get('status', 'all')
|
||||
context.update(fasting_widget_context(self.request.user))
|
||||
context.update(dashboard_weather_context(self.request.user))
|
||||
context.update(workout_context(self.request.user))
|
||||
context.update(check_in_context(
|
||||
self.request.user, selected_check_in_date(self.request.GET.get('check_in_date'), self.request.user),
|
||||
active_tab=self.request.GET.get('wellbeing_tab', 'pain')
|
||||
))
|
||||
return context
|
||||
|
||||
|
||||
class DailyPlannerView(LoginRequiredMixin, TemplateView):
|
||||
template_name = 'planner/daily_planner.html'
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
default_values = {'selected_date': timezone.localdate().isoformat(), 'energy_level': '3'}
|
||||
form = DailyPlannerForm(self.request.GET or default_values)
|
||||
context['form'] = form
|
||||
context['recommendations'] = []
|
||||
if form.is_valid():
|
||||
selected_date = form.cleaned_data['selected_date']
|
||||
energy_level = form.cleaned_data['energy_level']
|
||||
sick_day_settings = SickDaySettings.objects.filter(user=self.request.user).first()
|
||||
context.update(
|
||||
selected_date=selected_date,
|
||||
energy_level=energy_level,
|
||||
duration_budget=duration_budget_for_energy(energy_level),
|
||||
recommendations=daily_recommendations(
|
||||
self.request.user, selected_date, energy_level, sick_day_settings
|
||||
),
|
||||
)
|
||||
return context
|
||||
|
||||
|
||||
class TaskDetailView(OwnedTaskQuerysetMixin, DetailView):
|
||||
context_object_name = 'task'
|
||||
template_name = 'planner/task_detail.html'
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
add_predicted_weather(self.request.user, [context['task']])
|
||||
return context
|
||||
|
||||
|
||||
class TaskCreateView(LoginRequiredMixin, CreateView):
|
||||
model = Task
|
||||
form_class = TaskForm
|
||||
template_name = 'planner/task_form.html'
|
||||
|
||||
def get_form_kwargs(self):
|
||||
kwargs = super().get_form_kwargs()
|
||||
kwargs['owner'] = self.request.user
|
||||
return kwargs
|
||||
|
||||
def get_template_names(self):
|
||||
if self.request.headers.get('HX-Request') == 'true':
|
||||
return ['planner/partials/task_create_panel.html']
|
||||
return [self.template_name]
|
||||
|
||||
def form_valid(self, form):
|
||||
form.instance.owner = self.request.user
|
||||
response = super().form_valid(form)
|
||||
if self.request.headers.get('HX-Request') == 'true':
|
||||
tasks = Task.objects.filter(owner=self.request.user, parent_task__isnull=True).prefetch_related('subtasks')
|
||||
return render(self.request, 'planner/partials/task_list_content.html', {'tasks': add_predicted_weather(self.request.user, tasks)})
|
||||
return response
|
||||
|
||||
|
||||
class TaskUpdateView(OwnedTaskQuerysetMixin, UpdateView):
|
||||
form_class = TaskForm
|
||||
template_name = 'planner/task_form.html'
|
||||
|
||||
def get_form_kwargs(self):
|
||||
kwargs = super().get_form_kwargs()
|
||||
kwargs['owner'] = self.request.user
|
||||
return kwargs
|
||||
|
||||
|
||||
class TaskDeleteView(OwnedTaskQuerysetMixin, DeleteView):
|
||||
context_object_name = 'task'
|
||||
template_name = 'planner/task_confirm_delete.html'
|
||||
success_url = reverse_lazy('planner:task-list')
|
||||
|
||||
|
||||
class OwnedWorkoutQuerysetMixin(LoginRequiredMixin):
|
||||
def get_queryset(self):
|
||||
return Workout.objects.filter(owner=self.request.user)
|
||||
|
||||
|
||||
class WorkoutCreateView(LoginRequiredMixin, CreateView):
|
||||
model = Workout
|
||||
success_url = reverse_lazy('planner:task-list')
|
||||
form_class = WorkoutForm
|
||||
template_name = 'planner/workout_form.html'
|
||||
|
||||
def get_initial(self):
|
||||
return {**super().get_initial(), 'scheduled_for': timezone.localdate()}
|
||||
|
||||
def get_template_names(self):
|
||||
if self.request.headers.get('HX-Request') == 'true':
|
||||
return ['planner/partials/workout_form_panel.html']
|
||||
return [self.template_name]
|
||||
|
||||
def form_valid(self, form):
|
||||
form.instance.owner = self.request.user
|
||||
response = super().form_valid(form)
|
||||
if self.request.headers.get('HX-Request') == 'true':
|
||||
return render_workout_section(self.request)
|
||||
return redirect('planner:task-list')
|
||||
|
||||
|
||||
class WorkoutUpdateView(OwnedWorkoutQuerysetMixin, UpdateView):
|
||||
success_url = reverse_lazy('planner:task-list')
|
||||
form_class = WorkoutForm
|
||||
template_name = 'planner/workout_form.html'
|
||||
|
||||
def get_template_names(self):
|
||||
if self.request.headers.get('HX-Request') == 'true':
|
||||
return ['planner/partials/workout_form_panel.html']
|
||||
return [self.template_name]
|
||||
|
||||
def form_valid(self, form):
|
||||
response = super().form_valid(form)
|
||||
if self.request.headers.get('HX-Request') == 'true':
|
||||
return render_workout_section(self.request)
|
||||
return redirect('planner:task-list')
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET'])
|
||||
def workout_today(request):
|
||||
return render_workout_section(request)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def toggle_workout_completed(request, pk):
|
||||
workout = get_object_or_404(Workout, pk=pk, owner=request.user)
|
||||
toggle_workout_completion(workout, timezone.localdate())
|
||||
return render_workout_section(request)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def delete_workout(request, pk):
|
||||
workout = get_object_or_404(Workout, pk=pk, owner=request.user)
|
||||
workout.delete()
|
||||
return render_workout_section(request)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def toggle_task_completed(request, pk):
|
||||
task = get_object_or_404(Task.objects.prefetch_related('subtasks'), pk=pk, owner=request.user)
|
||||
task.is_completed = not task.is_completed
|
||||
task.save(update_fields=['is_completed', 'updated_at'])
|
||||
if request.POST.get('return_to_daily_planner'):
|
||||
selected_date = parse_date(request.POST.get('selected_date')) or timezone.localdate()
|
||||
try:
|
||||
energy_level = int(request.POST.get('energy_level', 3))
|
||||
except (TypeError, ValueError):
|
||||
energy_level = 3
|
||||
destination = (
|
||||
f"{reverse('planner:daily-planner')}?selected_date={selected_date.isoformat()}"
|
||||
f"&energy_level={energy_level}"
|
||||
)
|
||||
if request.headers.get('HX-Request') == 'true':
|
||||
response = HttpResponse(status=204)
|
||||
response['HX-Redirect'] = destination
|
||||
return response
|
||||
return redirect(destination)
|
||||
if request.headers.get('HX-Request') != 'true':
|
||||
return redirect('planner:task-list')
|
||||
return render(request, 'planner/partials/task_card.html', {'task': task})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def toggle_task_active(request, pk):
|
||||
task = get_object_or_404(Task.objects.prefetch_related('subtasks'), pk=pk, owner=request.user)
|
||||
task.is_active = not task.is_active
|
||||
task.save(update_fields=['is_active', 'updated_at'])
|
||||
return render(request, 'planner/partials/task_card.html', {'task': task})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def user_settings(request):
|
||||
profile, _ = UserSettings.objects.get_or_create(user=request.user)
|
||||
sick_day, _ = SickDaySettings.objects.get_or_create(user=request.user)
|
||||
fasting = FastingSettings.objects.filter(user=request.user).first()
|
||||
profile_form = UserSettingsForm(instance=profile)
|
||||
sick_form = SickDaySettingsForm(instance=sick_day)
|
||||
fasting_form = FastingSettingsForm(instance=fasting)
|
||||
time_zone_form = TimeZoneSettingsForm(instance=profile)
|
||||
|
||||
if request.method == 'POST':
|
||||
section = request.POST.get('section')
|
||||
if section == 'location':
|
||||
profile_form = UserSettingsForm(request.POST, instance=profile)
|
||||
if profile_form.is_valid():
|
||||
profile_form.save()
|
||||
messages.success(request, 'Your weather location was saved.')
|
||||
return redirect('planner:user-settings')
|
||||
elif section == 'sick-day':
|
||||
sick_form = SickDaySettingsForm(request.POST, instance=sick_day)
|
||||
if sick_form.is_valid():
|
||||
sick_form.save()
|
||||
messages.success(request, 'Sick Day settings were saved.')
|
||||
return redirect('planner:user-settings')
|
||||
elif section == 'time-zone':
|
||||
time_zone_form = TimeZoneSettingsForm(request.POST, instance=profile)
|
||||
if time_zone_form.is_valid():
|
||||
time_zone_form.save()
|
||||
messages.success(request, 'Your time zone was saved.')
|
||||
return redirect('planner:user-settings')
|
||||
elif section == 'fasting':
|
||||
fasting_form = FastingSettingsForm(request.POST, instance=fasting)
|
||||
if fasting_form.is_valid():
|
||||
configure_fasting(request.user, **fasting_form.cleaned_data)
|
||||
messages.success(request, 'Fasting settings were saved.')
|
||||
return redirect('planner:user-settings')
|
||||
else:
|
||||
return redirect('planner:user-settings')
|
||||
|
||||
return render(request, 'planner/user_settings.html', {
|
||||
'profile_form': profile_form,
|
||||
'sick_form': sick_form,
|
||||
'fasting_form': fasting_form,
|
||||
'time_zone_form': time_zone_form,
|
||||
})
|
||||
|
||||
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def register(request):
|
||||
if request.user.is_authenticated:
|
||||
return redirect('planner:task-list')
|
||||
form = RegistrationForm(request.POST or None)
|
||||
if request.method == 'POST' and form.is_valid():
|
||||
user = form.save()
|
||||
user.is_staff = False
|
||||
user.is_superuser = False
|
||||
user.save(update_fields=['is_staff', 'is_superuser'])
|
||||
login(request, user)
|
||||
return redirect('planner:task-list')
|
||||
return render(request, 'planner/register.html', {'form': form})
|
||||
|
||||
|
||||
@require_POST
|
||||
def logout_view(request):
|
||||
logout(request)
|
||||
return redirect('planner:login')
|
||||
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
ASGI config for tasksnest project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/6.1/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tasksnest.settings')
|
||||
|
||||
application = get_asgi_application()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
Django settings for tasksnest project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 6.1.1.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/6.1/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/6.1/ref/settings/
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'django-insecure-x%2-iw9@k2s1td)7m7-ww55w1x(5lh$j*luk8_fbytb-36il%t'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = ["localhost", "127.0.0.1", "tasksnest.jorendegraaf.eu"]
|
||||
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
|
||||
CSRF_TRUSTED_ORIGINS = [
|
||||
"https://tasksnest.jorendegraaf.eu",
|
||||
]
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'planner',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'planner.middleware.UserTimezoneMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'tasksnest.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'tasksnest.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/6.1/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/6.1/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/6.1/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'Europe/Amsterdam'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/6.1/howto/static-files/
|
||||
|
||||
STATIC_URL = 'static/'
|
||||
|
||||
# Vite writes production assets and its manifest here. In development templates
|
||||
# load modules from the Vite server configured by VITE_DEV_SERVER.
|
||||
VITE_DEV_SERVER = os.environ.get('VITE_DEV_SERVER', 'http://localhost:5173')
|
||||
VITE_USE_DEV_SERVER = os.environ.get('VITE_USE_DEV_SERVER', str(DEBUG)).lower() in {'1', 'true', 'yes'}
|
||||
VITE_MANIFEST_PATH = BASE_DIR / 'planner' / 'static' / 'planner' / 'dist' / '.vite' / 'manifest.json'
|
||||
|
||||
LOGIN_URL = 'planner:login'
|
||||
LOGIN_REDIRECT_URL = 'planner:task-list'
|
||||
LOGOUT_REDIRECT_URL = 'planner:login'
|
||||
|
||||
|
||||
# Email
|
||||
# https://docs.djangoproject.com/en/6.1/topics/email/#topic-email-configuration
|
||||
|
||||
MAILERS = {
|
||||
'default': {
|
||||
'BACKEND': 'django.core.mail.backends.console.EmailBackend',
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
URL configuration for tasksnest project.
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/6.1/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.urls import include, path
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
path('', include('planner.urls')),
|
||||
]
|
||||
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
WSGI config for tasksnest project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/6.1/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tasksnest.settings')
|
||||
|
||||
application = get_wsgi_application()
|
||||
@@ -0,0 +1,248 @@
|
||||
<#
|
||||
.Synopsis
|
||||
Activate a Python virtual environment for the current PowerShell session.
|
||||
|
||||
.Description
|
||||
Pushes the python executable for a virtual environment to the front of the
|
||||
$Env:PATH environment variable and sets the prompt to signify that you are
|
||||
in a Python virtual environment. Makes use of the command line switches as
|
||||
well as the `pyvenv.cfg` file values present in the virtual environment.
|
||||
|
||||
.Parameter VenvDir
|
||||
Path to the directory that contains the virtual environment to activate. The
|
||||
default value for this is the parent of the directory that the Activate.ps1
|
||||
script is located within.
|
||||
|
||||
.Parameter Prompt
|
||||
The prompt prefix to display when this virtual environment is activated. By
|
||||
default, this prompt is the name of the virtual environment folder (VenvDir)
|
||||
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
|
||||
|
||||
.Example
|
||||
Activate.ps1
|
||||
Activates the Python virtual environment that contains the Activate.ps1 script.
|
||||
|
||||
.Example
|
||||
Activate.ps1 -Verbose
|
||||
Activates the Python virtual environment that contains the Activate.ps1 script,
|
||||
and shows extra information about the activation as it executes.
|
||||
|
||||
.Example
|
||||
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
|
||||
Activates the Python virtual environment located in the specified location.
|
||||
|
||||
.Example
|
||||
Activate.ps1 -Prompt "MyPython"
|
||||
Activates the Python virtual environment that contains the Activate.ps1 script,
|
||||
and prefixes the current prompt with the specified string (surrounded in
|
||||
parentheses) while the virtual environment is active.
|
||||
|
||||
.Notes
|
||||
On Windows, it may be required to enable this Activate.ps1 script by setting the
|
||||
execution policy for the user. You can do this by issuing the following PowerShell
|
||||
command:
|
||||
|
||||
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
|
||||
|
||||
For more information on Execution Policies:
|
||||
https://go.microsoft.com/fwlink/?LinkID=135170
|
||||
|
||||
#>
|
||||
Param(
|
||||
[Parameter(Mandatory = $false)]
|
||||
[String]
|
||||
$VenvDir,
|
||||
[Parameter(Mandatory = $false)]
|
||||
[String]
|
||||
$Prompt
|
||||
)
|
||||
|
||||
<# Function declarations --------------------------------------------------- #>
|
||||
|
||||
<#
|
||||
.Synopsis
|
||||
Remove all shell session elements added by the Activate script, including the
|
||||
addition of the virtual environment's Python executable from the beginning of
|
||||
the PATH variable.
|
||||
|
||||
.Parameter NonDestructive
|
||||
If present, do not remove this function from the global namespace for the
|
||||
session.
|
||||
|
||||
#>
|
||||
function global:deactivate ([switch]$NonDestructive) {
|
||||
# Revert to original values
|
||||
|
||||
# The prior prompt:
|
||||
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
|
||||
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
|
||||
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
|
||||
}
|
||||
|
||||
# The prior PYTHONHOME:
|
||||
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
|
||||
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
|
||||
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
|
||||
}
|
||||
|
||||
# The prior PATH:
|
||||
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
|
||||
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
|
||||
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
|
||||
}
|
||||
|
||||
# Just remove the VIRTUAL_ENV altogether:
|
||||
if (Test-Path -Path Env:VIRTUAL_ENV) {
|
||||
Remove-Item -Path env:VIRTUAL_ENV
|
||||
}
|
||||
|
||||
# Just remove VIRTUAL_ENV_PROMPT altogether.
|
||||
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
|
||||
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
|
||||
}
|
||||
|
||||
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
|
||||
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
|
||||
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
|
||||
}
|
||||
|
||||
# Leave deactivate function in the global namespace if requested:
|
||||
if (-not $NonDestructive) {
|
||||
Remove-Item -Path function:deactivate
|
||||
}
|
||||
}
|
||||
|
||||
<#
|
||||
.Description
|
||||
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
|
||||
given folder, and returns them in a map.
|
||||
|
||||
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
|
||||
two strings separated by `=` (with any amount of whitespace surrounding the =)
|
||||
then it is considered a `key = value` line. The left hand string is the key,
|
||||
the right hand is the value.
|
||||
|
||||
If the value starts with a `'` or a `"` then the first and last character is
|
||||
stripped from the value before being captured.
|
||||
|
||||
.Parameter ConfigDir
|
||||
Path to the directory that contains the `pyvenv.cfg` file.
|
||||
#>
|
||||
function Get-PyVenvConfig(
|
||||
[String]
|
||||
$ConfigDir
|
||||
) {
|
||||
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
|
||||
|
||||
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
|
||||
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
|
||||
|
||||
# An empty map will be returned if no config file is found.
|
||||
$pyvenvConfig = @{ }
|
||||
|
||||
if ($pyvenvConfigPath) {
|
||||
|
||||
Write-Verbose "File exists, parse `key = value` lines"
|
||||
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
|
||||
|
||||
$pyvenvConfigContent | ForEach-Object {
|
||||
$keyval = $PSItem -split "\s*=\s*", 2
|
||||
if ($keyval[0] -and $keyval[1]) {
|
||||
$val = $keyval[1]
|
||||
|
||||
# Remove extraneous quotations around a string value.
|
||||
if ("'""".Contains($val.Substring(0, 1))) {
|
||||
$val = $val.Substring(1, $val.Length - 2)
|
||||
}
|
||||
|
||||
$pyvenvConfig[$keyval[0]] = $val
|
||||
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
|
||||
}
|
||||
}
|
||||
}
|
||||
return $pyvenvConfig
|
||||
}
|
||||
|
||||
|
||||
<# Begin Activate script --------------------------------------------------- #>
|
||||
|
||||
# Determine the containing directory of this script
|
||||
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
|
||||
$VenvExecDir = Get-Item -Path $VenvExecPath
|
||||
|
||||
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
|
||||
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
|
||||
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
|
||||
|
||||
# Set values required in priority: CmdLine, ConfigFile, Default
|
||||
# First, get the location of the virtual environment, it might not be
|
||||
# VenvExecDir if specified on the command line.
|
||||
if ($VenvDir) {
|
||||
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
|
||||
}
|
||||
else {
|
||||
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
|
||||
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
|
||||
Write-Verbose "VenvDir=$VenvDir"
|
||||
}
|
||||
|
||||
# Next, read the `pyvenv.cfg` file to determine any required value such
|
||||
# as `prompt`.
|
||||
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
|
||||
|
||||
# Next, set the prompt from the command line, or the config file, or
|
||||
# just use the name of the virtual environment folder.
|
||||
if ($Prompt) {
|
||||
Write-Verbose "Prompt specified as argument, using '$Prompt'"
|
||||
}
|
||||
else {
|
||||
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
|
||||
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
|
||||
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
|
||||
$Prompt = $pyvenvCfg['prompt'];
|
||||
}
|
||||
else {
|
||||
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
|
||||
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
|
||||
$Prompt = Split-Path -Path $venvDir -Leaf
|
||||
}
|
||||
}
|
||||
|
||||
Write-Verbose "Prompt = '$Prompt'"
|
||||
Write-Verbose "VenvDir='$VenvDir'"
|
||||
|
||||
# Deactivate any currently active virtual environment, but leave the
|
||||
# deactivate function in place.
|
||||
deactivate -nondestructive
|
||||
|
||||
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
|
||||
# that there is an activated venv.
|
||||
$env:VIRTUAL_ENV = $VenvDir
|
||||
|
||||
$env:VIRTUAL_ENV_PROMPT = $Prompt
|
||||
|
||||
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
|
||||
|
||||
Write-Verbose "Setting prompt to '$Prompt'"
|
||||
|
||||
# Set the prompt to include the env name
|
||||
# Make sure _OLD_VIRTUAL_PROMPT is global
|
||||
function global:_OLD_VIRTUAL_PROMPT { "" }
|
||||
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
|
||||
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
|
||||
|
||||
function global:prompt {
|
||||
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
|
||||
_OLD_VIRTUAL_PROMPT
|
||||
}
|
||||
}
|
||||
|
||||
# Clear PYTHONHOME
|
||||
if (Test-Path -Path Env:PYTHONHOME) {
|
||||
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
|
||||
Remove-Item -Path Env:PYTHONHOME
|
||||
}
|
||||
|
||||
# Add the venv to the PATH
|
||||
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
|
||||
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
|
||||
@@ -0,0 +1,76 @@
|
||||
# This file must be used with "source bin/activate" *from bash*
|
||||
# You cannot run it directly
|
||||
|
||||
deactivate () {
|
||||
# reset old environment variables
|
||||
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
|
||||
PATH="${_OLD_VIRTUAL_PATH:-}"
|
||||
export PATH
|
||||
unset _OLD_VIRTUAL_PATH
|
||||
fi
|
||||
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
|
||||
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
|
||||
export PYTHONHOME
|
||||
unset _OLD_VIRTUAL_PYTHONHOME
|
||||
fi
|
||||
|
||||
# Call hash to forget past locations. Without forgetting
|
||||
# past locations the $PATH changes we made may not be respected.
|
||||
# See "man bash" for more details. hash is usually a builtin of your shell
|
||||
hash -r 2> /dev/null || true
|
||||
|
||||
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
|
||||
PS1="${_OLD_VIRTUAL_PS1:-}"
|
||||
export PS1
|
||||
unset _OLD_VIRTUAL_PS1
|
||||
fi
|
||||
|
||||
unset VIRTUAL_ENV
|
||||
unset VIRTUAL_ENV_PROMPT
|
||||
if [ ! "${1:-}" = "nondestructive" ] ; then
|
||||
# Self destruct!
|
||||
unset -f deactivate
|
||||
fi
|
||||
}
|
||||
|
||||
# unset irrelevant variables
|
||||
deactivate nondestructive
|
||||
|
||||
# on Windows, a path can contain colons and backslashes and has to be converted:
|
||||
case "$(uname)" in
|
||||
CYGWIN*|MSYS*|MINGW*)
|
||||
# transform D:\path\to\venv to /d/path/to/venv on MSYS and MINGW
|
||||
# and to /cygdrive/d/path/to/venv on Cygwin
|
||||
VIRTUAL_ENV=$(cygpath /home/jorenmartijn/django/tasksnest)
|
||||
export VIRTUAL_ENV
|
||||
;;
|
||||
*)
|
||||
# use the path as-is
|
||||
export VIRTUAL_ENV=/home/jorenmartijn/django/tasksnest
|
||||
;;
|
||||
esac
|
||||
|
||||
_OLD_VIRTUAL_PATH="$PATH"
|
||||
PATH="$VIRTUAL_ENV/"bin":$PATH"
|
||||
export PATH
|
||||
|
||||
VIRTUAL_ENV_PROMPT=tasksnest
|
||||
export VIRTUAL_ENV_PROMPT
|
||||
|
||||
# unset PYTHONHOME if set
|
||||
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
|
||||
# could use `if (set -u; : $PYTHONHOME) ;` in bash
|
||||
if [ -n "${PYTHONHOME:-}" ] ; then
|
||||
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
|
||||
unset PYTHONHOME
|
||||
fi
|
||||
|
||||
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
|
||||
_OLD_VIRTUAL_PS1="${PS1:-}"
|
||||
PS1="("tasksnest") ${PS1:-}"
|
||||
export PS1
|
||||
fi
|
||||
|
||||
# Call hash to forget past commands. Without forgetting
|
||||
# past commands the $PATH changes we made may not be respected
|
||||
hash -r 2> /dev/null || true
|
||||
@@ -0,0 +1,27 @@
|
||||
# This file must be used with "source bin/activate.csh" *from csh*.
|
||||
# You cannot run it directly.
|
||||
|
||||
# Created by Davide Di Blasi <davidedb@gmail.com>.
|
||||
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
|
||||
|
||||
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
|
||||
|
||||
# Unset irrelevant variables.
|
||||
deactivate nondestructive
|
||||
|
||||
setenv VIRTUAL_ENV /home/jorenmartijn/django/tasksnest
|
||||
|
||||
set _OLD_VIRTUAL_PATH="$PATH"
|
||||
setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
|
||||
setenv VIRTUAL_ENV_PROMPT tasksnest
|
||||
|
||||
|
||||
set _OLD_VIRTUAL_PROMPT="$prompt"
|
||||
|
||||
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
|
||||
set prompt = "("tasksnest") $prompt:q"
|
||||
endif
|
||||
|
||||
alias pydoc python -m pydoc
|
||||
|
||||
rehash
|
||||
@@ -0,0 +1,69 @@
|
||||
# This file must be used with "source <venv>/bin/activate.fish" *from fish*
|
||||
# (https://fishshell.com/). You cannot run it directly.
|
||||
|
||||
function deactivate -d "Exit virtual environment and return to normal shell environment"
|
||||
# reset old environment variables
|
||||
if test -n "$_OLD_VIRTUAL_PATH"
|
||||
set -gx PATH $_OLD_VIRTUAL_PATH
|
||||
set -e _OLD_VIRTUAL_PATH
|
||||
end
|
||||
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
|
||||
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
|
||||
set -e _OLD_VIRTUAL_PYTHONHOME
|
||||
end
|
||||
|
||||
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
|
||||
set -e _OLD_FISH_PROMPT_OVERRIDE
|
||||
# prevents error when using nested fish instances (Issue #93858)
|
||||
if functions -q _old_fish_prompt
|
||||
functions -e fish_prompt
|
||||
functions -c _old_fish_prompt fish_prompt
|
||||
functions -e _old_fish_prompt
|
||||
end
|
||||
end
|
||||
|
||||
set -e VIRTUAL_ENV
|
||||
set -e VIRTUAL_ENV_PROMPT
|
||||
if test "$argv[1]" != "nondestructive"
|
||||
# Self-destruct!
|
||||
functions -e deactivate
|
||||
end
|
||||
end
|
||||
|
||||
# Unset irrelevant variables.
|
||||
deactivate nondestructive
|
||||
|
||||
set -gx VIRTUAL_ENV /home/jorenmartijn/django/tasksnest
|
||||
|
||||
set -gx _OLD_VIRTUAL_PATH $PATH
|
||||
set -gx PATH "$VIRTUAL_ENV/"bin $PATH
|
||||
set -gx VIRTUAL_ENV_PROMPT tasksnest
|
||||
|
||||
# Unset PYTHONHOME if set.
|
||||
if set -q PYTHONHOME
|
||||
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
|
||||
set -e PYTHONHOME
|
||||
end
|
||||
|
||||
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
|
||||
# fish uses a function instead of an env var to generate the prompt.
|
||||
|
||||
# Save the current fish_prompt function as the function _old_fish_prompt.
|
||||
functions -c fish_prompt _old_fish_prompt
|
||||
|
||||
# With the original prompt function renamed, we can override with our own.
|
||||
function fish_prompt
|
||||
# Save the return status of the last command.
|
||||
set -l old_status $status
|
||||
|
||||
# Output the venv prompt; color taken from the blue of the Python logo.
|
||||
printf "%s(%s)%s " (set_color 4B8BBE) tasksnest (set_color normal)
|
||||
|
||||
# Restore the return status of the previous command.
|
||||
echo "exit $old_status" | .
|
||||
# Output the original/"old" prompt.
|
||||
_old_fish_prompt
|
||||
end
|
||||
|
||||
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
|
||||
end
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/home/jorenmartijn/django/tasksnest/bin/python
|
||||
import sys
|
||||
from django.core.management import execute_from_command_line
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
||||
sys.exit(execute_from_command_line())
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/home/jorenmartijn/django/tasksnest/bin/python
|
||||
import sys
|
||||
from pip._internal.cli.main import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
||||
sys.exit(main())
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/home/jorenmartijn/django/tasksnest/bin/python
|
||||
import sys
|
||||
from pip._internal.cli.main import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
||||
sys.exit(main())
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/home/jorenmartijn/django/tasksnest/bin/python
|
||||
import sys
|
||||
from pip._internal.cli.main import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
||||
sys.exit(main())
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
/usr/bin/python
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
python
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
python
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/home/jorenmartijn/django/tasksnest/bin/python
|
||||
import sys
|
||||
from sqlparse.__main__ import main
|
||||
if __name__ == '__main__':
|
||||
sys.argv[0] = sys.argv[0].removesuffix('.exe')
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,249 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: asgiref
|
||||
Version: 3.12.1
|
||||
Summary: ASGI specs, helper code, and adapters
|
||||
Home-page: https://github.com/django/asgiref/
|
||||
Author: Django Software Foundation
|
||||
Author-email: foundation@djangoproject.com
|
||||
License: BSD-3-Clause
|
||||
Project-URL: Documentation, https://asgi.readthedocs.io/
|
||||
Project-URL: Further Documentation, https://docs.djangoproject.com/en/stable/topics/async/#async-adapter-functions
|
||||
Project-URL: Changelog, https://github.com/django/asgiref/blob/master/CHANGELOG.txt
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Environment :: Web Environment
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: License :: OSI Approved :: BSD License
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3 :: Only
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: 3.11
|
||||
Classifier: Programming Language :: Python :: 3.12
|
||||
Classifier: Programming Language :: Python :: 3.13
|
||||
Classifier: Programming Language :: Python :: 3.14
|
||||
Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
|
||||
Classifier: Topic :: Internet :: WWW/HTTP
|
||||
Requires-Python: >=3.10
|
||||
License-File: LICENSE
|
||||
Requires-Dist: typing_extensions>=4; python_version < "3.11"
|
||||
Provides-Extra: tests
|
||||
Requires-Dist: pytest; extra == "tests"
|
||||
Requires-Dist: pytest-asyncio; extra == "tests"
|
||||
Provides-Extra: mypy
|
||||
Requires-Dist: mypy>=1.14.0; extra == "mypy"
|
||||
Dynamic: license-file
|
||||
|
||||
asgiref
|
||||
=======
|
||||
|
||||
.. image:: https://github.com/django/asgiref/actions/workflows/tests.yml/badge.svg
|
||||
:target: https://github.com/django/asgiref/actions/workflows/tests.yml
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/asgiref.svg
|
||||
:target: https://pypi.python.org/pypi/asgiref
|
||||
|
||||
ASGI is a standard for Python asynchronous web apps and servers to communicate
|
||||
with each other, and positioned as an asynchronous successor to WSGI. You can
|
||||
read more at https://asgi.readthedocs.io/en/latest/
|
||||
|
||||
This package includes ASGI base libraries, such as:
|
||||
|
||||
* Sync-to-async and async-to-sync function wrappers, ``asgiref.sync``
|
||||
* Server base classes, ``asgiref.server``
|
||||
* A WSGI-to-ASGI adapter, in ``asgiref.wsgi``
|
||||
|
||||
|
||||
Function wrappers
|
||||
-----------------
|
||||
|
||||
These allow you to wrap or decorate async or sync functions to call them from
|
||||
the other style (so you can call async functions from a synchronous thread,
|
||||
or vice-versa).
|
||||
|
||||
In particular:
|
||||
|
||||
* AsyncToSync lets a synchronous subthread stop and wait while the async
|
||||
function is called on the main thread's event loop, and then control is
|
||||
returned to the thread when the async function is finished.
|
||||
|
||||
* SyncToAsync lets async code call a synchronous function, which is run in
|
||||
a threadpool and control returned to the async coroutine when the synchronous
|
||||
function completes.
|
||||
|
||||
The idea is to make it easier to call synchronous APIs from async code and
|
||||
asynchronous APIs from synchronous code so it's easier to transition code from
|
||||
one style to the other. In the case of Channels, we wrap the (synchronous)
|
||||
Django view system with SyncToAsync to allow it to run inside the (asynchronous)
|
||||
ASGI server.
|
||||
|
||||
Note that exactly what threads things run in is very specific, and aimed to
|
||||
keep maximum compatibility with old synchronous code. See
|
||||
"Synchronous code & Threads" below for a full explanation. By default,
|
||||
``sync_to_async`` will run all synchronous code in the program in the same
|
||||
thread for safety reasons; you can disable this for more performance with
|
||||
``@sync_to_async(thread_sensitive=False)``, but make sure that your code does
|
||||
not rely on anything bound to threads (like database connections) when you do.
|
||||
|
||||
|
||||
Threadlocal replacement
|
||||
-----------------------
|
||||
|
||||
This is a drop-in replacement for ``threading.local`` that works with both
|
||||
threads and asyncio Tasks. Even better, it will proxy values through from a
|
||||
task-local context to a thread-local context when you use ``sync_to_async``
|
||||
to run things in a threadpool, and vice-versa for ``async_to_sync``.
|
||||
|
||||
If you instead want true thread- and task-safety, you can set
|
||||
``thread_critical`` on the Local object to ensure this instead.
|
||||
|
||||
|
||||
Server base classes
|
||||
-------------------
|
||||
|
||||
Includes a ``StatelessServer`` class which provides all the hard work of
|
||||
writing a stateless server (as in, does not handle direct incoming sockets
|
||||
but instead consumes external streams or sockets to work out what is happening).
|
||||
|
||||
An example of such a server would be a chatbot server that connects out to
|
||||
a central chat server and provides a "connection scope" per user chatting to
|
||||
it. There's only one actual connection, but the server has to separate things
|
||||
into several scopes for easier writing of the code.
|
||||
|
||||
You can see an example of this being used in `frequensgi <https://github.com/andrewgodwin/frequensgi>`_.
|
||||
|
||||
|
||||
WSGI-to-ASGI adapter
|
||||
--------------------
|
||||
|
||||
Allows you to wrap a WSGI application so it appears as a valid ASGI application.
|
||||
|
||||
Simply wrap it around your WSGI application like so::
|
||||
|
||||
asgi_application = WsgiToAsgi(wsgi_application)
|
||||
|
||||
The WSGI application will be run in a synchronous threadpool, and the wrapped
|
||||
ASGI application will be one that accepts ``http`` class messages.
|
||||
|
||||
Please note that not all extended features of WSGI may be supported (such as
|
||||
file handles for incoming POST bodies).
|
||||
|
||||
|
||||
Dependencies
|
||||
------------
|
||||
|
||||
``asgiref`` requires Python 3.10 or higher.
|
||||
|
||||
|
||||
Contributing
|
||||
------------
|
||||
|
||||
Please refer to the
|
||||
`main Channels contributing docs <https://github.com/django/channels/blob/master/CONTRIBUTING.rst>`_.
|
||||
|
||||
|
||||
Testing
|
||||
'''''''
|
||||
|
||||
To run tests, make sure you have installed the ``tests`` extra with the package::
|
||||
|
||||
cd asgiref/
|
||||
pip install -e .[tests]
|
||||
pytest
|
||||
|
||||
|
||||
Building the documentation
|
||||
''''''''''''''''''''''''''
|
||||
|
||||
The documentation uses `Sphinx <http://www.sphinx-doc.org>`_::
|
||||
|
||||
cd asgiref/docs/
|
||||
pip install sphinx
|
||||
|
||||
To build the docs, you can use the default tools::
|
||||
|
||||
sphinx-build -b html . _build/html # or `make html`, if you've got make set up
|
||||
cd _build/html
|
||||
python -m http.server
|
||||
|
||||
...or you can use ``sphinx-autobuild`` to run a server and rebuild/reload
|
||||
your documentation changes automatically::
|
||||
|
||||
pip install sphinx-autobuild
|
||||
sphinx-autobuild . _build/html
|
||||
|
||||
|
||||
Releasing
|
||||
'''''''''
|
||||
|
||||
To release, first add details to CHANGELOG.txt and update the version number in ``asgiref/__init__.py``.
|
||||
|
||||
Then, build and push the packages::
|
||||
|
||||
python -m build
|
||||
twine upload dist/*
|
||||
rm -r asgiref.egg-info dist
|
||||
|
||||
|
||||
Implementation Details
|
||||
----------------------
|
||||
|
||||
Synchronous code & threads
|
||||
''''''''''''''''''''''''''
|
||||
|
||||
The ``asgiref.sync`` module provides two wrappers that let you go between
|
||||
asynchronous and synchronous code at will, while taking care of the rough edges
|
||||
for you.
|
||||
|
||||
Unfortunately, the rough edges are numerous, and the code has to work especially
|
||||
hard to keep things in the same thread as much as possible. Notably, the
|
||||
restrictions we are working with are:
|
||||
|
||||
* All synchronous code called through ``SyncToAsync`` and marked with
|
||||
``thread_sensitive`` should run in the same thread as each other (and if the
|
||||
outer layer of the program is synchronous, the main thread)
|
||||
|
||||
* If a thread already has a running async loop, ``AsyncToSync`` can't run things
|
||||
on that loop if it's blocked on synchronous code that is above you in the
|
||||
call stack.
|
||||
|
||||
The first compromise you get to might be that ``thread_sensitive`` code should
|
||||
just run in the same thread and not spawn in a sub-thread, fulfilling the first
|
||||
restriction, but that immediately runs you into the second restriction.
|
||||
|
||||
The only real solution is to essentially have a variant of ThreadPoolExecutor
|
||||
that executes any ``thread_sensitive`` code on the outermost synchronous
|
||||
thread - either the main thread, or a single spawned subthread.
|
||||
|
||||
This means you now have two basic states:
|
||||
|
||||
* If the outermost layer of your program is synchronous, then all async code
|
||||
run through ``AsyncToSync`` will run in a per-call event loop in arbitrary
|
||||
sub-threads, while all ``thread_sensitive`` code will run in the main thread.
|
||||
|
||||
* If the outermost layer of your program is asynchronous, then all async code
|
||||
runs on the main thread's event loop, and all ``thread_sensitive`` synchronous
|
||||
code will run in a single shared sub-thread.
|
||||
|
||||
Crucially, this means that in both cases there is a thread which is a shared
|
||||
resource that all ``thread_sensitive`` code must run on, and there is a chance
|
||||
that this thread is currently blocked on its own ``AsyncToSync`` call. Thus,
|
||||
``AsyncToSync`` needs to act as an executor for thread code while it's blocking.
|
||||
|
||||
The ``CurrentThreadExecutor`` class provides this functionality; rather than
|
||||
simply waiting on a Future, you can call its ``run_until_future`` method and
|
||||
it will run submitted code until that Future is done. This means that code
|
||||
inside the call can then run code on your thread.
|
||||
|
||||
|
||||
Maintenance and Security
|
||||
------------------------
|
||||
|
||||
To report security issues, please contact security@djangoproject.com. For GPG
|
||||
signatures and more security process information, see
|
||||
https://docs.djangoproject.com/en/dev/internals/security/.
|
||||
|
||||
To report bugs or request new features, please open a new GitHub issue.
|
||||
|
||||
This repository is part of the Channels project. For the shepherd and maintenance team, please see the
|
||||
`main Channels readme <https://github.com/django/channels/blob/master/README.rst>`_.
|
||||
@@ -0,0 +1,27 @@
|
||||
asgiref-3.12.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
||||
asgiref-3.12.1.dist-info/METADATA,sha256=LRAowPq6DzkafCP6uWBmHJsDOH7xoNcOBLgg3bO_opQ,9383
|
||||
asgiref-3.12.1.dist-info/RECORD,,
|
||||
asgiref-3.12.1.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
||||
asgiref-3.12.1.dist-info/licenses/LICENSE,sha256=uEZBXRtRTpwd_xSiLeuQbXlLxUbKYSn5UKGM0JHipmk,1552
|
||||
asgiref-3.12.1.dist-info/top_level.txt,sha256=bokQjCzwwERhdBiPdvYEZa4cHxT4NCeAffQNUqJ8ssg,8
|
||||
asgiref/__init__.py,sha256=4J9-DjMOtzdA7CSvdVspmfGUmFqJuTTG2pEaePRQA3I,23
|
||||
asgiref/__pycache__/__init__.cpython-313.pyc,,
|
||||
asgiref/__pycache__/compatibility.cpython-313.pyc,,
|
||||
asgiref/__pycache__/current_thread_executor.cpython-313.pyc,,
|
||||
asgiref/__pycache__/local.cpython-313.pyc,,
|
||||
asgiref/__pycache__/server.cpython-313.pyc,,
|
||||
asgiref/__pycache__/sync.cpython-313.pyc,,
|
||||
asgiref/__pycache__/testing.cpython-313.pyc,,
|
||||
asgiref/__pycache__/timeout.cpython-313.pyc,,
|
||||
asgiref/__pycache__/typing.cpython-313.pyc,,
|
||||
asgiref/__pycache__/wsgi.cpython-313.pyc,,
|
||||
asgiref/compatibility.py,sha256=DhY1SOpOvOw0Y1lSEjCqg-znRUQKecG3LTaV48MZi68,1606
|
||||
asgiref/current_thread_executor.py,sha256=iy9ui5vcbLge4YGFDyycrSsHR6x2idZQbtTvaIvagjQ,4068
|
||||
asgiref/local.py,sha256=S3SKnTQpR4nwhxJulPKbsB7urIQofH3iRUcYQ6ogUMQ,6568
|
||||
asgiref/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
||||
asgiref/server.py,sha256=UIYaF7z5ee8CaXlQ04gq6bUwaRKxW3LFIuuys-_AQQ8,6247
|
||||
asgiref/sync.py,sha256=U0Cl4BCRHtj2IsUu8FRRfct8GnFrP1tjUOPB-NBL9Bk,24206
|
||||
asgiref/testing.py,sha256=U5wcs_-ZYTO5SIGfl80EqRAGv_T8BHrAhvAKRuuztT4,4421
|
||||
asgiref/timeout.py,sha256=_d2F1WWjaoXjHYkCF3OH1gT6q4LJW3NCxRXyV35qqB0,3617
|
||||
asgiref/typing.py,sha256=Xuta94Om6mvPMULSAcsY13inxvyG__4WjS2vj9mWMEI,6185
|
||||
asgiref/wsgi.py,sha256=OSxanm5Qf-VfrOkAx62mYW0mOnh8pwaTz1099HbJzM0,7941
|
||||
@@ -0,0 +1,5 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: setuptools (83.0.0)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
Copyright (c) Django Software Foundation and individual contributors.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of Django nor the names of its contributors may be used
|
||||
to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -0,0 +1 @@
|
||||
asgiref
|
||||
@@ -0,0 +1 @@
|
||||
__version__ = "3.12.1"
|
||||
@@ -0,0 +1,48 @@
|
||||
import inspect
|
||||
|
||||
from .sync import iscoroutinefunction
|
||||
|
||||
|
||||
def is_double_callable(application):
|
||||
"""
|
||||
Tests to see if an application is a legacy-style (double-callable) application.
|
||||
"""
|
||||
# Look for a hint on the object first
|
||||
if getattr(application, "_asgi_single_callable", False):
|
||||
return False
|
||||
if getattr(application, "_asgi_double_callable", False):
|
||||
return True
|
||||
# Uninstanted classes are double-callable
|
||||
if inspect.isclass(application):
|
||||
return True
|
||||
# Instanted classes depend on their __call__
|
||||
if hasattr(application, "__call__"):
|
||||
# We only check to see if its __call__ is a coroutine function -
|
||||
# if it's not, it still might be a coroutine function itself.
|
||||
if iscoroutinefunction(application.__call__):
|
||||
return False
|
||||
# Non-classes we just check directly
|
||||
return not iscoroutinefunction(application)
|
||||
|
||||
|
||||
def double_to_single_callable(application):
|
||||
"""
|
||||
Transforms a double-callable ASGI application into a single-callable one.
|
||||
"""
|
||||
|
||||
async def new_application(scope, receive, send):
|
||||
instance = application(scope)
|
||||
return await instance(receive, send)
|
||||
|
||||
return new_application
|
||||
|
||||
|
||||
def guarantee_single_callable(application):
|
||||
"""
|
||||
Takes either a single- or double-callable application and always returns it
|
||||
in single-callable style. Use this to add backwards compatibility for ASGI
|
||||
2.0 applications to your server/test harness/etc.
|
||||
"""
|
||||
if is_double_callable(application):
|
||||
application = double_to_single_callable(application)
|
||||
return application
|
||||
@@ -0,0 +1,118 @@
|
||||
import threading
|
||||
from collections import deque
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import Executor, Future
|
||||
from typing import Any, ParamSpec, TypeVar
|
||||
|
||||
_T = TypeVar("_T")
|
||||
_P = ParamSpec("_P")
|
||||
_R = TypeVar("_R")
|
||||
|
||||
|
||||
class _WorkItem:
|
||||
"""
|
||||
Represents an item needing to be run in the executor.
|
||||
Copied from ThreadPoolExecutor (but it's private, so we're not going to rely on importing it)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
future: "Future[_R]",
|
||||
fn: Callable[_P, _R],
|
||||
*args: _P.args,
|
||||
**kwargs: _P.kwargs,
|
||||
):
|
||||
self.future = future
|
||||
self.fn = fn
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
|
||||
def run(self) -> None:
|
||||
__traceback_hide__ = True # noqa: F841
|
||||
if not self.future.set_running_or_notify_cancel():
|
||||
return
|
||||
try:
|
||||
result = self.fn(*self.args, **self.kwargs)
|
||||
except BaseException as exc:
|
||||
self.future.set_exception(exc)
|
||||
# Break a reference cycle with the exception 'exc'
|
||||
self = None # type: ignore[assignment]
|
||||
else:
|
||||
self.future.set_result(result)
|
||||
|
||||
|
||||
class CurrentThreadExecutor(Executor):
|
||||
"""
|
||||
An Executor that actually runs code in the thread it is instantiated in.
|
||||
Passed to other threads running async code, so they can run sync code in
|
||||
the thread they came from.
|
||||
"""
|
||||
|
||||
def __init__(self, old_executor: "CurrentThreadExecutor | None") -> None:
|
||||
self._work_thread = threading.current_thread()
|
||||
self._work_ready = threading.Condition(threading.Lock())
|
||||
self._work_items = deque[_WorkItem]() # synchronized by _work_ready
|
||||
self._broken = False # synchronized by _work_ready
|
||||
self._old_executor = old_executor
|
||||
|
||||
def run_until_future(self, future: "Future[Any]") -> None:
|
||||
"""
|
||||
Runs the code in the work queue until a result is available from the future.
|
||||
Should be run from the thread the executor is initialised in.
|
||||
"""
|
||||
# Check we're in the right thread
|
||||
if threading.current_thread() != self._work_thread:
|
||||
raise RuntimeError(
|
||||
"You cannot run CurrentThreadExecutor from a different thread"
|
||||
)
|
||||
|
||||
def done(future: "Future[Any]") -> None:
|
||||
with self._work_ready:
|
||||
self._broken = True
|
||||
self._work_ready.notify()
|
||||
|
||||
future.add_done_callback(done)
|
||||
# Keep getting and running work items until the future we're waiting for
|
||||
# is done and the queue is empty.
|
||||
while True:
|
||||
with self._work_ready:
|
||||
while not self._work_items and not self._broken:
|
||||
self._work_ready.wait()
|
||||
if not self._work_items:
|
||||
break
|
||||
# Get a work item and run it
|
||||
work_item = self._work_items.popleft()
|
||||
work_item.run()
|
||||
del work_item
|
||||
|
||||
def submit(
|
||||
self,
|
||||
fn: Callable[_P, _R],
|
||||
/,
|
||||
*args: _P.args,
|
||||
**kwargs: _P.kwargs,
|
||||
) -> "Future[_R]":
|
||||
# Check they're not submitting from the same thread
|
||||
if threading.current_thread() == self._work_thread:
|
||||
raise RuntimeError(
|
||||
"You cannot submit onto CurrentThreadExecutor from its own thread"
|
||||
)
|
||||
f: "Future[_R]" = Future()
|
||||
work_item = _WorkItem(f, fn, *args, **kwargs)
|
||||
|
||||
# Walk up the CurrentThreadExecutor stack to find the closest one still
|
||||
# running
|
||||
executor = self
|
||||
while True:
|
||||
with executor._work_ready:
|
||||
if not executor._broken:
|
||||
# Add to work queue
|
||||
executor._work_items.append(work_item)
|
||||
executor._work_ready.notify()
|
||||
break
|
||||
if executor._old_executor is None:
|
||||
raise RuntimeError("CurrentThreadExecutor already quit or is broken")
|
||||
executor = executor._old_executor
|
||||
|
||||
# Return the future
|
||||
return f
|
||||
@@ -0,0 +1,168 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import contextvars
|
||||
import threading
|
||||
from typing import Any, Union
|
||||
|
||||
|
||||
class _Storage:
|
||||
"""Thread-tagged storage for a non-thread-critical ``Local``.
|
||||
|
||||
The data is tagged with the identity of the thread that owns it. This lets
|
||||
``_CVar`` ignore data that leaked into an unrelated thread.
|
||||
|
||||
Python 3.14 added ``sys.flags.thread_inherit_context``, which is enabled by
|
||||
default on free-threaded builds. When set, a new thread starts with a copy
|
||||
of the spawning thread's context instead of an empty one, so the contextvar
|
||||
backing a ``Local`` would otherwise be visible in any thread spawned from
|
||||
one that had set it -- breaking the documented "thread-local in sync
|
||||
threads" behaviour. asgiref re-homes the storage to the current thread at
|
||||
the points where it *intentionally* moves work between threads (see
|
||||
``asgiref.sync._restore_context``); data merely inherited by an unrelated
|
||||
thread is never re-homed and so stays isolated.
|
||||
"""
|
||||
|
||||
__slots__ = ("thread_id", "data")
|
||||
|
||||
def __init__(self, thread_id: int, data: dict[str, Any]) -> None:
|
||||
self.thread_id = thread_id
|
||||
self.data = data
|
||||
|
||||
|
||||
def _rehome(storage: "_Storage") -> "_Storage":
|
||||
"""Return a copy of *storage* owned by the current thread."""
|
||||
return _Storage(threading.get_ident(), storage.data)
|
||||
|
||||
|
||||
class _CVar:
|
||||
"""Storage utility for Local."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._data: "contextvars.ContextVar[_Storage]" = contextvars.ContextVar(
|
||||
"asgiref.local"
|
||||
)
|
||||
|
||||
def _storage(self) -> "_Storage":
|
||||
# Only return storage that belongs to the current thread. Storage with
|
||||
# a different thread id was inherited by this thread (rather than
|
||||
# intentionally moved here by asgiref) and must not be visible.
|
||||
storage = self._data.get(None)
|
||||
if storage is None or storage.thread_id != threading.get_ident():
|
||||
return _Storage(threading.get_ident(), {})
|
||||
return storage
|
||||
|
||||
def __getattr__(self, key):
|
||||
try:
|
||||
return self._storage().data[key]
|
||||
except KeyError:
|
||||
raise AttributeError(f"{self!r} object has no attribute {key!r}")
|
||||
|
||||
def __setattr__(self, key: str, value: Any) -> None:
|
||||
if key == "_data":
|
||||
return super().__setattr__(key, value)
|
||||
|
||||
data = self._storage().data.copy()
|
||||
data[key] = value
|
||||
self._data.set(_Storage(threading.get_ident(), data))
|
||||
|
||||
def __delattr__(self, key: str) -> None:
|
||||
data = self._storage().data.copy()
|
||||
if key in data:
|
||||
del data[key]
|
||||
self._data.set(_Storage(threading.get_ident(), data))
|
||||
else:
|
||||
raise AttributeError(f"{self!r} object has no attribute {key!r}")
|
||||
|
||||
|
||||
class Local:
|
||||
"""Local storage for async tasks.
|
||||
|
||||
This is a namespace object (similar to `threading.local`) where data is
|
||||
also local to the current async task (if there is one).
|
||||
|
||||
In async threads, local means in the same sense as the `contextvars`
|
||||
module - i.e. a value set in an async frame will be visible:
|
||||
|
||||
- to other async code `await`-ed from this frame.
|
||||
- to tasks spawned using `asyncio` utilities (`create_task`, `wait_for`,
|
||||
`gather` and probably others).
|
||||
- to code scheduled in a sync thread using `sync_to_async`
|
||||
|
||||
In "sync" threads (a thread with no async event loop running), the
|
||||
data is thread-local, but additionally shared with async code executed
|
||||
via the `async_to_sync` utility, which schedules async code in a new thread
|
||||
and copies context across to that thread.
|
||||
|
||||
If `thread_critical` is True, then the local will only be visible per-thread,
|
||||
behaving exactly like `threading.local` if the thread is sync, and as
|
||||
`contextvars` if the thread is async. This allows genuinely thread-sensitive
|
||||
code (such as DB handles) to be kept strictly to their initial thread and
|
||||
disable the sharing across `sync_to_async` and `async_to_sync` wrapped calls.
|
||||
|
||||
Unlike plain `contextvars` objects, this utility is threadsafe.
|
||||
"""
|
||||
|
||||
def __init__(self, thread_critical: bool = False) -> None:
|
||||
self._thread_critical = thread_critical
|
||||
self._thread_lock = threading.RLock()
|
||||
|
||||
self._storage: "Union[threading.local, _CVar]"
|
||||
|
||||
if thread_critical:
|
||||
# Thread-local storage
|
||||
self._storage = threading.local()
|
||||
else:
|
||||
# Contextvar storage
|
||||
self._storage = _CVar()
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _lock_storage(self):
|
||||
# Thread safe access to storage
|
||||
if self._thread_critical:
|
||||
is_async = True
|
||||
try:
|
||||
# this is a test for are we in a async or sync
|
||||
# thread - will raise RuntimeError if there is
|
||||
# no current loop
|
||||
asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
is_async = False
|
||||
if not is_async:
|
||||
# We are in a sync thread, the storage is
|
||||
# just the plain thread local (i.e, "global within
|
||||
# this thread" - it doesn't matter where you are
|
||||
# in a call stack you see the same storage)
|
||||
yield self._storage
|
||||
else:
|
||||
# We are in an async thread - storage is still
|
||||
# local to this thread, but additionally should
|
||||
# behave like a context var (is only visible with
|
||||
# the same async call stack)
|
||||
|
||||
# Ensure context exists in the current thread
|
||||
if not hasattr(self._storage, "cvar"):
|
||||
self._storage.cvar = _CVar()
|
||||
|
||||
# self._storage is a thread local, so the members
|
||||
# can't be accessed in another thread (we don't
|
||||
# need any locks)
|
||||
yield self._storage.cvar
|
||||
else:
|
||||
# Lock for thread_critical=False as other threads
|
||||
# can access the exact same storage object
|
||||
with self._thread_lock:
|
||||
yield self._storage
|
||||
|
||||
def __getattr__(self, key):
|
||||
with self._lock_storage() as storage:
|
||||
return getattr(storage, key)
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
if key in ("_local", "_storage", "_thread_critical", "_thread_lock"):
|
||||
return super().__setattr__(key, value)
|
||||
with self._lock_storage() as storage:
|
||||
setattr(storage, key, value)
|
||||
|
||||
def __delattr__(self, key):
|
||||
with self._lock_storage() as storage:
|
||||
delattr(storage, key)
|
||||
@@ -0,0 +1,172 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from .compatibility import guarantee_single_callable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class StatelessServer:
|
||||
"""
|
||||
Base server class that handles basic concepts like application instance
|
||||
creation/pooling, exception handling, and similar, for stateless protocols
|
||||
(i.e. ones without actual incoming connections to the process)
|
||||
|
||||
Your code should override the handle() method, doing whatever it needs to,
|
||||
and calling get_or_create_application_instance with a unique `scope_id`
|
||||
and `scope` for the scope it wants to get.
|
||||
|
||||
If an application instance is found with the same `scope_id`, you are
|
||||
given its input queue, otherwise one is made for you with the scope provided
|
||||
and you are given that fresh new input queue. Either way, you should do
|
||||
something like:
|
||||
|
||||
input_queue = self.get_or_create_application_instance(
|
||||
"user-123456",
|
||||
{"type": "testprotocol", "user_id": "123456", "username": "andrew"},
|
||||
)
|
||||
input_queue.put_nowait(message)
|
||||
|
||||
If you try and create an application instance and there are already
|
||||
`max_application` instances, the oldest/least recently used one will be
|
||||
reclaimed and shut down to make space.
|
||||
|
||||
Application coroutines that error will be found periodically (every 100ms
|
||||
by default) and have their exceptions printed to the console. Override
|
||||
application_exception() if you want to do more when this happens.
|
||||
|
||||
If you override run(), make sure you handle things like launching the
|
||||
application checker.
|
||||
"""
|
||||
|
||||
application_checker_interval = 0.1
|
||||
|
||||
def __init__(self, application, max_applications=1000):
|
||||
# Parameters
|
||||
self.application = application
|
||||
self.max_applications = max_applications
|
||||
# Initialisation
|
||||
self.application_instances = {}
|
||||
|
||||
### Mainloop and handling
|
||||
|
||||
def run(self):
|
||||
"""
|
||||
Runs the asyncio event loop with our handler loop.
|
||||
"""
|
||||
try:
|
||||
asyncio.run(self.arun())
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Exiting due to Ctrl-C/interrupt")
|
||||
|
||||
async def arun(self):
|
||||
"""
|
||||
Runs the asyncio event loop with our handler loop.
|
||||
"""
|
||||
|
||||
class Done(Exception):
|
||||
pass
|
||||
|
||||
async def handle():
|
||||
await self.handle()
|
||||
raise Done
|
||||
|
||||
try:
|
||||
await asyncio.gather(self.application_checker(), handle())
|
||||
except Done:
|
||||
pass
|
||||
|
||||
async def handle(self):
|
||||
raise NotImplementedError("You must implement handle()")
|
||||
|
||||
async def application_send(self, scope, message):
|
||||
"""
|
||||
Receives outbound sends from applications and handles them.
|
||||
"""
|
||||
raise NotImplementedError("You must implement application_send()")
|
||||
|
||||
### Application instance management
|
||||
|
||||
def get_or_create_application_instance(self, scope_id, scope):
|
||||
"""
|
||||
Creates an application instance and returns its queue.
|
||||
"""
|
||||
if scope_id in self.application_instances:
|
||||
self.application_instances[scope_id]["last_used"] = time.time()
|
||||
return self.application_instances[scope_id]["input_queue"]
|
||||
# See if we need to delete an old one
|
||||
while len(self.application_instances) > self.max_applications:
|
||||
self.delete_oldest_application_instance()
|
||||
# Make an instance of the application
|
||||
input_queue = asyncio.Queue()
|
||||
application_instance = guarantee_single_callable(self.application)
|
||||
# Run it, and stash the future for later checking
|
||||
future = asyncio.ensure_future(
|
||||
application_instance(
|
||||
scope=scope,
|
||||
receive=input_queue.get,
|
||||
send=lambda message: self.application_send(scope, message),
|
||||
),
|
||||
)
|
||||
self.application_instances[scope_id] = {
|
||||
"input_queue": input_queue,
|
||||
"future": future,
|
||||
"scope": scope,
|
||||
"last_used": time.time(),
|
||||
}
|
||||
return input_queue
|
||||
|
||||
def delete_oldest_application_instance(self):
|
||||
"""
|
||||
Finds and deletes the oldest application instance
|
||||
"""
|
||||
oldest_time = min(
|
||||
details["last_used"] for details in self.application_instances.values()
|
||||
)
|
||||
for scope_id, details in self.application_instances.items():
|
||||
if details["last_used"] == oldest_time:
|
||||
self.delete_application_instance(scope_id)
|
||||
# Return to make sure we only delete one in case two have
|
||||
# the same oldest time
|
||||
return
|
||||
|
||||
def delete_application_instance(self, scope_id):
|
||||
"""
|
||||
Removes an application instance (makes sure its task is stopped,
|
||||
then removes it from the current set)
|
||||
"""
|
||||
details = self.application_instances[scope_id]
|
||||
del self.application_instances[scope_id]
|
||||
if not details["future"].done():
|
||||
details["future"].cancel()
|
||||
|
||||
async def application_checker(self):
|
||||
"""
|
||||
Goes through the set of current application instance Futures and cleans up
|
||||
any that are done/prints exceptions for any that errored.
|
||||
"""
|
||||
while True:
|
||||
await asyncio.sleep(self.application_checker_interval)
|
||||
for scope_id, details in list(self.application_instances.items()):
|
||||
if details["future"].done():
|
||||
exception = details["future"].exception()
|
||||
if exception:
|
||||
await self.application_exception(exception, details)
|
||||
try:
|
||||
del self.application_instances[scope_id]
|
||||
except KeyError:
|
||||
# Exception handling might have already got here before us. That's fine.
|
||||
pass
|
||||
|
||||
async def application_exception(self, exception, application_details):
|
||||
"""
|
||||
Called whenever an application coroutine has an exception.
|
||||
"""
|
||||
logging.error(
|
||||
"Exception inside application: %s\n%s%s",
|
||||
exception,
|
||||
"".join(traceback.format_tb(exception.__traceback__)),
|
||||
f" {exception}",
|
||||
)
|
||||
@@ -0,0 +1,667 @@
|
||||
import asyncio
|
||||
import asyncio.coroutines
|
||||
import contextvars
|
||||
import functools
|
||||
import inspect
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import warnings
|
||||
import weakref
|
||||
from collections.abc import Awaitable, Callable, Coroutine
|
||||
from concurrent.futures import Future, InvalidStateError, ThreadPoolExecutor
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict,
|
||||
Generic,
|
||||
List,
|
||||
Optional,
|
||||
ParamSpec,
|
||||
TypeVar,
|
||||
overload,
|
||||
)
|
||||
|
||||
from .current_thread_executor import CurrentThreadExecutor
|
||||
from .local import Local, _rehome, _Storage
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# This is not available to import at runtime
|
||||
from _typeshed import OptExcInfo
|
||||
|
||||
_F = TypeVar("_F", bound=Callable[..., Any])
|
||||
_P = ParamSpec("_P")
|
||||
_R = TypeVar("_R")
|
||||
|
||||
|
||||
def _restore_context(context: contextvars.Context) -> None:
|
||||
# Check for changes in contextvars, and set them to the current
|
||||
# context for downstream consumers
|
||||
for cvar in context:
|
||||
cvalue = context.get(cvar)
|
||||
# asgiref is deliberately moving this context onto the current thread,
|
||||
# so re-home any Local storage to it. This keeps Local data visible
|
||||
# across async_to_sync / sync_to_async boundaries while leaving data
|
||||
# merely inherited by an unrelated thread isolated (see asgiref.local).
|
||||
if isinstance(cvalue, _Storage):
|
||||
cvalue = _rehome(cvalue)
|
||||
try:
|
||||
if cvar.get() != cvalue:
|
||||
cvar.set(cvalue)
|
||||
except LookupError:
|
||||
cvar.set(cvalue)
|
||||
|
||||
|
||||
# Python 3.12 deprecates asyncio.iscoroutinefunction() as an alias for
|
||||
# inspect.iscoroutinefunction(), whilst also removing the _is_coroutine marker.
|
||||
# The latter is replaced with the inspect.markcoroutinefunction decorator.
|
||||
# Until 3.12 is the minimum supported Python version, provide a shim.
|
||||
|
||||
if hasattr(inspect, "markcoroutinefunction"):
|
||||
iscoroutinefunction = inspect.iscoroutinefunction
|
||||
markcoroutinefunction: Callable[[_F], _F] = inspect.markcoroutinefunction
|
||||
else:
|
||||
iscoroutinefunction = asyncio.iscoroutinefunction # type: ignore[assignment]
|
||||
|
||||
def markcoroutinefunction(func: _F) -> _F:
|
||||
func._is_coroutine = asyncio.coroutines._is_coroutine # type: ignore
|
||||
return func
|
||||
|
||||
|
||||
class AsyncSingleThreadContext:
|
||||
"""Context manager to run async code inside the same thread.
|
||||
|
||||
Normally, AsyncToSync functions run either inside a separate ThreadPoolExecutor or
|
||||
the main event loop if it exists. This context manager ensures that all AsyncToSync
|
||||
functions execute within the same thread.
|
||||
|
||||
This context manager is re-entrant, so only the outer-most call to
|
||||
AsyncSingleThreadContext will set the context.
|
||||
|
||||
Usage:
|
||||
|
||||
>>> import asyncio
|
||||
>>> with AsyncSingleThreadContext():
|
||||
... async_to_sync(asyncio.sleep(1))()
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.token = None
|
||||
|
||||
def __enter__(self):
|
||||
try:
|
||||
AsyncToSync.async_single_thread_context.get()
|
||||
except LookupError:
|
||||
self.token = AsyncToSync.async_single_thread_context.set(self)
|
||||
|
||||
return self
|
||||
|
||||
def __exit__(self, exc, value, tb):
|
||||
if not self.token:
|
||||
return
|
||||
|
||||
executor = AsyncToSync.context_to_thread_executor.pop(self, None)
|
||||
if executor:
|
||||
executor.shutdown()
|
||||
|
||||
AsyncToSync.async_single_thread_context.reset(self.token)
|
||||
|
||||
|
||||
class ThreadSensitiveContext:
|
||||
"""Async context manager to manage context for thread sensitive mode
|
||||
|
||||
This context manager controls which thread pool executor is used when in
|
||||
thread sensitive mode. By default, a single thread pool executor is shared
|
||||
within a process.
|
||||
|
||||
The ThreadSensitiveContext() context manager may be used to specify a
|
||||
thread pool per context.
|
||||
|
||||
This context manager is re-entrant, so only the outer-most call to
|
||||
ThreadSensitiveContext will set the context.
|
||||
|
||||
Usage:
|
||||
|
||||
>>> import time
|
||||
>>> async with ThreadSensitiveContext():
|
||||
... await sync_to_async(time.sleep, 1)()
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.token = None
|
||||
|
||||
async def __aenter__(self):
|
||||
try:
|
||||
SyncToAsync.thread_sensitive_context.get()
|
||||
except LookupError:
|
||||
self.token = SyncToAsync.thread_sensitive_context.set(self)
|
||||
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc, value, tb):
|
||||
if not self.token:
|
||||
return
|
||||
|
||||
executor = SyncToAsync.context_to_thread_executor.pop(self, None)
|
||||
SyncToAsync.thread_sensitive_context.reset(self.token)
|
||||
if executor:
|
||||
# The executor's worker thread may itself be waiting for this
|
||||
# event loop, so a blocking shutdown() here would deadlock it.
|
||||
# Join in a dedicated thread, not the loop's default executor:
|
||||
# work queued there may itself be needed to unpark the worker,
|
||||
# and joins occupying its slots would starve it.
|
||||
future: "Future[None]" = Future()
|
||||
|
||||
def join() -> None:
|
||||
executor.shutdown()
|
||||
try:
|
||||
future.set_result(None)
|
||||
except InvalidStateError:
|
||||
# The await below was cancelled while we were joining.
|
||||
pass
|
||||
|
||||
threading.Thread(target=join, daemon=True).start()
|
||||
await asyncio.wrap_future(future)
|
||||
|
||||
|
||||
class AsyncToSync(Generic[_P, _R]):
|
||||
"""
|
||||
Utility class which turns an awaitable that only works on the thread with
|
||||
the event loop into a synchronous callable that works in a subthread.
|
||||
|
||||
If the call stack contains an async loop, the code runs there.
|
||||
Otherwise, the code runs in a new loop in a new thread.
|
||||
|
||||
Either way, this thread then pauses and waits to run any thread_sensitive
|
||||
code called from further down the call stack using SyncToAsync, before
|
||||
finally exiting once the async task returns.
|
||||
"""
|
||||
|
||||
# Keeps a reference to the CurrentThreadExecutor in local context, so that
|
||||
# any sync_to_async inside the wrapped code can find it.
|
||||
executors: "Local" = Local()
|
||||
|
||||
# When we can't find a CurrentThreadExecutor from the context, such as
|
||||
# inside create_task, we'll look it up here from the running event loop.
|
||||
loop_thread_executors: "Dict[asyncio.AbstractEventLoop, CurrentThreadExecutor]" = {}
|
||||
|
||||
async_single_thread_context: "contextvars.ContextVar[AsyncSingleThreadContext]" = (
|
||||
contextvars.ContextVar("async_single_thread_context")
|
||||
)
|
||||
|
||||
context_to_thread_executor: (
|
||||
"weakref.WeakKeyDictionary[AsyncSingleThreadContext, ThreadPoolExecutor]"
|
||||
) = weakref.WeakKeyDictionary()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
awaitable: Callable[_P, Coroutine[Any, Any, _R]] | Callable[_P, Awaitable[_R]],
|
||||
force_new_loop: bool = False,
|
||||
):
|
||||
if not callable(awaitable) or (
|
||||
not iscoroutinefunction(awaitable)
|
||||
and not iscoroutinefunction(getattr(awaitable, "__call__", awaitable))
|
||||
):
|
||||
# Python does not have very reliable detection of async functions
|
||||
# (lots of false negatives) so this is just a warning.
|
||||
warnings.warn(
|
||||
"async_to_sync was passed a non-async-marked callable", stacklevel=2
|
||||
)
|
||||
self.awaitable = awaitable
|
||||
try:
|
||||
self.__self__ = self.awaitable.__self__ # type: ignore[union-attr]
|
||||
except AttributeError:
|
||||
pass
|
||||
self.force_new_loop = force_new_loop
|
||||
|
||||
def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
|
||||
__traceback_hide__ = True # noqa: F841
|
||||
|
||||
main_event_loop = None
|
||||
if not self.force_new_loop:
|
||||
# There's no event loop in this thread. Look for the threadlocal if
|
||||
# we're inside SyncToAsync
|
||||
main_event_loop_pid = getattr(
|
||||
SyncToAsync.threadlocal, "main_event_loop_pid", None
|
||||
)
|
||||
# We make sure the parent loop is from the same process - if
|
||||
# they've forked, this is not going to be valid any more (#194)
|
||||
if main_event_loop_pid and main_event_loop_pid == os.getpid():
|
||||
main_event_loop = getattr(
|
||||
SyncToAsync.threadlocal, "main_event_loop", None
|
||||
)
|
||||
|
||||
# You can't call AsyncToSync from a thread with a running event loop
|
||||
try:
|
||||
asyncio.get_running_loop()
|
||||
except RuntimeError:
|
||||
pass
|
||||
else:
|
||||
raise RuntimeError(
|
||||
"You cannot use AsyncToSync in the same thread as an async event loop - "
|
||||
"just await the async function directly."
|
||||
)
|
||||
|
||||
# Make a future for the return information
|
||||
call_result: "Future[_R]" = Future()
|
||||
|
||||
# Make a CurrentThreadExecutor we'll use to idle in this thread - we
|
||||
# need one for every sync frame, even if there's one above us in the
|
||||
# same thread.
|
||||
old_executor = getattr(self.executors, "current", None)
|
||||
current_executor = CurrentThreadExecutor(old_executor)
|
||||
self.executors.current = current_executor
|
||||
|
||||
# Wrapping context in list so it can be reassigned from within
|
||||
# `main_wrap`.
|
||||
context = [contextvars.copy_context()]
|
||||
|
||||
# Get task context so that parent task knows which task to propagate
|
||||
# an asyncio.CancelledError to.
|
||||
task_context = getattr(SyncToAsync.threadlocal, "task_context", None)
|
||||
|
||||
# Use call_soon_threadsafe to schedule a synchronous callback on the
|
||||
# main event loop's thread if it's there, otherwise make a new loop
|
||||
# in this thread.
|
||||
try:
|
||||
awaitable = self.main_wrap(
|
||||
call_result,
|
||||
sys.exc_info(),
|
||||
task_context,
|
||||
context,
|
||||
# prepare an awaitable which can be passed as is to self.main_wrap,
|
||||
# so that `args` and `kwargs` don't need to be
|
||||
# destructured when passed to self.main_wrap
|
||||
# (which is required by `ParamSpec`)
|
||||
# as that may cause overlapping arguments
|
||||
self.awaitable(*args, **kwargs),
|
||||
)
|
||||
|
||||
async def new_loop_wrap() -> None:
|
||||
loop = asyncio.get_running_loop()
|
||||
self.loop_thread_executors[loop] = current_executor
|
||||
try:
|
||||
await awaitable
|
||||
finally:
|
||||
del self.loop_thread_executors[loop]
|
||||
|
||||
if main_event_loop is not None:
|
||||
try:
|
||||
main_event_loop.call_soon_threadsafe(
|
||||
main_event_loop.create_task, awaitable
|
||||
)
|
||||
except RuntimeError:
|
||||
running_in_main_event_loop = False
|
||||
else:
|
||||
running_in_main_event_loop = True
|
||||
# Run the CurrentThreadExecutor until the future is done.
|
||||
current_executor.run_until_future(call_result)
|
||||
else:
|
||||
running_in_main_event_loop = False
|
||||
|
||||
if not running_in_main_event_loop:
|
||||
loop_executor = None
|
||||
|
||||
if self.async_single_thread_context.get(None):
|
||||
single_thread_context = self.async_single_thread_context.get()
|
||||
|
||||
if single_thread_context in self.context_to_thread_executor:
|
||||
loop_executor = self.context_to_thread_executor[
|
||||
single_thread_context
|
||||
]
|
||||
else:
|
||||
loop_executor = ThreadPoolExecutor(max_workers=1)
|
||||
self.context_to_thread_executor[single_thread_context] = (
|
||||
loop_executor
|
||||
)
|
||||
else:
|
||||
# Make our own event loop - in a new thread - and run inside that.
|
||||
loop_executor = ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
loop_future = loop_executor.submit(asyncio.run, new_loop_wrap())
|
||||
# Run the CurrentThreadExecutor until the future is done.
|
||||
current_executor.run_until_future(loop_future)
|
||||
# Wait for future and/or allow for exception propagation
|
||||
loop_future.result()
|
||||
finally:
|
||||
_restore_context(context[0])
|
||||
# Restore old current thread executor state
|
||||
self.executors.current = old_executor
|
||||
|
||||
# Wait for results from the future.
|
||||
return call_result.result()
|
||||
|
||||
def __get__(self, parent: Any, objtype: Any) -> Callable[_P, _R]:
|
||||
"""
|
||||
Include self for methods
|
||||
"""
|
||||
func = functools.partial(self.__call__, parent)
|
||||
return functools.update_wrapper(func, self.awaitable)
|
||||
|
||||
async def main_wrap(
|
||||
self,
|
||||
call_result: "Future[_R]",
|
||||
exc_info: "OptExcInfo",
|
||||
task_context: "Optional[List[asyncio.Task[Any]]]",
|
||||
context: list[contextvars.Context],
|
||||
awaitable: Coroutine[Any, Any, _R] | Awaitable[_R],
|
||||
) -> None:
|
||||
"""
|
||||
Wraps the awaitable with something that puts the result into the
|
||||
result/exception future.
|
||||
"""
|
||||
|
||||
__traceback_hide__ = True # noqa: F841
|
||||
|
||||
if context is not None:
|
||||
_restore_context(context[0])
|
||||
|
||||
current_task = asyncio.current_task()
|
||||
if current_task is not None and task_context is not None:
|
||||
task_context.append(current_task)
|
||||
|
||||
try:
|
||||
# If we have an exception, run the function inside the except block
|
||||
# after raising it so exc_info is correctly populated.
|
||||
if exc_info[1]:
|
||||
try:
|
||||
raise exc_info[1]
|
||||
except BaseException:
|
||||
result = await awaitable
|
||||
else:
|
||||
result = await awaitable
|
||||
except BaseException as e:
|
||||
call_result.set_exception(e)
|
||||
else:
|
||||
call_result.set_result(result)
|
||||
finally:
|
||||
if current_task is not None and task_context is not None:
|
||||
task_context.remove(current_task)
|
||||
context[0] = contextvars.copy_context()
|
||||
|
||||
|
||||
class SyncToAsync(Generic[_P, _R]):
|
||||
"""
|
||||
Utility class which turns a synchronous callable into an awaitable that
|
||||
runs in a threadpool. It also sets a threadlocal inside the thread so
|
||||
calls to AsyncToSync can escape it.
|
||||
|
||||
If thread_sensitive is passed, the code will run in the same thread as any
|
||||
outer code. This is needed for underlying Python code that is not
|
||||
threadsafe (for example, code which handles SQLite database connections).
|
||||
|
||||
If the outermost program is async (i.e. SyncToAsync is outermost), then
|
||||
this will be a dedicated single sub-thread that all sync code runs in,
|
||||
one after the other. If the outermost program is sync (i.e. AsyncToSync is
|
||||
outermost), this will just be the main thread. This is achieved by idling
|
||||
with a CurrentThreadExecutor while AsyncToSync is blocking its sync parent,
|
||||
rather than just blocking.
|
||||
|
||||
If executor is passed in, that will be used instead of the loop's default executor.
|
||||
In order to pass in an executor, thread_sensitive must be set to False, otherwise
|
||||
a TypeError will be raised.
|
||||
"""
|
||||
|
||||
# Storage for main event loop references
|
||||
threadlocal = threading.local()
|
||||
|
||||
# Single-thread executor for thread-sensitive code
|
||||
single_thread_executor = ThreadPoolExecutor(max_workers=1)
|
||||
|
||||
# Maintain a contextvar for the current execution context. Optionally used
|
||||
# for thread sensitive mode.
|
||||
thread_sensitive_context: "contextvars.ContextVar[ThreadSensitiveContext]" = (
|
||||
contextvars.ContextVar("thread_sensitive_context")
|
||||
)
|
||||
|
||||
# Contextvar that is used to detect if the single thread executor
|
||||
# would be awaited on while already being used in the same context
|
||||
deadlock_context: "contextvars.ContextVar[bool]" = contextvars.ContextVar(
|
||||
"deadlock_context"
|
||||
)
|
||||
|
||||
# Maintaining a weak reference to the context ensures that thread pools are
|
||||
# erased once the context goes out of scope. This terminates the thread pool.
|
||||
context_to_thread_executor: (
|
||||
"weakref.WeakKeyDictionary[ThreadSensitiveContext, ThreadPoolExecutor]"
|
||||
) = weakref.WeakKeyDictionary()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
func: Callable[_P, _R],
|
||||
thread_sensitive: bool = True,
|
||||
executor: Optional["ThreadPoolExecutor"] = None,
|
||||
context: contextvars.Context | None = None,
|
||||
) -> None:
|
||||
if (
|
||||
not callable(func)
|
||||
or iscoroutinefunction(func)
|
||||
or iscoroutinefunction(getattr(func, "__call__", func))
|
||||
):
|
||||
raise TypeError("sync_to_async can only be applied to sync functions.")
|
||||
|
||||
functools.update_wrapper(self, func)
|
||||
self.func = func
|
||||
self.context = context
|
||||
|
||||
self._thread_sensitive = thread_sensitive
|
||||
markcoroutinefunction(self)
|
||||
if thread_sensitive and executor is not None:
|
||||
raise TypeError("executor must not be set when thread_sensitive is True")
|
||||
self._executor = executor
|
||||
try:
|
||||
self.__self__ = func.__self__ # type: ignore
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
async def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
|
||||
__traceback_hide__ = True # noqa: F841
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
# Work out what thread to run the code in
|
||||
if self._thread_sensitive:
|
||||
current_thread_executor = getattr(AsyncToSync.executors, "current", None)
|
||||
if current_thread_executor:
|
||||
# If we have a parent sync thread above somewhere, use that
|
||||
executor = current_thread_executor
|
||||
elif self.thread_sensitive_context.get(None):
|
||||
# If we have a way of retrieving the current context, attempt
|
||||
# to use a per-context thread pool executor
|
||||
thread_sensitive_context = self.thread_sensitive_context.get()
|
||||
|
||||
if thread_sensitive_context in self.context_to_thread_executor:
|
||||
# Re-use thread executor in current context
|
||||
executor = self.context_to_thread_executor[thread_sensitive_context]
|
||||
else:
|
||||
# Create new thread executor in current context
|
||||
executor = ThreadPoolExecutor(max_workers=1)
|
||||
self.context_to_thread_executor[thread_sensitive_context] = executor
|
||||
elif loop in AsyncToSync.loop_thread_executors:
|
||||
# Re-use thread executor for running loop
|
||||
executor = AsyncToSync.loop_thread_executors[loop]
|
||||
elif self.deadlock_context.get(False):
|
||||
raise RuntimeError(
|
||||
"Single thread executor already being used, would deadlock"
|
||||
)
|
||||
else:
|
||||
# Otherwise, we run it in a fixed single thread
|
||||
executor = self.single_thread_executor
|
||||
self.deadlock_context.set(True)
|
||||
else:
|
||||
# Use the passed in executor, or the loop's default if it is None
|
||||
executor = self._executor
|
||||
|
||||
context = contextvars.copy_context() if self.context is None else self.context
|
||||
# ``child`` is the deferred sync function to be run, with its args
|
||||
# and kwargs bound.
|
||||
child = functools.partial(self.func, *args, **kwargs)
|
||||
|
||||
# On the worker thread, thread_handler runs ``func(child)``. ``func``
|
||||
# enters ``context`` (via context.run); then, inside it, ``run_child``
|
||||
# re-homes any Local storage to the worker thread so it stays visible
|
||||
# there (see _restore_context), and finally calls ``child``.
|
||||
def func(child: Callable[[], _R]) -> _R:
|
||||
def run_child() -> _R:
|
||||
_restore_context(context)
|
||||
return child()
|
||||
|
||||
return context.run(run_child)
|
||||
|
||||
task_context: list[asyncio.Task[Any]] = []
|
||||
|
||||
# Run the code in the right thread
|
||||
exec_coro = loop.run_in_executor(
|
||||
executor,
|
||||
functools.partial(
|
||||
self.thread_handler,
|
||||
loop,
|
||||
sys.exc_info(),
|
||||
task_context,
|
||||
func,
|
||||
child,
|
||||
),
|
||||
)
|
||||
ret: _R
|
||||
try:
|
||||
ret = await asyncio.shield(exec_coro)
|
||||
except asyncio.CancelledError:
|
||||
cancel_parent = True
|
||||
try:
|
||||
task = task_context[0]
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
cancel_parent = False
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
except IndexError:
|
||||
pass
|
||||
if exec_coro.done():
|
||||
raise
|
||||
if cancel_parent:
|
||||
exec_coro.cancel()
|
||||
ret = await exec_coro
|
||||
finally:
|
||||
if self.context is None:
|
||||
_restore_context(context)
|
||||
self.deadlock_context.set(False)
|
||||
|
||||
return ret
|
||||
|
||||
def __get__(
|
||||
self, parent: Any, objtype: Any
|
||||
) -> Callable[_P, Coroutine[Any, Any, _R]]:
|
||||
"""
|
||||
Include self for methods
|
||||
"""
|
||||
func = functools.partial(self.__call__, parent)
|
||||
return functools.update_wrapper(func, self.func)
|
||||
|
||||
def thread_handler(self, loop, exc_info, task_context, func, *args, **kwargs):
|
||||
"""
|
||||
Wraps the sync application with exception handling.
|
||||
"""
|
||||
|
||||
__traceback_hide__ = True # noqa: F841
|
||||
|
||||
# Set the threadlocal for AsyncToSync
|
||||
self.threadlocal.main_event_loop = loop
|
||||
self.threadlocal.main_event_loop_pid = os.getpid()
|
||||
self.threadlocal.task_context = task_context
|
||||
|
||||
# Run the function
|
||||
# If we have an exception, run the function inside the except block
|
||||
# after raising it so exc_info is correctly populated.
|
||||
if exc_info[1]:
|
||||
try:
|
||||
raise exc_info[1]
|
||||
except BaseException:
|
||||
return func(*args, **kwargs)
|
||||
else:
|
||||
return func(*args, **kwargs)
|
||||
|
||||
|
||||
@overload
|
||||
def async_to_sync(
|
||||
*,
|
||||
force_new_loop: bool = False,
|
||||
) -> Callable[
|
||||
[Callable[_P, Coroutine[Any, Any, _R]] | Callable[_P, Awaitable[_R]]],
|
||||
Callable[_P, _R],
|
||||
]: ...
|
||||
|
||||
|
||||
@overload
|
||||
def async_to_sync(
|
||||
awaitable: Callable[_P, Coroutine[Any, Any, _R]] | Callable[_P, Awaitable[_R]],
|
||||
*,
|
||||
force_new_loop: bool = False,
|
||||
) -> Callable[_P, _R]: ...
|
||||
|
||||
|
||||
def async_to_sync(
|
||||
awaitable: None | (
|
||||
Callable[_P, Coroutine[Any, Any, _R]] | Callable[_P, Awaitable[_R]]
|
||||
) = None,
|
||||
*,
|
||||
force_new_loop: bool = False,
|
||||
) -> (
|
||||
Callable[
|
||||
[Callable[_P, Coroutine[Any, Any, _R]] | Callable[_P, Awaitable[_R]]],
|
||||
Callable[_P, _R],
|
||||
]
|
||||
| Callable[_P, _R]
|
||||
):
|
||||
if awaitable is None:
|
||||
return lambda f: AsyncToSync(
|
||||
f,
|
||||
force_new_loop=force_new_loop,
|
||||
)
|
||||
return AsyncToSync(
|
||||
awaitable,
|
||||
force_new_loop=force_new_loop,
|
||||
)
|
||||
|
||||
|
||||
@overload
|
||||
def sync_to_async(
|
||||
*,
|
||||
thread_sensitive: bool = True,
|
||||
executor: Optional["ThreadPoolExecutor"] = None,
|
||||
context: contextvars.Context | None = None,
|
||||
) -> Callable[[Callable[_P, _R]], Callable[_P, Coroutine[Any, Any, _R]]]: ...
|
||||
|
||||
|
||||
@overload
|
||||
def sync_to_async(
|
||||
func: Callable[_P, _R],
|
||||
*,
|
||||
thread_sensitive: bool = True,
|
||||
executor: Optional["ThreadPoolExecutor"] = None,
|
||||
context: contextvars.Context | None = None,
|
||||
) -> Callable[_P, Coroutine[Any, Any, _R]]: ...
|
||||
|
||||
|
||||
def sync_to_async(
|
||||
func: Callable[_P, _R] | None = None,
|
||||
*,
|
||||
thread_sensitive: bool = True,
|
||||
executor: Optional["ThreadPoolExecutor"] = None,
|
||||
context: contextvars.Context | None = None,
|
||||
) -> (
|
||||
Callable[[Callable[_P, _R]], Callable[_P, Coroutine[Any, Any, _R]]]
|
||||
| Callable[_P, Coroutine[Any, Any, _R]]
|
||||
):
|
||||
if func is None:
|
||||
return lambda f: SyncToAsync(
|
||||
f,
|
||||
thread_sensitive=thread_sensitive,
|
||||
executor=executor,
|
||||
context=context,
|
||||
)
|
||||
return SyncToAsync(
|
||||
func,
|
||||
thread_sensitive=thread_sensitive,
|
||||
executor=executor,
|
||||
context=context,
|
||||
)
|
||||
@@ -0,0 +1,137 @@
|
||||
import asyncio
|
||||
import contextvars
|
||||
import time
|
||||
|
||||
from .compatibility import guarantee_single_callable
|
||||
from .timeout import timeout as async_timeout
|
||||
|
||||
|
||||
class ApplicationCommunicator:
|
||||
"""
|
||||
Runs an ASGI application in a test mode, allowing sending of
|
||||
messages to it and retrieval of messages it sends.
|
||||
"""
|
||||
|
||||
def __init__(self, application, scope):
|
||||
self._future = None
|
||||
self.application = guarantee_single_callable(application)
|
||||
self.scope = scope
|
||||
self._input_queue = None
|
||||
self._output_queue = None
|
||||
|
||||
# For Python 3.9 we need to lazily bind the queues, on 3.10+ they bind the
|
||||
# event loop lazily.
|
||||
@property
|
||||
def input_queue(self):
|
||||
if self._input_queue is None:
|
||||
self._input_queue = asyncio.Queue()
|
||||
return self._input_queue
|
||||
|
||||
@property
|
||||
def output_queue(self):
|
||||
if self._output_queue is None:
|
||||
self._output_queue = asyncio.Queue()
|
||||
return self._output_queue
|
||||
|
||||
@property
|
||||
def future(self):
|
||||
if self._future is None:
|
||||
# Clear context - this ensures that context vars set in the testing scope
|
||||
# are not "leaked" into the application which would normally begin with
|
||||
# an empty context. In Python >= 3.11 this could also be written as:
|
||||
# asyncio.create_task(..., context=contextvars.Context())
|
||||
self._future = contextvars.Context().run(
|
||||
asyncio.create_task,
|
||||
self.application(
|
||||
self.scope, self.input_queue.get, self.output_queue.put
|
||||
),
|
||||
)
|
||||
return self._future
|
||||
|
||||
async def wait(self, timeout=1):
|
||||
"""
|
||||
Waits for the application to stop itself and returns any exceptions.
|
||||
"""
|
||||
try:
|
||||
async with async_timeout(timeout):
|
||||
try:
|
||||
await self.future
|
||||
self.future.result()
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
finally:
|
||||
if not self.future.done():
|
||||
self.future.cancel()
|
||||
try:
|
||||
await self.future
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
def stop(self, exceptions=True):
|
||||
future = self._future
|
||||
if future is None:
|
||||
return
|
||||
|
||||
if not future.done():
|
||||
future.cancel()
|
||||
elif exceptions:
|
||||
# Give a chance to raise any exceptions
|
||||
future.result()
|
||||
|
||||
def __del__(self):
|
||||
# Clean up on deletion
|
||||
try:
|
||||
self.stop(exceptions=False)
|
||||
except RuntimeError:
|
||||
# Event loop already stopped
|
||||
pass
|
||||
|
||||
async def send_input(self, message):
|
||||
"""
|
||||
Sends a single message to the application
|
||||
"""
|
||||
# Make sure there's not an exception to raise from the task
|
||||
if self.future.done():
|
||||
self.future.result()
|
||||
|
||||
# Give it the message
|
||||
await self.input_queue.put(message)
|
||||
|
||||
async def receive_output(self, timeout=1):
|
||||
"""
|
||||
Receives a single message from the application, with optional timeout.
|
||||
"""
|
||||
# Make sure there's not an exception to raise from the task
|
||||
if self.future.done():
|
||||
self.future.result()
|
||||
# Wait and receive the message
|
||||
try:
|
||||
async with async_timeout(timeout):
|
||||
return await self.output_queue.get()
|
||||
except asyncio.TimeoutError as e:
|
||||
# See if we have another error to raise inside
|
||||
if self.future.done():
|
||||
self.future.result()
|
||||
else:
|
||||
self.future.cancel()
|
||||
try:
|
||||
await self.future
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
raise e
|
||||
|
||||
async def receive_nothing(self, timeout=0.1, interval=0.01):
|
||||
"""
|
||||
Checks that there is no message to receive in the given time.
|
||||
"""
|
||||
# Make sure there's not an exception to raise from the task
|
||||
if self.future.done():
|
||||
self.future.result()
|
||||
|
||||
# `interval` has precedence over `timeout`
|
||||
start = time.monotonic()
|
||||
while time.monotonic() - start < timeout:
|
||||
if not self.output_queue.empty():
|
||||
return False
|
||||
await asyncio.sleep(interval)
|
||||
return self.output_queue.empty()
|
||||
@@ -0,0 +1,118 @@
|
||||
# This code is originally sourced from the aio-libs project "async_timeout",
|
||||
# under the Apache 2.0 license. You may see the original project at
|
||||
# https://github.com/aio-libs/async-timeout
|
||||
|
||||
# It is vendored here to reduce chain-dependencies on this library, and
|
||||
# modified slightly to remove some features we don't use.
|
||||
|
||||
|
||||
import asyncio
|
||||
import warnings
|
||||
from types import TracebackType
|
||||
from typing import Any # noqa
|
||||
from typing import Optional # noqa
|
||||
|
||||
|
||||
class timeout:
|
||||
"""timeout context manager.
|
||||
|
||||
Useful in cases when you want to apply timeout logic around block
|
||||
of code or in cases when asyncio.wait_for is not suitable. For example:
|
||||
|
||||
>>> with timeout(0.001):
|
||||
... async with aiohttp.get('https://github.com') as r:
|
||||
... await r.text()
|
||||
|
||||
|
||||
timeout - value in seconds or None to disable timeout logic
|
||||
loop - asyncio compatible event loop
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
timeout: float | None,
|
||||
*,
|
||||
loop: asyncio.AbstractEventLoop | None = None,
|
||||
) -> None:
|
||||
self._timeout = timeout
|
||||
if loop is None:
|
||||
loop = asyncio.get_running_loop()
|
||||
else:
|
||||
warnings.warn(
|
||||
"""The loop argument to timeout() is deprecated.""", DeprecationWarning
|
||||
)
|
||||
self._loop = loop
|
||||
self._task = None # type: Optional[asyncio.Task[Any]]
|
||||
self._cancelled = False
|
||||
self._cancel_handler = None # type: Optional[asyncio.Handle]
|
||||
self._cancel_at = None # type: Optional[float]
|
||||
|
||||
def __enter__(self) -> "timeout":
|
||||
return self._do_enter()
|
||||
|
||||
def __exit__(
|
||||
self,
|
||||
exc_type: type[BaseException],
|
||||
exc_val: BaseException,
|
||||
exc_tb: TracebackType,
|
||||
) -> bool | None:
|
||||
self._do_exit(exc_type)
|
||||
return None
|
||||
|
||||
async def __aenter__(self) -> "timeout":
|
||||
return self._do_enter()
|
||||
|
||||
async def __aexit__(
|
||||
self,
|
||||
exc_type: type[BaseException],
|
||||
exc_val: BaseException,
|
||||
exc_tb: TracebackType,
|
||||
) -> None:
|
||||
self._do_exit(exc_type)
|
||||
|
||||
@property
|
||||
def expired(self) -> bool:
|
||||
return self._cancelled
|
||||
|
||||
@property
|
||||
def remaining(self) -> float | None:
|
||||
if self._cancel_at is not None:
|
||||
return max(self._cancel_at - self._loop.time(), 0.0)
|
||||
else:
|
||||
return None
|
||||
|
||||
def _do_enter(self) -> "timeout":
|
||||
# Support Tornado 5- without timeout
|
||||
# Details: https://github.com/python/asyncio/issues/392
|
||||
if self._timeout is None:
|
||||
return self
|
||||
|
||||
self._task = asyncio.current_task(self._loop)
|
||||
if self._task is None:
|
||||
raise RuntimeError(
|
||||
"Timeout context manager should be used " "inside a task"
|
||||
)
|
||||
|
||||
if self._timeout <= 0:
|
||||
self._loop.call_soon(self._cancel_task)
|
||||
return self
|
||||
|
||||
self._cancel_at = self._loop.time() + self._timeout
|
||||
self._cancel_handler = self._loop.call_at(self._cancel_at, self._cancel_task)
|
||||
return self
|
||||
|
||||
def _do_exit(self, exc_type: type[BaseException]) -> None:
|
||||
if exc_type is asyncio.CancelledError and self._cancelled:
|
||||
self._cancel_handler = None
|
||||
self._task = None
|
||||
raise asyncio.TimeoutError
|
||||
if self._timeout is not None and self._cancel_handler is not None:
|
||||
self._cancel_handler.cancel()
|
||||
self._cancel_handler = None
|
||||
self._task = None
|
||||
return None
|
||||
|
||||
def _cancel_task(self) -> None:
|
||||
if self._task is not None:
|
||||
self._task.cancel()
|
||||
self._cancelled = True
|
||||
@@ -0,0 +1,267 @@
|
||||
import sys
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
from typing import Any, Literal, Protocol, TypedDict, Union
|
||||
|
||||
if sys.version_info >= (3, 11):
|
||||
from typing import NotRequired
|
||||
else:
|
||||
from typing_extensions import NotRequired
|
||||
|
||||
__all__ = (
|
||||
"ASGIVersions",
|
||||
"HTTPScope",
|
||||
"WebSocketScope",
|
||||
"LifespanScope",
|
||||
"WWWScope",
|
||||
"Scope",
|
||||
"HTTPRequestEvent",
|
||||
"HTTPResponseStartEvent",
|
||||
"HTTPResponseBodyEvent",
|
||||
"HTTPResponseTrailersEvent",
|
||||
"HTTPResponsePathsendEvent",
|
||||
"HTTPServerPushEvent",
|
||||
"HTTPDisconnectEvent",
|
||||
"WebSocketConnectEvent",
|
||||
"WebSocketAcceptEvent",
|
||||
"WebSocketReceiveEvent",
|
||||
"WebSocketSendEvent",
|
||||
"WebSocketResponseStartEvent",
|
||||
"WebSocketResponseBodyEvent",
|
||||
"WebSocketDisconnectEvent",
|
||||
"WebSocketCloseEvent",
|
||||
"LifespanStartupEvent",
|
||||
"LifespanShutdownEvent",
|
||||
"LifespanStartupCompleteEvent",
|
||||
"LifespanStartupFailedEvent",
|
||||
"LifespanShutdownCompleteEvent",
|
||||
"LifespanShutdownFailedEvent",
|
||||
"ASGIReceiveEvent",
|
||||
"ASGISendEvent",
|
||||
"ASGIReceiveCallable",
|
||||
"ASGISendCallable",
|
||||
"ASGI2Protocol",
|
||||
"ASGI2Application",
|
||||
"ASGI3Application",
|
||||
"ASGIApplication",
|
||||
)
|
||||
|
||||
|
||||
class ASGIVersions(TypedDict):
|
||||
spec_version: str
|
||||
version: Literal["2.0"] | Literal["3.0"]
|
||||
|
||||
|
||||
class HTTPScope(TypedDict):
|
||||
type: Literal["http"]
|
||||
asgi: ASGIVersions
|
||||
http_version: str
|
||||
method: str
|
||||
scheme: str
|
||||
path: str
|
||||
raw_path: bytes
|
||||
query_string: bytes
|
||||
root_path: str
|
||||
headers: Iterable[tuple[bytes, bytes]]
|
||||
client: tuple[str, int] | None
|
||||
server: tuple[str, int | None] | None
|
||||
state: NotRequired[dict[str, Any]]
|
||||
extensions: dict[str, dict[object, object]] | None
|
||||
|
||||
|
||||
class WebSocketScope(TypedDict):
|
||||
type: Literal["websocket"]
|
||||
asgi: ASGIVersions
|
||||
http_version: str
|
||||
scheme: str
|
||||
path: str
|
||||
raw_path: bytes
|
||||
query_string: bytes
|
||||
root_path: str
|
||||
headers: Iterable[tuple[bytes, bytes]]
|
||||
client: tuple[str, int] | None
|
||||
server: tuple[str, int | None] | None
|
||||
subprotocols: Iterable[str]
|
||||
state: NotRequired[dict[str, Any]]
|
||||
extensions: dict[str, dict[object, object]] | None
|
||||
|
||||
|
||||
class LifespanScope(TypedDict):
|
||||
type: Literal["lifespan"]
|
||||
asgi: ASGIVersions
|
||||
state: NotRequired[dict[str, Any]]
|
||||
|
||||
|
||||
WWWScope = Union[HTTPScope, WebSocketScope]
|
||||
Scope = Union[HTTPScope, WebSocketScope, LifespanScope]
|
||||
|
||||
|
||||
class HTTPRequestEvent(TypedDict):
|
||||
type: Literal["http.request"]
|
||||
body: bytes
|
||||
more_body: bool
|
||||
|
||||
|
||||
class HTTPResponseDebugEvent(TypedDict):
|
||||
type: Literal["http.response.debug"]
|
||||
info: dict[str, object]
|
||||
|
||||
|
||||
class HTTPResponseStartEvent(TypedDict):
|
||||
type: Literal["http.response.start"]
|
||||
status: int
|
||||
headers: Iterable[tuple[bytes, bytes]]
|
||||
trailers: bool
|
||||
|
||||
|
||||
class HTTPResponseBodyEvent(TypedDict):
|
||||
type: Literal["http.response.body"]
|
||||
body: bytes
|
||||
more_body: bool
|
||||
|
||||
|
||||
class HTTPResponseTrailersEvent(TypedDict):
|
||||
type: Literal["http.response.trailers"]
|
||||
headers: Iterable[tuple[bytes, bytes]]
|
||||
more_trailers: bool
|
||||
|
||||
|
||||
class HTTPResponsePathsendEvent(TypedDict):
|
||||
type: Literal["http.response.pathsend"]
|
||||
path: str
|
||||
|
||||
|
||||
class HTTPServerPushEvent(TypedDict):
|
||||
type: Literal["http.response.push"]
|
||||
path: str
|
||||
headers: Iterable[tuple[bytes, bytes]]
|
||||
|
||||
|
||||
class HTTPDisconnectEvent(TypedDict):
|
||||
type: Literal["http.disconnect"]
|
||||
|
||||
|
||||
class WebSocketConnectEvent(TypedDict):
|
||||
type: Literal["websocket.connect"]
|
||||
|
||||
|
||||
class WebSocketAcceptEvent(TypedDict):
|
||||
type: Literal["websocket.accept"]
|
||||
subprotocol: str | None
|
||||
headers: Iterable[tuple[bytes, bytes]]
|
||||
|
||||
|
||||
class WebSocketReceiveEvent(TypedDict):
|
||||
type: Literal["websocket.receive"]
|
||||
bytes: bytes | None
|
||||
text: str | None
|
||||
|
||||
|
||||
class WebSocketSendEvent(TypedDict):
|
||||
type: Literal["websocket.send"]
|
||||
bytes: bytes | None
|
||||
text: str | None
|
||||
|
||||
|
||||
class WebSocketResponseStartEvent(TypedDict):
|
||||
type: Literal["websocket.http.response.start"]
|
||||
status: int
|
||||
headers: Iterable[tuple[bytes, bytes]]
|
||||
|
||||
|
||||
class WebSocketResponseBodyEvent(TypedDict):
|
||||
type: Literal["websocket.http.response.body"]
|
||||
body: bytes
|
||||
more_body: bool
|
||||
|
||||
|
||||
class WebSocketDisconnectEvent(TypedDict):
|
||||
type: Literal["websocket.disconnect"]
|
||||
code: int
|
||||
reason: str | None
|
||||
|
||||
|
||||
class WebSocketCloseEvent(TypedDict):
|
||||
type: Literal["websocket.close"]
|
||||
code: int
|
||||
reason: str | None
|
||||
|
||||
|
||||
class LifespanStartupEvent(TypedDict):
|
||||
type: Literal["lifespan.startup"]
|
||||
|
||||
|
||||
class LifespanShutdownEvent(TypedDict):
|
||||
type: Literal["lifespan.shutdown"]
|
||||
|
||||
|
||||
class LifespanStartupCompleteEvent(TypedDict):
|
||||
type: Literal["lifespan.startup.complete"]
|
||||
|
||||
|
||||
class LifespanStartupFailedEvent(TypedDict):
|
||||
type: Literal["lifespan.startup.failed"]
|
||||
message: str
|
||||
|
||||
|
||||
class LifespanShutdownCompleteEvent(TypedDict):
|
||||
type: Literal["lifespan.shutdown.complete"]
|
||||
|
||||
|
||||
class LifespanShutdownFailedEvent(TypedDict):
|
||||
type: Literal["lifespan.shutdown.failed"]
|
||||
message: str
|
||||
|
||||
|
||||
ASGIReceiveEvent = Union[
|
||||
HTTPRequestEvent,
|
||||
HTTPDisconnectEvent,
|
||||
WebSocketConnectEvent,
|
||||
WebSocketReceiveEvent,
|
||||
WebSocketDisconnectEvent,
|
||||
LifespanStartupEvent,
|
||||
LifespanShutdownEvent,
|
||||
]
|
||||
|
||||
|
||||
ASGISendEvent = Union[
|
||||
HTTPResponseStartEvent,
|
||||
HTTPResponseBodyEvent,
|
||||
HTTPResponseTrailersEvent,
|
||||
HTTPServerPushEvent,
|
||||
HTTPDisconnectEvent,
|
||||
WebSocketAcceptEvent,
|
||||
WebSocketSendEvent,
|
||||
WebSocketResponseStartEvent,
|
||||
WebSocketResponseBodyEvent,
|
||||
WebSocketCloseEvent,
|
||||
LifespanStartupCompleteEvent,
|
||||
LifespanStartupFailedEvent,
|
||||
LifespanShutdownCompleteEvent,
|
||||
LifespanShutdownFailedEvent,
|
||||
]
|
||||
|
||||
|
||||
ASGIReceiveCallable = Callable[[], Awaitable[ASGIReceiveEvent]]
|
||||
ASGISendCallable = Callable[[ASGISendEvent], Awaitable[None]]
|
||||
|
||||
|
||||
class ASGI2Protocol(Protocol):
|
||||
def __init__(self, scope: Scope) -> None: ...
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
receive: ASGIReceiveCallable,
|
||||
send: ASGISendCallable,
|
||||
) -> None: ...
|
||||
|
||||
|
||||
ASGI2Application = type[ASGI2Protocol]
|
||||
ASGI3Application = Callable[
|
||||
[
|
||||
Scope,
|
||||
ASGIReceiveCallable,
|
||||
ASGISendCallable,
|
||||
],
|
||||
Awaitable[None],
|
||||
]
|
||||
ASGIApplication = Union[ASGI2Application, ASGI3Application]
|
||||
@@ -0,0 +1,197 @@
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from tempfile import SpooledTemporaryFile
|
||||
|
||||
from asgiref.sync import AsyncToSync, sync_to_async
|
||||
|
||||
|
||||
class WsgiToAsgi:
|
||||
"""
|
||||
Wraps a WSGI application to make it into an ASGI application.
|
||||
"""
|
||||
|
||||
def __init__(self, wsgi_application, duplicate_header_limit=100):
|
||||
self.wsgi_application = wsgi_application
|
||||
self.duplicate_header_limit = duplicate_header_limit
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
"""
|
||||
ASGI application instantiation point.
|
||||
We return a new WsgiToAsgiInstance here with the WSGI app
|
||||
and the scope, ready to respond when it is __call__ed.
|
||||
"""
|
||||
await WsgiToAsgiInstance(self.wsgi_application, self.duplicate_header_limit)(
|
||||
scope, receive, send
|
||||
)
|
||||
|
||||
|
||||
class WsgiToAsgiInstance:
|
||||
"""
|
||||
Per-socket instance of a wrapped WSGI application
|
||||
"""
|
||||
|
||||
def __init__(self, wsgi_application, duplicate_header_limit=100):
|
||||
self.wsgi_application = wsgi_application
|
||||
self.duplicate_header_limit = duplicate_header_limit
|
||||
self.response_started = False
|
||||
self.response_content_length = None
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
raise ValueError("WSGI wrapper received a non-HTTP scope")
|
||||
self.scope = scope
|
||||
with SpooledTemporaryFile(max_size=65536) as body:
|
||||
# Alright, wait for the http.request messages
|
||||
while True:
|
||||
message = await receive()
|
||||
if message["type"] != "http.request":
|
||||
raise ValueError("WSGI wrapper received a non-HTTP-request message")
|
||||
body.write(message.get("body", b""))
|
||||
if not message.get("more_body"):
|
||||
break
|
||||
body.seek(0)
|
||||
# Wrap send so it can be called from the subthread
|
||||
self.sync_send = AsyncToSync(send)
|
||||
# Call the WSGI app
|
||||
await self.run_wsgi_app(body)
|
||||
|
||||
def build_environ(self, scope, body):
|
||||
"""
|
||||
Builds a scope and request body into a WSGI environ object.
|
||||
"""
|
||||
script_name = scope.get("root_path", "").encode("utf8").decode("latin1")
|
||||
path_info = scope["path"].encode("utf8").decode("latin1")
|
||||
if path_info.startswith(script_name):
|
||||
path_info = path_info[len(script_name) :]
|
||||
environ = {
|
||||
"REQUEST_METHOD": scope["method"],
|
||||
"SCRIPT_NAME": script_name,
|
||||
"PATH_INFO": path_info,
|
||||
"QUERY_STRING": scope["query_string"].decode("ascii"),
|
||||
"SERVER_PROTOCOL": "HTTP/%s" % scope["http_version"],
|
||||
"wsgi.version": (1, 0),
|
||||
"wsgi.url_scheme": scope.get("scheme", "http"),
|
||||
"wsgi.input": body,
|
||||
"wsgi.errors": sys.stderr,
|
||||
"wsgi.multithread": True,
|
||||
"wsgi.multiprocess": True,
|
||||
"wsgi.run_once": False,
|
||||
}
|
||||
# Get server name and port - required in WSGI, not in ASGI
|
||||
if "server" in scope:
|
||||
environ["SERVER_NAME"] = scope["server"][0]
|
||||
environ["SERVER_PORT"] = str(scope["server"][1])
|
||||
else:
|
||||
environ["SERVER_NAME"] = "localhost"
|
||||
environ["SERVER_PORT"] = "80"
|
||||
|
||||
if scope.get("client") is not None:
|
||||
environ["REMOTE_ADDR"] = scope["client"][0]
|
||||
|
||||
# Go through headers and make them into environ entries
|
||||
_headers = defaultdict(list)
|
||||
for name, value in self.scope.get("headers", []):
|
||||
name = name.decode("latin1")
|
||||
if name == "content-length":
|
||||
corrected_name = "CONTENT_LENGTH"
|
||||
elif name == "content-type":
|
||||
corrected_name = "CONTENT_TYPE"
|
||||
else:
|
||||
corrected_name = "HTTP_%s" % name.upper().replace("-", "_")
|
||||
# HTTPbis say only ASCII chars are allowed in headers, but we latin1 just in case
|
||||
value = value.decode("latin1")
|
||||
if (
|
||||
self.duplicate_header_limit
|
||||
and len(_headers[corrected_name]) >= self.duplicate_header_limit
|
||||
):
|
||||
raise ValueError(
|
||||
f"Too many duplicate headers: {corrected_name} exceeds limit of"
|
||||
f"{self.duplicate_header_limit}"
|
||||
)
|
||||
_headers[corrected_name].append(value)
|
||||
for name, values in _headers.items():
|
||||
environ[name] = ",".join(values)
|
||||
return environ
|
||||
|
||||
def start_response(self, status, response_headers, exc_info=None):
|
||||
"""
|
||||
WSGI start_response callable.
|
||||
"""
|
||||
# Don't allow re-calling once response has begun
|
||||
if self.response_started:
|
||||
raise exc_info[1].with_traceback(exc_info[2])
|
||||
# Don't allow re-calling without exc_info
|
||||
if hasattr(self, "response_start") and exc_info is None:
|
||||
raise ValueError(
|
||||
"You cannot call start_response a second time without exc_info"
|
||||
)
|
||||
# Extract status code
|
||||
status_code, _ = status.split(" ", 1)
|
||||
status_code = int(status_code)
|
||||
# Extract headers
|
||||
headers = [
|
||||
(name.lower().encode("ascii"), value.encode("ascii"))
|
||||
for name, value in response_headers
|
||||
]
|
||||
# Extract content-length
|
||||
self.response_content_length = None
|
||||
for name, value in response_headers:
|
||||
if name.lower() == "content-length":
|
||||
self.response_content_length = int(value)
|
||||
# Build and send response start message.
|
||||
self.response_start = {
|
||||
"type": "http.response.start",
|
||||
"status": status_code,
|
||||
"headers": headers,
|
||||
}
|
||||
|
||||
@sync_to_async
|
||||
def run_wsgi_app(self, body):
|
||||
"""
|
||||
Called in a subthread to run the WSGI app. We encapsulate like
|
||||
this so that the start_response callable is called in the same thread.
|
||||
"""
|
||||
# Translate the scope and incoming request body into a WSGI environ
|
||||
try:
|
||||
environ = self.build_environ(self.scope, body)
|
||||
except ValueError:
|
||||
# Return 400 Bad Request if header limit exceeded
|
||||
self.sync_send(
|
||||
{
|
||||
"type": "http.response.start",
|
||||
"status": 400,
|
||||
"headers": [(b"content-type", b"text/plain")],
|
||||
}
|
||||
)
|
||||
self.sync_send(
|
||||
{
|
||||
"type": "http.response.body",
|
||||
"body": b"Bad Request: Too many duplicate headers",
|
||||
}
|
||||
)
|
||||
return
|
||||
# Run the WSGI app
|
||||
bytes_sent = 0
|
||||
for output in self.wsgi_application(environ, self.start_response):
|
||||
# If this is the first response, include the response headers
|
||||
if not self.response_started:
|
||||
self.response_started = True
|
||||
self.sync_send(self.response_start)
|
||||
# If the application supplies a Content-Length header
|
||||
if self.response_content_length is not None:
|
||||
# The server should not transmit more bytes to the client than the header allows
|
||||
bytes_allowed = self.response_content_length - bytes_sent
|
||||
if len(output) > bytes_allowed:
|
||||
output = output[:bytes_allowed]
|
||||
self.sync_send(
|
||||
{"type": "http.response.body", "body": output, "more_body": True}
|
||||
)
|
||||
bytes_sent += len(output)
|
||||
# The server should stop iterating over the response when enough data has been sent
|
||||
if bytes_sent == self.response_content_length:
|
||||
break
|
||||
# Close connection
|
||||
if not self.response_started:
|
||||
self.response_started = True
|
||||
self.sync_send(self.response_start)
|
||||
self.sync_send({"type": "http.response.body"})
|
||||
@@ -0,0 +1 @@
|
||||
pip
|
||||
@@ -0,0 +1,94 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: Django
|
||||
Version: 6.1.1
|
||||
Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design.
|
||||
Author-email: Django Software Foundation <foundation@djangoproject.com>
|
||||
License-Expression: BSD-3-Clause
|
||||
Project-URL: Homepage, https://www.djangoproject.com/
|
||||
Project-URL: Documentation, https://docs.djangoproject.com/
|
||||
Project-URL: Release notes, https://docs.djangoproject.com/en/stable/releases/
|
||||
Project-URL: Funding, https://www.djangoproject.com/fundraising/
|
||||
Project-URL: Source, https://github.com/django/django
|
||||
Project-URL: Tracker, https://code.djangoproject.com/
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Environment :: Web Environment
|
||||
Classifier: Framework :: Django
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3 :: Only
|
||||
Classifier: Programming Language :: Python :: 3.12
|
||||
Classifier: Programming Language :: Python :: 3.13
|
||||
Classifier: Programming Language :: Python :: 3.14
|
||||
Classifier: Topic :: Internet :: WWW/HTTP
|
||||
Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
|
||||
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI
|
||||
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Requires-Python: >=3.12
|
||||
Description-Content-Type: text/x-rst
|
||||
License-File: LICENSE
|
||||
License-File: LICENSE.python
|
||||
License-File: AUTHORS
|
||||
Requires-Dist: asgiref>=3.9.1
|
||||
Requires-Dist: sqlparse>=0.5.0
|
||||
Requires-Dist: tzdata; sys_platform == "win32"
|
||||
Provides-Extra: argon2
|
||||
Requires-Dist: argon2-cffi>=23.1.0; extra == "argon2"
|
||||
Provides-Extra: bcrypt
|
||||
Requires-Dist: bcrypt>=4.1.1; extra == "bcrypt"
|
||||
Dynamic: license-file
|
||||
|
||||
======
|
||||
Django
|
||||
======
|
||||
|
||||
Django is a high-level Python web framework that encourages rapid development
|
||||
and clean, pragmatic design. Thanks for checking it out.
|
||||
|
||||
All documentation is in the "``docs``" directory and online at
|
||||
https://docs.djangoproject.com/en/stable/. If you're just getting started,
|
||||
here's how we recommend you read the docs:
|
||||
|
||||
* First, read ``docs/intro/install.txt`` for instructions on installing Django.
|
||||
|
||||
* Next, work through the tutorials in order (``docs/intro/tutorial01.txt``,
|
||||
``docs/intro/tutorial02.txt``, etc.).
|
||||
|
||||
* If you want to set up an actual deployment server, read
|
||||
``docs/howto/deployment/index.txt`` for instructions.
|
||||
|
||||
* You'll probably want to read through the topical guides (in ``docs/topics``)
|
||||
next; from there you can jump to the HOWTOs (in ``docs/howto``) for specific
|
||||
problems, and check out the reference (``docs/ref``) for gory details.
|
||||
|
||||
* See ``docs/README`` for instructions on building an HTML version of the docs.
|
||||
|
||||
Docs are updated rigorously. If you find any problems in the docs, or think
|
||||
they should be clarified in any way, please take 30 seconds to fill out a
|
||||
ticket here: https://code.djangoproject.com/newticket
|
||||
|
||||
To get more help:
|
||||
|
||||
* Join the `Django Discord community <https://chat.djangoproject.com>`_.
|
||||
|
||||
* Join the community on the `Django Forum <https://forum.djangoproject.com/>`_.
|
||||
|
||||
To contribute to Django:
|
||||
|
||||
* Check out https://docs.djangoproject.com/en/dev/internals/contributing/ for
|
||||
information about getting involved.
|
||||
|
||||
To run Django's test suite:
|
||||
|
||||
* Follow the instructions in the "Unit tests" section of
|
||||
``docs/internals/contributing/writing-code/unit-tests.txt``, published online at
|
||||
https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/#running-the-unit-tests
|
||||
|
||||
Supporting the Development of Django
|
||||
====================================
|
||||
|
||||
Django's development depends on your contributions.
|
||||
|
||||
If you depend on Django, remember to support the Django Software Foundation: https://www.djangoproject.com/fundraising/
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user