Skip to content

Commit

Permalink
Merge pull request #43 from CropWatchDevelopment/user-edit-names
Browse files Browse the repository at this point in the history
now able to rename locations
  • Loading branch information
CropWatchDevelopment authored May 8, 2024
2 parents befa453 + b2c234e commit fa41b34
Show file tree
Hide file tree
Showing 5 changed files with 165 additions and 6 deletions.
80 changes: 80 additions & 0 deletions src/lib/components/ui/EditLocationNameDialog.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { mdiClose, mdiFloppy, mdiPencil } from '@mdi/js';
import { toast } from '@zerodevx/svelte-toast';
import { Button, Dialog, TextField } from 'svelte-ux';
import { _ } from 'svelte-i18n';
export let currentLocationName: string = '';
let currentLocationNameStatic = currentLocationName;
export let locationId: number = -1;
let open = false;
const handleSubmit = () => {
fetch(`/api/v1/locations/${locationId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: currentLocationName })
})
.then((res) => {
if (res.ok) {
toast.push(`Location name updated successfully`, {
theme: {
'--toastBackground': 'green',
'--toastColor': 'black'
}
});
currentLocationNameStatic = currentLocationName;
} else {
toast.push(`Location name updated FAILED`, {
theme: {
'--toastBackground': 'red',
'--toastColor': 'black'
}
});
currentLocationName = currentLocationNameStatic;
open = false;
}
return res.json();
})
.then((data) => {
console.log(data);
currentLocationName = data.name;
open = false;
})
.catch((err) => {
console.error(err);
currentLocationName = currentLocationNameStatic;
open = false;
});
};
const closing = () => {
currentLocationName = currentLocationNameStatic;
open = false;
};
</script>

<Button on:click={() => (open = true)} icon={mdiPencil} size="sm" />

<form action={`/api/v1/locations/${locationId}`} method="PUT">
<Dialog bind:open on:close={() => closing()}>
<div slot="title">{$_('rename_dialog.rename')} {currentLocationNameStatic} {$_('rename_dialog.to_what')}</div>
<div class="m-4">
<TextField name="newName" label={$_('rename_dialog.new_name')} bind:value={currentLocationName} />
</div>
<div class="flex flex-row mt-1 p-2">
<Button variant="fill" icon={mdiClose} on:click={() => (open = false)} color="danger">{$_('close')}</Button>
<span class="flex-grow" />
<Button
variant="fill"
type="button"
icon={mdiFloppy}
on:click={() => handleSubmit()}
color="success">{$_('save')}</Button
>
</div>
</Dialog>
</form>
9 changes: 5 additions & 4 deletions src/lib/components/ui/dashboardCard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@
import { get, writable } from 'svelte/store';
import { isDayTime } from '$lib/utilities/isDayTime';
import { goto } from '$app/navigation';
import { mdiArrowRight, mdiArrowRightCircle, mdiEye, mdiLink } from '@mdi/js';
import { mdiArrowRight, mdiArrowRightCircle, mdiEye, mdiLink, mdiPencil } from '@mdi/js';
import { _ } from 'svelte-i18n';
import moment from 'moment';
import EditLocationNameDialog from './EditLocationNameDialog.svelte';
export let data;
const locationId = data.location_id;
const locationName: string = data.cw_locations.name ?? '--';
let locationName: string = data.cw_locations.name ?? '--';
const temperature: number = data.weatherJSON.temperature ?? 0;
const rainfall: number = data.weatherJSON.rainfall ?? 0;
const humidity: number = data.weatherJSON.humidity ?? 0;
Expand Down Expand Up @@ -80,8 +81,8 @@
</div>
</a>
<div class="pl-2 pt-2">
<h2 class="text-xl my-3 flex flex-row">
{locationName ?? '--'}
<h2 class="text-xl my-3 flex flex-row items-center">
{locationName ?? '--'} <EditLocationNameDialog {locationId} bind:currentLocationName={locationName} />
<span class="flex flex-grow" />
<Button variant="outline" color="primary" icon={mdiArrowRight} on:click={() => goto(`app/locations/${locationId}`)} />
</h2>
Expand Down
9 changes: 8 additions & 1 deletion src/lib/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -226,5 +226,12 @@
"were_to_send_email": "Where should we send you a link for password reset?",
"please_check_email": "Recovery Email Sent, Please check your messages.",
"error_sending_email": "There was an error sending the email, contact support."
}
},
"save": "Save",
"rename_dialog": {
"to_what": "to what?",
"rename": "Rename",
"new_name": "New Name"
},
"close": "Close"
}
9 changes: 8 additions & 1 deletion src/lib/i18n/locales/jp.json
Original file line number Diff line number Diff line change
Expand Up @@ -248,5 +248,12 @@
"were_to_send_email": "リカバリーメールを送信するEメールアドレスを入力してください。",
"please_check_email": "Eメールを確認してください",
"error_sending_email": "Eメールの送信中にエラーが発生しました。"
}
},
"save": "保存",
"rename_dialog": {
"to_what": "を変更する",
"rename": " ",
"new_name": "新しい名前"
},
"close": "閉じる"
}
64 changes: 64 additions & 0 deletions src/routes/(api)/api/v1/locations/[id]/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,68 @@ export const GET: RequestHandler = async ({ url, params, locals: { supabase, saf
'Content-Type': 'application/json',
}
});
}

export const PUT: RequestHandler = async ({ params, request, locals: { supabase, safeGetSession } }) => {
const { session } = await safeGetSession();
if (!session) {
throw redirect(303, '/auth/unauthorized');
}

const body = new URLSearchParams(await request.json());
const name = body.get('name');


if (!name) {
return new Response(
JSON.stringify({ error: 'name is required' }),
{
status: 400,
});
}

const locationId = +(params.id ?? 0);
if (locationId === 0) {
return new Response(
JSON.stringify({ error: 'location_id is required' }),
{
status: 400,
});
}
const { data, error } = await supabase
.from('cw_location_owners')
.select('*, cw_locations(*)')
.eq('location_id', locationId)
.eq('user_id', session.user.id)
.limit(1)
.single();

if (error) {
return new Response(
JSON.stringify(error),
{
status: 500,
headers: {
'Content-Type': 'application/json',
}
});
}

const { data: updatedData, error: updateError } = await supabase
.from('cw_locations')
.update({'name': name})
.eq('location_id', data.cw_locations.location_id)
.select()
.single();

return new Response(
JSON.stringify(updatedData) ||
JSON.stringify(updateError),
{
status: updatedData ? 200 : 500,
statusText: updatedData ? 'OK' : updateError,
headers: {
'Content-Type': 'application/json',
}
});
}

0 comments on commit fa41b34

Please sign in to comment.