mirror of
https://github.com/seanmorley15/AdventureLog.git
synced 2025-08-04 20:55:19 +02:00
commit
17fe400632
8 changed files with 324 additions and 27 deletions
|
@ -11,6 +11,8 @@ from rest_framework.permissions import IsAuthenticated
|
|||
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
|
||||
|
@ -58,11 +60,37 @@ class AdventureViewSet(viewsets.ModelViewSet):
|
|||
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)
|
||||
|
@ -104,7 +132,7 @@ class AdventureViewSet(viewsets.ModelViewSet):
|
|||
# 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)
|
||||
|
@ -151,6 +179,29 @@ class CollectionViewSet(viewsets.ModelViewSet):
|
|||
|
||||
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):
|
||||
|
|
|
@ -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() {
|
||||
|
@ -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);
|
||||
}
|
||||
|
@ -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"
|
||||
>
|
||||
|
@ -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" />
|
||||
|
@ -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}
|
||||
|
@ -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>
|
||||
|
|
|
@ -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() {
|
||||
|
@ -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
frontend/src/lib/components/CollectionLink.svelte
Normal file
58
frontend/src/lib/components/CollectionLink.svelte
Normal file
|
@ -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>
|
|
@ -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;
|
||||
|
@ -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;
|
||||
|
@ -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">
|
||||
|
|
|
@ -8,6 +8,8 @@
|
|||
|
||||
export let type: string = 'visited';
|
||||
|
||||
import Wikipedia from '~icons/mdi/wikipedia';
|
||||
|
||||
let newAdventure: Adventure = {
|
||||
id: NaN,
|
||||
type: type,
|
||||
|
@ -49,6 +51,14 @@
|
|||
}
|
||||
}
|
||||
|
||||
async function generateDesc() {
|
||||
let res = await fetch(`/api/generate/desc/?name=${newAdventure.name}`);
|
||||
let data = await res.json();
|
||||
if (data.extract) {
|
||||
newAdventure.description = data.extract;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit(event: Event) {
|
||||
event.preventDefault();
|
||||
const form = event.target as HTMLFormElement;
|
||||
|
@ -179,6 +189,9 @@
|
|||
bind:value={newAdventure.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={generateDesc}
|
||||
><Wikipedia class="inline-block -mt-1 mb-1 w-6 h-6" />Generate Description</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-2">
|
||||
|
|
58
frontend/src/routes/api/[...path]/+server.ts
Normal file
58
frontend/src/routes/api/[...path]/+server.ts
Normal file
|
@ -0,0 +1,58 @@
|
|||
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
|
||||
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
|
||||
import { json } from '@sveltejs/kit';
|
||||
|
||||
/** @type {import('./$types').RequestHandler} */
|
||||
export async function GET({ url, params, request, fetch, cookies }) {
|
||||
return handleRequest(url, params, request, fetch, cookies);
|
||||
}
|
||||
|
||||
/** @type {import('./$types').RequestHandler} */
|
||||
export async function POST({ url, params, request, fetch, cookies }) {
|
||||
return handleRequest(url, params, request, fetch, cookies);
|
||||
}
|
||||
|
||||
export async function PATCH({ url, params, request, fetch, cookies }) {
|
||||
return handleRequest(url, params, request, fetch, cookies);
|
||||
}
|
||||
|
||||
export async function PUT({ url, params, request, fetch, cookies }) {
|
||||
return handleRequest(url, params, request, fetch, cookies);
|
||||
}
|
||||
|
||||
export async function DELETE({ url, params, request, fetch, cookies }) {
|
||||
return handleRequest(url, params, request, fetch, cookies);
|
||||
}
|
||||
|
||||
// Implement other HTTP methods as needed (PUT, DELETE, etc.)
|
||||
|
||||
async function handleRequest(url: any, params: any, request: any, fetch: any, cookies: any) {
|
||||
const path = params.path;
|
||||
const targetUrl = `${endpoint}/api/${path}${url.search}/`;
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
|
||||
const authCookie = cookies.get('auth');
|
||||
|
||||
if (authCookie) {
|
||||
headers.set('Cookie', `${authCookie}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(targetUrl, {
|
||||
method: request.method,
|
||||
headers: headers,
|
||||
body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.text() : undefined
|
||||
});
|
||||
|
||||
const responseData = await response.text();
|
||||
|
||||
return new Response(responseData, {
|
||||
status: response.status,
|
||||
headers: response.headers
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error forwarding request:', error);
|
||||
return json({ error: 'Internal Server Error' }, { status: 500 });
|
||||
}
|
||||
}
|
|
@ -179,7 +179,12 @@
|
|||
{#if currentView == 'cards'}
|
||||
<div class="flex flex-wrap gap-4 mr-4 justify-center content-center">
|
||||
{#each collections as collection}
|
||||
<CollectionCard {collection} on:delete={deleteCollection} on:edit={editCollection} />
|
||||
<CollectionCard
|
||||
type=""
|
||||
{collection}
|
||||
on:delete={deleteCollection}
|
||||
on:edit={editCollection}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
@ -229,8 +234,7 @@
|
|||
class="radio radio-primary"
|
||||
/>
|
||||
<br />
|
||||
<p class="text-md font-semibold mt-2 mb-2">Order By</p>
|
||||
<label for="name">Name</label>
|
||||
|
||||
<input
|
||||
type="radio"
|
||||
name="order_by"
|
||||
|
@ -238,6 +242,7 @@
|
|||
class="radio radio-primary"
|
||||
checked
|
||||
value="name"
|
||||
hidden
|
||||
/>
|
||||
<button type="submit" class="btn btn-primary mt-4">Filter</button>
|
||||
</form>
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue