222 lines
10 KiB
Python
222 lines
10 KiB
Python
import hashlib
|
|
import json
|
|
from django.core.exceptions import PermissionDenied, ValidationError
|
|
from django.db import transaction
|
|
from django.db.models import Q, Max
|
|
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, Card, CardRevision, Column, CreationKey, Membership, Project, Tag
|
|
|
|
|
|
class RevisionConflict(Exception):
|
|
def __init__(self, current):
|
|
self.current = current
|
|
|
|
|
|
def accessible(user):
|
|
if not user.is_authenticated:
|
|
return Project.objects.none()
|
|
return Project.objects.filter(Q(owner=user) | Q(memberships__user=user)).distinct()
|
|
|
|
|
|
def project_for(user, identifier, write=False):
|
|
project = get_object_or_404(accessible(user), pk=identifier)
|
|
if write and project.owner_id != user.pk and not Membership.objects.filter(project=project, user=user, role='editor').exists():
|
|
raise PermissionDenied
|
|
return project
|
|
|
|
|
|
def card_for(user, identifier, write=False):
|
|
card = get_object_or_404(Card.objects.select_related('project', 'column'), pk=identifier, project__in=accessible(user))
|
|
if write:
|
|
project_for(user, card.project_id, write=True)
|
|
return card
|
|
|
|
|
|
@transaction.atomic
|
|
def create_project(user, *, name, description='', git_repository_url=''):
|
|
if not name.strip():
|
|
raise ValidationError('Project name is required.')
|
|
if Project.objects.filter(owner=user, name__iexact=name.strip()).exists():
|
|
raise ValidationError('You already have a project with this name.')
|
|
if git_repository_url:
|
|
URLValidator(schemes=['https'])(git_repository_url)
|
|
base = slugify(name) or 'project'
|
|
slug = base
|
|
n = 2
|
|
while Project.objects.filter(owner=user, slug=slug).exists():
|
|
slug = f'{base}-{n}'
|
|
n += 1
|
|
project = Project(owner=user, name=name, slug=slug, description=description, git_repository_url=git_repository_url)
|
|
project.full_clean()
|
|
project.save()
|
|
board = Board.objects.create(project=project)
|
|
for index, title in enumerate(('To-do', 'In Progress', 'Done')):
|
|
Column.objects.create(board=board, name=title, position=index, is_default=index == 0, is_done=index == 2)
|
|
Activity.objects.create(project=project, actor=user, action='project.created')
|
|
return project
|
|
|
|
|
|
@transaction.atomic
|
|
def create_card(user, project, *, title, markdown='', column=None, priority='medium', card_type='task', origin='web', idempotency_key=None):
|
|
project_for(user, project.pk, write=True)
|
|
if priority not in dict(Card.PRIORITY) or card_type not in dict(Card.TYPE):
|
|
raise ValidationError('Invalid priority or card type.')
|
|
if not title.strip():
|
|
raise ValidationError('Card title is required.')
|
|
if idempotency_key:
|
|
if len(idempotency_key) > 128:
|
|
raise ValidationError('Idempotency key is too long.')
|
|
payload = json.dumps({'project': str(project.pk), 'title': title, 'markdown': markdown, 'column': str(column.pk) if column else None, 'priority': priority, 'card_type': card_type}, sort_keys=True)
|
|
payload_hash = hashlib.sha256(payload.encode()).hexdigest()
|
|
existing = CreationKey.objects.filter(user=user, key=idempotency_key).select_related('card').first()
|
|
if existing:
|
|
if existing.payload_hash != payload_hash:
|
|
raise ValidationError('Idempotency key was already used with different card details.')
|
|
return existing.card
|
|
column = column or project.board.columns.get(is_default=True, archived=False)
|
|
if column.board_id != project.board.pk or column.archived:
|
|
raise ValidationError('Column is not available in this project.')
|
|
position = (Card.objects.filter(column=column, archived=False).aggregate(Max('position'))['position__max'] or 0) + 1
|
|
card = Card(project=project, column=column, title=title, description_markdown=markdown,
|
|
priority=priority, card_type=card_type, position=position, created_by=user,
|
|
completed_at=timezone.now() if column.is_done else None)
|
|
card.full_clean()
|
|
card.save()
|
|
CardRevision.objects.create(card=card, revision=1, markdown=markdown, actor=user)
|
|
Activity.objects.create(project=project, card=card, actor=user, action='card.created', origin=origin)
|
|
if idempotency_key:
|
|
CreationKey.objects.create(user=user, key=idempotency_key, payload_hash=payload_hash, card=card)
|
|
return card
|
|
|
|
|
|
@transaction.atomic
|
|
def update_card(user, card, *, expected_revision=None, origin='web', **changes):
|
|
card = Card.objects.select_for_update().get(pk=card.pk)
|
|
project_for(user, card.project_id, write=True)
|
|
allowed = {'title', 'description_markdown', 'priority', 'card_type', 'is_blocked', 'blocked_reason', 'archived', 'due_date'}
|
|
if set(changes) - allowed:
|
|
raise ValidationError('Unsupported card field.')
|
|
if 'priority' in changes and changes['priority'] not in dict(Card.PRIORITY):
|
|
raise ValidationError('Invalid priority.')
|
|
markdown_changed = 'description_markdown' in changes and changes['description_markdown'] != card.description_markdown
|
|
if changes and (expected_revision is None or int(expected_revision) != card.revision):
|
|
raise RevisionConflict(card.revision)
|
|
changed = []
|
|
for field, value in changes.items():
|
|
if getattr(card, field) != value:
|
|
setattr(card, field, value)
|
|
changed.append(field)
|
|
if changed:
|
|
card.revision += 1
|
|
card.full_clean()
|
|
card.save()
|
|
CardRevision.objects.create(card=card, revision=card.revision, markdown=card.description_markdown, actor=user)
|
|
Activity.objects.create(project=card.project, card=card, actor=user, action='card.updated', detail={'fields': changed}, origin=origin)
|
|
return card
|
|
|
|
|
|
@transaction.atomic
|
|
def move_card(user, card, column, position=None, origin='web'):
|
|
card = Card.objects.select_for_update().get(pk=card.pk)
|
|
project_for(user, card.project_id, write=True)
|
|
if column.board.project_id != card.project_id or column.archived:
|
|
raise ValidationError('Column is not available in this project.')
|
|
old_column = card.column_id
|
|
card.column = column
|
|
card.completed_at = timezone.now() if column.is_done and not card.completed_at else (None if not column.is_done else card.completed_at)
|
|
siblings = list(Card.objects.filter(column=column, archived=False).exclude(pk=card.pk).order_by('position', 'created_at'))
|
|
index = len(siblings) if position is None else max(0, min(int(position), len(siblings)))
|
|
siblings.insert(index, card)
|
|
for i, item in enumerate(siblings):
|
|
item.position = i
|
|
item.save(update_fields=['position'])
|
|
card.save()
|
|
Activity.objects.create(project=card.project, card=card, actor=user, action='card.moved', detail={'from': str(old_column), 'to': str(column.pk)}, origin=origin)
|
|
return card
|
|
|
|
|
|
@transaction.atomic
|
|
def set_default(user, column):
|
|
project_for(user, column.board.project_id, write=True)
|
|
if column.archived:
|
|
raise ValidationError('Archived column cannot be the default.')
|
|
Column.objects.filter(board=column.board, is_default=True).update(is_default=False)
|
|
column.is_default = True
|
|
column.save(update_fields=['is_default'])
|
|
return column
|
|
|
|
|
|
@transaction.atomic
|
|
def archive_column(user, column):
|
|
project_for(user, column.board.project_id, write=True)
|
|
if column.is_default or column.cards.filter(archived=False).exists():
|
|
raise ValidationError('Choose another default and move cards before archiving this column.')
|
|
column.archived = True
|
|
column.save(update_fields=['archived'])
|
|
return column
|
|
|
|
|
|
@transaction.atomic
|
|
def reorder_columns(user, project, ids):
|
|
project_for(user, project.pk, write=True)
|
|
columns = list(project.board.columns.filter(archived=False))
|
|
if len(ids) != len(columns) or set(map(str, ids)) != {str(c.pk) for c in columns}:
|
|
raise ValidationError('Invalid column order.')
|
|
for index, identifier in enumerate(ids):
|
|
Column.objects.filter(pk=identifier, board=project.board).update(position=index)
|
|
return columns
|
|
|
|
|
|
@transaction.atomic
|
|
def shift_column(user, column, direction):
|
|
project = project_for(user, column.board.project_id, write=True)
|
|
ids = [str(c.pk) for c in project.board.columns.filter(archived=False)]
|
|
index = ids.index(str(column.pk))
|
|
target = max(0, min(index + direction, len(ids) - 1))
|
|
ids[index], ids[target] = ids[target], ids[index]
|
|
reorder_columns(user, project, ids)
|
|
return column
|
|
|
|
|
|
@transaction.atomic
|
|
def update_column(user, column, *, name=None, color=None, is_done=None, origin='web'):
|
|
column = Column.objects.select_for_update().get(pk=column.pk)
|
|
project = project_for(user, column.board.project_id, write=True)
|
|
if name is not None:
|
|
column.name = name
|
|
if color is not None:
|
|
column.color = color
|
|
completion_changed = is_done is not None and column.is_done != is_done
|
|
if is_done is not None:
|
|
column.is_done = is_done
|
|
column.full_clean()
|
|
column.save()
|
|
if completion_changed:
|
|
Card.objects.filter(column=column, archived=False).update(completed_at=timezone.now() if is_done else None)
|
|
Activity.objects.create(project=project, actor=user, action='column.updated', detail={'column_id': str(column.pk)}, origin=origin)
|
|
return column
|
|
|
|
|
|
def set_assignee(user, card, assignee, origin='web'):
|
|
project_for(user, card.project_id, write=True)
|
|
if assignee and assignee.pk != card.project.owner_id and not Membership.objects.filter(project=card.project, user=assignee).exists():
|
|
raise ValidationError('Assignee must have access to this project.')
|
|
card.assignee = assignee
|
|
card.save(update_fields=['assignee', 'updated_at'])
|
|
Activity.objects.create(project=card.project, card=card, actor=user, action='card.assigned', detail={'assignee': assignee.pk if assignee else None}, origin=origin)
|
|
return card
|
|
|
|
|
|
@transaction.atomic
|
|
def set_tags(user, card, tags, origin='web'):
|
|
project_for(user, card.project_id, write=True)
|
|
tags = list(tags)
|
|
if any(tag.project_id != card.project_id for tag in tags):
|
|
raise ValidationError('Tags must belong to this project.')
|
|
card.tags.set(tags)
|
|
Activity.objects.create(project=card.project, card=card, actor=user, action='card.tags_changed', origin=origin)
|
|
return card
|