Skip to content

Commit

Permalink
Merge pull request #129 from seanmorley15/development
Browse files Browse the repository at this point in the history
Development
  • Loading branch information
seanmorley15 authored Jul 16, 2024
2 parents fa1f2b1 + 58cb6ba commit 17fe400
Show file tree
Hide file tree
Showing 8 changed files with 324 additions and 27 deletions.
63 changes: 57 additions & 6 deletions backend/server/adventures/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from django.db.models import Q, Prefetch
from .permissions import IsOwnerOrReadOnly, IsPublicReadOnly
from rest_framework.pagination import PageNumberPagination
from django.shortcuts import get_object_or_404
from rest_framework import status

class StandardResultsSetPagination(PageNumberPagination):
page_size = 10
Expand Down Expand Up @@ -58,11 +60,37 @@ def apply_sorting(self, queryset):
return queryset.order_by(ordering)

def get_queryset(self):
queryset = Adventure.objects.annotate(
).filter(
Q(is_public=True) | Q(user_id=self.request.user.id)
)
return self.apply_sorting(queryset)
if self.action == 'retrieve':
# For individual adventure retrieval, include public adventures
return Adventure.objects.filter(
Q(is_public=True) | Q(user_id=self.request.user.id)
)
else:
# For other actions, only include user's own adventures
return Adventure.objects.filter(user_id=self.request.user.id)

def list(self, request, *args, **kwargs):
# Prevent listing all adventures
return Response({"detail": "Listing all adventures is not allowed."},
status=status.HTTP_403_FORBIDDEN)

def retrieve(self, request, *args, **kwargs):
queryset = self.get_queryset()
adventure = get_object_or_404(queryset, pk=kwargs['pk'])
serializer = self.get_serializer(adventure)
return Response(serializer.data)

def perform_create(self, serializer):
adventure = serializer.save(user_id=self.request.user)
if adventure.collection:
adventure.is_public = adventure.collection.is_public
adventure.save()

def perform_update(self, serializer):
adventure = serializer.save()
if adventure.collection:
adventure.is_public = adventure.collection.is_public
adventure.save()

def perform_create(self, serializer):
serializer.save(user_id=self.request.user)
Expand Down Expand Up @@ -104,7 +132,7 @@ def all(self, request):
# Q(is_public=True) | Q(user_id=request.user.id), collection=None
# )
queryset = Adventure.objects.filter(
Q(is_public=True) | Q(user_id=request.user.id)
Q(user_id=request.user.id)
)

queryset = self.apply_sorting(queryset)
Expand Down Expand Up @@ -151,6 +179,29 @@ def apply_sorting(self, queryset):

return queryset.order_by(ordering)

def list(self, request, *args, **kwargs):
# make sure the user is authenticated
if not request.user.is_authenticated:
return Response({"error": "User is not authenticated"}, status=400)
queryset = self.get_queryset()
queryset = self.apply_sorting(queryset)
collections = self.paginate_and_respond(queryset, request)
return collections

@action(detail=False, methods=['get'])
def all(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)
)

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
99 changes: 97 additions & 2 deletions frontend/src/lib/components/AdventureCard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,16 @@
import MapMarker from '~icons/mdi/map-marker';
import { addToast } from '$lib/toasts';
import Link from '~icons/mdi/link-variant';
import CheckBold from '~icons/mdi/check-bold';
import FormatListBulletedSquare from '~icons/mdi/format-list-bulleted-square';
import LinkVariantRemove from '~icons/mdi/link-variant-remove';
import Plus from '~icons/mdi/plus';
import CollectionLink from './CollectionLink.svelte';
export let type: string;
let isCollectionModalOpen: boolean = false;
export let adventure: Adventure;
async function deleteAdventure() {
Expand All @@ -32,6 +39,61 @@
}
}
async function removeFromCollection() {
let res = await fetch(`/api/adventures/${adventure.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ collection: null })
});
if (res.ok) {
console.log('Adventure removed from collection');
addToast('info', 'Adventure removed from collection successfully!');
dispatch('delete', adventure.id);
} else {
console.log('Error removing adventure from collection');
}
}
function changeType(newType: string) {
return async () => {
let res = await fetch(`/api/adventures/${adventure.id}/`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ type: newType })
});
if (res.ok) {
console.log('Adventure type changed');
addToast('info', 'Adventure type changed successfully!');
adventure.type = newType;
} else {
console.log('Error changing adventure type');
}
};
}
async function linkCollection(event: CustomEvent<number>) {
let collectionId = event.detail;
let res = await fetch(`/api/adventures/${adventure.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ collection: collectionId })
});
if (res.ok) {
console.log('Adventure linked to collection');
addToast('info', 'Adventure linked to collection successfully!');
isCollectionModalOpen = false;
dispatch('delete', adventure.id);
} else {
console.log('Error linking adventure to collection');
}
}
function editAdventure() {
dispatch('edit', adventure);
}
Expand All @@ -41,6 +103,10 @@
}
</script>

{#if isCollectionModalOpen}
<CollectionLink on:link={linkCollection} on:close={() => (isCollectionModalOpen = false)} />
{/if}

<div
class="card w-full max-w-xs sm:max-w-sm md:max-w-md lg:max-w-md xl:max-w-md bg-primary-content shadow-xl overflow-hidden text-base-content"
>
Expand All @@ -61,6 +127,14 @@
<h2 class="card-title break-words text-wrap">
{adventure.name}
</h2>
<div>
{#if adventure.type == 'visited'}
<div class="badge badge-primary">Visited</div>
{:else}
<div class="badge badge-secondary">Planned</div>
{/if}
<div class="badge badge-neutral">{adventure.is_public ? 'Public' : 'Private'}</div>
</div>
{#if adventure.location && adventure.location !== ''}
<div class="inline-flex items-center">
<MapMarker class="w-5 h-5 mr-1" />
Expand Down Expand Up @@ -90,7 +164,7 @@
<button class="btn btn-primary" on:click={editAdventure}>
<FileDocumentEdit class="w-6 h-6" />
</button>
<button class="btn btn-secondary" on:click={deleteAdventure}
<button class="btn btn-warning" on:click={deleteAdventure}
><TrashCan class="w-6 h-6" /></button
>
{/if}
Expand All @@ -101,13 +175,34 @@
<button class="btn btn-primary" on:click={editAdventure}>
<FileDocumentEdit class="w-6 h-6" />
</button>
<button class="btn btn-secondary" on:click={deleteAdventure}
<button class="btn btn-warning" on:click={deleteAdventure}
><TrashCan class="w-6 h-6" /></button
>
{/if}
{#if type == 'link'}
<button class="btn btn-primary" on:click={link}><Link class="w-6 h-6" /></button>
{/if}
{#if adventure.type == 'visited'}
<button class="btn btn-secondary" on:click={changeType('planned')}
><FormatListBulletedSquare class="w-6 h-6" /></button
>
{/if}

{#if adventure.type == 'planned'}
<button class="btn btn-secondary" on:click={changeType('visited')}
><CheckBold class="w-6 h-6" /></button
>
{/if}
{#if adventure.collection}
<button class="btn btn-secondary" on:click={removeFromCollection}
><LinkVariantRemove class="w-6 h-6" /></button
>
{/if}
{#if !adventure.collection}
<button class="btn btn-secondary" on:click={() => (isCollectionModalOpen = true)}
><Plus class="w-6 h-6" /></button
>
{/if}
</div>
</div>
</div>
30 changes: 21 additions & 9 deletions frontend/src/lib/components/CollectionCard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,13 @@
import { goto } from '$app/navigation';
import type { Collection } from '$lib/types';
import { addToast } from '$lib/toasts';
import Plus from '~icons/mdi/plus';
const dispatch = createEventDispatcher();
export let type: String | undefined | null;
// export let type: String;
function editAdventure() {
Expand Down Expand Up @@ -43,15 +48,22 @@
<h2 class="card-title overflow-ellipsis">{collection.name}</h2>
<p>{collection.adventures.length} Adventures</p>
<div class="card-actions justify-end">
<button on:click={deleteCollection} 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>
<button class="btn btn-primary" on:click={() => goto(`/collections/${collection.id}`)}
><Launch class="w-5 h-5 mr-1" /></button
>
{#if type != 'link'}
<button on:click={deleteCollection} 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>
<button class="btn btn-primary" on:click={() => goto(`/collections/${collection.id}`)}
><Launch class="w-5 h-5 mr-1" /></button
>
{/if}
{#if type == 'link'}
<button class="btn btn-primary" on:click={() => dispatch('link', collection.id)}>
<Plus class="w-5 h-5 mr-1" />
</button>
{/if}
</div>
</div>
</div>
58 changes: 58 additions & 0 deletions frontend/src/lib/components/CollectionLink.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<script lang="ts">
import type { Adventure, Collection } from '$lib/types';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import { onMount } from 'svelte';
import CollectionCard from './CollectionCard.svelte';
let modal: HTMLDialogElement;
let collections: Collection[] = [];
onMount(async () => {
modal = document.getElementById('my_modal_1') as HTMLDialogElement;
if (modal) {
modal.showModal();
}
let res = await fetch(`/api/collections/all/`, {
method: 'GET'
});
let result = await res.json();
collections = result as Collection[];
if (result.type === 'success' && result.data) {
collections = result.data.adventures as Collection[];
}
});
function close() {
dispatch('close');
}
function link(event: CustomEvent<number>) {
dispatch('link', event.detail);
}
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
dispatch('close');
}
}
</script>

<dialog id="my_modal_1" class="modal">
<!-- svelte-ignore a11y-no-noninteractive-element-interactions -->
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<div class="modal-box w-11/12 max-w-5xl" role="dialog" on:keydown={handleKeydown} tabindex="0">
<h1 class="text-center font-bold text-4xl mb-6">My Collections</h1>
<div class="flex flex-wrap gap-4 mr-4 justify-center content-center">
{#each collections as collection}
<CollectionCard {collection} type="link" on:link={link} />
{/each}
{#if collections.length === 0}
<p class="text-center text-lg">No collections found to add this adventure to.</p>
{/if}
</div>
<button class="btn btn-primary" on:click={close}>Close</button>
</div>
</dialog>
19 changes: 12 additions & 7 deletions frontend/src/lib/components/EditAdventure.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import Attachment from '~icons/mdi/attachment';
import PointSelectionModal from './PointSelectionModal.svelte';
import Earth from '~icons/mdi/earth';
import Wikipedia from '~icons/mdi/wikipedia';
onMount(async () => {
modal = document.getElementById('my_modal_1') as HTMLDialogElement;
Expand All @@ -42,6 +43,14 @@
}
}
async function generateDesc() {
let res = await fetch(`/api/generate/desc/?name=${adventureToEdit.name}`);
let data = await res.json();
if (data.extract) {
adventureToEdit.description = data.extract;
}
}
async function handleSubmit(event: Event) {
event.preventDefault();
const form = event.target as HTMLFormElement;
Expand Down Expand Up @@ -166,13 +175,9 @@
bind:value={adventureToEdit.description}
class="input input-bordered w-full max-w-xs mt-1 mb-2"
/>
<!-- <button
class="btn btn-neutral ml-2"
type="button"
on:click={generate}
><iconify-icon icon="mdi:wikipedia" class="text-xl -mb-1"
></iconify-icon>Generate Description</button
> -->
<button class="btn btn-neutral ml-2" type="button" on:click={generateDesc}
><Wikipedia class="inline-block -mt-1 mb-1 w-6 h-6" />Generate Description</button
>
</div>
</div>
<div class="mb-2">
Expand Down
Loading

0 comments on commit 17fe400

Please sign in to comment.