1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-19 12:59:36 +02:00

collections v2

This commit is contained in:
Sean Morley 2024-07-15 12:09:20 -04:00
parent 533453b764
commit e533dda328
11 changed files with 332 additions and 102 deletions

View file

@ -30,6 +30,7 @@ class AdventureViewSet(viewsets.ModelViewSet):
def apply_sorting(self, queryset): def apply_sorting(self, queryset):
order_by = self.request.query_params.get('order_by', 'name') order_by = self.request.query_params.get('order_by', 'name')
order_direction = self.request.query_params.get('order_direction', 'asc') order_direction = self.request.query_params.get('order_direction', 'asc')
include_collections = self.request.query_params.get('include_collections', 'false')
valid_order_by = ['name', 'type', 'date', 'rating'] valid_order_by = ['name', 'type', 'date', 'rating']
if order_by not in valid_order_by: if order_by not in valid_order_by:
@ -50,6 +51,9 @@ class AdventureViewSet(viewsets.ModelViewSet):
print(f"Ordering by: {ordering}") # For debugging print(f"Ordering by: {ordering}") # For debugging
if include_collections == 'false':
queryset = queryset.filter(collection = None)
return queryset.order_by(ordering) return queryset.order_by(ordering)
def get_queryset(self): def get_queryset(self):
@ -76,7 +80,7 @@ class AdventureViewSet(viewsets.ModelViewSet):
for adventure_type in types: for adventure_type in types:
if adventure_type in ['visited', 'planned']: if adventure_type in ['visited', 'planned']:
queryset |= Adventure.objects.filter( queryset |= Adventure.objects.filter(
type=adventure_type, user_id=request.user.id, collection=None) type=adventure_type, user_id=request.user.id)
queryset = self.apply_sorting(queryset) queryset = self.apply_sorting(queryset)
adventures = self.paginate_and_respond(queryset, request) adventures = self.paginate_and_respond(queryset, request)
@ -86,8 +90,25 @@ class AdventureViewSet(viewsets.ModelViewSet):
def all(self, request): def all(self, request):
if not request.user.is_authenticated: if not request.user.is_authenticated:
return Response({"error": "User is not authenticated"}, status=400) return Response({"error": "User is not authenticated"}, status=400)
queryset = Adventure.objects.filter(user_id=request.user.id) # include_collections = request.query_params.get('include_collections', 'false')
# if include_collections not in ['true', 'false']:
# include_collections = 'false'
# if include_collections == 'true':
# queryset = Adventure.objects.filter(
# Q(is_public=True) | Q(user_id=request.user.id)
# )
# else:
# queryset = Adventure.objects.filter(
# 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)
)
queryset = self.apply_sorting(queryset)
serializer = self.get_serializer(queryset, many=True) serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data) return Response(serializer.data)
def paginate_and_respond(self, queryset, request): def paginate_and_respond(self, queryset, request):

View file

@ -10,6 +10,7 @@
import Calendar from '~icons/mdi/calendar'; import Calendar from '~icons/mdi/calendar';
import MapMarker from '~icons/mdi/map-marker'; import MapMarker from '~icons/mdi/map-marker';
import { addToast } from '$lib/toasts'; import { addToast } from '$lib/toasts';
import Link from '~icons/mdi/link-variant';
export let type: string; export let type: string;
@ -34,6 +35,10 @@
function editAdventure() { function editAdventure() {
dispatch('edit', adventure); dispatch('edit', adventure);
} }
function link() {
dispatch('link', adventure);
}
</script> </script>
<div <div
@ -100,6 +105,9 @@
><TrashCan class="w-6 h-6" /></button ><TrashCan class="w-6 h-6" /></button
> >
{/if} {/if}
{#if type == 'link'}
<button class="btn btn-primary" on:click={link}><Link class="w-6 h-6" /></button>
{/if}
</div> </div>
</div> </div>
</div> </div>

View file

@ -0,0 +1,59 @@
<script lang="ts">
import { deserialize } from '$app/forms';
import type { Adventure } from '$lib/types';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
import type { ActionResult } from '@sveltejs/kit';
import { onMount } from 'svelte';
import AdventureCard from './AdventureCard.svelte';
let modal: HTMLDialogElement;
let adventures: Adventure[] = [];
onMount(async () => {
modal = document.getElementById('my_modal_1') as HTMLDialogElement;
if (modal) {
modal.showModal();
}
let formData = new FormData();
formData.append('include_collections', 'false');
let res = await fetch(`/adventures?/all`, {
method: 'POST',
body: formData
});
const result: ActionResult = deserialize(await res.text());
console.log(result);
if (result.type === 'success' && result.data) {
adventures = result.data.adventures as Adventure[];
}
});
function close() {
dispatch('close');
}
function add(event: CustomEvent<Adventure>) {
dispatch('add', 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" role="dialog" on:keydown={handleKeydown} tabindex="0">
<div class="flex flex-wrap gap-4 mr-4 justify-center content-center">
{#each adventures as adventure}
<AdventureCard type="link" {adventure} on:link={add} />
{/each}
</div>
<button class="btn btn-primary" on:click={close}>Close</button>
</div>
</dialog>

View file

@ -8,25 +8,28 @@
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import type { Collection } from '$lib/types'; import type { Collection } from '$lib/types';
import { addToast } from '$lib/toasts';
const dispatch = createEventDispatcher(); const dispatch = createEventDispatcher();
// export let type: String; // export let type: String;
export let collection: Collection; export let collection: Collection;
// function remove() { async function deleteCollection() {
// dispatch("remove", trip.id); let res = await fetch(`/collections/${collection.id}?/delete`, {
// } method: 'POST',
// function edit() {} headers: {
// function add() { 'Content-Type': 'application/x-www-form-urlencoded'
// dispatch("add", trip); }
// } });
if (res.ok) {
// // TODO: Implement markVisited function console.log('Collection deleted');
// function markVisited() { addToast('info', 'Adventure deleted successfully!');
// console.log(trip.id); dispatch('delete', collection.id);
// dispatch("markVisited", trip); } else {
// } console.log('Error deleting adventure');
}
}
</script> </script>
<div <div
@ -36,8 +39,10 @@
<h2 class="card-title overflow-ellipsis">{collection.name}</h2> <h2 class="card-title overflow-ellipsis">{collection.name}</h2>
<p>{collection.adventures.length} Adventures</p> <p>{collection.adventures.length} Adventures</p>
<div class="card-actions justify-end"> <div class="card-actions justify-end">
<button class="btn btn-secondary"><TrashCanOutline class="w-5 h-5 mr-1" /></button> <button on:click={deleteCollection} class="btn btn-secondary"
<button class="btn btn-primary" on:click={() => goto(`/trip/${collection.id}`)} ><TrashCanOutline class="w-5 h-5 mr-1" /></button
>
<button class="btn btn-primary" on:click={() => goto(`/collections/${collection.id}`)}
><Launch class="w-5 h-5 mr-1" /></button ><Launch class="w-5 h-5 mr-1" /></button
> >
</div> </div>

View file

@ -362,6 +362,13 @@ export const actions: Actions = {
const visited = formData.get('visited'); const visited = formData.get('visited');
const planned = formData.get('planned'); const planned = formData.get('planned');
let include_collections = formData.get('include_collections') as string;
if (include_collections) {
include_collections = 'true';
} else {
include_collections = 'false';
}
const order_direction = formData.get('order_direction') as string; const order_direction = formData.get('order_direction') as string;
const order_by = formData.get('order_by') as string; const order_by = formData.get('order_by') as string;
@ -397,7 +404,7 @@ export const actions: Actions = {
console.log(filterString); console.log(filterString);
let visitedFetch = await fetch( let visitedFetch = await fetch(
`${serverEndpoint}/api/adventures/filtered?types=${filterString}&order_by=${order_by}&order_direction=${order_direction}`, `${serverEndpoint}/api/adventures/filtered?types=${filterString}&order_by=${order_by}&order_direction=${order_direction}&include_collections=${include_collections}`,
{ {
headers: { headers: {
Cookie: `${event.cookies.get('auth')}` Cookie: `${event.cookies.get('auth')}`
@ -502,5 +509,46 @@ export const actions: Actions = {
body: { error: 'Failed to fetch data' } body: { error: 'Failed to fetch data' }
}; };
} }
},
all: async (event) => {
if (!event.locals.user) {
return {
status: 401,
body: { message: 'Unauthorized' }
};
}
const formData = await event.request.formData();
let include_collections = formData.get('include_collections') as string;
if (include_collections !== 'true' && include_collections !== 'false') {
include_collections = 'false';
}
let adventures: Adventure[] = [];
let visitedFetch = await fetch(
`${serverEndpoint}/api/adventures/all/?include_collections=${include_collections}`,
{
headers: {
Cookie: `${event.cookies.get('auth')}`,
'Content-Type': 'application/json'
}
}
);
if (!visitedFetch.ok) {
console.error('Failed to fetch all adventures');
return redirect(302, '/login');
} else {
console.log('Fetched all adventures');
let res = await visitedFetch.json();
console.log(res);
adventures = res as Adventure[];
}
return {
adventures
};
} }
}; };

View file

@ -281,6 +281,16 @@
id="rating" id="rating"
class="radio radio-primary" class="radio radio-primary"
/> />
<br />
<label class="label cursor-pointer">
<span class="label-text">Include Collection Adventures</span>
<input
type="checkbox"
name="include_collections"
id="include_collections"
class="checkbox checkbox-primary"
/>
</label>
<button type="submit" class="btn btn-primary mt-4">Filter</button> <button type="submit" class="btn btn-primary mt-4">Filter</button>
</form> </form>
<div class="divider"></div> <div class="divider"></div>

View file

@ -1,4 +1,3 @@
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL']; const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Adventure } from '$lib/types'; import type { Adventure } from '$lib/types';
@ -89,5 +88,74 @@ export const actions: Actions = {
status: 204 status: 204
}; };
} }
},
addToCollection: async (event) => {
const id = event.params as { id: string };
const adventureId = id.id;
const formData = await event.request.formData();
const trip_id = formData.get('collection_id');
if (!trip_id) {
return {
status: 400,
error: { message: 'Missing collection id' }
};
}
if (!event.locals.user) {
const refresh = event.cookies.get('refresh');
let auth = event.cookies.get('auth');
if (!refresh) {
return {
status: 401,
body: { message: 'Unauthorized' }
};
}
let res = await tryRefreshToken(refresh);
if (res) {
auth = res;
event.cookies.set('auth', auth, {
httpOnly: true,
sameSite: 'lax',
expires: new Date(Date.now() + 60 * 60 * 1000), // 60 minutes
path: '/'
});
} else {
return {
status: 401,
body: { message: 'Unauthorized' }
};
}
}
if (!adventureId) {
return {
status: 400,
error: new Error('Bad request')
};
}
let trip_id_number: number = parseInt(trip_id as string);
let res = await fetch(`${serverEndpoint}/api/adventures/${event.params.id}/`, {
method: 'PATCH',
headers: {
Cookie: `${event.cookies.get('auth')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ collection: trip_id_number })
});
let res2 = await res.json();
console.log(res2);
if (!res.ok) {
return {
status: res.status,
error: new Error('Failed to delete adventure')
};
} else {
return {
status: 204
};
}
} }
}; };

View file

@ -66,6 +66,10 @@
}; };
} }
function deleteCollection(event: CustomEvent<number>) {
collections = collections.filter((collection) => collection.id !== event.detail);
}
function sort({ attribute, order }: { attribute: string; order: string }) { function sort({ attribute, order }: { attribute: string; order: string }) {
currentSort.attribute = attribute; currentSort.attribute = attribute;
currentSort.order = order; currentSort.order = order;
@ -174,7 +178,7 @@
{#if currentView == 'cards'} {#if currentView == 'cards'}
<div class="flex flex-wrap gap-4 mr-4 justify-center content-center"> <div class="flex flex-wrap gap-4 mr-4 justify-center content-center">
{#each collections as collection} {#each collections as collection}
<CollectionCard {collection} /> <CollectionCard {collection} on:delete={deleteCollection} />
{/each} {/each}
</div> </div>
{/if} {/if}

View file

@ -1,7 +1,7 @@
import { redirect } from '@sveltejs/kit'; import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL']; const PUBLIC_SERVER_URL = process.env['PUBLIC_SERVER_URL'];
import type { Adventure } from '$lib/types'; import type { Adventure, Collection } from '$lib/types';
const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000'; const endpoint = PUBLIC_SERVER_URL || 'http://localhost:8000';
export const load = (async (event) => { export const load = (async (event) => {
@ -19,7 +19,7 @@ export const load = (async (event) => {
} }
}; };
} else { } else {
let collection = (await request.json()) as Adventure; let collection = (await request.json()) as Collection;
return { return {
props: { props: {
@ -71,18 +71,19 @@ export const actions: Actions = {
}; };
} }
let res = await fetch(`${serverEndpoint}/api/adventures/${event.params.id}`, { let res = await fetch(`${serverEndpoint}/api/collections/${event.params.id}`, {
method: 'DELETE', method: 'DELETE',
headers: { headers: {
Cookie: `${event.cookies.get('auth')}`, Cookie: `${event.cookies.get('auth')}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}); });
console.log(res); console.log(res);
if (!res.ok) { if (!res.ok) {
return { return {
status: res.status, status: res.status,
error: new Error('Failed to delete adventure') error: new Error('Failed to delete collection')
}; };
} else { } else {
return { return {

View file

@ -1,40 +1,65 @@
<!-- <script lang="ts">
import AdventureCard from '$lib/components/AdventureCard.svelte';
import type { Adventure } from '$lib/types';
export let data;
console.log(data);
let adventure: Adventure | null = data.props.adventure;
</script>
{#if !adventure}
<p>Adventure not found</p>
{:else}
<AdventureCard {adventure} type={adventure.type} />
{/if} -->
<script lang="ts"> <script lang="ts">
import type { Adventure } from '$lib/types'; import type { Adventure, Collection } from '$lib/types';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import type { PageData } from './$types'; import type { PageData } from './$types';
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import Lost from '$lib/assets/undraw_lost.svg'; import Lost from '$lib/assets/undraw_lost.svg';
import Plus from '~icons/mdi/plus';
import AdventureCard from '$lib/components/AdventureCard.svelte';
import AdventureLink from '$lib/components/AdventureLink.svelte';
export let data: PageData; export let data: PageData;
let adventure: Adventure; let collection: Collection;
let adventures: Adventure[] = [];
let notFound: boolean = false; let notFound: boolean = false;
let isShowingCreateModal: boolean = false;
onMount(() => { onMount(() => {
if (data.props.adventure) { if (data.props.adventure) {
adventure = data.props.adventure; collection = data.props.adventure;
adventures = collection.adventures as Adventure[];
} else { } else {
notFound = true; notFound = true;
} }
}); });
async function addAdventure(event: CustomEvent<Adventure>) {
console.log(event.detail);
if (adventures.find((a) => a.id === event.detail.id)) {
return;
} else {
let adventure = event.detail;
let formData = new FormData();
formData.append('collection_id', collection.id.toString());
let res = await fetch(`/adventures/${adventure.id}?/addToCollection`, {
method: 'POST',
body: formData // Remove the Content-Type header
});
if (res.ok) {
console.log('Adventure added to collection');
adventures = [...adventures, adventure];
} else {
console.log('Error adding adventure to collection');
}
}
}
</script> </script>
{#if isShowingCreateModal}
<AdventureLink
on:close={() => {
isShowingCreateModal = false;
}}
on:add={addAdventure}
/>
{/if}
{#if notFound} {#if notFound}
<div <div
class="flex min-h-[100dvh] flex-col items-center justify-center bg-background px-4 py-12 sm:px-6 lg:px-8 -mt-20" class="flex min-h-[100dvh] flex-col items-center justify-center bg-background px-4 py-12 sm:px-6 lg:px-8 -mt-20"
@ -57,71 +82,52 @@
</div> </div>
{/if} {/if}
{#if !adventure && !notFound} {#if !collection && !notFound}
<div class="flex justify-center items-center w-full mt-16"> <div class="flex justify-center items-center w-full mt-16">
<span class="loading loading-spinner w-24 h-24"></span> <span class="loading loading-spinner w-24 h-24"></span>
</div> </div>
{/if} {/if}
{#if adventure} {#if collection}
{#if adventure.name} <div class="fixed bottom-4 right-4 z-[999]">
<h1 class="text-center font-extrabold text-4xl mb-2">{adventure.name}</h1> <div class="flex flex-row items-center justify-center gap-4">
{/if} <div class="dropdown dropdown-top dropdown-end">
{#if adventure.location} <div tabindex="0" role="button" class="btn m-1 size-16 btn-primary">
<p class="text-center text-2xl"> <Plus class="w-8 h-8" />
<iconify-icon icon="mdi:map-marker" class="text-xl -mb-0.5" </div>
></iconify-icon>{adventure.location} <!-- svelte-ignore a11y-no-noninteractive-tabindex -->
</p> <ul
{/if} tabindex="0"
{#if adventure.date} class="dropdown-content z-[1] menu p-4 shadow bg-base-300 text-base-content rounded-box w-52 gap-4"
<p class="text-center text-lg mt-4 pl-16 pr-16"> >
Visited on: {adventure.date} <p class="text-center font-bold text-lg">Link new...</p>
</p> <button
{/if} class="btn btn-primary"
{#if adventure.rating !== undefined && adventure.rating !== null} on:click={() => {
<div class="flex justify-center items-center"> isShowingCreateModal = true;
<div class="rating" aria-readonly="true"> }}
{#each Array.from({ length: 5 }, (_, i) => i + 1) as star} >
<input Adventure</button
type="radio" >
name="rating-1"
class="mask mask-star" <!-- <button
checked={star <= adventure.rating} class="btn btn-primary"
disabled on:click={() => (isShowingNewTrip = true)}>Trip Planner</button
/> > -->
{/each} </ul>
</div> </div>
</div> </div>
</div>
{#if collection.name}
<h1 class="text-center font-extrabold text-4xl mb-2">{collection.name}</h1>
{/if} {/if}
{#if adventure.description} <h1 class="text-center font-semibold text-2xl mt-4 mb-2">Linked Adventures</h1>
<p class="text-center text-lg mt-4 pl-16 pr-16">{adventure.description}</p> <div class="flex flex-wrap gap-4 mr-4 justify-center content-center">
{/if} {#each adventures as adventure}
{#if adventure.link} <AdventureCard type={adventure.type} {adventure} />
<div class="flex justify-center items-center mt-4"> {/each}
<a href={adventure.link} target="_blank" rel="noopener noreferrer" class="btn btn-primary"> </div>
Visit Website
</a> {#if collection.description}
</div> <p class="text-center text-lg mt-4 pl-16 pr-16">{collection.description}</p>
{/if}
{#if adventure.activity_types && adventure.activity_types.length > 0}
<div class="flex justify-center items-center mt-4">
<p class="text-center text-lg">Activities:&nbsp</p>
<ul class="flex flex-wrap">
{#each adventure.activity_types as activity}
<div class="badge badge-primary mr-1 text-md font-semibold pb-2 pt-1 mb-1">
{activity}
</div>
{/each}
</ul>
</div>
{/if}
{#if adventure.image}
<div class="flex content-center justify-center">
<!-- svelte-ignore a11y-img-redundant-alt -->
<img
src={adventure.image}
alt="Adventure Image"
class="w-1/2 mt-4 align-middle rounded-lg shadow-lg"
/>
</div>
{/if} {/if}
{/if} {/if}

View file

@ -75,7 +75,7 @@
</div> </div>
<div class="stat"> <div class="stat">
<div class="stat-title">Trips</div> <div class="stat-title">Collections</div>
<div class="stat-value text-center">{stats.trips_count}</div> <div class="stat-value text-center">{stats.trips_count}</div>
<!-- <div class="stat-desc">↘︎ 90 (14%)</div> --> <!-- <div class="stat-desc">↘︎ 90 (14%)</div> -->
</div> </div>