latest changes

This commit is contained in:
Joren de Graaf
2026-10-22 10:24:33 +02:00
parent 9a5210a48f
commit 3a12d56f8b
33 changed files with 1179 additions and 96 deletions
@@ -0,0 +1,30 @@
# Generated by Django 6.1.2 on 2026-10-22 01:16
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0006_documentationsync_projectdocument'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ProjectMoveKey',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.CharField(max_length=128)),
('payload_hash', models.CharField(max_length=64)),
('result', models.JSONField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'constraints': [models.UniqueConstraint(fields=('user', 'key'), name='unique_project_move_key')],
},
),
]
+11
View File
@@ -215,6 +215,17 @@ class BulkUpdateKey(models.Model):
constraints = [models.UniqueConstraint(fields=['user', 'key'], name='unique_bulk_update_key')]
class ProjectMoveKey(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
key = models.CharField(max_length=128)
payload_hash = models.CharField(max_length=64)
result = models.JSONField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
constraints = [models.UniqueConstraint(fields=['user', 'key'], name='unique_project_move_key')]
class Activity(models.Model):
project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='activity')
card = models.ForeignKey(Card, null=True, blank=True, on_delete=models.CASCADE, related_name='activity')
+96 -1
View File
@@ -8,7 +8,7 @@ from django.core.validators import URLValidator
from django.shortcuts import get_object_or_404
from django.utils import timezone
from django.utils.text import slugify
from .models import Activity, Board, BulkUpdateKey, Card, CardRevision, Column, CreationKey, Membership, Project, Tag
from .models import Activity, Board, BulkUpdateKey, Card, CardRevision, Column, CreationKey, Membership, Project, ProjectMoveKey, Tag
class RevisionConflict(Exception):
@@ -145,6 +145,101 @@ def move_card(user, card, column, position=None, origin='web', record_revision=T
return card
@transaction.atomic
def move_card_to_project(user, card, target_project, *, target_column=None, expected_revision,
idempotency_key=None, origin='web'):
"""Move a card between editable projects without replacing its identity or children."""
if idempotency_key:
if len(idempotency_key) > 128:
raise ValidationError('Idempotency key is too long.')
payload = json.dumps({'card': str(card.pk), 'target_project': str(target_project.pk),
'target_column': str(target_column.pk) if target_column else None,
'expected_revision': int(expected_revision)}, sort_keys=True)
payload_hash = hashlib.sha256(payload.encode()).hexdigest()
user.__class__.objects.select_for_update().get(pk=user.pk)
existing = ProjectMoveKey.objects.select_for_update().filter(user=user, key=idempotency_key).first()
if existing:
if existing.payload_hash != payload_hash:
raise ValidationError('Idempotency key was already used with different move details.')
current = Card.objects.select_for_update().select_related('project').get(pk=card.pk)
project_for(user, current.project_id, write=True)
if current.project_id != target_project.pk:
raise ValidationError('The original move is no longer available to replay.')
return current, existing.result
card = Card.objects.select_for_update().select_related('project', 'column').get(pk=card.pk)
source = project_for(user, card.project_id, write=True)
target_project = project_for(user, target_project.pk, write=True)
if source.pk == target_project.pk:
raise ValidationError('Choose a different project. Use the column move for this project.')
if source.archived or target_project.archived:
raise ValidationError('Cards cannot be moved from or into an archived project.')
if card.revision != int(expected_revision):
raise RevisionConflict(card.revision)
if target_column is None:
active_columns = target_project.board.columns.filter(archived=False)
target_column = active_columns.filter(is_default=True).first() or active_columns.first()
if (target_column is None or target_column.board_id != target_project.board.pk or target_column.archived):
raise ValidationError('Column is not available in the destination project.')
warnings = []
if card.assignee_id and card.assignee_id != target_project.owner_id and not Membership.objects.filter(project=target_project, user_id=card.assignee_id).exists():
warnings.append(f"Assignee {card.assignee.get_full_name() or card.assignee.username} was cleared because they do not have access to the destination project.")
card.assignee = None
old_tags = list(card.tags.all())
target_tags = list(Tag.objects.filter(project=target_project).order_by('pk'))
tags_by_name = {tag.name.casefold(): tag for tag in target_tags}
mapped_tags = []
for tag in old_tags:
match = tags_by_name.get(tag.name.casefold())
if match:
mapped_tags.append(match)
else:
warnings.append(f"Tag “{tag.name}” was cleared because it does not exist in the destination project.")
old_column_id = card.column_id
old_column_name = card.column.name
original_updated_at = card.updated_at
siblings = list(Card.objects.filter(column=target_column, archived=False).exclude(pk=card.pk).order_by('position', 'created_at'))
card.project = target_project
card.column = target_column
card.position = len(siblings)
card.completed_at = timezone.now() if target_column.is_done else None
card.revision += 1
card.full_clean()
card.save(update_fields=['project', 'column', 'position', 'completed_at', 'revision', 'assignee'])
card.updated_at = original_updated_at
card.tags.set(mapped_tags)
for index, sibling in enumerate(Card.objects.filter(column_id=old_column_id, archived=False).order_by('position', 'created_at')):
if sibling.position != index:
sibling.position = index
sibling.save(update_fields=['position'])
for index, sibling in enumerate(siblings):
if sibling.position != index:
sibling.position = index
sibling.save(update_fields=['position'])
# The card's prior activity follows its stable UUID into the destination.
Activity.objects.filter(card=card).update(project=target_project)
CardRevision.objects.create(card=card, revision=card.revision, markdown=card.description_markdown, actor=user)
detail = {'from_project': str(source.pk), 'from_column': str(old_column_id),
'from_column_name': old_column_name, 'to_project': str(target_project.pk),
'to_column': str(target_column.pk), 'to_column_name': target_column.name}
Activity.objects.create(project=source, actor=user, action='card.moved_project_out',
detail={'card_id': str(card.pk), 'title': card.title, **detail}, origin=origin)
Activity.objects.create(project=target_project, card=card, actor=user, action='card.moved_project',
detail=detail, origin=origin)
result = {'source_project_id': str(source.pk), 'source_project_name': source.name,
'source_column_id': str(old_column_id),
'target_project_id': str(target_project.pk), 'target_column_id': str(target_column.pk),
'target_project_name': target_project.name, 'target_column_name': target_column.name,
'revision': card.revision, 'url': f'/projects/cards/{card.pk}/', 'warnings': warnings}
if idempotency_key:
ProjectMoveKey.objects.create(user=user, key=idempotency_key, payload_hash=payload_hash, result=result)
return card, result
@transaction.atomic
def set_default(user, column):
project_for(user, column.board.project_id, write=True)
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
.project-card-messages{margin:0 0 1rem}.project-card-message{margin:0;padding:.8rem 1rem;border-radius:.7rem;background:var(--surface);color:var(--text);border:1px solid var(--border)}.project-card-message.success{border-color:var(--accent);background:color-mix(in srgb,var(--accent) 10%,var(--surface))}.project-card-message.error{border-color:var(--danger,#b42318)}.project-card-actions-menu .project-move-unavailable{display:block;padding:.65rem .8rem;color:var(--text-muted);font-size:.8rem}
+47
View File
@@ -0,0 +1,47 @@
(() => {
const dialog = document.querySelector('[data-project-move-dialog]');
if (!dialog || dialog.dataset.initialized) return;
dialog.dataset.initialized = 'true';
const projectSelect = dialog.querySelector('[data-move-project]');
const columnSelect = dialog.querySelector('[data-move-column]');
const confirmation = dialog.querySelector('[data-move-confirmation]');
const form = dialog.querySelector('[data-project-move-form]');
const opener = document.querySelector('[data-open-move-dialog]');
const source = document.querySelector('.project-card-heading .project-card-eyebrow')?.textContent.trim() || 'this project';
const update = () => {
if (!projectSelect || !columnSelect) return;
const selectedProject = projectSelect.selectedOptions[0];
const projectId = selectedProject.value;
const defaultId = selectedProject.dataset.defaultColumn;
const defaultName = selectedProject.dataset.defaultName;
for (const option of columnSelect.options) {
const visible = !option.dataset.projectId || option.dataset.projectId === projectId;
option.hidden = !visible;
option.disabled = !visible;
}
const requested = [...columnSelect.options].find(option => option.value === defaultId);
if (requested) columnSelect.value = requested.value;
else columnSelect.value = '';
const chosen = columnSelect.selectedOptions[0];
const columnName = chosen?.value ? chosen.textContent.split(' · ').slice(1).join(' · ').replace(/ \(default\)$/, '') : defaultName;
confirmation.textContent = `Move this card from ${source} to ${selectedProject.textContent} · ${columnName}? Its notes, files, and history will move with it.`;
};
opener?.addEventListener('click', () => {
update();
dialog.showModal();
});
dialog.querySelectorAll('[data-close-move-dialog]').forEach(button => button.addEventListener('click', () => dialog.close()));
dialog.addEventListener('close', () => opener?.focus());
projectSelect?.addEventListener('change', update);
columnSelect?.addEventListener('change', update);
form?.addEventListener('submit', () => {
const submit = form.querySelector('[data-move-submit]');
if (submit) {
submit.disabled = true;
submit.textContent = 'Moving…';
}
});
update();
})();
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -1,4 +1,4 @@
<div id="kanban-columns" class="d-flex gap-3 overflow-auto" style="min-height:20rem">
<div id="kanban-columns" class="d-flex gap-3 overflow-auto" style="min-height:20rem" aria-describedby="board-scroll-help">
{% for column in columns %}
<section class="card flex-shrink-0" style="width:19rem;border-top:4px solid {{ column.color }}" data-column-card="{{ column.id }}">
<div class="card-header d-flex justify-content-between align-items-center">
@@ -31,6 +31,7 @@
</div>
</article>
{% endfor %}
{% if not column.visible_cards %}<p class="project-column-empty">{% if show_archived %}No archived cards in this column.{% else %}No cards in this column yet.{% endif %}</p>{% endif %}
</div>
</section>
{% endfor %}
+11 -1
View File
@@ -1 +1,11 @@
<div class="row g-3">{% for project in projects %}<div class="col-md-6 col-xl-4"><div class="card h-100"><div class="card-body"><h2 class="h5"><a href="{% url 'projects:board' project.id %}">{{ project.name }}</a></h2><p>{{ project.description|truncatechars:180 }}</p><small>{{ project.card_count }} cards</small><div class="d-flex flex-wrap align-items-center gap-2 mt-3"><a class="btn btn-outline-primary btn-sm" href="{% url 'projects:docs_home' project.id %}">Browse documentation</a>{% if project.git_repository_url %}<a href="{{ project.git_repository_url }}" rel="noopener noreferrer">Repository</a>{% endif %}</div></div></div></div>{% empty %}<p>No projects found.</p>{% endfor %}</div>{% if page_obj.has_other_pages %}<nav aria-label="Project pages" class="mt-3">{% if page_obj.has_previous %}<a href="?{{ filters_query }}&page={{ page_obj.previous_page_number }}">Previous</a>{% endif %} <span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span> {% if page_obj.has_next %}<a href="?{{ filters_query }}&page={{ page_obj.next_page_number }}">Next</a>{% endif %}</nav>{% endif %}
{% if projects %}<div class="projects-card-grid" aria-label="{% if show_archived %}Archived projects{% else %}Active projects{% endif %}">
{% for project in projects %}<article class="project-index-card{% if project.archived %} is-archived{% endif %}">
<div class="project-index-card-top"><span class="project-index-icon" aria-hidden="true"><i class="bi bi-kanban"></i></span>{% if project.archived %}<span class="project-archived-badge"><i class="bi bi-archive" aria-hidden="true"></i> Archived</span>{% endif %}</div>
<h2><a href="{% url 'projects:board' project.id %}">{{ project.name }}</a></h2>
<p class="project-index-description">{{ project.description|default:'No project description yet.'|truncatechars:180 }}</p>
<div class="project-index-progress"><div class="project-index-progress-copy"><span>{{ project.done_card_count }} of {{ project.active_card_count }} active cards done</span><strong>{{ project.progress_percent }}%</strong></div><div class="project-index-progress-track" role="progressbar" aria-valuenow="{{ project.progress_percent }}" aria-valuemin="0" aria-valuemax="100" aria-label="{{ project.name }} completion"><span style="width:{{ project.progress_percent }}%"></span></div></div>
<div class="project-index-meta"><span><i class="bi bi-card-checklist" aria-hidden="true"></i>{{ project.card_count }} card{{ project.card_count|pluralize }}</span>{% if project.git_repository_url %}<a href="{{ project.git_repository_url }}" rel="noopener noreferrer"><i class="bi bi-github" aria-hidden="true"></i> Repository</a>{% endif %}</div>
<div class="project-index-actions"><a class="btn btn-success" href="{% url 'projects:board' project.id %}"><i class="bi bi-arrow-up-right" aria-hidden="true"></i> Open board</a><a class="btn btn-outline-secondary" href="{% url 'projects:docs_home' project.id %}"><i class="bi bi-journal-text" aria-hidden="true"></i><span class="visually-hidden">Browse documentation for {{ project.name }}</span><span aria-hidden="true">Docs</span></a></div>
</article>{% endfor %}
</div>{% else %}<div class="projects-empty-state"><span class="projects-empty-icon" aria-hidden="true"><i class="bi bi-kanban"></i></span><h2>{% if query %}No matching projects{% elif show_archived %}No archived projects{% else %}No projects yet{% endif %}</h2><p>{% if query %}Try a different project or card search.{% elif show_archived %}Archived projects will appear here.{% else %}Create a project to start organizing cards and specifications.{% endif %}</p>{% if not query and not show_archived %}<a class="btn btn-success" href="{% url 'projects:create' %}"><i class="bi bi-plus-lg" aria-hidden="true"></i> New project</a>{% endif %}</div>{% endif %}
{% if page_obj.has_other_pages %}<nav class="projects-pagination" aria-label="Project pages">{% if page_obj.has_previous %}<a class="btn btn-outline-secondary" href="?{% if filters_query %}{{ filters_query }}&amp;{% endif %}page={{ page_obj.previous_page_number }}"><i class="bi bi-arrow-left" aria-hidden="true"></i> Previous</a>{% else %}<span></span>{% endif %}<span>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</span>{% if page_obj.has_next %}<a class="btn btn-outline-secondary" href="?{% if filters_query %}{{ filters_query }}&amp;{% endif %}page={{ page_obj.next_page_number }}">Next <i class="bi bi-arrow-right" aria-hidden="true"></i></a>{% else %}<span></span>{% endif %}</nav>{% endif %}
+106 -53
View File
@@ -1,59 +1,112 @@
{% extends 'core/base.html' %}
{% load static %}
{% block extra_head %}<link rel="stylesheet" href="{% static 'projects/board_mobile.css' %}">{% endblock %}
{% block content %}
<style>.htmx-indicator{display:none}.htmx-request.htmx-indicator,.htmx-request .htmx-indicator{display:inline}</style>
<div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
<div><a href="{% url 'projects:list' %}">All projects</a><h1>{{ project.name }}</h1><p>{{ project.description }}</p>{% if project.git_repository_url %}<a href="{{ project.git_repository_url }}" rel="noopener noreferrer">Repository</a>{% endif %}<p class="mt-2 mb-0">{{ done_count }} of {{ total_count }} cards done</p></div>
<div class="d-flex flex-wrap align-items-center gap-2">
<a class="btn btn-primary" href="{% url 'projects:docs_home' project.id %}">Browse documentation</a>
{% if can_edit %}<a class="btn btn-outline-secondary" href="{% url 'projects:edit' project.id %}">Edit project</a>{% if project.archived %}<form class="d-inline" method="post" action="{% url 'projects:restore' project.id %}">{% csrf_token %}<button class="btn btn-outline-success">Restore project</button></form>{% else %}<form class="d-inline" method="post" action="{% url 'projects:archive' project.id %}">{% csrf_token %}<button class="btn btn-outline-danger">Archive project</button></form><a class="btn btn-success" href="{% url 'projects:card_create' project.id %}">New card</a>{% endif %}{% endif %}
</div>
<div class="project-board-page">
<header class="project-board-header">
<div class="project-board-heading">
<a class="project-back-link" href="{% url 'projects:list' %}"><i class="bi bi-arrow-left" aria-hidden="true"></i><span>All projects</span></a>
<div class="project-title-row"><div><h1>{{ project.name }}</h1>{% if project.git_repository_url %}<a class="project-repo-link" href="{{ project.git_repository_url }}" rel="noopener noreferrer"><i class="bi bi-github" aria-hidden="true"></i> Repository</a>{% endif %}</div>
{% if can_edit %}<details class="project-actions-menu"><summary aria-label="Project actions"><i class="bi bi-three-dots" aria-hidden="true"></i><span class="visually-hidden">Project actions</span></summary><div class="project-actions-popover"><a href="{% url 'projects:edit' project.id %}">Edit project</a>{% if project.archived %}<form method="post" action="{% url 'projects:restore' project.id %}">{% csrf_token %}<button type="submit">Restore project</button></form>{% else %}<form method="post" action="{% url 'projects:archive' project.id %}" onsubmit="return confirm('Archive this project?')">{% csrf_token %}<button type="submit" class="text-danger">Archive project</button></form>{% endif %}</div></details>{% endif %}
</div>
{% if project.description %}<p class="project-description">{{ project.description }}</p>{% endif %}
<div class="project-progress" aria-label="{{ done_count }} of {{ total_count }} cards complete"><div class="project-progress-copy"><strong>{{ done_count }} / {{ total_count }}</strong><span>cards complete</span></div><div class="project-progress-track" role="progressbar" aria-valuenow="{{ progress_percent }}" aria-valuemin="0" aria-valuemax="100" aria-label="Project completion"><span style="width:{{ progress_percent }}%"></span></div></div>
</div>
<div class="project-header-actions">{% if can_edit and not project.archived %}<a class="btn btn-success project-new-card" href="{% url 'projects:card_create' project.id %}"><i class="bi bi-plus-lg" aria-hidden="true"></i> New card</a>{% endif %}<a class="btn btn-outline-secondary project-docs-link" href="{% url 'projects:docs_home' project.id %}"><i class="bi bi-journal-text" aria-hidden="true"></i> Browse documentation</a></div>
</header>
<div class="project-priority-summary" aria-label="Open cards by priority">{% for label,count in priority_counts %}<span><i class="priority-dot priority-{{ label|lower }}" aria-hidden="true"></i>{{ label }} <strong>{{ count }}</strong></span>{% endfor %}</div>
<form class="project-board-filters" method="get" role="search" id="project-board-filters">
<label class="project-search"><i class="bi bi-search" aria-hidden="true"></i><span class="visually-hidden">Search cards</span><input class="form-control" name="q" value="{{ query }}" placeholder="Search cards and specifications" hx-get="{% url 'projects:board' project.id %}" hx-trigger="input changed delay:300ms" hx-target="#board-results" hx-include="closest form" hx-indicator="#board-search-loading"></label>
<button class="btn btn-outline-secondary project-filter-open" type="button" aria-haspopup="dialog" aria-controls="project-filter-sheet" aria-expanded="false"><i class="bi bi-sliders" aria-hidden="true"></i><span>Filters</span><span class="project-filter-count" data-filter-count aria-label="{{ active_filter_count }} active filters" {% if not active_filter_count %}hidden{% endif %}>{{ active_filter_count }}</span></button>
<section class="project-filter-sheet" id="project-filter-sheet" role="dialog" aria-modal="true" aria-labelledby="filter-sheet-title" hidden>
<div class="project-filter-scrim" data-filter-close></div><div class="project-filter-panel"><div class="project-filter-heading"><h2 id="filter-sheet-title">Filter cards</h2><button type="button" class="project-filter-close" aria-label="Close filters" data-filter-close><i class="bi bi-x-lg" aria-hidden="true"></i></button></div>
<label class="project-filter-field">Priority<select class="form-select" name="priority" aria-label="Priority" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All priorities</option><option value="high" {% if selected_priority == 'high' %}selected{% endif %}>High</option><option value="medium" {% if selected_priority == 'medium' %}selected{% endif %}>Medium</option><option value="low" {% if selected_priority == 'low' %}selected{% endif %}>Low</option></select></label>
<label class="project-filter-field">Type<select class="form-select" name="card_type" aria-label="Card type" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All types</option>{% for value,label in card_types %}<option value="{{ value }}" {% if value == selected_type %}selected{% endif %}>{{ label }}</option>{% endfor %}</select></label>
<label class="project-filter-field">Column<select class="form-select" name="column" aria-label="Column" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All columns</option>{% for choice in columns %}<option value="{{ choice.id }}" {% if choice.id|stringformat:'s' == selected_column %}selected{% endif %}>{{ choice.name }}</option>{% endfor %}</select></label>
<label class="project-filter-field">Assignee<select class="form-select" name="assignee" aria-label="Assignee" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All assignees</option>{% for person in assignable %}<option value="{{ person.id }}" {% if person.id|stringformat:'s' == selected_assignee %}selected{% endif %}>{{ person.username }}</option>{% endfor %}</select></label>
<label class="project-filter-field">Tag<select class="form-select" name="tag" aria-label="Tag" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All tags</option>{% for tag in tags %}<option value="{{ tag.id }}" {% if tag.id|stringformat:'s' == selected_tag %}selected{% endif %}>{{ tag.name }}</option>{% endfor %}</select></label>
<div class="project-filter-footer"><a class="btn btn-link" href="{% url 'projects:board' project.id %}">Clear all</a><button class="btn btn-success" type="button" data-filter-close>Done</button></div>
</div>
</section>
<label class="project-archived-toggle"><input class="form-check-input" type="checkbox" name="archived" value="1" {% if show_archived %}checked{% endif %} hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><span>Show archived cards</span></label>
</form>
<span id="board-search-loading" class="htmx-indicator project-loading" role="status">Updating cards…</span>
{% if can_edit and not show_archived %}<div class="project-bulk-toolbar" id="bulk-toolbar"><span id="bulk-count" role="status" aria-live="polite">0 cards selected</span><button type="button" class="btn btn-outline-primary btn-sm" id="bulk-edit-button" disabled>Bulk edit</button><button type="button" class="btn btn-outline-secondary btn-sm" id="bulk-clear-button">Clear selection</button></div>{% endif %}
<section class="project-board-section" aria-label="Project board"><p class="visually-hidden" id="board-scroll-help">On narrow screens, scroll horizontally to see more columns. Use the move controls on each card to move it without dragging.</p>{% if columns|length > 1 %}<div class="project-board-scroll-hint" aria-hidden="true"><i class="bi bi-arrow-left-right"></i> Scroll to see more columns</div>{% endif %}<div id="board-results">{% include 'projects/_board.html' %}</div></section>
{% if can_edit %}<div class="project-board-management"><a class="btn btn-outline-secondary" href="{% url 'projects:column_create' project.id %}">Add column</a><a class="btn btn-outline-secondary" href="{% url 'projects:tag_create' project.id %}">Add tag</a></div>{% endif %}
<section class="project-activity" id="project-activity" aria-labelledby="project-activity-title"><div class="project-section-heading"><div><p class="project-section-eyebrow">UPDATES</p><h2 id="project-activity-title">Recent activity</h2></div>{% if older_activity %}<a href="#all-project-activity" data-open-activity>View all</a>{% endif %}</div>
{% if recent_activity %}<ol class="project-activity-list">{% for event in recent_activity %}<li><span class="project-activity-marker" aria-hidden="true"><i class="bi bi-arrow-left-right"></i></span><div><p>{% if event.card %}<a href="{% url 'projects:card' event.card_id %}">{{ event.card.title }}</a> {{ event.display_action }}{% else %}{{ event.display_action }}{% endif %}</p><small>{% if event.actor %}{{ event.actor }}{% else %}A former member{% endif %} · <time datetime="{{ event.created_at|date:'c' }}" title="{{ event.created_at|date:'DATETIME_FORMAT' }}">{{ event.created_at|timesince }} ago</time></small></div></li>{% endfor %}</ol>
{% if older_activity %}<details class="project-all-activity" id="all-project-activity"><summary>View all activity ({{ older_activity|length }} older events)</summary><ol class="project-activity-list">{% for event in older_activity %}<li><span class="project-activity-marker" aria-hidden="true"><i class="bi bi-arrow-left-right"></i></span><div><p>{% if event.card %}<a href="{% url 'projects:card' event.card_id %}">{{ event.card.title }}</a> {{ event.display_action }}{% else %}{{ event.display_action }}{% endif %}</p><small>{% if event.actor %}{{ event.actor }}{% else %}A former member{% endif %} · <time datetime="{{ event.created_at|date:'c' }}">{{ event.created_at|date:'M j, Y · H:i' }}</time></small></div></li>{% endfor %}</ol></details>{% endif %}
{% else %}<p class="project-activity-empty">No activity yet. Updates will appear here.</p>{% endif %}
</section>
</div>
<div class="d-flex gap-3 flex-wrap mb-3">{% for label,count in priority_counts %}<span class="badge text-bg-light border">{{ label }}: {{ count }} open</span>{% endfor %}</div>
<form class="row g-2 mb-3" method="get" role="search">
<div class="col"><input class="form-control" name="q" value="{{ query }}" placeholder="Search cards and specifications" aria-label="Search cards" hx-get="{% url 'projects:board' project.id %}" hx-trigger="input changed delay:300ms" hx-target="#board-results" hx-include="closest form" hx-indicator="#board-search-loading"></div>
<div class="col-auto"><select class="form-select" name="priority" aria-label="Priority" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All priorities</option><option value="high" {% if selected_priority == 'high' %}selected{% endif %}>High</option><option value="medium" {% if selected_priority == 'medium' %}selected{% endif %}>Medium</option><option value="low" {% if selected_priority == 'low' %}selected{% endif %}>Low</option></select></div>
<div class="col-auto"><select class="form-select" name="card_type" aria-label="Card type" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All types</option>{% for value,label in card_types %}<option value="{{ value }}" {% if value == selected_type %}selected{% endif %}>{{ label }}</option>{% endfor %}</select></div>
<div class="col-auto"><select class="form-select" name="column" aria-label="Column" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All columns</option>{% for choice in columns %}<option value="{{ choice.id }}" {% if choice.id|stringformat:'s' == selected_column %}selected{% endif %}>{{ choice.name }}</option>{% endfor %}</select></div>
<div class="col-auto"><select class="form-select" name="assignee" aria-label="Assignee" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All assignees</option>{% for person in assignable %}<option value="{{ person.id }}" {% if person.id|stringformat:'s' == selected_assignee %}selected{% endif %}>{{ person.username }}</option>{% endfor %}</select></div>
<div class="col-auto"><select class="form-select" name="tag" aria-label="Tag" hx-get="{% url 'projects:board' project.id %}" hx-trigger="change" hx-target="#board-results" hx-include="closest form"><option value="">All tags</option>{% for tag in tags %}<option value="{{ tag.id }}" {% if tag.id|stringformat:'s' == selected_tag %}selected{% endif %}>{{ tag.name }}</option>{% endfor %}</select></div>
<div class="col-auto"><label><input type="checkbox" name="archived" value="1" {% if show_archived %}checked{% endif %}> Archived</label></div>
<div class="col-auto"><a class="btn btn-outline-secondary" href="{% url 'projects:board' project.id %}">Clear</a></div>
</form>
<span id="board-search-loading" class="htmx-indicator" role="status">Searching…</span>
{% if can_edit and not show_archived %}<div class="d-flex align-items-center gap-2 mb-2" id="bulk-toolbar"><span id="bulk-count" role="status" aria-live="polite">0 cards selected</span><button type="button" class="btn btn-outline-primary btn-sm" id="bulk-edit-button" disabled>Bulk edit</button><button type="button" class="btn btn-outline-secondary btn-sm" id="bulk-clear-button">Clear selection</button></div>{% endif %}
<div id="board-results">{% include 'projects/_board.html' %}</div>
{% if can_edit %}<a class="btn btn-outline-secondary mt-3" href="{% url 'projects:column_create' project.id %}">Add column</a>
<a class="btn btn-outline-secondary mt-3" href="{% url 'projects:tag_create' project.id %}">Add tag</a>{% endif %}
<h2 class="h5 mt-4">Recent activity</h2><ul>{% for event in recent_activity %}<li>{{ event.created_at }} · {{ event.action }}{% if event.actor %} by {{ event.actor }}{% endif %}</li>{% empty %}<li>No activity yet.</li>{% endfor %}</ul>
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
{% if can_edit %}
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.6/Sortable.min.js"></script>
<script>
const csrf = document.querySelector('[name=csrfmiddlewaretoken]').value;
function wireBoard() {
document.querySelectorAll('[data-column]').forEach(el => new Sortable(el, {group:'cards', animation:150, onEnd:event => {
const form = new FormData(); form.append('column_id', event.to.dataset.column); form.append('position', event.newIndex);
fetch(event.item.dataset.move, {method:'POST', headers:{'X-CSRFToken':csrf}, body:form}).then(response => {if (!response.ok) location.reload()});
}}));
const columns = document.querySelector('#kanban-columns');
if (columns) new Sortable(columns, {animation:150, handle:'.card-header', onEnd:() => {
const form = new FormData();
columns.querySelectorAll('[data-column-card]').forEach(item => form.append('columns', item.dataset.columnCard));
fetch('{% url 'projects:column_reorder' project.id %}', {method:'POST', headers:{'X-CSRFToken':csrf}, body:form}).then(response => {if (!response.ok) location.reload()});
}});
}
wireBoard(); document.body.addEventListener('htmx:afterSwap', wireBoard);
const bulkCount = document.getElementById('bulk-count');
function selectedBulkCards() { return [...document.querySelectorAll('.bulk-card-choice:checked')]; }
function updateBulkCount() { if (!bulkCount) return; const n = selectedBulkCards().length; bulkCount.textContent = `${n} card${n === 1 ? '' : 's'} selected`; document.getElementById('bulk-edit-button').disabled = n === 0; }
document.addEventListener('change', event => { if (event.target.matches('.bulk-card-choice')) updateBulkCount(); });
document.getElementById('bulk-clear-button')?.addEventListener('click', () => { selectedBulkCards().forEach(box => box.checked = false); updateBulkCount(); });
document.getElementById('bulk-edit-button')?.addEventListener('click', () => {
const query = new URLSearchParams(); selectedBulkCards().forEach(box => query.append('card', box.value));
location.href = '{% url 'projects:cards_bulk_edit' project.id %}?' + query.toString();
});
document.body.addEventListener('htmx:afterSwap', updateBulkCount);
</script>
{% csrf_token %}
{% endif %}
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
{% if can_edit %}<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.6/Sortable.min.js"></script>{% endif %}
<script>
(() => {
const csrf = document.querySelector('[name=csrfmiddlewaretoken]')?.value;
const sortables = new WeakMap();
function destroyBoard(root) { if (!root) return; root.querySelectorAll('[data-column], #kanban-columns').forEach(node => { sortables.get(node)?.destroy(); sortables.delete(node); }); }
function wireBoard(root = document) {
{% if can_edit %}
root.querySelectorAll('[data-column]').forEach(el => { if (sortables.has(el)) return; const instance = new Sortable(el, {group:'cards', animation:150, onEnd:event => {
const form = new FormData(); form.append('column_id', event.to.dataset.column); form.append('position', event.newIndex);
fetch(event.item.dataset.move, {method:'POST', headers:{'X-CSRFToken':csrf}, body:form}).then(response => {if (!response.ok) location.reload()});
}}); sortables.set(el, instance); });
const columns = root.querySelector('#kanban-columns');
if (columns && !sortables.has(columns)) sortables.set(columns, new Sortable(columns, {animation:150, handle:'.card-header', onEnd:() => {
const form = new FormData(); columns.querySelectorAll('[data-column-card]').forEach(item => form.append('columns', item.dataset.columnCard));
fetch('{% url 'projects:column_reorder' project.id %}', {method:'POST', headers:{'X-CSRFToken':csrf}, body:form}).then(response => {if (!response.ok) location.reload()});
}}));
{% endif %}
}
wireBoard();
document.body.addEventListener('htmx:beforeSwap', event => { if (event.detail.target?.id === 'board-results') destroyBoard(event.detail.target); });
document.body.addEventListener('htmx:afterSwap', event => { if (event.detail.target?.id === 'board-results') wireBoard(event.detail.target); updateBulkCount(); });
const bulkCount = document.getElementById('bulk-count');
function selectedBulkCards() { return [...document.querySelectorAll('.bulk-card-choice:checked')]; }
function updateBulkCount() {
const toolbar = document.getElementById('bulk-toolbar');
const archivedToggle = document.querySelector('[name="archived"]');
if (toolbar && archivedToggle) toolbar.hidden = archivedToggle.checked;
if (!bulkCount || toolbar?.hidden) return;
const n = selectedBulkCards().length; bulkCount.textContent = `${n} card${n === 1 ? '' : 's'} selected`; document.getElementById('bulk-edit-button').disabled = n === 0;
}
document.addEventListener('change', event => { if (event.target.matches('.bulk-card-choice')) updateBulkCount(); });
document.getElementById('bulk-clear-button')?.addEventListener('click', () => { selectedBulkCards().forEach(box => box.checked = false); updateBulkCount(); });
document.getElementById('bulk-edit-button')?.addEventListener('click', () => { const query = new URLSearchParams(); selectedBulkCards().forEach(box => query.append('card', box.value)); location.href = '{% url 'projects:cards_bulk_edit' project.id %}?' + query.toString(); });
const sheet = document.getElementById('project-filter-sheet');
const openButton = document.querySelector('.project-filter-open');
const firstField = sheet?.querySelector('select');
let focusBeforeSheet;
function closeSheet() { if (!sheet || sheet.hidden) return; sheet.hidden = true; openButton.setAttribute('aria-expanded', 'false'); document.body.style.overflow = ''; focusBeforeSheet?.focus(); }
openButton?.addEventListener('click', () => { focusBeforeSheet = document.activeElement; sheet.hidden = false; openButton.setAttribute('aria-expanded', 'true'); document.body.style.overflow = 'hidden'; firstField?.focus(); });
sheet?.querySelectorAll('[data-filter-close]').forEach(button => button.addEventListener('click', closeSheet));
sheet?.addEventListener('keydown', event => {
if (event.key === 'Escape') { closeSheet(); return; }
if (event.key !== 'Tab') return;
const focusable = [...sheet.querySelectorAll('a[href],button:not([disabled]),select:not([disabled]),input:not([disabled]),[tabindex]:not([tabindex="-1"])')];
if (!focusable.length) return;
const first = focusable[0], last = focusable[focusable.length - 1];
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
});
sheet?.addEventListener('click', event => { if (event.target.classList.contains('project-filter-scrim')) closeSheet(); });
const filterCountBadge = document.querySelector('[data-filter-count]');
function updateFilterCount() {
if (!filterCountBadge) return;
const count = ['priority','card_type','column','assignee','tag'].filter(name => document.querySelector(`[name="${name}"]`)?.value).length;
filterCountBadge.textContent = count; filterCountBadge.hidden = count === 0;
filterCountBadge.setAttribute('aria-label', `${count} active filter${count === 1 ? '' : 's'}`);
}
document.getElementById('project-board-filters')?.addEventListener('change', updateFilterCount);
document.querySelector('[data-open-activity]')?.addEventListener('click', () => { const details = document.getElementById('all-project-activity'); if (details) details.open = true; });
})();
</script>
{% endblock %}
+43 -14
View File
@@ -1,18 +1,47 @@
{% extends 'core/base.html' %}{% load project_markdown static %}
{% block extra_head %}<link rel="stylesheet" href="{% static 'projects/card_detail.css' %}"><link rel="stylesheet" href="{% static 'projects/card_move.css' %}">{% endblock %}
{% block content %}
<a href="{% url 'projects:board' card.project_id %}">← {{ card.project.name }}</a>
<div class="d-flex justify-content-between mt-3"><h1>{{ card.title }}</h1>{% if can_edit %}<div><a class="btn btn-outline-secondary" href="{% url 'projects:card_edit' card.id %}">Edit</a> {% if card.archived %}<form method="post" action="{% url 'projects:card_restore' card.id %}" class="d-inline">{% csrf_token %}<button class="btn btn-outline-success">Restore</button></form>{% else %}<form method="post" action="{% url 'projects:card_archive' card.id %}" class="d-inline">{% csrf_token %}<button class="btn btn-outline-danger">Archive</button></form>{% endif %}</div>{% endif %}</div>
<p><span class="badge text-bg-secondary">{{ card.get_priority_display }}</span> {{ card.column.name }} · {{ card.get_card_type_display }} · Revision {{ card.revision }}</p>
<div class="card card-body mb-4 markdown-body">{{ card.description_markdown|safe_markdown }}</div>
<details><summary>Raw Markdown</summary><pre>{{ card.description_markdown }}</pre></details>
<section aria-labelledby="card-files-heading" class="mt-4"><h2 id="card-files-heading" class="h4">Card files</h2>
{% include 'projects/_attachment_list.html' with files=card_files %}
{% if can_edit %}<form method="post" enctype="multipart/form-data" action="{% url 'projects:attachment_upload' card.id %}" class="mb-3" data-attachment-upload>{% csrf_token %}<label for="card-files-input" class="form-label">Add card files</label><input id="card-files-input" class="form-control" type="file" name="files" multiple required><button class="btn btn-outline-primary mt-2">Upload files</button><progress hidden max="100" value="0" aria-label="Upload progress"></progress><span role="status" aria-live="polite"></span></form>{% endif %}</section>
<h2 class="h4 mt-4">Progress notes</h2>
{% for comment in comments %}<div class="card card-body mb-2"><small>{{ comment.author }} · {{ comment.created_at }}</small><p>{{ comment.body|linebreaksbr }}</p><h3 class="h6">Files on this progress note</h3>
{% include 'projects/_attachment_list.html' with files=comment.attachments.all %}
{% if can_edit %}<form method="post" enctype="multipart/form-data" action="{% url 'projects:attachment_upload' card.id %}" data-attachment-upload>{% csrf_token %}<input type="hidden" name="comment_id" value="{{ comment.id }}"><label for="note-files-{{ comment.id }}" class="form-label">Add files to this note</label><input id="note-files-{{ comment.id }}" class="form-control" type="file" name="files" multiple required><button class="btn btn-outline-primary mt-2">Upload files</button><progress hidden max="100" value="0" aria-label="Upload progress"></progress><span role="status" aria-live="polite"></span></form>{% endif %}</div>{% endfor %}
{% if can_edit %}<form method="post" action="{% url 'projects:card_comment' card.id %}">{% csrf_token %}<label for="comment">Add note</label><textarea class="form-control" id="comment" name="body" required></textarea><button class="btn btn-success mt-2">Add note</button></form>{% endif %}
<h2 class="h4 mt-4">History</h2><ul>{% for event in card.activity.all %}<li>{{ event.created_at }} · {{ event.action }} by {{ event.actor }}</li>{% endfor %}</ul>
<div class="project-card-page">
{% if messages %}<div class="project-card-messages" aria-live="polite">{% for message in messages %}<p class="project-card-message {{ message.tags }}" role="{% if message.tags == 'error' %}alert{% else %}status{% endif %}">{{ message }}</p>{% endfor %}</div>{% endif %}
<nav class="project-card-breadcrumb" aria-label="Breadcrumb"><a href="{% url 'projects:board' card.project_id %}"><i class="bi bi-arrow-left" aria-hidden="true"></i><span>{{ card.project.name }}</span></a><span aria-hidden="true">/</span><span aria-current="page">{{ card.title }}</span></nav>
{% if card.archived %}<p class="project-card-archived" role="status"><i class="bi bi-archive" aria-hidden="true"></i> This card is archived.</p>{% endif %}
<header class="project-card-header">
<div class="project-card-heading"><p class="project-card-eyebrow">{{ card.project.name }}</p><h1>{{ card.title }}</h1><div class="project-card-badges"><span class="project-card-badge priority-{{ card.priority }}">{{ card.get_priority_display }} priority</span><span class="project-card-badge"><i class="bi bi-kanban" aria-hidden="true"></i>{{ card.column.name }}</span><span class="project-card-badge"><i class="bi bi-bookmark" aria-hidden="true"></i>{{ card.get_card_type_display }}</span><span class="project-card-badge">Revision {{ card.revision }}</span>{% if card.is_blocked %}<span class="project-card-badge blocked"><i class="bi bi-exclamation-circle" aria-hidden="true"></i>Blocked</span>{% endif %}</div></div>
{% if can_edit %}<details class="project-card-actions"><summary aria-label="Card actions"><i class="bi bi-three-dots" aria-hidden="true"></i><span class="visually-hidden">Card actions</span></summary><div class="project-card-actions-menu"><a href="{% url 'projects:card_edit' card.id %}"><i class="bi bi-pencil" aria-hidden="true"></i>Edit card</a>{% if destination_options %}<button type="button" data-open-move-dialog><i class="bi bi-box-arrow-right" aria-hidden="true"></i>Move to project</button>{% else %}<span class="project-move-unavailable" role="status">No other editable projects are available.</span>{% endif %}{% if card.archived %}<form method="post" action="{% url 'projects:card_restore' card.id %}">{% csrf_token %}<button type="submit"><i class="bi bi-arrow-counterclockwise" aria-hidden="true"></i>Restore card</button></form>{% else %}<form method="post" action="{% url 'projects:card_archive' card.id %}" onsubmit="return confirm('Archive this card?')">{% csrf_token %}<button type="submit" class="danger"><i class="bi bi-archive" aria-hidden="true"></i>Archive card</button></form>{% endif %}</div></details>{% endif %}
</header>
{% if can_edit %}<dialog class="project-move-dialog" data-project-move-dialog aria-labelledby="move-card-title"><form method="post" action="{% url 'projects:card_move_project' card.id %}" data-project-move-form>{% csrf_token %}<input type="hidden" name="expected_revision" value="{{ card.revision }}"><input type="hidden" name="idempotency_key" value="{{ move_idempotency_key }}"><div class="project-move-dialog-heading"><div><p class="project-card-eyebrow">MOVE CARD</p><h2 id="move-card-title">Move to another project</h2></div><button type="button" class="project-move-close" data-close-move-dialog aria-label="Close dialog">×</button></div>
{% if destination_options %}<label for="move-target-project">Destination project</label><select id="move-target-project" class="form-select" name="target_project_id" required data-move-project>{% for option in destination_options %}<option value="{{ option.project.pk }}" data-default-column="{% if option.default_column %}{{ option.default_column.pk }}{% endif %}" data-default-name="{% if option.default_column %}{{ option.default_column.name }}{% else %}No default column{% endif %}">{{ option.project.name }}</option>{% endfor %}</select><label for="move-target-column">Destination column</label><select id="move-target-column" class="form-select" name="target_column_id" data-move-column><option value="" data-project-id="">Use project default</option>{% for option in destination_options %}{% for column in option.columns %}<option value="{{ column.pk }}" data-project-id="{{ option.project.pk }}"{% if forloop.parentloop.first and column.is_default %} selected{% endif %}>{{ option.project.name }} · {{ column.name }}{% if column.is_default %} (default){% endif %}</option>{% endfor %}{% endfor %}</select><p class="project-move-confirmation" data-move-confirmation role="status" aria-live="polite">This moves the card from {{ card.project.name }} to the selected project.</p><div class="project-move-dialog-actions"><button type="button" class="btn btn-outline-secondary" data-close-move-dialog>Cancel</button><button type="submit" class="btn btn-success" data-move-submit>Move card</button></div>{% else %}<p>No other active projects are available for you to edit.</p><button type="button" class="btn btn-outline-secondary" data-close-move-dialog>Close</button>{% endif %}</form></dialog>{% endif %}
<div class="project-card-layout">
<main class="project-card-main">
<section class="project-detail-panel project-description-panel" aria-labelledby="card-description-title"><div class="project-detail-heading"><div><p class="project-card-eyebrow">CARD DETAILS</p><h2 id="card-description-title">Description</h2></div><span class="project-updated">Updated {{ card.updated_at|timesince }} ago</span></div>
{% if card.description_markdown %}<div class="project-card-markdown markdown-body">{{ card.description_markdown|safe_markdown }}</div>{% else %}<p class="project-empty-state">No description has been added to this card.</p>{% endif %}
<details class="project-raw-markdown"><summary><i class="bi bi-code-slash" aria-hidden="true"></i> View raw Markdown</summary><pre><code>{{ card.description_markdown }}</code></pre></details>
</section>
<section class="project-card-notes" id="progress-notes" aria-labelledby="progress-notes-title"><div class="project-detail-heading"><div><p class="project-card-eyebrow">DISCUSSION</p><h2 id="progress-notes-title">Progress notes <span class="project-count">{{ comments|length }}</span></h2></div></div>
{% if can_edit %}<form class="project-note-form" method="post" action="{% url 'projects:card_comment' card.id %}">{% csrf_token %}<label for="comment">Add a progress note</label><textarea class="form-control" id="comment" name="body" rows="3" required placeholder="Share an update…"></textarea><div class="project-note-submit"><small>Notes are visible to project members.</small><button class="btn btn-success" type="submit"><i class="bi bi-send" aria-hidden="true"></i> Add note</button></div></form>{% endif %}
<div class="project-note-list">{% for comment in comments %}<article class="project-note-card"><header><span class="project-note-avatar" aria-hidden="true">{{ comment.author.username|slice:':1'|upper }}</span><div><strong>{{ comment.author }}</strong><time datetime="{{ comment.created_at|date:'c' }}" title="{{ comment.created_at|date:'DATETIME_FORMAT' }}">{{ comment.created_at|date:'M j, Y · H:i' }}</time></div></header><p class="project-note-body">{{ comment.body|linebreaksbr }}</p><h3 class="project-note-files-title">Files on this progress note</h3>{% include 'projects/_attachment_list.html' with files=comment.attachments.all %}
{% if can_edit %}<form method="post" enctype="multipart/form-data" action="{% url 'projects:attachment_upload' card.id %}" class="project-upload-form" data-attachment-upload>{% csrf_token %}<input type="hidden" name="comment_id" value="{{ comment.id }}"><label for="note-files-{{ comment.id }}"><i class="bi bi-paperclip" aria-hidden="true"></i> Add files to this note</label><input id="note-files-{{ comment.id }}" class="form-control" type="file" name="files" multiple required><button class="btn btn-outline-secondary" type="submit">Upload files</button><progress hidden max="100" value="0" aria-label="Upload progress"></progress><span role="status" aria-live="polite"></span></form>{% endif %}
</article>{% empty %}<p class="project-empty-state">No progress notes yet.</p>{% endfor %}</div>
</section>
</main>
<aside class="project-card-sidebar" aria-label="Card information">
<section class="project-detail-panel project-properties" aria-labelledby="card-properties-title"><div class="project-detail-heading"><h2 id="card-properties-title">Card info</h2></div><dl>
<div><dt>Status</dt><dd>{{ card.column.name }}</dd></div><div><dt>Priority</dt><dd><span class="project-property-dot priority-{{ card.priority }}"></span>{{ card.get_priority_display }}</dd></div><div><dt>Type</dt><dd>{{ card.get_card_type_display }}</dd></div><div><dt>Assignee</dt><dd>{% if card.assignee %}{{ card.assignee.get_full_name|default:card.assignee.username }}{% else %}Unassigned{% endif %}</dd></div><div><dt>Due date</dt><dd>{% if card.due_date %}<time datetime="{{ card.due_date|date:'Y-m-d' }}">{{ card.due_date|date:'M j, Y' }}</time>{% else %}No due date{% endif %}</dd></div><div><dt>Created</dt><dd><time datetime="{{ card.created_at|date:'c' }}">{{ card.created_at|date:'M j, Y' }}</time></dd></div>
{% if card.tags.exists %}<div class="project-tags-row"><dt>Tags</dt><dd>{% for tag in card.tags.all %}<span class="project-tag">{{ tag.name }}</span>{% endfor %}</dd></div>{% endif %}
</dl>{% if card.is_blocked and card.blocked_reason %}<div class="project-blocked-reason"><strong>Blocked because</strong><p>{{ card.blocked_reason }}</p></div>{% endif %}</section>
<section class="project-detail-panel project-card-files" aria-labelledby="card-files-heading"><div class="project-detail-heading"><h2 id="card-files-heading">Card files <span class="project-count">{{ card_files|length }}</span></h2></div>{% include 'projects/_attachment_list.html' with files=card_files %}
{% if can_edit %}<form method="post" enctype="multipart/form-data" action="{% url 'projects:attachment_upload' card.id %}" class="project-upload-form" data-attachment-upload>{% csrf_token %}<label for="card-files-input"><i class="bi bi-paperclip" aria-hidden="true"></i> Add card files</label><input id="card-files-input" class="form-control" type="file" name="files" multiple required><button class="btn btn-outline-secondary" type="submit">Upload files</button><progress hidden max="100" value="0" aria-label="Upload progress"></progress><span role="status" aria-live="polite"></span></form>{% endif %}
</section>
<details class="project-detail-panel project-card-history"><summary><span><i class="bi bi-clock-history" aria-hidden="true"></i> History</span><span class="project-count">{{ history|length }}</span></summary>{% if history %}<ol class="project-history-list">{% for event in history %}<li><p>{{ event.display_action }}</p><small>{% if event.actor %}{{ event.actor }}{% else %}A former member{% endif %} · <time datetime="{{ event.created_at|date:'c' }}" title="{{ event.created_at|date:'DATETIME_FORMAT' }}">{{ event.created_at|date:'M j, Y · H:i' }}</time></small></li>{% endfor %}</ol>{% else %}<p class="project-empty-state">No history yet.</p>{% endif %}</details>
</aside>
</div>
</div>
<script defer src="{% static 'projects/attachments.js' %}"></script>
{% if can_edit and destination_options %}<script defer src="{% static 'projects/card_move.js' %}"></script>{% endif %}
{% endblock %}
+16 -1
View File
@@ -1 +1,16 @@
{% extends 'core/base.html' %}{% block content %}<style>.htmx-indicator{display:none}.htmx-request.htmx-indicator,.htmx-request .htmx-indicator{display:inline}</style><div class="d-flex justify-content-between align-items-center mb-4"><div><h1>Projects</h1><p>Boards and specifications across your workspace.</p></div><a class="btn btn-success" href="{% url 'projects:create' %}">New project</a></div><p><a href="{% url 'projects:list' %}">Active</a> · <a href="{% url 'projects:list' %}?archived=1">Archived</a></p><form method="get" role="search" class="mb-3"><label for="project-search" class="form-label">Search projects and cards</label><input id="project-search" class="form-control" name="q" value="{{ query }}" hx-get="{% url 'projects:list' %}{% if show_archived %}?archived=1{% endif %}" hx-trigger="input changed delay:300ms" hx-target="#project-results" hx-indicator="#search-loading"><span id="search-loading" class="htmx-indicator" role="status">Searching…</span> <a class="btn btn-sm btn-outline-secondary" href="{% url 'projects:list' %}{% if show_archived %}?archived=1{% endif %}">Clear</a></form><div id="project-results">{% include 'projects/_project_list.html' %}</div><script src="https://unpkg.com/htmx.org@2.0.4"></script>{% endblock %}
{% extends 'core/base.html' %}{% load static %}
{% block extra_head %}<link rel="stylesheet" href="{% static 'projects/project_list.css' %}">{% endblock %}
{% block content %}
<div class="projects-index">
<header class="projects-index-header"><div><p class="projects-index-eyebrow">WORKSPACE</p><h1>Projects</h1><p class="projects-index-intro">Boards and specifications across your workspace.</p></div><a class="btn btn-success projects-new-button" href="{% url 'projects:create' %}"><i class="bi bi-plus-lg" aria-hidden="true"></i> New project</a></header>
<nav class="projects-view-tabs" aria-label="Project views"><a href="{% url 'projects:list' %}{% if query %}?q={{ query|urlencode }}{% endif %}" {% if not show_archived %}aria-current="page"{% endif %}><i class="bi bi-grid" aria-hidden="true"></i> Active</a><a href="{% url 'projects:list' %}?{% if query %}q={{ query|urlencode }}&amp;{% endif %}archived=1" {% if show_archived %}aria-current="page"{% endif %}><i class="bi bi-archive" aria-hidden="true"></i> Archived</a></nav>
<form class="projects-search-form" method="get" role="search">
{% if show_archived %}<input type="hidden" name="archived" value="1">{% endif %}
<label class="projects-search-box" for="project-search"><i class="bi bi-search" aria-hidden="true"></i><span class="visually-hidden">Search projects and cards</span><input id="project-search" class="form-control" name="q" value="{{ query }}" placeholder="Search projects and cards" hx-get="{% url 'projects:list' %}{% if show_archived %}?archived=1{% endif %}" hx-trigger="input changed delay:300ms" hx-target="#project-results" hx-include="closest form" hx-indicator="#search-loading"></label>
<span id="search-loading" class="htmx-indicator" role="status">Searching projects…</span>
{% if query %}<a class="btn btn-outline-secondary projects-clear-search" href="{% url 'projects:list' %}{% if show_archived %}?archived=1{% endif %}"><i class="bi bi-x-lg" aria-hidden="true"></i><span>Clear</span></a>{% endif %}
</form>
<div id="project-results">{% include 'projects/_project_list.html' %}</div>
</div>
<script src="https://unpkg.com/htmx.org@2.0.4"></script>
{% endblock %}
+41 -1
View File
@@ -1,10 +1,12 @@
import base64
import hashlib
import json
import asyncio
import os
from urllib.parse import parse_qs, urlparse
from django.contrib.auth import get_user_model
from django.test import TestCase, Client as DjangoClient
from django.test import TestCase, TransactionTestCase, Client as DjangoClient
from django.conf import settings
from asgiref.sync import async_to_sync
from unittest.mock import patch
@@ -58,6 +60,13 @@ class OAuthMcpTests(TestCase):
project = create_project(self.user, name='Private')
self.assertEqual(self.client.get(f'/projects/{project.pk}/').status_code, 302)
def test_cross_project_move_tool_is_registered_with_revision_and_uuid_contract(self):
tool = create_server()._tool_manager.get_tool('cards_move_project')
self.assertIn('another editable project', tool.description)
self.assertEqual(set(tool.parameters['required']), {'card_id', 'target_project', 'expected_revision'})
self.assertIn('idempotency_key', tool.parameters['properties'])
def test_client_registration_requires_authenticated_user_and_csrf(self):
metadata = {'client_name': 'Private test client', 'redirect_uris': ['https://client.example/callback'],
'grant_types': ['authorization_code', 'refresh_token'], 'token_endpoint_auth_method': 'none'}
@@ -90,3 +99,34 @@ class OAuthMcpTests(TestCase):
with patch('mcp_server.server.get_access_token', return_value=read):
with self.assertRaises(ToolError):
async_to_sync(server.call_tool)('cards_set_priority', {'card_id': card['id'], 'priority': 'high', 'expected_revision': 1})
class CrossProjectMoveMcpTests(TransactionTestCase):
def test_cross_project_move_mcp_handler_returns_same_move_result(self):
user = get_user_model().objects.create_user('move-mcp-user', password='test-password')
source = create_project(user, name='MCP source')
destination = create_project(user, name='MCP destination')
from .services import create_card
card = create_card(user, source, title='Move through MCP')
server = create_server()
tool = server._tool_manager.get_tool('cards_move_project')
class InlineAwaitable:
def __init__(self, function):
self.function = function
async def __call__(self):
return self.function()
with patch('mcp_server.server._actor', return_value=user), \
patch('mcp_server.server.sync_to_async', side_effect=lambda function: InlineAwaitable(function)), \
patch.dict(os.environ, {'DJANGO_ALLOW_ASYNC_UNSAFE': 'true'}):
data = asyncio.run(tool.fn(card_id=str(card.pk), target_project=str(destination.pk),
target_column_id=str(destination.board.columns.get(is_default=True).pk),
expected_revision=card.revision))
card.refresh_from_db()
self.assertEqual(data['id'], str(card.pk))
self.assertEqual(data['project_id'], str(destination.pk))
self.assertEqual(data['revision'], 2)
self.assertEqual(data['move']['source_project_id'], str(source.pk))
self.assertEqual(data['move']['target_column_id'], str(card.column_id))
+209 -6
View File
@@ -1,14 +1,14 @@
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.test import TestCase, Client, override_settings
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.http import HttpResponse
from django.http import HttpResponse, Http404
from django.utils import timezone
from unittest.mock import patch
from .models import Activity, Card, CardRevision, Membership, Profile
from .models import Activity, Card, CardRevision, CardComment, CardAttachment, Column, Membership, Profile, Tag
from .forms import ProfileForm
from .middleware import ProfileTimezoneMiddleware
from .services import RevisionConflict, bulk_update_cards, card_for, create_card, create_project, move_card, update_card, update_column
from .services import RevisionConflict, bulk_update_cards, card_for, create_card, create_project, move_card, move_card_to_project, update_card, update_column
class ProjectWorkflowTests(TestCase):
@@ -46,17 +46,220 @@ class ProjectWorkflowTests(TestCase):
card.refresh_from_db()
self.assertIsNotNone(card.completed_at)
def test_cross_project_move_preserves_identity_and_children_and_maps_project_data(self):
destination = create_project(self.owner, name='Destination')
card = create_card(self.owner, self.project, title='Keep me', markdown='# Keep this')
source_sibling = create_card(self.owner, self.project, title='Source sibling')
destination_sibling = create_card(self.owner, destination, title='Destination sibling')
original_updated_at = card.updated_at
card.assignee = self.other
card.save(update_fields=['assignee'])
Membership.objects.create(project=destination, user=self.other, role='viewer')
comment = CardComment.objects.create(card=card, author=self.owner, body='Progress note')
attachment = CardAttachment.objects.create(card=card, comment=comment, file='card-attachments/test.txt',
original_filename='test.txt', title='Source file', mime_type='text/plain', byte_size=4, sha256='a' * 64)
source_tag = Tag.objects.create(project=self.project, name='Roadmap')
target_tag = Tag.objects.create(project=destination, name='roadmap')
card.tags.add(source_tag)
old_activity = card.activity.first()
destination_column = destination.board.columns.get(is_default=True)
moved, result = move_card_to_project(self.owner, card, destination,
target_column=destination_column, expected_revision=card.revision, idempotency_key='move-preserve')
moved.refresh_from_db()
self.assertEqual(moved.pk, card.pk)
self.assertEqual(moved.project_id, destination.pk)
self.assertEqual(moved.column_id, destination_column.pk)
self.assertEqual(moved.position, 1)
source_sibling.refresh_from_db()
self.assertEqual(source_sibling.position, 0)
destination_sibling.refresh_from_db()
self.assertEqual(destination_sibling.position, 0)
self.assertEqual(moved.revision, card.revision + 1)
self.assertEqual(moved.description_markdown, '# Keep this')
self.assertEqual(moved.updated_at, original_updated_at)
self.assertEqual(moved.assignee_id, self.other.pk)
self.assertEqual(list(moved.revisions.order_by('revision').values_list('revision', flat=True)), [1, 2])
self.assertEqual(list(moved.tags.all()), [target_tag])
self.assertEqual(moved.comments.get(pk=comment.pk).body, 'Progress note')
self.assertEqual(moved.attachments.get(pk=attachment.pk).file.name, 'card-attachments/test.txt')
old_activity.refresh_from_db()
self.assertEqual(old_activity.project_id, destination.pk)
self.assertTrue(moved.activity.filter(action='card.moved_project').exists())
source_event = Activity.objects.get(project=self.project, action='card.moved_project_out')
self.assertEqual(source_event.detail['card_id'], str(card.pk))
self.assertEqual(result['source_project_id'], str(self.project.pk))
self.assertEqual(result['revision'], moved.revision)
def test_cross_project_move_clears_invalid_assignee_and_tags_with_warnings(self):
destination = create_project(self.owner, name='Destination')
card = create_card(self.owner, self.project, title='Transfer')
card.assignee = self.other
card.save(update_fields=['assignee'])
tag = Tag.objects.create(project=self.project, name='Only here')
card.tags.add(tag)
moved, result = move_card_to_project(self.owner, card, destination, expected_revision=card.revision)
self.assertIsNone(moved.assignee_id)
self.assertFalse(moved.tags.exists())
self.assertEqual(len(result['warnings']), 2)
def test_cross_project_move_validates_access_column_revision_and_idempotency(self):
destination = create_project(self.owner, name='Destination')
private_destination = create_project(self.other, name='Private destination')
archived_destination = create_project(self.owner, name='Archived destination')
archived_destination.archived = True
archived_destination.save(update_fields=['archived'])
card = create_card(self.owner, self.project, title='Transfer')
foreign_column = private_destination.board.columns.get(is_default=True)
with self.assertRaises(ValidationError):
move_card_to_project(self.owner, card, destination, target_column=foreign_column, expected_revision=1)
with self.assertRaises(RevisionConflict):
move_card_to_project(self.owner, card, destination, expected_revision=0)
with self.assertRaises(Http404):
move_card_to_project(self.owner, card, private_destination, expected_revision=1)
with self.assertRaises(ValidationError):
move_card_to_project(self.owner, card, archived_destination, expected_revision=1)
moved, _ = move_card_to_project(self.owner, card, destination, expected_revision=1, idempotency_key='retry-1')
replay, result = move_card_to_project(self.owner, card, destination, expected_revision=1, idempotency_key='retry-1')
self.assertEqual(replay.pk, moved.pk)
self.assertEqual(result['revision'], moved.revision)
with self.assertRaises(ValidationError):
move_card_to_project(self.owner, card, private_destination, expected_revision=1, idempotency_key='retry-1')
def test_cross_project_move_ui_requires_csrf_and_shows_success_or_stale_feedback(self):
destination = create_project(self.owner, name='Destination')
card = create_card(self.owner, self.project, title='Transfer')
browser = Client(enforce_csrf_checks=True)
browser.force_login(self.owner)
detail = browser.get(reverse('projects:card', args=[card.pk]))
self.assertContains(detail, 'Move to project')
self.assertContains(detail, 'Destination')
csrf = browser.cookies['csrftoken'].value
move_url = reverse('projects:card_move_project', args=[card.pk])
payload = {'target_project_id': str(destination.pk), 'target_column_id': '',
'expected_revision': str(card.revision), 'idempotency_key': 'web-move-1'}
self.assertEqual(browser.post(move_url, payload).status_code, 403)
stale = browser.post(move_url, {**payload, 'expected_revision': '0', 'idempotency_key': 'web-stale'}, HTTP_X_CSRFTOKEN=csrf)
self.assertEqual(stale.status_code, 302)
stale_detail = browser.get(reverse('projects:card', args=[card.pk]))
self.assertContains(stale_detail, 'This card changed before it could be moved.')
response = browser.post(move_url, payload, HTTP_X_CSRFTOKEN=csrf)
self.assertEqual(response.status_code, 302)
self.assertEqual(response['Location'], reverse('projects:card', args=[card.pk]))
self.assertEqual(Card.objects.get(pk=card.pk).project_id, destination.pk)
self.assertContains(browser.get(reverse('projects:card', args=[card.pk])), 'Moved “Transfer” from BoomCast to Destination.')
def test_cross_project_move_rolls_back_when_revision_creation_fails(self):
destination = create_project(self.owner, name='Destination')
card = create_card(self.owner, self.project, title='Transfer')
with patch.object(CardRevision.objects, 'create', side_effect=RuntimeError('revision store unavailable')):
with self.assertRaises(RuntimeError):
move_card_to_project(self.owner, card, destination, expected_revision=card.revision)
card.refresh_from_db()
self.assertEqual(card.project_id, self.project.pk)
self.assertEqual(card.revision, 1)
self.assertFalse(Activity.objects.filter(action='card.moved_project_out').exists())
def test_board_filters_and_escaped_markdown(self):
card = create_card(self.owner, self.project, title='Danger', markdown='<script>alert(1)</script>\n\n# Safe')
self.client.force_login(self.owner)
response = self.client.get(reverse('projects:board', args=[self.project.pk]), {'priority': 'medium'})
self.assertContains(response, 'Danger')
visible = [card for column in response.context['columns'] for card in column.visible_cards]
self.assertEqual([item.pk for item in visible], [card.pk])
response = self.client.get(reverse('projects:board', args=[self.project.pk]), {'priority': 'high'})
self.assertNotContains(response, 'Danger')
visible = [item for column in response.context['columns'] for item in column.visible_cards]
self.assertEqual(visible, [])
response = self.client.get(reverse('projects:card', args=[card.pk]))
self.assertNotContains(response, '<script>alert(1)</script>', html=False)
self.assertContains(response, '<h1>Safe</h1>', html=False)
def test_board_archive_filter_and_mobile_filter_sheet(self):
active = create_card(self.owner, self.project, title='Active card')
archived = create_card(self.owner, self.project, title='Archived card')
archived.archived = True
archived.save(update_fields=['archived'])
self.client.force_login(self.owner)
response = self.client.get(reverse('projects:board', args=[self.project.pk]))
visible = [card for column in response.context['columns'] for card in column.visible_cards]
self.assertEqual([card.pk for card in visible], [active.pk])
self.assertContains(response, 'role="dialog"')
self.assertContains(response, 'Show archived cards')
response = self.client.get(reverse('projects:board', args=[self.project.pk]), {'archived': '1'})
visible = [card for column in response.context['columns'] for card in column.visible_cards]
self.assertEqual([card.pk for card in visible], [archived.pk])
def test_board_progress_is_zero_safe_and_activity_is_human_readable(self):
self.client.force_login(self.owner)
response = self.client.get(reverse('projects:board', args=[self.project.pk]))
self.assertEqual(response.context['progress_percent'], 0)
self.assertContains(response, '0 / 0')
card = create_card(self.owner, self.project, title='Timeline card')
for index in range(5):
Activity.objects.create(project=self.project, card=card, actor=self.owner,
action='card.moved', detail={'sequence': index})
response = self.client.get(reverse('projects:board', args=[self.project.pk]))
self.assertEqual(len(response.context['recent_activity']), 3)
self.assertGreater(len(response.context['older_activity']), 0)
self.assertContains(response, 'moved a card')
self.assertContains(response, 'View all')
def test_card_detail_uses_responsive_layout_and_readable_history(self):
card = create_card(self.owner, self.project, title='Detail view card', markdown='# Description\n\nCard detail text.')
self.client.force_login(self.owner)
response = self.client.get(reverse('projects:card', args=[card.pk]))
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'projects/card_detail.css')
self.assertContains(response, 'Description')
self.assertContains(response, 'Card info')
self.assertContains(response, 'Progress notes')
self.assertContains(response, 'View raw Markdown')
self.assertContains(response, 'created this card')
self.assertContains(response, 'Edit card')
self.assertContains(response, 'Add a progress note')
def test_card_detail_preserves_viewer_read_only_permissions(self):
card = create_card(self.owner, self.project, title='Viewer detail card', markdown='Readable for the team.')
Membership.objects.create(project=self.project, user=self.other, role='viewer')
self.client.force_login(self.other)
response = self.client.get(reverse('projects:card', args=[card.pk]))
self.assertContains(response, 'Readable for the team.')
self.assertContains(response, 'Card info')
self.assertNotContains(response, 'Edit card')
self.assertNotContains(response, 'Add a progress note')
self.assertNotContains(response, 'Add card files')
def test_projects_index_preserves_search_access_and_archived_view(self):
finished = create_card(self.owner, self.project, title='Searchable milestone')
move_card(self.owner, finished, self.project.board.columns.get(is_done=True))
archived_card = create_card(self.owner, self.project, title='Old milestone')
archived_card.archived = True
archived_card.save(update_fields=['archived'])
private_project = create_project(self.other, name='Private workspace')
self.client.force_login(self.owner)
url = reverse('projects:list')
response = self.client.get(url)
self.assertContains(response, 'projects/project_list.css')
self.assertContains(response, 'BoomCast')
self.assertNotContains(response, 'Private workspace')
project = next(item for item in response.context['projects'] if item.pk == self.project.pk)
self.assertEqual(project.card_count, 2)
self.assertEqual(project.active_card_count, 1)
self.assertEqual(project.done_card_count, 1)
self.assertEqual(project.progress_percent, 100)
response = self.client.get(url, {'q': 'Searchable'})
self.assertContains(response, 'BoomCast')
self.assertContains(response, 'Open board')
response = self.client.get(url, {'q': 'Searchable'}, HTTP_HX_REQUEST='true')
self.assertContains(response, 'BoomCast')
self.assertEqual(response.context['query'], 'Searchable')
self.project.archived = True
self.project.save(update_fields=['archived'])
response = self.client.get(url, {'archived': '1'})
self.assertContains(response, 'Archived')
self.assertContains(response, 'BoomCast')
self.assertNotContains(response, 'Private workspace')
def test_completion_flag_updates_existing_cards(self):
card = create_card(self.owner, self.project, title='Complete later')
column = card.column
+1
View File
@@ -27,6 +27,7 @@ urlpatterns = [
path('cards/<uuid:card_id>/', views.card_detail, name='card'),
path('cards/<uuid:card_id>/edit/', views.card_edit, name='card_edit'),
path('cards/<uuid:card_id>/move/', views.card_move, name='card_move'),
path('cards/<uuid:card_id>/move-project/', views.card_move_project, name='card_move_project'),
path('cards/<uuid:card_id>/comment/', views.card_comment, name='card_comment'),
path('cards/<uuid:card_id>/attachments/', views.attachment_upload, name='attachment_upload'),
path('attachments/<uuid:attachment_id>/download/', views.attachment_download, name='attachment_download'),
+73 -5
View File
@@ -1,5 +1,6 @@
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.contrib import messages
from django.contrib.auth.views import LoginView
from django.core.cache import cache
from django.core import signing
@@ -20,7 +21,7 @@ from django.utils import timezone
from django.conf import settings
from oauth2_provider.models import get_access_token_model, revoke_access_token
from .forms import CardForm, ColumnForm, ProfileForm, ProjectForm, TagForm
from .models import Activity, Card, CardComment, CardAttachment, Column, Profile, Membership, Tag
from .models import Activity, Card, CardComment, CardAttachment, Column, Profile, Membership, Tag, Project
from . import services
from . import attachments
from . import documentation
@@ -30,6 +31,21 @@ from .models import DocumentationSync, ProjectDocument
from urllib.parse import quote
ACTIVITY_ACTION_LABELS = {
'project.created': 'created the project', 'card.created': 'created a card',
'card.updated': 'updated a card', 'card.moved': 'moved a card',
'card.moved_project': 'moved this card to another project',
'card.moved_project_out': 'moved a card to another project',
'card.assigned': 'changed a card assignment', 'card.tags_changed': 'updated card tags',
'card.bulk_updated': 'updated a card', 'column.updated': 'updated a column',
'attachment.added': 'added an attachment', 'attachment.deleted': 'removed an attachment',
}
def activity_display_action(action):
return ACTIVITY_ACTION_LABELS.get(action, action.replace('.', ' ').replace('_', ' '))
class ThrottledLoginView(LoginView):
template_name = 'projects/login.html'
@@ -62,8 +78,14 @@ def project_list(request):
projects = services.accessible(request.user).filter(archived=show_archived)
if query:
projects = projects.filter(Q(name__icontains=query) | Q(description__icontains=query) | Q(cards__title__icontains=query) | Q(cards__description_markdown__icontains=query) | Q(tag__name__icontains=query)).distinct()
projects = projects.annotate(card_count=Count('cards', distinct=True)).order_by('name')
projects = projects.annotate(
card_count=Count('cards', distinct=True),
active_card_count=Count('cards', filter=Q(cards__archived=False), distinct=True),
done_card_count=Count('cards', filter=Q(cards__archived=False, cards__column__is_done=True), distinct=True),
).order_by('name')
page_obj = Paginator(projects, 12).get_page(request.GET.get('page'))
for project in page_obj:
project.progress_percent = round(project.done_card_count * 100 / project.active_card_count) if project.active_card_count else 0
filters = request.GET.copy(); filters.pop('page', None)
template = 'projects/_project_list.html' if request.headers.get('HX-Request') else 'projects/list.html'
return render(request, template, {'projects': page_obj, 'page_obj': page_obj, 'filters_query': filters.urlencode(), 'query': query, 'show_archived': show_archived, 'section': 'projects', 'title': 'Projects'})
@@ -133,8 +155,14 @@ def board(request, project_id):
column.active_count = Card.objects.filter(column=column, archived=False).count()
assignable_ids = [project.owner_id, *project.memberships.values_list('user_id', flat=True)]
active_cards = Card.objects.filter(project=project, archived=False)
context = {'project': project, 'columns': columns, 'page_obj': page_obj, 'filters_query': filters.urlencode(), 'query': query, 'title': project.name, 'section': 'projects', 'card_count': len(cards), 'total_count': active_cards.count(), 'done_count': active_cards.filter(column__is_done=True).count(), 'priority_counts': [(label, active_cards.filter(priority=value, column__is_done=False).count()) for value, label in Card.PRIORITY], 'recent_activity': Activity.objects.filter(project=project).select_related('actor')[:5], 'selected_priority': request.GET.get('priority', ''), 'selected_type': request.GET.get('card_type', ''), 'selected_assignee': request.GET.get('assignee', ''), 'selected_tag': request.GET.get('tag', ''), 'selected_column': request.GET.get('column', ''), 'show_archived': show_archived, 'tags': Tag.objects.filter(project=project).order_by('name'), 'assignable': get_user_model().objects.filter(pk__in=assignable_ids).order_by('username'), 'card_types': Card.TYPE, 'can_edit': can_edit}
template = 'projects/_board.html' if request.headers.get('HX-Request') else 'projects/board.html'
is_htmx = bool(request.headers.get('HX-Request'))
all_activity = [] if is_htmx else list(Activity.objects.filter(project=project).select_related('actor', 'card'))
for event in all_activity:
event.display_action = activity_display_action(event.action)
done_count = active_cards.filter(column__is_done=True).count()
total_count = active_cards.count()
context = {'project': project, 'columns': columns, 'page_obj': page_obj, 'filters_query': filters.urlencode(), 'query': query, 'title': project.name, 'section': 'projects', 'card_count': len(cards), 'total_count': total_count, 'done_count': done_count, 'progress_percent': round(done_count * 100 / total_count) if total_count else 0, 'priority_counts': [(label, active_cards.filter(priority=value, column__is_done=False).count()) for value, label in Card.PRIORITY], 'recent_activity': all_activity[:3], 'older_activity': all_activity[3:], 'selected_priority': request.GET.get('priority', ''), 'selected_type': request.GET.get('card_type', ''), 'selected_assignee': request.GET.get('assignee', ''), 'selected_tag': request.GET.get('tag', ''), 'selected_column': request.GET.get('column', ''), 'show_archived': show_archived, 'active_filter_count': sum(bool(request.GET.get(key)) for key in ('priority', 'card_type', 'column', 'assignee', 'tag')), 'tags': Tag.objects.filter(project=project).order_by('name'), 'assignable': get_user_model().objects.filter(pk__in=assignable_ids).order_by('username'), 'card_types': Card.TYPE, 'can_edit': can_edit}
template = 'projects/_board.html' if is_htmx else 'projects/board.html'
return render(request, template, context)
@@ -204,11 +232,51 @@ def card_create(request, project_id):
def card_detail(request, card_id):
card = services.card_for(request.user, card_id)
can_edit = card.project.owner_id == request.user.pk or Membership.objects.filter(project=card.project, user=request.user, role='editor').exists()
return render(request, 'projects/card.html', {'card': card, 'can_edit': can_edit, 'title': card.title, 'section': 'projects',
history = card.activity.select_related('actor').all()
for event in history:
event.display_action = activity_display_action(event.action).replace('a card', 'this card')
destinations = Project.objects.filter(archived=False).filter(Q(owner=request.user) | Q(memberships__user=request.user, memberships__role='editor')).exclude(pk=card.project_id).distinct().select_related('board').order_by('name') if can_edit else Project.objects.none()
destination_options = []
for project in destinations:
columns = list(project.board.columns.filter(archived=False).order_by('position'))
if not columns:
continue
default_column = next((column for column in columns if column.is_default), columns[0])
destination_options.append({'project': project, 'columns': columns,
'default_column': default_column})
return render(request, 'projects/card.html', {'card': card, 'can_edit': can_edit, 'title': card.title, 'section': 'projects', 'history': history,
'destination_options': destination_options, 'move_idempotency_key': uuid.uuid4(),
'card_files': card.attachments.filter(comment__isnull=True).select_related('uploaded_by'),
'comments': card.comments.prefetch_related('attachments').select_related('author').order_by('created_at')})
@login_required
@require_POST
def card_move_project(request, card_id):
card = services.card_for(request.user, card_id, write=True)
try:
target_id = uuid.UUID(request.POST.get('target_project_id', ''))
target_project = services.project_for(request.user, target_id, write=True)
column_id = request.POST.get('target_column_id') or None
target_column = get_object_or_404(Column, pk=column_id) if column_id else None
moved, result = services.move_card_to_project(
request.user, card, target_project, target_column=target_column,
expected_revision=request.POST.get('expected_revision'),
idempotency_key=request.POST.get('idempotency_key') or None,
)
except services.RevisionConflict as conflict:
messages.error(request, f'This card changed before it could be moved. Current revision: {conflict.current}. Reload the card and try again.')
return redirect('projects:card', card_id=card.pk)
except (ValueError, TypeError, ValidationError) as exc:
messages.error(request, '; '.join(exc.messages) if isinstance(exc, ValidationError) else 'The card could not be moved. Reload the card and try again.')
return redirect('projects:card', card_id=card.pk)
message = f'Moved “{moved.title}” from {result["source_project_name"]} to {result["target_project_name"]}.'
if result['warnings']:
message += ' ' + ' '.join(result['warnings'])
messages.success(request, message)
return redirect('projects:card', card_id=moved.pk)
@login_required
@require_POST
def attachment_upload(request, card_id):