Skip to content

Commit

Permalink
Merge pull request #173 from seanmorley15/development
Browse files Browse the repository at this point in the history
Collection Archive Update
  • Loading branch information
seanmorley15 authored Aug 7, 2024
2 parents 1efa19b + a87797f commit 48dbe1b
Show file tree
Hide file tree
Showing 10 changed files with 232 additions and 34 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.7 on 2024-08-07 16:20

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('adventures', '0020_checklist_checklistitem'),
]

operations = [
migrations.AddField(
model_name='collection',
name='is_archived',
field=models.BooleanField(default=False),
),
]
1 change: 1 addition & 0 deletions backend/server/adventures/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class Collection(models.Model):
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True)
is_archived = models.BooleanField(default=False)


# if connected adventures are private and collection is public, raise an error
Expand Down
2 changes: 1 addition & 1 deletion backend/server/adventures/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,5 +205,5 @@ class CollectionSerializer(serializers.ModelSerializer):
class Meta:
model = Collection
# fields are all plus the adventures field
fields = ['id', 'description', 'user_id', 'name', 'is_public', 'adventures', 'created_at', 'start_date', 'end_date', 'transportations', 'notes', 'updated_at', 'checklists']
fields = ['id', 'description', 'user_id', 'name', 'is_public', 'adventures', 'created_at', 'start_date', 'end_date', 'transportations', 'notes', 'updated_at', 'checklists', 'is_archived']
read_only_fields = ['id', 'created_at', 'updated_at', 'user_id']
54 changes: 26 additions & 28 deletions backend/server/adventures/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,8 @@ class CollectionViewSet(viewsets.ModelViewSet):
permission_classes = [IsOwnerOrReadOnly, IsPublicReadOnly]
pagination_class = StandardResultsSetPagination

def get_queryset(self):
print(self.request.user.id)
return Collection.objects.filter(user_id=self.request.user.id)
# def get_queryset(self):
# return Collection.objects.filter(Q(user_id=self.request.user.id) & Q(is_archived=False))

def apply_sorting(self, queryset):
order_by = self.request.query_params.get('order_by', 'name')
Expand Down Expand Up @@ -263,6 +262,20 @@ def all(self, request):

return Response(serializer.data)

@action(detail=False, methods=['get'])
def archived(self, request):
if not request.user.is_authenticated:
return Response({"error": "User is not authenticated"}, status=400)

queryset = Collection.objects.filter(
Q(user_id=request.user.id) & Q(is_archived=True)
)

queryset = self.apply_sorting(queryset)
serializer = self.get_serializer(queryset, many=True)

return Response(serializer.data)

# this make the is_public field of the collection cascade to the adventures
@transaction.atomic
def update(self, request, *args, **kwargs):
Expand Down Expand Up @@ -298,36 +311,21 @@ def update(self, request, *args, **kwargs):
return Response(serializer.data)

def get_queryset(self):

adventures = None
if self.action == 'destroy':
return Collection.objects.filter(user_id=self.request.user.id)

if self.action in ['update', 'partial_update']:
return Collection.objects.filter(user_id=self.request.user.id)

if self.action == 'retrieve':
# For individual collection retrieval, include public collections
adventures = Collection.objects.filter(
return Collection.objects.filter(
Q(is_public=True) | Q(user_id=self.request.user.id)
)
else:
# For other actions, only include user's own collections
adventures = Collection.objects.filter(user_id=self.request.user.id)

# adventures = adventures.prefetch_related(
# Prefetch('adventure_set', queryset=Adventure.objects.filter(
# Q(is_public=True) | Q(user_id=self.request.user.id)
# ))
# ).prefetch_related(
# Prefetch('transportation_set', queryset=Transportation.objects.filter(
# Q(is_public=True) | Q(user_id=self.request.user.id)
# ))
# ).prefetch_related(
# Prefetch('note_set', queryset=Note.objects.filter(
# Q(is_public=True) | Q(user_id=self.request.user.id)
# ))
# ).prefetch_related(
# Prefetch('checklist_set', queryset=Checklist.objects.filter(
# Q(is_public=True) | Q(user_id=self.request.user.id)
# ))
# )
return self.apply_sorting(adventures)
# For other actions (like list), only include user's non-archived collections
return Collection.objects.filter(
Q(user_id=self.request.user.id) & Q(is_archived=False)
)

def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
Expand Down
61 changes: 56 additions & 5 deletions frontend/src/lib/components/CollectionCard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
import TrashCanOutline from '~icons/mdi/trash-can-outline';
import FileDocumentEdit from '~icons/mdi/file-document-edit';
import ArchiveArrowDown from '~icons/mdi/archive-arrow-down';
import ArchiveArrowUp from '~icons/mdi/archive-arrow-up';
import { goto } from '$app/navigation';
import type { Collection } from '$lib/types';
import { addToast } from '$lib/toasts';
import Plus from '~icons/mdi/plus';
import { json } from '@sveltejs/kit';
import DeleteWarning from './DeleteWarning.svelte';
const dispatch = createEventDispatcher();
Expand All @@ -22,6 +26,24 @@
dispatch('edit', collection);
}
async function archiveCollection(is_archived: boolean) {
console.log(JSON.stringify({ is_archived: is_archived }));
let res = await fetch(`/api/collections/${collection.id}/`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ is_archived: is_archived })
});
if (res.ok) {
console.log(`Collection ${is_archived ? 'archived' : 'unarchived'}`);
addToast('info', `Adventure ${is_archived ? 'archived' : 'unarchived'} successfully!`);
dispatch('delete', collection.id);
} else {
console.log('Error archiving adventure');
}
}
export let collection: Collection;
async function deleteCollection() {
Expand All @@ -39,8 +61,21 @@
console.log('Error deleting adventure');
}
}
let isWarningModalOpen: boolean = false;
</script>

{#if isWarningModalOpen}
<DeleteWarning
title="Delete Collection"
button_text="Delete"
description="Are you sure you want to delete this collection? This action cannot be undone."
is_warning={true}
on:close={() => (isWarningModalOpen = false)}
on:confirm={deleteCollection}
/>
{/if}

<div
class="card min-w-max lg:w-96 md:w-80 sm:w-60 xs:w-40 bg-primary-content shadow-xl overflow-hidden text-base-content"
>
Expand All @@ -61,15 +96,22 @@
) + 1}{' '}
days
</p>{/if}
<div class="badge badge-neutral">{collection.is_public ? 'Public' : 'Private'}</div>
<div class="inline-flex gap-2 mb-2">
<div class="badge badge-neutral">{collection.is_public ? 'Public' : 'Private'}</div>
{#if collection.is_archived}
<div class="badge badge-warning">Archived</div>
{/if}
</div>
<div class="card-actions justify-end">
{#if type != 'link'}
<button on:click={deleteCollection} class="btn btn-secondary"
<button on:click={() => (isWarningModalOpen = true)} class="btn btn-secondary"
><TrashCanOutline class="w-5 h-5 mr-1" /></button
>
<button class="btn btn-primary" on:click={editAdventure}>
<FileDocumentEdit class="w-6 h-6" />
</button>
{#if !collection.is_archived}
<button class="btn btn-primary" on:click={editAdventure}>
<FileDocumentEdit class="w-6 h-6" />
</button>
{/if}
<button class="btn btn-primary" on:click={() => goto(`/collections/${collection.id}`)}
><Launch class="w-5 h-5 mr-1" /></button
>
Expand All @@ -79,6 +121,15 @@
<Plus class="w-5 h-5 mr-1" />
</button>
{/if}
{#if collection.is_archived}
<button class="btn btn-primary" on:click={() => archiveCollection(false)}>
<ArchiveArrowUp class="w-5 h-5 mr-1" />
</button>
{:else}
<button class="btn btn-primary" on:click={() => archiveCollection(true)}>
<ArchiveArrowDown class="w-5 h-5 mr" />
</button>
{/if}
</div>
</div>
</div>
44 changes: 44 additions & 0 deletions frontend/src/lib/components/DeleteWarning.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import { onMount } from 'svelte';
let modal: HTMLDialogElement;
export let title: string;
export let button_text: string;
export let description: string;
export let is_warning: boolean;
onMount(() => {
modal = document.getElementById('my_modal_1') as HTMLDialogElement;
if (modal) {
modal.showModal();
}
});
function close() {
dispatch('close');
}
function confirm() {
dispatch('close');
dispatch('confirm');
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
dispatch('close');
}
}
</script>

<dialog id="my_modal_1" class="modal {is_warning ? 'bg-primary' : ''}">
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<div class="modal-box" role="dialog" on:keydown={handleKeydown} tabindex="0">
<h3 class="font-bold text-lg">{title}</h3>
<p class="py-1 mb-4">{description}</p>
<button class="btn btn-warning mr-2" on:click={confirm}>{button_text}</button>
<button class="btn btn-neutral" on:click={close}>Cancel</button>
</div>
</dialog>
1 change: 1 addition & 0 deletions frontend/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export type Collection = {
transportations?: Transportation[];
notes?: Note[];
checklists?: Checklist[];
is_archived?: boolean;
};

export type OpenStreetMapPlace = {
Expand Down
6 changes: 6 additions & 0 deletions frontend/src/routes/collections/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script lang="ts">
import { enhance, deserialize } from '$app/forms';
import { goto } from '$app/navigation';
import AdventureCard from '$lib/components/AdventureCard.svelte';
import CollectionCard from '$lib/components/CollectionCard.svelte';
import EditAdventure from '$lib/components/EditAdventure.svelte';
Expand Down Expand Up @@ -247,6 +248,11 @@
<button type="submit" class="btn btn-success btn-primary mt-4">Filter</button>
</form>
<div class="divider"></div>
<button
type="submit"
class="btn btn-neutral btn-primary mt-4"
on:click={() => goto('/collections/archived')}>Archived Collections</button
>
</div>
</ul>
</div>
Expand Down
35 changes: 35 additions & 0 deletions frontend/src/routes/collections/archived/+page.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Adventure } from '$lib/types';
const serverEndpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';

export const load = (async (event) => {
if (!event.locals.user) {
return redirect(302, '/login');
} else {
let next = null;
let previous = null;
let count = 0;
let adventures: Adventure[] = [];
let initialFetch = await fetch(`${serverEndpoint}/api/collections/archived/`, {
headers: {
Cookie: `${event.cookies.get('auth')}`
}
});
if (!initialFetch.ok) {
console.error('Failed to fetch visited adventures');
return redirect(302, '/login');
} else {
let res = await initialFetch.json();
let visited = res as Adventure[];
adventures = [...adventures, ...visited];
}

return {
props: {
adventures
}
};
}
}) satisfies PageServerLoad;
44 changes: 44 additions & 0 deletions frontend/src/routes/collections/archived/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<script lang="ts">
import { enhance, deserialize } from '$app/forms';
import AdventureCard from '$lib/components/AdventureCard.svelte';
import CollectionCard from '$lib/components/CollectionCard.svelte';
import EditAdventure from '$lib/components/EditAdventure.svelte';
import EditCollection from '$lib/components/EditCollection.svelte';
import NewAdventure from '$lib/components/NewAdventure.svelte';
import NewCollection from '$lib/components/NewCollection.svelte';
import NotFound from '$lib/components/NotFound.svelte';
import type { Adventure, Collection } from '$lib/types';
import Plus from '~icons/mdi/plus';
export let data: any;
console.log(data);
let collections: Collection[] = data.props.adventures || [];
function deleteCollection(event: CustomEvent<number>) {
collections = collections.filter((collection) => collection.id !== event.detail);
}
</script>

<div class="drawer lg:drawer-open">
<div class="drawer-content">
<!-- Page content -->
<h1 class="text-center font-bold text-4xl mb-6">Archived Collections</h1>
{#if collections.length === 0}
<NotFound error={undefined} />
{/if}
<div class="p-4">
<div class="flex flex-wrap gap-4 mr-4 justify-center content-center">
{#each collections as collection}
<CollectionCard type="" {collection} on:delete={deleteCollection} />
{/each}
</div>
</div>
</div>
</div>

<svelte:head>
<title>Collections</title>
<meta name="description" content="View your adventure collections." />
</svelte:head>

0 comments on commit 48dbe1b

Please sign in to comment.