feat: task relatedTasks script setup

This commit is contained in:
Dominik Pschenitschni 2022-09-15 12:52:38 +02:00
parent a38075f376
commit 943d5f7975
No known key found for this signature in database
GPG key ID: B257AC0149F43A77
7 changed files with 239 additions and 226 deletions

View file

@ -25,49 +25,48 @@
</transition> </transition>
</label> </label>
<div class="field" key="field-search"> <div class="field" key="field-search">
<multiselect <Multiselect
:placeholder="$t('task.relation.searchPlaceholder')" :placeholder="$t('task.relation.searchPlaceholder')"
@search="findTasks" @search="findTasks"
:loading="taskService.loading" :loading="taskService.loading"
:search-results="mappedFoundTasks" :search-results="mappedFoundTasks"
label="title" label="title"
v-model="newTaskRelationTask" v-model="newTaskRelation.task"
:creatable="true" :creatable="true"
:create-placeholder="$t('task.relation.createPlaceholder')" :create-placeholder="$t('task.relation.createPlaceholder')"
@create="createAndRelateTask" @create="createAndRelateTask"
@select="addTaskRelation"
> >
<template #searchResult="props"> <template #searchResult="{option: task}">
<span v-if="typeof props.option !== 'string'" class="search-result"> <span v-if="typeof task !== 'string'" class="search-result">
<span <span
class="different-list" class="different-list"
v-if="props.option.listId !== listId" v-if="task.listId !== listId"
> >
<span <span
v-if="props.option.differentNamespace !== null" v-if="task.differentNamespace !== null"
v-tooltip="$t('task.relation.differentNamespace')"> v-tooltip="$t('task.relation.differentNamespace')">
{{ props.option.differentNamespace }} > {{ task.differentNamespace }} >
</span> </span>
<span <span
v-if="props.option.differentList !== null" v-if="task.differentList !== null"
v-tooltip="$t('task.relation.differentList')"> v-tooltip="$t('task.relation.differentList')">
{{ props.option.differentList }} > {{ task.differentList }} >
</span> </span>
</span> </span>
{{ props.option.title }} {{ task.title }}
</span> </span>
<span class="search-result" v-else> <span class="search-result" v-else>
{{ props.option }} {{ task }}
</span> </span>
</template> </template>
</multiselect> </Multiselect>
</div> </div>
<div class="field has-addons mb-4" key="field-kind"> <div class="field has-addons mb-4" key="field-kind">
<div class="control is-expanded"> <div class="control is-expanded">
<div class="select is-fullwidth has-defaults"> <div class="select is-fullwidth has-defaults">
<select v-model="newTaskRelationKind"> <select v-model="newTaskRelation.kind">
<option value="unset">{{ $t('task.relation.select') }}</option> <option value="unset">{{ $t('task.relation.select') }}</option>
<option :key="rk" :value="rk" v-for="rk in relationKinds"> <option :key="`option_${rk}`" :value="rk" v-for="rk in RELATION_KINDS">
{{ $tc(`task.relation.kinds.${rk}`, 1) }} {{ $tc(`task.relation.kinds.${rk}`, 1) }}
</option> </option>
</select> </select>
@ -85,7 +84,7 @@
<div class="tasks"> <div class="tasks">
<div :key="t.id" class="task" v-for="t in rts.tasks"> <div :key="t.id" class="task" v-for="t in rts.tasks">
<router-link <router-link
:to="{ name: $route.name, params: { id: t.id } }" :to="{ name: route.name as string, params: { id: t.id } }"
:class="{ 'is-strikethrough': t.done}"> :class="{ 'is-strikethrough': t.done}">
<span <span
class="different-list" class="different-list"
@ -106,7 +105,10 @@
</router-link> </router-link>
<BaseButton <BaseButton
v-if="editEnabled" v-if="editEnabled"
@click="() => {showDeleteModal = true; relationToDelete = {relationKind: rts.kind, otherTaskId: t.id}}" @click="setRelationToDelete({
relationKind: rts.kind,
otherTaskId: t.id
})"
class="remove" class="remove"
> >
<icon icon="trash-alt"/> <icon icon="trash-alt"/>
@ -118,204 +120,216 @@
{{ $t('task.relation.noneYet') }} {{ $t('task.relation.noneYet') }}
</p> </p>
<!-- Delete modal --> <modal
<transition name="modal"> v-if="relationToDelete !== undefined"
<modal @close="relationToDelete = undefined"
@close="showDeleteModal = false" @submit="removeTaskRelation()"
@submit="removeTaskRelation()" >
v-if="showDeleteModal" <template #header><span>{{ $t('task.relation.delete') }}</span></template>
>
<template #header><span>{{ $t('task.relation.delete') }}</span></template>
<template #text> <template #text>
<p> <p>
{{ $t('task.relation.deleteText1') }}<br/> {{ $t('task.relation.deleteText1') }}<br/>
<strong class="has-text-white">{{ $t('misc.cannotBeUndone') }}</strong> <strong class="has-text-white">{{ $t('misc.cannotBeUndone') }}</strong>
</p> </p>
</template> </template>
</modal> </modal>
</transition>
</div> </div>
</template> </template>
<script lang="ts"> <script setup lang="ts">
import {defineComponent} from 'vue' import {ref, reactive, shallowReactive, watch, computed, type PropType} from 'vue'
import {useI18n} from 'vue-i18n'
import {useRoute} from 'vue-router'
import {useStore} from '@/store'
import TaskService from '../../../services/task' import TaskService from '@/services/task'
import TaskModel from '../../../models/task' import TaskModel from '@/models/task'
import TaskRelationService from '../../../services/taskRelation' import type {ITask} from '@/modelTypes/ITask'
import type {ITaskRelation} from '@/modelTypes/ITaskRelation'
import {RELATION_KINDS, RELATION_KIND, type IRelationKind} from '@/types/IRelationKind'
import TaskRelationService from '@/services/taskRelation'
import TaskRelationModel from '@/models/taskRelation' import TaskRelationModel from '@/models/taskRelation'
import { RELATION_KIND, RELATION_KINDS } from '@/types/IRelationKind'
import BaseButton from '@/components/base/BaseButton.vue' import BaseButton from '@/components/base/BaseButton.vue'
import Multiselect from '@/components/input/multiselect.vue' import Multiselect from '@/components/input/multiselect.vue'
import { error } from '@/message'
export default defineComponent({ const props = defineProps({
name: 'relatedTasks', taskId: {
data() { type: Number,
return { required: true,
relatedTasks: {},
taskService: new TaskService(),
foundTasks: [],
relationKinds: RELATION_KINDS,
newTaskRelationTask: new TaskModel(),
newTaskRelationKind: RELATION_KIND.RELATED,
taskRelationService: new TaskRelationService(),
showDeleteModal: false,
relationToDelete: {},
saved: false,
showNewRelationForm: false,
query: '',
}
}, },
components: { initialRelatedTasks: {
BaseButton, type: Object as PropType<ITask['relatedTasks']>,
Multiselect, default: () => ({}),
}, },
props: { showNoRelationsNotice: {
taskId: { type: Boolean,
type: Number, default: false,
required: true,
},
initialRelatedTasks: {
type: Object,
default: () => {
},
},
showNoRelationsNotice: {
type: Boolean,
default: false,
},
listId: {
type: Number,
default: 0,
},
editEnabled: {
default: true,
},
}, },
watch: { listId: {
initialRelatedTasks: { type: Number,
handler(value) { default: 0,
this.relatedTasks = value
},
immediate: true,
},
}, },
computed: { editEnabled: {
showCreate() { default: true,
return Object.keys(this.relatedTasks).length === 0 || this.showNewRelationForm
},
namespace() {
return this.$store.getters['namespaces/getListAndNamespaceById'](this.listId, true)?.namespace
},
mappedRelatedTasks() {
return Object.entries(this.relatedTasks).map(([kind, tasks]) => ({
title: this.$tc(`task.relation.kinds.${kind}`, tasks.length),
tasks: this.mapRelatedTasks(tasks),
kind,
}))
},
mappedFoundTasks() {
return this.mapRelatedTasks(this.foundTasks.filter(t => t.id !== this.taskId))
},
},
methods: {
async findTasks(query: string) {
this.query = query
this.foundTasks = await this.taskService.getAll({}, {s: query})
},
async addTaskRelation() {
if (this.newTaskRelationTask.id === 0 && this.query !== '') {
return this.createAndRelateTask(this.query)
}
if (this.newTaskRelationTask.id === 0) {
this.$message.error({message: this.$t('task.relation.taskRequired')})
return
}
const rel = new TaskRelationModel({
taskId: this.taskId,
otherTaskId: this.newTaskRelationTask.id,
relationKind: this.newTaskRelationKind,
})
await this.taskRelationService.create(rel)
if (!this.relatedTasks[this.newTaskRelationKind]) {
this.relatedTasks[this.newTaskRelationKind] = []
}
this.relatedTasks[this.newTaskRelationKind].push(this.newTaskRelationTask)
this.newTaskRelationTask = null
this.saved = true
this.showNewRelationForm = false
setTimeout(() => {
this.saved = false
}, 2000)
},
async removeTaskRelation() {
const rel = new TaskRelationModel({
relationKind: this.relationToDelete.relationKind,
taskId: this.taskId,
otherTaskId: this.relationToDelete.otherTaskId,
})
try {
await this.taskRelationService.delete(rel)
const kind = this.relationToDelete.relationKind
for (const t in this.relatedTasks[kind]) {
if (this.relatedTasks[kind][t].id === this.relationToDelete.otherTaskId) {
this.relatedTasks[kind].splice(t, 1)
break
}
}
this.saved = true
setTimeout(() => {
this.saved = false
}, 2000)
} finally {
this.showDeleteModal = false
}
},
async createAndRelateTask(title) {
const newTask = new TaskModel({title: title, listId: this.listId})
this.newTaskRelationTask = await this.taskService.create(newTask)
await this.addTaskRelation()
},
relationKindTitle(kind, length) {
return this.$tc(`task.relation.kinds.${kind}`, length)
},
mapRelatedTasks(tasks) {
return tasks
.map(task => {
// by doing this here once we can save a lot of duplicate calls in the template
const listAndNamespace = this.$store.getters['namespaces/getListAndNamespaceById'](task.listId, true)
const {
list,
namespace,
} = listAndNamespace === null ? {list: null, namespace: null} : listAndNamespace
return {
...task,
differentNamespace:
(namespace !== null &&
namespace.id !== this.namespace.id &&
namespace?.title) || null,
differentList:
(list !== null &&
task.listId !== this.listId &&
list?.title) || null,
}
})
},
}, },
}) })
const store = useStore()
const route = useRoute()
const {t} = useI18n({useScope: 'global'})
type TaskRelation = {kind: IRelationKind, task: ITask}
const taskService = shallowReactive(new TaskService())
const relatedTasks = ref<ITask['relatedTasks']>({})
const newTaskRelation: TaskRelation = reactive({
kind: RELATION_KIND.RELATED,
task: new TaskModel(),
})
watch(
() => props.initialRelatedTasks,
(value) => {
relatedTasks.value = value
},
{immediate: true},
)
const showNewRelationForm = ref(false)
const showCreate = computed(() => Object.keys(relatedTasks.value).length === 0 || showNewRelationForm.value)
const query = ref('')
const foundTasks = ref<ITask[]>([])
async function findTasks(newQuery: string) {
query.value = newQuery
foundTasks.value = await taskService.getAll({}, {s: newQuery})
}
const getListAndNamespaceById = (listId: number) => store.getters['namespaces/getListAndNamespaceById'](listId, true)
const namespace = computed(() => getListAndNamespaceById(props.listId)?.namespace)
function mapRelatedTasks(tasks: ITask[]) {
return tasks.map(task => {
// by doing this here once we can save a lot of duplicate calls in the template
const {
list,
namespace: taskNamespace,
} = getListAndNamespaceById(task.listId) || {list: null, namespace: null}
return {
...task,
differentNamespace:
(taskNamespace !== null &&
taskNamespace.id !== namespace.value.id &&
taskNamespace?.title) || null,
differentList:
(list !== null &&
task.listId !== props.listId &&
list?.title) || null,
}
})
}
const mapRelationKindsTitleGetter = computed(() => ({
'subtask': (count: number) => t('task.relation.kinds.subtask', count),
'parenttask': (count: number) => t('task.relation.kinds.parenttask', count),
'related': (count: number) => t('task.relation.kinds.related', count),
'duplicateof': (count: number) => t('task.relation.kinds.duplicateof', count),
'duplicates': (count: number) => t('task.relation.kinds.duplicates', count),
'blocking': (count: number) => t('task.relation.kinds.blocking', count),
'blocked': (count: number) => t('task.relation.kinds.blocked', count),
'precedes': (count: number) => t('task.relation.kinds.precedes', count),
'follows': (count: number) => t('task.relation.kinds.follows', count),
'copiedfrom': (count: number) => t('task.relation.kinds.copiedfrom', count),
'copiedto': (count: number) => t('task.relation.kinds.copiedto', count),
}))
const mappedRelatedTasks = computed(() => Object.entries(relatedTasks.value).map(
([kind, tasks]) => ({
title: mapRelationKindsTitleGetter.value[kind as IRelationKind](tasks.length),
tasks: mapRelatedTasks(tasks),
kind: kind as IRelationKind,
}),
))
const mappedFoundTasks = computed(() => mapRelatedTasks(foundTasks.value.filter(t => t.id !== props.taskId)))
const taskRelationService = shallowReactive(new TaskRelationService())
const saved = ref(false)
async function addTaskRelation() {
if (newTaskRelation.task.id === 0 && query.value !== '') {
return createAndRelateTask(query.value)
}
if (newTaskRelation.task.id === 0) {
error({message: t('task.relation.taskRequired')})
return
}
await taskRelationService.create(new TaskRelationModel({
taskId: props.taskId,
otherTaskId: newTaskRelation.task.id,
relationKind: newTaskRelation.kind,
}))
relatedTasks.value[newTaskRelation.kind] = [
...(relatedTasks.value[newTaskRelation.kind] || []),
newTaskRelation.task,
]
newTaskRelation.task = new TaskModel()
saved.value = true
showNewRelationForm.value = false
setTimeout(() => {
saved.value = false
}, 2000)
}
const relationToDelete = ref<Partial<ITaskRelation>>()
function setRelationToDelete(relation: Partial<ITaskRelation>) {
relationToDelete.value = relation
}
async function removeTaskRelation() {
const relation = relationToDelete.value
if (!relation || !relation.relationKind || !relation.otherTaskId) {
relationToDelete.value = undefined
return
}
try {
const relationKind = relation.relationKind
await taskRelationService.delete(new TaskRelationModel({
relationKind,
taskId: props.taskId,
otherTaskId: relation.otherTaskId,
}))
relatedTasks.value[relationKind] = relatedTasks.value[relationKind]?.filter(
({id}) => id !== relation.otherTaskId,
)
saved.value = true
setTimeout(() => {
saved.value = false
}, 2000)
} finally {
relationToDelete.value = undefined
}
}
async function createAndRelateTask(title: string) {
const newTask = await taskService.create(new TaskModel({title, listId: props.listId}))
console.log('new task created', JSON.parse(JSON.stringify(newTask)))
newTaskRelation.task = newTask
await addTaskRelation()
}
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@ -366,15 +380,16 @@ export default defineComponent({
} }
} }
.remove {
text-align: center;
color: var(--danger);
opacity: 0;
transition: opacity $transition;
}
} }
.related-tasks:hover .tasks .task .remove { .remove {
text-align: center;
color: var(--danger);
opacity: 0;
transition: opacity $transition;
}
.task:hover .remove {
opacity: 1; opacity: 1;
} }

View file

@ -31,7 +31,7 @@ export interface ITask extends IAbstract {
parentTaskId: ITask['id'] parentTaskId: ITask['id']
hexColor: string hexColor: string
percentDone: number percentDone: number
relatedTasks: Partial<Record<IRelationKind, ITask>>, relatedTasks: Partial<Record<IRelationKind, ITask[]>>,
attachments: IAttachment[] attachments: IAttachment[]
identifier: string identifier: string
index: number index: number

View file

@ -56,7 +56,7 @@ export default class TaskModel extends AbstractModel<ITask> implements ITask {
parentTaskId: ITask['id'] = 0 parentTaskId: ITask['id'] = 0
hexColor = '' hexColor = ''
percentDone = 0 percentDone = 0
relatedTasks: Partial<Record<IRelationKind, ITask>> = {} relatedTasks: Partial<Record<IRelationKind, ITask[]>> = {}
attachments: IAttachment[] = [] attachments: IAttachment[] = []
identifier = '' identifier = ''
index = 0 index = 0
@ -73,7 +73,7 @@ export default class TaskModel extends AbstractModel<ITask> implements ITask {
listId: IList['id'] = 0 listId: IList['id'] = 0
bucketId: IBucket['id'] = 0 bucketId: IBucket['id'] = 0
constructor(data: Partial<ITask>) { constructor(data: Partial<ITask> = {}) {
super() super()
this.assignData(data) this.assignData(data)
@ -109,7 +109,7 @@ export default class TaskModel extends AbstractModel<ITask> implements ITask {
this.hexColor = '#' + this.hexColor this.hexColor = '#' + this.hexColor
} }
// Make all subtasks to task models // Convert all subtasks to task models
Object.keys(this.relatedTasks).forEach(relationKind => { Object.keys(this.relatedTasks).forEach(relationKind => {
this.relatedTasks[relationKind] = this.relatedTasks[relationKind].map(t => { this.relatedTasks[relationKind] = this.relatedTasks[relationKind].map(t => {
return new TaskModel(t) return new TaskModel(t)

View file

@ -5,15 +5,15 @@ import type {ITaskRelation} from '@/modelTypes/ITaskRelation'
import type {ITask} from '@/modelTypes/ITask' import type {ITask} from '@/modelTypes/ITask'
import type {IUser} from '@/modelTypes/IUser' import type {IUser} from '@/modelTypes/IUser'
import type {IRelationKind} from '@/types/IRelationKind' import {RELATION_KIND, type IRelationKind} from '@/types/IRelationKind'
export default class TaskRelationModel extends AbstractModel<ITaskRelation> implements ITaskRelation { export default class TaskRelationModel extends AbstractModel<ITaskRelation> implements ITaskRelation {
id = 0 id = 0
otherTaskId: ITask['id'] = 0 otherTaskId: ITask['id'] = 0
taskId: ITask['id'] = 0 taskId: ITask['id'] = 0
relationKind: IRelationKind = '' relationKind: IRelationKind = RELATION_KIND.RELATED
createdBy: IUser = UserModel createdBy: IUser = new UserModel()
created: Date = null created: Date = new Date
constructor(data: Partial<ITaskRelation>) { constructor(data: Partial<ITaskRelation>) {
super() super()

View file

@ -14,7 +14,7 @@ export default class UserModel extends AbstractModel<IUser> implements IUser {
updated: Date = null updated: Date = null
settings: IUserSettings = null settings: IUserSettings = null
constructor(data: Partial<IUser>) { constructor(data: Partial<IUser> = {}) {
super() super()
this.assignData(data) this.assignData(data)

View file

@ -3,8 +3,6 @@ import type { RouteLocation } from 'vue-router'
import {saveLastVisited} from '@/helpers/saveLastVisited' import {saveLastVisited} from '@/helpers/saveLastVisited'
import {store} from '@/store' import {store} from '@/store'
import type ListModel from '@/models/list'
import {saveListView, getListView} from '@/helpers/saveListView' import {saveListView, getListView} from '@/helpers/saveListView'
import {parseDateOrString} from '@/helpers/time/parseDateOrString' import {parseDateOrString} from '@/helpers/time/parseDateOrString'
import {getNextWeekDate} from '@/helpers/time/getNextWeekDate' import {getNextWeekDate} from '@/helpers/time/getNextWeekDate'
@ -223,7 +221,7 @@ const router = createRouter({
meta: { meta: {
showAsModal: true, showAsModal: true,
}, },
props: route => ({ namespaceId: parseInt(route.params.id as string) }), props: route => ({ namespaceId: Number(route.params.id as string) }),
}, },
{ {
path: '/namespaces/:namespaceId/settings/share', path: '/namespaces/:namespaceId/settings/share',
@ -254,7 +252,7 @@ const router = createRouter({
path: '/tasks/:id', path: '/tasks/:id',
name: 'task.detail', name: 'task.detail',
component: TaskDetailView, component: TaskDetailView,
props: route => ({ taskId: parseInt(route.params.id as string) }), props: route => ({ taskId: Number(route.params.id as string) }),
}, },
{ {
path: '/tasks/by/upcoming', path: '/tasks/by/upcoming',
@ -279,7 +277,7 @@ const router = createRouter({
path: '/lists/:listId/settings/edit', path: '/lists/:listId/settings/edit',
name: 'list.settings.edit', name: 'list.settings.edit',
component: ListSettingEdit, component: ListSettingEdit,
props: route => ({ listId: parseInt(route.params.listId as ListModel['id']) }), props: route => ({ listId: Number(route.params.listId as string) }),
meta: { meta: {
showAsModal: true, showAsModal: true,
}, },
@ -371,21 +369,21 @@ const router = createRouter({
name: 'list.list', name: 'list.list',
component: ListList, component: ListList,
beforeEnter: (to) => saveListView(to.params.listId, to.name), beforeEnter: (to) => saveListView(to.params.listId, to.name),
props: route => ({ listId: parseInt(route.params.listId as string) }), props: route => ({ listId: Number(route.params.listId as string) }),
}, },
{ {
path: '/lists/:listId/gantt', path: '/lists/:listId/gantt',
name: 'list.gantt', name: 'list.gantt',
component: ListGantt, component: ListGantt,
beforeEnter: (to) => saveListView(to.params.listId, to.name), beforeEnter: (to) => saveListView(to.params.listId, to.name),
props: route => ({ listId: parseInt(route.params.listId as string) }), props: route => ({ listId: Number(route.params.listId as string) }),
}, },
{ {
path: '/lists/:listId/table', path: '/lists/:listId/table',
name: 'list.table', name: 'list.table',
component: ListTable, component: ListTable,
beforeEnter: (to) => saveListView(to.params.listId, to.name), beforeEnter: (to) => saveListView(to.params.listId, to.name),
props: route => ({ listId: parseInt(route.params.listId as string) }), props: route => ({ listId: Number(route.params.listId as string) }),
}, },
{ {
path: '/lists/:listId/kanban', path: '/lists/:listId/kanban',
@ -400,7 +398,7 @@ const router = createRouter({
setTitle(listFromStore.title) setTitle(listFromStore.title)
} }
}, },
props: route => ({ listId: parseInt(route.params.listId as string) }), props: route => ({ listId: Number(route.params.listId as string) }),
}, },
{ {
path: '/teams', path: '/teams',

View file

@ -153,10 +153,10 @@ export const useListStore = defineStore('list', {
}, },
}) })
export function useList(listId: MaybeRef<ListModel['id']>) { export function useList(listId: MaybeRef<IList['id']>) {
const listService = shallowReactive(new ListService()) const listService = shallowReactive(new ListService())
const {loading: isLoading} = toRefs(listService) const {loading: isLoading} = toRefs(listService)
const list : ListModel = reactive(new ListModel({})) const list: ListModel = reactive(new ListModel())
const {t} = useI18n({useScope: 'global'}) const {t} = useI18n({useScope: 'global'})
watch( watch(