Compare commits

...

11 Commits

Author SHA1 Message Date
Alex
e9d6b58f20 frontend: admin/users page delete inserts and error handling 2025-02-18 11:37:47 +01:00
Alex
42edc70490 subscriptionEditForm: permissions 2025-02-18 11:37:16 +01:00
Alex
64b368e617 frontend usereditform locale 2025-02-18 11:36:19 +01:00
Alex
e11a05a85f frontend formatting login page 2025-02-18 11:35:27 +01:00
Alex
89841ade55 locale 2025-02-18 11:34:28 +01:00
Alex
89a7780c54 backend refactor: userdeletion 2025-02-18 11:34:21 +01:00
Alex
9d83afa525 add: deletesubscription 2025-02-18 11:33:21 +01:00
Alex
d1273d3e23 backend: add: new error messages 2025-02-18 11:32:33 +01:00
Alex
0fab8791f9 locale 2025-02-18 11:31:45 +01:00
Alex
59d9169646 fix cookies 2025-02-18 11:31:27 +01:00
Alex
f1fe64855d add: light theme 2025-02-18 11:31:01 +01:00
18 changed files with 588 additions and 252 deletions

View File

@@ -1,68 +1,81 @@
<script> <script>
import { onMount } from "svelte"; import { onMount } from 'svelte';
import { applyAction, enhance } from "$app/forms"; import { applyAction, enhance } from '$app/forms';
import { page } from "$app/stores"; import { page } from '$app/stores';
// import Developer from "$lib/img/hero-image.png"; // import Developer from "$lib/img/hero-image.png";
// import Avatar from "$lib/img/TeamAvatar.jpeg"; // import Avatar from "$lib/img/TeamAvatar.jpeg";
import { t } from "svelte-i18n"; import { t } from 'svelte-i18n';
onMount(() => { import { writable } from 'svelte/store';
console.log("Page data in Header:", $page); onMount(() => {
}); console.log('Page data in Header:', $page);
document.documentElement.setAttribute('data-theme', $theme);
});
$: { $: {
console.log("Page data updated:", $page); console.log('Page data updated:', $page);
} }
// Create a theme store
const theme = writable(
typeof window !== 'undefined' ? localStorage.getItem('theme') || 'dark' : 'dark'
);
// Update theme and localStorage when changed
function toggleTheme() {
theme.update((current) => {
const newTheme = current === 'dark' ? 'bright' : 'dark';
localStorage.setItem('theme', newTheme);
document.documentElement.setAttribute('data-theme', newTheme);
return newTheme;
});
}
</script> </script>
<header class="header"> <header class="header">
<div class="header-container"> <div class="header-container">
<div class="header-left"> <div class="header-left">
<div class="header-crafted-by-container"> <div class="header-crafted-by-container">
<!-- <a href="https://tiny-bits.net/"> <!-- <a href="https://tiny-bits.net/">
<span>Developed by</span><img <span>Developed by</span><img
src={Developer} src={Developer}
alt="Alexander Stölting" alt="Alexander Stölting"
/> --> /> -->
<!-- </a> --> <!-- </a> -->
</div> </div>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="header-nav-item" class:active={$page.url.pathname === "/"}> <div class="header-nav-item" class:active={$page.url.pathname === '/'}>
<a href="/">home</a> <a href="/">home</a>
</div> </div>
{#if !$page.data.user} {#if !$page.data.user}
<div <div class="header-nav-item" class:active={$page.url.pathname === '/auth/login'}>
class="header-nav-item" <a href="/auth/login">login</a>
class:active={$page.url.pathname === "/auth/login"} </div>
> <!-- <div
<a href="/auth/login">login</a>
</div>
<!-- <div
class="header-nav-item" class="header-nav-item"
class:active={$page.url.pathname === "/auth/register"} class:active={$page.url.pathname === "/auth/register"}
> >
<a href="/auth/register">register</a> <a href="/auth/register">register</a>
</div> --> </div> -->
{:else} {:else}
<div class="header-nav-item"> <div class="header-nav-item">
<a href="/auth/about/{$page.data.user.id}"> <a href="/auth/about/{$page.data.user.id}">
<!-- <img <!-- <img
src={$page.data.user.profile_picture ? $page.data.user.profile_picture : Avatar} src={$page.data.user.profile_picture ? $page.data.user.profile_picture : Avatar}
alt={`${$page.data.user.first_name} ${$page.data.user.last_name}`} alt={`${$page.data.user.first_name} ${$page.data.user.last_name}`}
/> --> /> -->
{$page.data.user.first_name} {$page.data.user.first_name}
{$page.data.user.last_name} {$page.data.user.last_name}
</a> </a>
</div> </div>
{#if $page.data.user.role_id > 0} {#if $page.data.user.role_id > 0}
<div <div
class="header-nav-item" class="header-nav-item"
class:active={$page.url.pathname.startsWith("/auth/admin/users")} class:active={$page.url.pathname.startsWith('/auth/admin/users')}
> >
<a href="/auth/admin/users">{$t("user.management")}</a> <a href="/auth/admin/users">{$t('user.management')}</a>
</div> </div>
{/if} {/if}
<!-- {#if $page.data.user.is_superuser} <!-- {#if $page.data.user.is_superuser}
<div <div
class="header-nav-item" class="header-nav-item"
class:active={$page.url.pathname.startsWith("/auth/admin")} class:active={$page.url.pathname.startsWith("/auth/admin")}
@@ -70,19 +83,109 @@
<a href="/auth/admin">admin</a> <a href="/auth/admin">admin</a>
</div> </div>
{/if} --> {/if} -->
<form <form
class="header-nav-item" class="header-nav-item"
action="/auth/logout" action="/auth/logout"
method="POST" method="POST"
use:enhance={async () => { use:enhance={async () => {
return async ({ result }) => { return async ({ result }) => {
await applyAction(result); await applyAction(result);
}; };
}} }}
> >
<button type="submit">logout</button> <button type="submit">logout</button>
</form> </form>
{/if} {/if}
</div> <div class="theme-toggle">
</div> <label class="switch">
<input type="checkbox" checked={$theme === 'bright'} on:change={toggleTheme} />
<span class="slider">
<i class="fas fa-sun"></i>
<i class="fas fa-moon"></i>
</span>
</label>
</div>
</div>
</div>
</header> </header>
<style>
.theme-toggle {
display: flex;
align-items: center;
margin-left: 20px;
}
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 30px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--surface0);
transition: 0.4s;
border-radius: 30px;
padding: 4px;
}
.slider:before {
position: absolute;
content: '';
height: 22px;
width: 22px;
left: 4px;
bottom: 4px;
background-color: var(--text);
transition: 0.4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: var(--surface0);
}
input:checked + .slider:before {
transform: translateX(30px);
}
.fa-sun,
.fa-moon {
position: absolute;
font-size: 16px;
top: 7px;
color: var(--text);
transition: 0.4s;
}
.fa-sun {
left: 7px;
opacity: 0;
}
.fa-moon {
right: 7px;
opacity: 1;
}
input:checked + .slider .fa-sun {
opacity: 1;
}
input:checked + .slider .fa-moon {
opacity: 0;
}
</style>

View File

@@ -29,11 +29,8 @@
included_hours_per_month: 0 included_hours_per_month: 0
}; };
$: { console.log('Opening subscription modal with:', subscription);
if (subscription !== undefined) { $: subscription = subscription || { ...blankSubscription };
subscription = subscription === null ? { ...blankSubscription } : { ...subscription };
}
}
$: isLoading = subscription === undefined || user === undefined; $: isLoading = subscription === undefined || user === undefined;
let isUpdating = false; let isUpdating = false;
@@ -56,8 +53,10 @@
<SmallLoader width={30} message={$t('loading.subscription_data')} /> <SmallLoader width={30} message={$t('loading.subscription_data')} />
{:else if user && subscription} {:else if user && subscription}
<form class="content" action="?/updateSubscription" method="POST" use:enhance={handleUpdate}> <form class="content" action="?/updateSubscription" method="POST" use:enhance={handleUpdate}>
<input name="usbscription[id]" type="hidden" bind:value={subscription.id} /> <input name="susbscription[id]" type="hidden" bind:value={subscription.id} />
<h1 class="step-title" style="text-align: center;">{$t('subscritption.edit')}</h1> <h1 class="step-title" style="text-align: center;">
{subscription.id ? $t('subscription.edit') : $t('subscription.create')}
</h1>
{#if form?.errors} {#if form?.errors}
{#each form?.errors as error (error.id)} {#each form?.errors as error (error.id)}
<h4 <h4
@@ -76,7 +75,7 @@
bind:value={subscription.name} bind:value={subscription.name}
placeholder={$t('placeholder.subscription_name')} placeholder={$t('placeholder.subscription_name')}
required={true} required={true}
readonly={user.role_id < 8} readonly={subscription.id > 0}
/> />
<InputField <InputField
name="subscription[details]" name="subscription[details]"
@@ -92,7 +91,7 @@
label={$t('subscription.conditions')} label={$t('subscription.conditions')}
bind:value={subscription.conditions} bind:value={subscription.conditions}
placeholder={$t('placeholder.subscription_conditions')} placeholder={$t('placeholder.subscription_conditions')}
readonly={user.role_id < 8} readonly={subscription.id > 0}
/> />
<InputField <InputField
name="subscription[monthly_fee]" name="subscription[monthly_fee]"
@@ -101,7 +100,7 @@
bind:value={subscription.monthly_fee} bind:value={subscription.monthly_fee}
placeholder={$t('placeholder.subscription_monthly_fee')} placeholder={$t('placeholder.subscription_monthly_fee')}
required={true} required={true}
readonly={user.role_id < 8} readonly={subscription.id > 0}
/> />
<InputField <InputField
name="subscription[hourly_rate]" name="subscription[hourly_rate]"
@@ -109,21 +108,21 @@
label={$t('subscription.hourly_rate')} label={$t('subscription.hourly_rate')}
bind:value={subscription.hourly_rate} bind:value={subscription.hourly_rate}
required={true} required={true}
readonly={user.role_id < 8} readonly={subscription.id > 0}
/> />
<InputField <InputField
name="subscription[included_hours_per_year]" name="subscription[included_hours_per_year]"
type="number" type="number"
label={$t('subscription.included_hours_per_year')} label={$t('subscription.included_hours_per_year')}
bind:value={subscription.included_hours_per_year} bind:value={subscription.included_hours_per_year}
readonly={user.role_id < 8} readonly={subscription.id > 0}
/> />
<InputField <InputField
name="included_hours_per_month" name="included_hours_per_month"
type="number" type="number"
label={$t('subscription.included_hours_per_month')} label={$t('subscription.included_hours_per_month')}
bind:value={subscription.included_hours_per_month} bind:value={subscription.included_hours_per_month}
readonly={user.role_id < 8} readonly={subscription.id > 0}
/> />
</div> </div>
<div class="button-container"> <div class="button-container">

View File

@@ -186,7 +186,9 @@
{:else if localUser} {:else if localUser}
<form class="content" action="?/updateUser" method="POST" use:enhance={handleUpdate}> <form class="content" action="?/updateUser" method="POST" use:enhance={handleUpdate}>
<input name="user[id]" type="hidden" bind:value={localUser.id} /> <input name="user[id]" type="hidden" bind:value={localUser.id} />
<h1 class="step-title" style="text-align: center;">{$t('user.edit')}</h1> <h1 class="step-title" style="text-align: center;">
{localUser.id ? $t('user.edit') : $t('user.create')}
</h1>
{#if form?.success} {#if form?.success}
<h4 <h4
class="step-subtitle warning" class="step-subtitle warning"

View File

@@ -1,4 +1,6 @@
:root { :root {
--white: #ffffff;
--black: #000000;
--rosewater: #f5e0dc; --rosewater: #f5e0dc;
--flamingo: #f2cdcd; --flamingo: #f2cdcd;
--pink: #f5c2e7; --pink: #f5c2e7;
@@ -26,6 +28,69 @@
--mantle: #181825; --mantle: #181825;
--crust: #11111b; --crust: #11111b;
--modal-backdrop: rgba(49, 50, 68, 0.45); /* For Mocha theme */ --modal-backdrop: rgba(49, 50, 68, 0.45); /* For Mocha theme */
/* Bright theme (Latte) colors */
--bright-white: #000000;
--bright-black: #ffffff;
--bright-rosewater: #dc8a78;
--bright-flamingo: #dd7878;
--bright-pink: #ea76cb;
--bright-mauve: #8839ef;
--bright-red: #d20f39;
--bright-maroon: #e64553;
--bright-peach: #fe640b;
--bright-yellow: #df8e1d;
--bright-green: #40a02b;
--bright-teal: #179299;
--bright-sky: #04a5e5;
--bright-sapphire: #209fb5;
--bright-blue: #1e66f5;
--bright-lavender: #7287fd;
--bright-text: #4c4f69;
--bright-subtext1: #5c5f77;
--bright-subtext0: #6c6f85;
--bright-overlay2: #7c7f93;
--bright-overlay1: #8c8fa1;
--bright-overlay0: #9ca0b0;
--bright-surface2: #acb0be;
--bright-surface1: #bcc0cc;
--bright-surface0: #ccd0da;
--bright-base: #eff1f5;
--bright-mantle: #e6e9ef;
--bright-crust: #dce0e8;
--bright-modal-backdrop: rgba(220, 224, 232, 0.45);
}
[data-theme='bright'] {
--white: var(--bright-white);
--black: var(--bright-black);
--rosewater: var(--bright-rosewater);
--flamingo: var(--bright-flamingo);
--pink: var(--bright-pink);
--mauve: var(--bright-mauve);
--red: var(--bright-red);
--maroon: var(--bright-maroon);
--peach: var(--bright-peach);
--yellow: var(--bright-yellow);
--green: var(--bright-green);
--teal: var(--bright-teal);
--sky: var(--bright-sky);
--sapphire: var(--bright-sapphire);
--blue: var(--bright-blue);
--lavender: var(--bright-lavender);
--text: var(--bright-text);
--subtext1: var(--bright-subtext1);
--subtext0: var(--bright-subtext0);
--overlay2: var(--bright-overlay2);
--overlay1: var(--bright-overlay1);
--overlay0: var(--bright-overlay0);
--surface2: var(--bright-surface2);
--surface1: var(--bright-surface1);
--surface0: var(--bright-surface0);
--base: var(--bright-base);
--mantle: var(--bright-mantle);
--crust: var(--bright-crust);
--modal-backdrop: var(--bright-modal-backdrop);
} }
@font-face { @font-face {
@@ -247,7 +312,7 @@ li strong {
transition: transition:
border-color 0.3s ease-in-out, border-color 0.3s ease-in-out,
background-color 0.3s ease-in-out; background-color 0.3s ease-in-out;
color: white; color: var(--white);
text-transform: uppercase; text-transform: uppercase;
font-weight: 500; font-weight: 500;
padding: 18px 28px; padding: 18px 28px;
@@ -264,7 +329,7 @@ li strong {
transition: transition:
border-color 0.3s ease-in-out, border-color 0.3s ease-in-out,
background-color 0.3s ease-in-out; background-color 0.3s ease-in-out;
color: white; color: var(--white);
text-transform: uppercase; text-transform: uppercase;
font-weight: 500; font-weight: 500;
padding: 18px 28px; padding: 18px 28px;
@@ -274,14 +339,14 @@ li strong {
border: 1px solid var(--mauve); border: 1px solid var(--mauve);
} }
.button-colorful:hover { .button-colorful:hover {
background-color: #c907ff; background-color: var(--bright-mauve);
border-color: #c907ff; border-color: var(--bright-mauve);
} }
.button-orange { .button-orange {
transition: transition:
border-color 0.3s ease-in-out, border-color 0.3s ease-in-out,
background-color 0.3s ease-in-out; background-color 0.3s ease-in-out;
color: white; color: var(--white);
text-transform: uppercase; text-transform: uppercase;
font-weight: 500; font-weight: 500;
padding: 18px 28px; padding: 18px 28px;
@@ -291,14 +356,14 @@ li strong {
border: 1px solid var(--peach); border: 1px solid var(--peach);
} }
.button-orange:hover { .button-orange:hover {
background-color: #ca3f12; background-color: var(--bright-peach);
border-color: #ca3f12; border-color: var(--bright-peach);
} }
.button-colorful:disabled { .button-colorful:disabled {
transition: transition:
border-color 0.3s ease-in-out, border-color 0.3s ease-in-out,
background-color 0.3s ease-in-out; background-color 0.3s ease-in-out;
color: white; color: var(--white);
text-transform: uppercase; text-transform: uppercase;
font-weight: 500; font-weight: 500;
padding: 18px 28px; padding: 18px 28px;
@@ -338,7 +403,7 @@ li strong {
.container { .container {
transition: opacity 0.2s ease-in-out; transition: opacity 0.2s ease-in-out;
color: white; color: var(--white);
letter-spacing: 0; letter-spacing: 0;
opacity: 1; opacity: 1;
} }
@@ -348,7 +413,7 @@ li strong {
flex-grow: 1; flex-grow: 1;
} }
.container .content .step-title { .container .content .step-title {
color: #fff; color: var(--white);
font-size: 20px; font-size: 20px;
font-weight: 500; font-weight: 500;
line-height: 86px; line-height: 86px;
@@ -449,7 +514,7 @@ li strong {
.btn.primary { .btn.primary {
background-color: var(--blue); background-color: var(--blue);
border-color: var(--blue); border-color: var(--blue);
color: white; color: var(--white);
} }
.btn.primary:hover { .btn.primary:hover {
@@ -460,7 +525,7 @@ li strong {
.btn.danger { .btn.danger {
background-color: var(--red); background-color: var(--red);
border-color: var(--red); border-color: var(--red);
color: white; color: var(--white);
} }
.btn.danger:hover { .btn.danger:hover {
@@ -508,7 +573,7 @@ li strong {
} }
.footer-branding-container { .footer-branding-container {
color: white; color: var(--white);
font-weight: 300; font-weight: 300;
margin-bottom: 73px; margin-bottom: 73px;
} }
@@ -527,7 +592,7 @@ li strong {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
margin-bottom: 16px; margin-bottom: 16px;
color: white; color: var(--white);
} }
.footer-branding-container .footer-branding .footer-crafted-by-container span { .footer-branding-container .footer-branding .footer-crafted-by-container span {
display: inline-block; display: inline-block;
@@ -541,12 +606,12 @@ li strong {
} }
.footer-branding-container .footer-branding .footer-copyright { .footer-branding-container .footer-branding .footer-copyright {
color: #696969; color: var(--overlay0);
letter-spacing: 0.5px; letter-spacing: 0.5px;
} }
.footer-container { .footer-container {
width: 100%; width: 100%;
color: white; color: var(--white);
box-sizing: border-box; box-sizing: border-box;
display: flex; display: flex;
justify-content: center; justify-content: center;
@@ -575,7 +640,7 @@ li strong {
#000 1deg calc(360deg / var(--n) - var(--g) - 1deg), #000 1deg calc(360deg / var(--n) - var(--g) - 1deg),
#0000 calc(360deg / var(--n) - var(--g)) calc(360deg / var(--n)) #0000 calc(360deg / var(--n) - var(--g)) calc(360deg / var(--n))
), ),
radial-gradient(farthest-side, #0000 calc(98% - var(--b)), #000 calc(100% - var(--b))); radial-gradient(farthest-side, #0000 calc(98% - var(--b)), var(--black) calc(100% - var(--b)));
-webkit-mask: var(--_m); -webkit-mask: var(--_m);
mask: var(--_m); mask: var(--_m);
-webkit-mask-composite: destination-in; -webkit-mask-composite: destination-in;

View File

@@ -103,6 +103,7 @@ export default {
user: { user: {
login: 'Nutzer Anmeldung', login: 'Nutzer Anmeldung',
edit: 'Nutzer bearbeiten', edit: 'Nutzer bearbeiten',
create: 'Nutzer erstellen',
user: 'Nutzer', user: 'Nutzer',
management: 'Mitgliederverwaltung', management: 'Mitgliederverwaltung',
id: 'Mitgliedsnr', id: 'Mitgliedsnr',
@@ -114,6 +115,7 @@ export default {
subscription: { subscription: {
name: 'Modellname', name: 'Modellname',
edit: 'Modell bearbeiten', edit: 'Modell bearbeiten',
create: 'Modell erstellen',
subscription: 'Tarifmodell', subscription: 'Tarifmodell',
subscriptions: 'Tarifmodelle', subscriptions: 'Tarifmodelle',
conditions: 'Bedingungen', conditions: 'Bedingungen',
@@ -126,6 +128,10 @@ export default {
user_data: 'Lade Nutzerdaten', user_data: 'Lade Nutzerdaten',
subscription_data: 'Lade Modelldaten' subscription_data: 'Lade Modelldaten'
}, },
dialog: {
user_deletion: 'Soll der Nutzer {firstname} {lastname} wirklich gelöscht werden?',
subscription_deletion: 'Soll das Tarifmodell {name} wirklich gelöscht werden?'
},
cancel: 'Abbrechen', cancel: 'Abbrechen',
confirm: 'Bestätigen', confirm: 'Bestätigen',
actions: 'Aktionen', actions: 'Aktionen',

View File

@@ -185,14 +185,6 @@ export function refreshCookie(newToken, event) {
sameSite: 'lax', sameSite: 'lax',
maxAge: 5 * 24 * 60 * 60 // 5 days in seconds maxAge: 5 * 24 * 60 * 60 // 5 days in seconds
}); });
} else {
cookies.set('jwt', match[1], {
path: '/',
httpOnly: true,
secure: process.env.NODE_ENV === 'production', // Secure in production
sameSite: 'lax',
maxAge: 5 * 24 * 60 * 60 // 5 days in seconds
});
} }
} }
} }

View File

@@ -65,6 +65,7 @@ export const actions = {
userDatesFromRFC3339(locals.user); userDatesFromRFC3339(locals.user);
throw redirect(303, `/auth/admin/users`); throw redirect(303, `/auth/admin/users`);
}, },
/** /**
* *
* @param request - The request object * @param request - The request object
@@ -73,7 +74,7 @@ export const actions = {
* @param locals - The local object, housing current user * @param locals - The local object, housing current user
* @returns Error data or redirects user to the home page or the previous page * @returns Error data or redirects user to the home page or the previous page
*/ */
updateSubscription: async ({ request, fetch, cookies, locals }) => { updateSubscription: async ({ request, fetch, cookies }) => {
let formData = await request.formData(); let formData = await request.formData();
const rawData = formDataToObject(formData); const rawData = formDataToObject(formData);
@@ -81,7 +82,7 @@ export const actions = {
const isCreating = !processedData.subscription.id || processedData.subscription.id === 0; const isCreating = !processedData.subscription.id || processedData.subscription.id === 0;
console.log('Is creating: ', isCreating); console.log('Is creating: ', isCreating);
const apiURL = `${BASE_API_URI}/backend/subscriptions/upsert`; const apiURL = `${BASE_API_URI}/backend/membership/subscriptions`;
/** @type {RequestInit} */ /** @type {RequestInit} */
const requestOptions = { const requestOptions = {
@@ -104,8 +105,86 @@ export const actions = {
const response = await res.json(); const response = await res.json();
console.log('Server success response:', response); console.log('Server success response:', response);
locals.user = response; throw redirect(303, `/auth/admin/users`);
userDatesFromRFC3339(locals.user); },
/**
*
* @param request - The request object
* @param fetch - Fetch object from sveltekit
* @param cookies - SvelteKit's cookie object
* @param locals - The local object, housing current user
* @returns
*/
userDelete: async ({ request, fetch, cookies }) => {
let formData = await request.formData();
const rawData = formDataToObject(formData);
const processedData = processUserFormData(rawData);
const apiURL = `${BASE_API_URI}/backend/users/delete`;
/** @type {RequestInit} */
const requestOptions = {
method: 'DELETE',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Cookie: `jwt=${cookies.get('jwt')}`
},
body: JSON.stringify(processedData)
};
const res = await fetch(apiURL, requestOptions);
if (!res.ok) {
const response = await res.json();
const errors = formatError(response.errors);
return fail(400, { errors: errors });
}
const response = await res.json();
console.log('Server success response:', response);
throw redirect(303, `/auth/admin/users`);
},
/**
*
* @param request - The request object
* @param fetch - Fetch object from sveltekit
* @param cookies - SvelteKit's cookie object
* @param locals - The local object, housing current subscription
* @returns
*/
subscriptionDelete: async ({ request, fetch, cookies }) => {
let formData = await request.formData();
const rawData = formDataToObject(formData);
const processedData = processSubscriptionFormData(rawData);
const apiURL = `${BASE_API_URI}/backend/membership/subscriptions`;
/** @type {RequestInit} */
const requestOptions = {
method: 'DELETE',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Cookie: `jwt=${cookies.get('jwt')}`
},
body: JSON.stringify(processedData)
};
const res = await fetch(apiURL, requestOptions);
if (!res.ok) {
const response = await res.json();
const errors = formatError(response.errors);
return fail(400, { errors: errors });
}
const response = await res.json();
console.log('Server success response:', response);
throw redirect(303, `/auth/admin/users`); throw redirect(303, `/auth/admin/users`);
} }
}; };

View File

@@ -4,6 +4,8 @@
import SubscriptionEditForm from '$lib/components/SubscriptionEditForm.svelte'; import SubscriptionEditForm from '$lib/components/SubscriptionEditForm.svelte';
import { t } from 'svelte-i18n'; import { t } from 'svelte-i18n';
import { page } from '$app/stores'; import { page } from '$app/stores';
import { applyAction, enhance } from '$app/forms';
import { receive, send } from '$lib/utils/helpers';
/** @type {import('./$types').ActionData} */ /** @type {import('./$types').ActionData} */
export let form; export let form;
@@ -21,7 +23,8 @@
let selectedUser = null; let selectedUser = null;
/** @type{App.Types['subscription'] | null} */ /** @type{App.Types['subscription'] | null} */
let selectedSubscription = null; let selectedSubscription = null;
let showModal = false; let showSubscriptionModal = false;
let showUserModal = false;
/** /**
* Opens the edit modal for the selected user. * Opens the edit modal for the selected user.
@@ -29,7 +32,7 @@
*/ */
const openEditUserModal = (user) => { const openEditUserModal = (user) => {
selectedUser = user; selectedUser = user;
showModal = true; showUserModal = true;
}; };
/** /**
@@ -38,11 +41,12 @@
*/ */
const openEditSubscriptionModal = (subscription) => { const openEditSubscriptionModal = (subscription) => {
selectedSubscription = subscription; selectedSubscription = subscription;
showModal = true; showSubscriptionModal = true;
}; };
const close = () => { const close = () => {
showModal = false; showUserModal = false;
showSubscriptionModal = false;
selectedUser = null; selectedUser = null;
selectedSubscription = null; selectedSubscription = null;
if (form) { if (form) {
@@ -98,6 +102,18 @@
<!-- Main Content --> <!-- Main Content -->
<main class="main-content"> <main class="main-content">
{#if form?.errors}
{#each form?.errors as error (error.id)}
<h4
class="step-subtitle warning"
in:receive|global={{ key: error.id }}
out:send|global={{ key: error.id }}
>
{$t(error.field) + ': ' + $t(error.key)}
</h4>
{/each}
{/if}
{#if activeSection === 'users'} {#if activeSection === 'users'}
<div class="section-header"> <div class="section-header">
<h2>{$t('users')}</h2> <h2>{$t('users')}</h2>
@@ -139,10 +155,38 @@
<i class="fas fa-edit"></i> <i class="fas fa-edit"></i>
{$t('edit')} {$t('edit')}
</button> </button>
<button class="btn danger"> <form
<i class="fas fa-trash"></i> method="POST"
{$t('delete')} action="?/userDelete"
</button> use:enhance={() => {
return async ({ result }) => {
if (result.type === 'success' || result.type === 'redirect') {
await applyAction(result);
}
};
}}
on:submit|preventDefault={(/** @type {SubmitEvent} */ e) => {
if (
!confirm(
$t('dialog.user_deletion', {
values: {
firstname: user.first_name || '',
lastname: user.last_name || ''
}
})
)
) {
e.preventDefault(); // Cancel form submission if user declines
}
}}
>
<input type="hidden" name="user[id]" value={user.id} />
<input type="hidden" name="user[last_name]" value={user.last_name} />
<button class="btn danger" type="submit">
<i class="fas fa-trash"></i>
{$t('delete')}
</button>
</form>
</div> </div>
</div> </div>
</details> </details>
@@ -152,7 +196,7 @@
<div class="section-header"> <div class="section-header">
<h2>{$t('subscription.subscriptions')}</h2> <h2>{$t('subscription.subscriptions')}</h2>
{#if user.role_id == 8} {#if user.role_id == 8}
<button class="btn primary" on:click={() => openEditUserModal(null)}> <button class="btn primary" on:click={() => openEditSubscriptionModal(null)}>
<i class="fas fa-plus"></i> <i class="fas fa-plus"></i>
{$t('add_new')} {$t('add_new')}
</button> </button>
@@ -211,10 +255,42 @@
{$t('edit')} {$t('edit')}
</button> </button>
{#if !users.some(/** @param{App.Locals['user']} user */ (user) => user.membership?.subscription_model?.id === subscription.id)} {#if !users.some(/** @param{App.Locals['user']} user */ (user) => user.membership?.subscription_model?.id === subscription.id)}
<button class="btn danger"> <form
<i class="fas fa-trash"></i> method="POST"
{$t('delete')} action="?/subscriptionDelete"
</button> use:enhance={() => {
return async ({ result }) => {
if (result.type === 'success' || result.type === 'redirect') {
await applyAction(result);
} else {
document
.querySelector('.accordion-content')
?.scrollTo({ top: 0, behavior: 'smooth' });
await applyAction(result);
}
};
}}
on:submit|preventDefault={(/** @type {SubmitEvent} */ e) => {
if (
!confirm(
$t('dialog.subscription_deletion', {
values: {
name: subscription.name || ''
}
})
)
) {
e.preventDefault(); // Cancel form submission if user declines
}
}}
>
<input type="hidden" name="subscription[id]" value={subscription.id} />
<input type="hidden" name="subscription[name]" value={subscription.name} />
<button class="btn danger" type="submit">
<i class="fas fa-trash"></i>
{$t('delete')}
</button>
</form>
{/if} {/if}
</div> </div>
{/if} {/if}
@@ -252,26 +328,26 @@
</div> </div>
</div> </div>
{#if showModal} {#if showUserModal}
<Modal on:close={close}> <Modal on:close={close}>
{#if selectedUser} <UserEditForm
<UserEditForm {form}
{form} user={selectedUser}
user={selectedUser} {subscriptions}
{subscriptions} {licence_categories}
{licence_categories} on:cancel={close}
on:cancel={close} on:close={close}
on:close={close} />
/> </Modal>
{:else if selectedSubscription} {:else if showSubscriptionModal}
<SubscriptionEditForm <Modal on:close={close}>
{form} <SubscriptionEditForm
{user} {form}
subscription={selectedSubscription} {user}
on:cancel={close} subscription={selectedSubscription}
on:close={close} on:cancel={close}
/> on:close={close}
{/if} />
</Modal> </Modal>
{/if} {/if}

View File

@@ -1,94 +1,78 @@
<script> <script>
import { applyAction, enhance } from "$app/forms"; import { applyAction, enhance } from '$app/forms';
import { page } from "$app/stores"; import { page } from '$app/stores';
import { receive, send } from "$lib/utils/helpers"; import { receive, send } from '$lib/utils/helpers';
import { t } from "svelte-i18n"; import { t } from 'svelte-i18n';
/** @type {import('./$types').ActionData} */ /** @type {import('./$types').ActionData} */
export let form; export let form;
/** @type {import('./$types').SubmitFunction} */ /** @type {import('./$types').SubmitFunction} */
const handleLogin = async () => { const handleLogin = async () => {
return async ({ result }) => { return async ({ result }) => {
await applyAction(result); await applyAction(result);
}; };
}; };
let message = ""; let message = '';
if ($page.url.searchParams.get("message")) { if ($page.url.searchParams.get('message')) {
message = $page.url.search.split("=")[1].replaceAll("%20", " "); message = $page.url.search.split('=')[1].replaceAll('%20', ' ');
} }
</script> </script>
<div class="container"> <div class="container">
<form <form class="content" method="POST" action="?/login" use:enhance={handleLogin}>
class="content" <h1 class="step-title">{$t('user.login')}</h1>
method="POST" {#if form?.errors}
action="?/login" {#each form?.errors as error (error.id)}
use:enhance={handleLogin} <h4
> class="step-subtitle warning"
<h1 class="step-title">{$t("user.login")}</h1> in:receive|global={{ key: error.id }}
{#if form?.errors} out:send|global={{ key: error.id }}
{#each form?.errors as error (error.id)} >
<h4 {$t(error.key)}
class="step-subtitle warning" </h4>
in:receive|global={{ key: error.id }} {/each}
out:send|global={{ key: error.id }} {/if}
>
{$t(error.key)}
</h4>
{/each}
{/if}
{#if message} {#if message}
<h4 class="step-subtitle">{message}</h4> <h4 class="step-subtitle">{message}</h4>
{/if} {/if}
<input <input type="hidden" name="next" value={$page.url.searchParams.get('next')} />
type="hidden" <div class="input-box">
name="next" <span class="label">{$t('user.email')}:</span>
value={$page.url.searchParams.get("next")} <input class="input" type="email" name="email" placeholder="{$t('placeholder.email')} " />
/> </div>
<div class="input-box"> <div class="input-box">
<span class="label">{$t("email")}:</span> <span class="label">{$t('password')}:</span>
<input <div class="input-wrapper">
class="input" <input
type="email" class="input"
name="email" type="password"
placeholder="{$t('placeholder.email')} " name="password"
/> placeholder={$t('placeholder.password')}
</div> />
<div class="input-box"> <a href="/auth/password/request-change" class="forgot-password">{$t('forgot_password')}?</a>
<span class="label">{$t("password")}:</span> </div>
<div class="input-wrapper"> </div>
<input <div class="btn-container">
class="input" <button class="button-dark">{$t('login')} </button>
type="password" </div>
name="password" </form>
placeholder={$t("placeholder.password")}
/>
<a href="/auth/password/request-change" class="forgot-password"
>{$t("forgot_password")}?</a
>
</div>
</div>
<div class="btn-container">
<button class="button-dark">{$t("login")} </button>
</div>
</form>
</div> </div>
<style> <style>
.input-wrapper { .input-wrapper {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
align-items: flex-end; align-items: flex-end;
width: 100%; width: 100%;
max-width: 444px; max-width: 444px;
} }
.forgot-password { .forgot-password {
margin-top: 0.5rem; margin-top: 0.5rem;
font-size: 0.9em; font-size: 0.9em;
} }
</style> </style>

View File

@@ -37,7 +37,7 @@ func (mc *MembershipController) RegisterSubscription(c *gin.Context) {
} }
if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) { if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) {
utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to register subscription", http.StatusForbidden, "user", "server.error.unauthorized") utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to register subscription", http.StatusForbidden, "user.user", "server.error.unauthorized")
return return
} }
@@ -75,7 +75,7 @@ func (mc *MembershipController) UpdateHandler(c *gin.Context) {
} }
if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) { if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) {
utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to update subscription", http.StatusForbidden, "user", "server.error.unauthorized") utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to update subscription", http.StatusForbidden, "user.user", "server.error.unauthorized")
return return
} }
@@ -104,7 +104,14 @@ func (mc *MembershipController) UpdateHandler(c *gin.Context) {
} }
func (mc *MembershipController) DeleteSubscription(c *gin.Context) { func (mc *MembershipController) DeleteSubscription(c *gin.Context) {
var membershipdata MembershipData type deleteData struct {
Subscription struct {
ID uint `json:"id"`
Name string `json:"name"`
} `json:"subscription"`
}
var data deleteData
requestUser, err := mc.UserController.ExtractUserFromContext(c) requestUser, err := mc.UserController.ExtractUserFromContext(c)
if err != nil { if err != nil {
utils.RespondWithError(c, err, "Error extracting user from context in subscription UpdateHandler", http.StatusBadRequest, "general", "server.validation.no_auth_tokenw") utils.RespondWithError(c, err, "Error extracting user from context in subscription UpdateHandler", http.StatusBadRequest, "general", "server.validation.no_auth_tokenw")
@@ -112,16 +119,16 @@ func (mc *MembershipController) DeleteSubscription(c *gin.Context) {
} }
if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) { if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) {
utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to update subscription", http.StatusForbidden, "user", "server.error.unauthorized") utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to update subscription", http.StatusForbidden, "user.user", "server.error.unauthorized")
return return
} }
if err := c.ShouldBindJSON(&membershipdata); err != nil { if err := c.ShouldBindJSON(&data); err != nil {
utils.HandleValidationError(c, err) utils.HandleValidationError(c, err)
return return
} }
if err := mc.Service.DeleteSubscription(&membershipdata.Subscription); err != nil { if err := mc.Service.DeleteSubscription(&data.Subscription.ID, &data.Subscription.Name); err != nil {
utils.RespondWithError(c, err, "Error during subscription Deletion", http.StatusExpectationFailed, "subscription", "server.error.not_possible") utils.RespondWithError(c, err, "Error during subscription Deletion", http.StatusExpectationFailed, "subscription", "server.error.not_possible")
return return
} }

View File

@@ -7,6 +7,7 @@ import (
"testing" "testing"
"GoMembership/internal/constants" "GoMembership/internal/constants"
"GoMembership/internal/database"
"GoMembership/internal/models" "GoMembership/internal/models"
"GoMembership/pkg/logger" "GoMembership/pkg/logger"
@@ -332,6 +333,13 @@ func getSubscriptionUpdateData() []UpdateSubscriptionTest {
} }
func getSubscriptionDeleteData() []DeleteSubscriptionTest { func getSubscriptionDeleteData() []DeleteSubscriptionTest {
var premiumSub, basicSub models.SubscriptionModel
database.DB.Where("name = ?", "Premium").First(&premiumSub)
database.DB.Where("name = ?", "Basic").First(&basicSub)
logger.Error.Printf("premiumSub.ID: %v", premiumSub.ID)
logger.Error.Printf("basicSub.ID: %v", basicSub.ID)
return []DeleteSubscriptionTest{ return []DeleteSubscriptionTest{
{ {
Name: "Delete non-existent subscription should fail", Name: "Delete non-existent subscription should fail",
@@ -341,17 +349,19 @@ func getSubscriptionDeleteData() []DeleteSubscriptionTest {
Input: GenerateInputJSON( Input: GenerateInputJSON(
customizeSubscription(func(subscription MembershipData) MembershipData { customizeSubscription(func(subscription MembershipData) MembershipData {
subscription.Subscription.Name = "NonExistentSubscription" subscription.Subscription.Name = "NonExistentSubscription"
subscription.Subscription.ID = basicSub.ID
return subscription return subscription
})), })),
}, },
{ {
Name: "Delete subscription without name should fail", Name: "Delete subscription without name should fail",
WantResponse: http.StatusBadRequest, WantResponse: http.StatusExpectationFailed,
WantDBData: map[string]interface{}{"name": ""}, WantDBData: map[string]interface{}{"name": ""},
Assert: false, Assert: false,
Input: GenerateInputJSON( Input: GenerateInputJSON(
customizeSubscription(func(subscription MembershipData) MembershipData { customizeSubscription(func(subscription MembershipData) MembershipData {
subscription.Subscription.Name = "" subscription.Subscription.Name = ""
subscription.Subscription.ID = basicSub.ID
return subscription return subscription
})), })),
}, },
@@ -363,6 +373,7 @@ func getSubscriptionDeleteData() []DeleteSubscriptionTest {
Input: GenerateInputJSON( Input: GenerateInputJSON(
customizeSubscription(func(subscription MembershipData) MembershipData { customizeSubscription(func(subscription MembershipData) MembershipData {
subscription.Subscription.Name = "Basic" subscription.Subscription.Name = "Basic"
subscription.Subscription.ID = basicSub.ID
return subscription return subscription
})), })),
}, },
@@ -374,6 +385,7 @@ func getSubscriptionDeleteData() []DeleteSubscriptionTest {
Input: GenerateInputJSON( Input: GenerateInputJSON(
customizeSubscription(func(subscription MembershipData) MembershipData { customizeSubscription(func(subscription MembershipData) MembershipData {
subscription.Subscription.Name = "Premium" subscription.Subscription.Name = "Premium"
subscription.Subscription.ID = premiumSub.ID
return subscription return subscription
})), })),
}, },

View File

@@ -47,7 +47,7 @@ func (uc *UserController) CurrentUserHandler(c *gin.Context) {
func (uc *UserController) GetAllUsers(c *gin.Context) { func (uc *UserController) GetAllUsers(c *gin.Context) {
users, err := uc.Service.GetUsers(nil) users, err := uc.Service.GetUsers(nil)
if err != nil { if err != nil {
utils.RespondWithError(c, err, "Error getting users in GetAllUsers", http.StatusInternalServerError, "user", "server.error.internal_server_error") utils.RespondWithError(c, err, "Error getting users in GetAllUsers", http.StatusInternalServerError, "user.user", "server.error.internal_server_error")
return return
} }
@@ -80,7 +80,7 @@ func (uc *UserController) UpdateHandler(c *gin.Context) {
user = updateData.User user = updateData.User
if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) && user.ID != requestUser.ID { if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) && user.ID != requestUser.ID {
utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to update user", http.StatusForbidden, "user", "server.error.unauthorized") utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to update user", http.StatusForbidden, "user.user", "server.error.unauthorized")
return return
} }
@@ -99,30 +99,35 @@ func (uc *UserController) DeleteUser(c *gin.Context) {
requestUser, err := uc.ExtractUserFromContext(c) requestUser, err := uc.ExtractUserFromContext(c)
if err != nil { if err != nil {
utils.RespondWithError(c, err, "Error extracting user from context in UpdateHandler", http.StatusBadRequest, "general", "server.validation.no_auth_tokenw") utils.RespondWithError(c, err, "Error extracting user from context in DeleteUser", http.StatusBadRequest, "general", "server.validation.no_auth_tokenw")
return return
} }
type deleteData = struct { type deleteData struct {
ID uint `json:"id"` User struct {
LastName string `json:"lastname"` ID uint `json:"id"`
LastName string `json:"last_name"`
} `json:"user"`
} }
var deletedUser deleteData var data deleteData
if err := c.ShouldBindJSON(&deletedUser); err != nil { if err := c.ShouldBindJSON(&data); err != nil {
utils.HandleValidationError(c, err) utils.HandleValidationError(c, err)
return return
} }
if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) && deletedUser.ID != requestUser.ID { if !utils.HasPrivilige(requestUser, constants.Priviliges.Update) && data.User.ID != requestUser.ID {
utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to delete user", http.StatusForbidden, "user", "server.error.unauthorized") utils.RespondWithError(c, errors.ErrNotAuthorized, "Not allowed to delete user", http.StatusForbidden, "user.user", "server.error.unauthorized")
return return
} }
if err := uc.Service.DeleteUser(deletedUser.LastName, deletedUser.ID); err != nil { logger.Error.Printf("Deleting user: %v", data.User)
utils.RespondWithError(c, err, "Error during user deletion", http.StatusInternalServerError, "user", "server.error.internal_server_error") if err := uc.Service.DeleteUser(data.User.LastName, data.User.ID); err != nil {
utils.RespondWithError(c, err, "Error during user deletion", http.StatusInternalServerError, "user.user", "server.error.internal_server_error")
return return
} }
c.JSON(http.StatusOK, gin.H{"message": "User deleted successfully"})
} }
func (uc *UserController) ExtractUserFromContext(c *gin.Context) (*models.User, error) { func (uc *UserController) ExtractUserFromContext(c *gin.Context) (*models.User, error) {

View File

@@ -585,7 +585,7 @@ func testUpdateUser(t *testing.T, loginCookie http.Cookie) {
}, },
expectedStatus: http.StatusForbidden, expectedStatus: http.StatusForbidden,
expectedErrors: []map[string]string{ expectedErrors: []map[string]string{
{"field": "user", "key": "server.error.unauthorized"}, {"field": "user.user", "key": "server.error.unauthorized"},
}, },
}, },
{ {

View File

@@ -14,7 +14,7 @@ type SubscriptionModelsRepositoryInterface interface {
GetSubscriptionModelNames() ([]string, error) GetSubscriptionModelNames() ([]string, error)
GetSubscriptions(where map[string]interface{}) (*[]models.SubscriptionModel, error) GetSubscriptions(where map[string]interface{}) (*[]models.SubscriptionModel, error)
// GetUsersBySubscription(id uint) (*[]models.SubscriptionModel, error) // GetUsersBySubscription(id uint) (*[]models.SubscriptionModel, error)
DeleteSubscription(subscription *models.SubscriptionModel) error DeleteSubscription(id *uint) error
} }
type SubscriptionModelsRepository struct{} type SubscriptionModelsRepository struct{}
@@ -37,9 +37,9 @@ func (sr *SubscriptionModelsRepository) UpdateSubscription(subscription *models.
return subscription, nil return subscription, nil
} }
func (sr *SubscriptionModelsRepository) DeleteSubscription(subscription *models.SubscriptionModel) error { func (sr *SubscriptionModelsRepository) DeleteSubscription(id *uint) error {
result := database.DB.Delete(&models.SubscriptionModel{}, subscription.ID) result := database.DB.Delete(&models.SubscriptionModel{}, id)
if result.Error != nil { if result.Error != nil {
return result.Error return result.Error
} }

View File

@@ -38,7 +38,7 @@ func RegisterRoutes(router *gin.Engine, userController *controllers.UserControll
membershipRouter.GET("/subscriptions", membershipcontroller.GetSubscriptions) membershipRouter.GET("/subscriptions", membershipcontroller.GetSubscriptions)
membershipRouter.PATCH("/subscriptions", membershipcontroller.UpdateHandler) membershipRouter.PATCH("/subscriptions", membershipcontroller.UpdateHandler)
membershipRouter.POST("/subscriptions", membershipcontroller.RegisterSubscription) membershipRouter.POST("/subscriptions", membershipcontroller.RegisterSubscription)
membershipRouter.DELETE("/subscriptions", membershipcontroller.DeleteSubscription)
} }
licenceRouter := router.Group("/backend/licence") licenceRouter := router.Group("/backend/licence")

View File

@@ -13,7 +13,7 @@ type MembershipServiceInterface interface {
FindMembershipByUserID(userID uint) (*models.Membership, error) FindMembershipByUserID(userID uint) (*models.Membership, error)
RegisterSubscription(subscription *models.SubscriptionModel) (uint, error) RegisterSubscription(subscription *models.SubscriptionModel) (uint, error)
UpdateSubscription(subscription *models.SubscriptionModel) (*models.SubscriptionModel, error) UpdateSubscription(subscription *models.SubscriptionModel) (*models.SubscriptionModel, error)
DeleteSubscription(subscription *models.SubscriptionModel) error DeleteSubscription(id *uint, name *string) error
GetSubscriptionModelNames() ([]string, error) GetSubscriptionModelNames() ([]string, error)
GetSubscriptionByName(modelname *string) (*models.SubscriptionModel, error) GetSubscriptionByName(modelname *string) (*models.SubscriptionModel, error)
GetSubscriptions(where map[string]interface{}) (*[]models.SubscriptionModel, error) GetSubscriptions(where map[string]interface{}) (*[]models.SubscriptionModel, error)
@@ -50,17 +50,21 @@ func (service *MembershipService) UpdateSubscription(subscription *models.Subscr
} }
func (service *MembershipService) DeleteSubscription(subscription *models.SubscriptionModel) error { func (service *MembershipService) DeleteSubscription(id *uint, name *string) error {
exists, err := repositories.GetSubscriptionByName(&subscription.Name) if *name == "" {
return errors.ErrNoData
}
exists, err := repositories.GetSubscriptionByName(name)
if err != nil { if err != nil {
return err return err
} }
if exists == nil { if exists == nil {
return errors.ErrNotFound return errors.ErrNotFound
} }
if *id != exists.ID {
subscription.ID = exists.ID return errors.ErrInvalidSubscriptionData
usersInSubscription, err := repositories.GetUsersBySubscription(subscription.ID) }
usersInSubscription, err := repositories.GetUsersBySubscription(*id)
if err != nil { if err != nil {
return err return err
@@ -68,7 +72,7 @@ func (service *MembershipService) DeleteSubscription(subscription *models.Subscr
if len(*usersInSubscription) > 0 { if len(*usersInSubscription) > 0 {
return errors.ErrSubscriptionInUse return errors.ErrSubscriptionInUse
} }
return service.SubscriptionRepo.DeleteSubscription(subscription) return service.SubscriptionRepo.DeleteSubscription(id)
} }
func (service *MembershipService) FindMembershipByUserID(userID uint) (*models.Membership, error) { func (service *MembershipService) FindMembershipByUserID(userID uint) (*models.Membership, error) {

View File

@@ -39,12 +39,12 @@ func HandleValidationError(c *gin.Context, err error) {
func HandleUserUpdateError(c *gin.Context, err error) { func HandleUserUpdateError(c *gin.Context, err error) {
switch err { switch err {
case errors.ErrUserNotFound: case errors.ErrUserNotFound:
RespondWithError(c, err, "Error while updating user", http.StatusNotFound, "user", "server.validation.user_not_found") RespondWithError(c, err, "Error while updating user", http.StatusNotFound, "user.user", "server.validation.user_not_found")
case errors.ErrInvalidUserData: case errors.ErrInvalidUserData:
RespondWithError(c, err, "Error while updating user", http.StatusBadRequest, "user", "server.validation.invalid_user_data") RespondWithError(c, err, "Error while updating user", http.StatusBadRequest, "user.user", "server.validation.invalid_user_data")
case errors.ErrSubscriptionNotFound: case errors.ErrSubscriptionNotFound:
RespondWithError(c, err, "Error while updating user", http.StatusBadRequest, "subscription", "server.validation.subscription_data") RespondWithError(c, err, "Error while updating user", http.StatusBadRequest, "subscription", "server.validation.subscription_data")
default: default:
RespondWithError(c, err, "Error while updating user", http.StatusInternalServerError, "user", "server.error.internal_server_error") RespondWithError(c, err, "Error while updating user", http.StatusInternalServerError, "user.user", "server.error.internal_server_error")
} }
} }

View File

@@ -44,6 +44,8 @@ var (
ValErrParentIDNotSet = errors.New("Parent Membership ID not provided") ValErrParentIDNotSet = errors.New("Parent Membership ID not provided")
ValErrParentIDNotFound = errors.New("Parent Membership ID not found") ValErrParentIDNotFound = errors.New("Parent Membership ID not found")
ErrSubscriptionNotFound = errors.New("Subscription Model not found") ErrSubscriptionNotFound = errors.New("Subscription Model not found")
ErrSubscriptionInUse = errors.New("This subscription is in active use by existing members.")
ErrInvalidSubscriptionData = errors.New("Provided subscription data is invalid. Immutable fields where changed.")
) )
var Responses = struct { var Responses = struct {