122 lines
5.8 KiB
Python
122 lines
5.8 KiB
Python
from django.core.exceptions import PermissionDenied, ValidationError
|
|
from django.db import transaction
|
|
from django.db.models import Q, Max
|
|
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, Membership, Project
|
|
|
|
|
|
class RevisionConflict(Exception):
|
|
def __init__(self, current):
|
|
self.current = current
|
|
|
|
|
|
def accessible(user):
|
|
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=''):
|
|
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.objects.create(owner=user, name=name, slug=slug, description=description, git_repository_url=git_repository_url)
|
|
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'):
|
|
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.')
|
|
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.objects.create(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)
|
|
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)
|
|
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 markdown_changed:
|
|
card.revision += 1
|
|
if changed:
|
|
card.save()
|
|
if markdown_changed:
|
|
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
|