9 Commits

Author SHA1 Message Date
AleksDw
aa5caf4375 Update modify.html 2025-06-01 18:21:20 +02:00
AleksDw
26635b4e88 Add leaving event 2025-06-01 17:21:00 +02:00
AleksDw
7e3759927f Add applying to event 2025-06-01 17:13:47 +02:00
AleksDw
b440a0334c Fix api/auth/my_events endpoint 2025-06-01 17:11:01 +02:00
AleksDw
69895f4f35 Revert "Apply to Event"
This reverts commit 5d362e2a39.
2025-06-01 17:10:12 +02:00
AleksDw
5d362e2a39 Apply to Event 2025-06-01 15:06:13 +02:00
AleksDw
a81a57654c Merge branch 'EventRegistrationEndpoints' 2025-06-01 14:20:46 +02:00
AleksDw
48184cd8b6 Add remove endpoint 2025-05-31 02:24:54 +02:00
AleksDw
f2ccde2ea6 Join, leave, registrations endpoints
todo: remove smb from event endpoint
2025-05-31 02:19:01 +02:00
11 changed files with 333 additions and 18 deletions

View File

@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;
using WebApp.Entities;
namespace WebApp.DTOs;
// Output values in JSON file
public record class EventRegistrationDto(
int EventId,
int UserId,
DateTime RegisteredAt
);

View File

@@ -1,4 +1,4 @@
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using WebApp.Data; using WebApp.Data;
@@ -95,9 +95,16 @@ namespace WebApp.Endpoints
if(!user.IsOrganisation) if(!user.IsOrganisation)
{ {
var events = await context.EventRegistrations
var eventIds = await context.EventRegistrations
.Where(er => er.UserId == user.UserId) .Where(er => er.UserId == user.UserId)
.Select(er => er.Event.ToEventSummaryNoErDto()) .Select(er => er.EventId)
.ToListAsync();
var events = await context.Events
.Where(e => eventIds.Contains(e.EventId))
.Include(e => e.Organisation)
.Select(e => e.ToEventSummaryDto())
.ToListAsync(); .ToListAsync();
return Results.Ok(events); return Results.Ok(events);

View File

@@ -0,0 +1,135 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography;
using WebApp.Data;
using WebApp.DTOs;
using WebApp.Entities;
using WebApp.Mapping;
namespace WebApp.Endpoints
{
public static class EventsRegistrationEndpoints
{
const string GetEventEndpointRegistrationName = "GetEventRegistration";
public static RouteGroupBuilder MapEventsRegistrationEndpoints(this WebApplication app)
{
var group = app.MapGroup("api/events")
.WithParameterValidation();
// POST /api/events/join/{id}
group.MapPost("/join/{id}",
async (int id, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null)
return Results.Json(new { success = false, error_msg = "Event not found." });
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
User? user = await guhf.GetUserFromToken(token);
if (user is null || user.IsOrganisation)
return Results.Json(new { success = false, error_msg = "Unauthorized or organisations cannot register for events." });
if (await dbContext.EventRegistrations.AnyAsync(er => er.UserId == user.UserId && er.EventId == id))
return Results.Json(new { success = false, error_msg = "You are already registered for this event." });
if (Eve.EventDate < DateTime.UtcNow)
return Results.Json(new { success = false, error_msg = "This event has already ended." });
EventRegistration registration = new EventRegistration
{
UserId = user.UserId,
EventId = id,
RegisteredAt = DateTime.UtcNow
};
dbContext.EventRegistrations.Add(registration);
await dbContext.SaveChangesAsync();
return Results.Json(new { success = true });
});
// POST /api/events/leave/{id}
group.MapPost("/leave/{id}",
async (int id, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null)
return Results.Json(new { success = false, error_msg = "Event not found." });
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
User? user = await guhf.GetUserFromToken(token);
if (user is null)
return Results.Json(new { success = false, error_msg = "Unauthorized." });
if (!await dbContext.EventRegistrations.AnyAsync(er => er.UserId == user.UserId && er.EventId == id))
return Results.Json(new { success = false, error_msg = "You are not registered for this event." });
if (Eve.EventDate < DateTime.UtcNow)
return Results.Json(new { success = false, error_msg = "This event has already ended." });
EventRegistration? registration = await dbContext.EventRegistrations
.FirstOrDefaultAsync(er => er.UserId == user.UserId && er.EventId == id);
dbContext.EventRegistrations.Remove(registration);
await dbContext.SaveChangesAsync();
return Results.Json(new { success = true });
});
// GET /api/events/registrations/{id}
group.MapGet("/registrations/{id}",
async (int id, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null)
return Results.Json(new { success = false, error_msg = "Event not found." });
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
Organisation? org = await guhf.GetOrganisationFromToken(token);
if (org is null || org.OrganisationId != Eve.OrganisationId)
return Results.Json(new { success = false, error_msg = "Unauthorized." });
var registrations = await dbContext.EventRegistrations
.Where(er => er.EventId == id)
.Select(er => er.ToEventRegistrationDto())
.ToListAsync();
return Results.Json(new
{
success = true,
registrations
});
});
// POST /api/events/remove/{id}/{userId}
group.MapPost("/remove/{id}/{userId}",
async (int id, int userId, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
{
Event? Eve = await dbContext.Events.FindAsync(id);
if (Eve is null)
return Results.Json(new { success = false, error_msg = "Event not found." });
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
Organisation? org = await guhf.GetOrganisationFromToken(token);
if (org is null || org.OrganisationId != Eve.OrganisationId)
return Results.Json(new { success = false, error_msg = "Unauthorized." });
EventRegistration? registration = await dbContext.EventRegistrations
.FirstOrDefaultAsync(er => er.UserId == userId && er.EventId == id);
if (registration is null)
return Results.Json(new { success = false, error_msg = "Registration not found." });
dbContext.EventRegistrations.Remove(registration);
await dbContext.SaveChangesAsync();
return Results.Json(new { success = true });
});
return group;
}
}
}

View File

@@ -0,0 +1,17 @@
using WebApp.DTOs;
using WebApp.Entities;
namespace WebApp.Mapping
{
public static class EventRegistrationMapping
{
public static EventRegistrationDto ToEventRegistrationDto(this EventRegistration er)
{
return new EventRegistrationDto(
er.EventId,
er.UserId,
er.RegisteredAt
);
}
}
}

View File

@@ -53,5 +53,6 @@ app.UseRouting(); // Enables routing to match incoming request to endpoints
app.MapEventsEndpoints(); app.MapEventsEndpoints();
app.MapOrganizationsEndpoints(); app.MapOrganizationsEndpoints();
app.MapAuthEndpoints(); app.MapAuthEndpoints();
app.MapEventsRegistrationEndpoints();
app.Run(); app.Run();

View File

@@ -1,4 +1,4 @@
import { getEvent, getMyAccount, unhideElementById } from './generalUseHelpers.js'; import { getEvent, getMyAccount, unhideElementById, getMyRegisteredEventIds } from './generalUseHelpers.js';
const queryString = window.location.search; const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString); const urlParams = new URLSearchParams(queryString);
@@ -9,6 +9,8 @@ document.addEventListener("DOMContentLoaded", async () => {
var container = document.getElementById("mainContainer"); var container = document.getElementById("mainContainer");
const modifyBtn = document.getElementById("editBtn"); const modifyBtn = document.getElementById("editBtn");
const removeBtn = document.getElementById("removeBtn"); const removeBtn = document.getElementById("removeBtn");
const applyBtn = document.getElementById("applyBtn");
const leaveBtn = document.getElementById("leaveBtn");
var org_id: number = -1; var org_id: number = -1;
try { try {
@@ -28,11 +30,11 @@ document.addEventListener("DOMContentLoaded", async () => {
try { try {
if (eventId) thisEvent = await getEvent(eventId); if (eventId) thisEvent = await getEvent(eventId);
} catch (err) { } catch (err) {
if (container !== null) container.innerHTML = `<p class="text-danger">To wydarzenie nie istnieje! <a href="/" style="color:#2898BD;">Powrót -></a></p>`; if (container !== null) container.innerHTML = `<p class="text-danger">To wydarzenie nie istnieje! <a href="/" style="color:#2898BD;">Powr<EFBFBD>t -></a></p>`;
} }
if (thisEvent == null) { if (thisEvent == null) {
if (container !== null) container.innerHTML = `<p class="text-danger">B³¹d we wczytywaniu wydarzenia. <a href="/" style="color:#2898BD;">Powrót -></a></p>`; if (container !== null) container.innerHTML = `<p class="text-danger">Błąd we wczytywaniu wydarzenia. <a href="/" style="color:#2898BD;">Powrót -></a></p>`;
} else { } else {
const titleText = document.getElementById( "titleText") as HTMLElement; const titleText = document.getElementById( "titleText") as HTMLElement;
@@ -51,14 +53,21 @@ document.addEventListener("DOMContentLoaded", async () => {
organizerText.innerHTML = "Organized by: " + thisEvent.organisationName; organizerText.innerHTML = "Organized by: " + thisEvent.organisationName;
if (org_id == thisEvent.organisationId) { if (org_id == thisEvent.organisationId) {
// U¿ytkownik jest organizacj¹, która // Użytkownik jest organizacją, która
// stworzy³a to wydarzenie // stworzyła to wydarzenie
unhideElementById(document, "editBtn"); unhideElementById(document, "editBtn");
unhideElementById(document, "removeBtn"); unhideElementById(document, "removeBtn");
} else if (org_id == -1) { } else if (org_id == -1) {
// U¿ytkownik jest wolontariuszem // Użytkownik jest wolontariuszem
const registeredIds = await getMyRegisteredEventIds();
const isRegistered = registeredIds.includes(Number(eventId));
if (isRegistered) {
unhideElementById(document, "leaveBtn");
} else {
unhideElementById(document, "applyBtn"); unhideElementById(document, "applyBtn");
} }
}
unhideElementById(document, "mainContainer"); unhideElementById(document, "mainContainer");
@@ -76,7 +85,7 @@ document.addEventListener("DOMContentLoaded", async () => {
if (!confirmed) return; if (!confirmed) return;
try { try {
// Wysy³a ¿¹danie DELETE do API // Wysyła żądanie DELETE do API
const response = await fetch(`/api/events/${eventId}`, { const response = await fetch(`/api/events/${eventId}`, {
method: "DELETE" method: "DELETE"
}); });
@@ -94,4 +103,59 @@ document.addEventListener("DOMContentLoaded", async () => {
}); });
} }
if (applyBtn) {
applyBtn.addEventListener("click", async (e) => {
try {
const response = await fetch(`/api/events/join/${eventId}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
});
const result: {
success: boolean;
error_msg?: string;
} = await response.json();
if (result.success) {
window.location.href = `/view.html?event=${eventId}`;
} else {
alert(`Error: ${result.error_msg ?? "Unknown error occurred."}`);
}
} catch (error) {
console.error("Failed to apply:", error);
alert("Failed to apply.");
}
});
}
if (leaveBtn) {
leaveBtn.addEventListener("click", async (e) => {
try {
const response = await fetch(`/api/events/leave/${eventId}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
});
const result: {
success: boolean;
error_msg?: string;
} = await response.json();
if (result.success) {
window.location.href = `/view.html?event=${eventId}`;
} else {
alert(`Error: ${result.error_msg ?? "Unknown error occurred."}`);
}
} catch (error) {
console.error("Failed to leave:", error)
alert("Failed to leave.")
}
});
}
}); });

View File

@@ -36,9 +36,20 @@ export async function getEvent(id: string): Promise<EventData> {
export async function getMyAccount(): Promise<MyAccount> { export async function getMyAccount(): Promise<MyAccount> {
const res = await fetch("/api/auth/my_account"); const res = await fetch("/api/auth/my_account");
if (!res.ok) { if (!res.ok) {
throw Error("U¿ytkownik niezalogowany!"); throw Error("U<EFBFBD>ytkownik niezalogowany!");
} }
const data = await res.json(); const data = await res.json();
return data; return data;
} }
export async function getMyRegisteredEventIds(): Promise<number[]> {
const res = await fetch("/api/auth/my_events");
if (!res.ok) {
throw Error("Użytkownik niezalogowany!");
}
const events = await res.json();
return events.map((event: { eventId: number }) => event.eventId);
}

View File

@@ -7,7 +7,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
import { getEvent, getMyAccount, unhideElementById } from './generalUseHelpers.js'; import { getEvent, getMyAccount, unhideElementById, getMyRegisteredEventIds } from './generalUseHelpers.js';
const queryString = window.location.search; const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString); const urlParams = new URLSearchParams(queryString);
const eventId = urlParams.get('event'); const eventId = urlParams.get('event');
@@ -15,6 +15,8 @@ document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, vo
var container = document.getElementById("mainContainer"); var container = document.getElementById("mainContainer");
const modifyBtn = document.getElementById("editBtn"); const modifyBtn = document.getElementById("editBtn");
const removeBtn = document.getElementById("removeBtn"); const removeBtn = document.getElementById("removeBtn");
const applyBtn = document.getElementById("applyBtn");
const leaveBtn = document.getElementById("leaveBtn");
var org_id = -1; var org_id = -1;
try { try {
var user = yield getMyAccount(); var user = yield getMyAccount();
@@ -36,7 +38,7 @@ document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, vo
} }
catch (err) { catch (err) {
if (container !== null) if (container !== null)
container.innerHTML = `<p class="text-danger">To wydarzenie nie istnieje! <a href="/" style="color:#2898BD;">Powrót -></a></p>`; container.innerHTML = `<p class="text-danger">To wydarzenie nie istnieje! <a href="/" style="color:#2898BD;">Powr<EFBFBD>t -></a></p>`;
} }
if (thisEvent == null) { if (thisEvent == null) {
if (container !== null) if (container !== null)
@@ -63,8 +65,15 @@ document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, vo
} }
else if (org_id == -1) { else if (org_id == -1) {
// Użytkownik jest wolontariuszem // Użytkownik jest wolontariuszem
const registeredIds = yield getMyRegisteredEventIds();
const isRegistered = registeredIds.includes(Number(eventId));
if (isRegistered) {
unhideElementById(document, "leaveBtn");
}
else {
unhideElementById(document, "applyBtn"); unhideElementById(document, "applyBtn");
} }
}
unhideElementById(document, "mainContainer"); unhideElementById(document, "mainContainer");
} }
if (modifyBtn) { if (modifyBtn) {
@@ -96,4 +105,52 @@ document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, vo
} }
})); }));
} }
if (applyBtn) {
applyBtn.addEventListener("click", (e) => __awaiter(void 0, void 0, void 0, function* () {
var _b;
try {
const response = yield fetch(`/api/events/join/${eventId}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
});
const result = yield response.json();
if (result.success) {
window.location.href = `/view.html?event=${eventId}`;
}
else {
alert(`Error: ${(_b = result.error_msg) !== null && _b !== void 0 ? _b : "Unknown error occurred."}`);
}
}
catch (error) {
console.error("Failed to apply:", error);
alert("Failed to apply.");
}
}));
}
if (leaveBtn) {
leaveBtn.addEventListener("click", (e) => __awaiter(void 0, void 0, void 0, function* () {
var _c;
try {
const response = yield fetch(`/api/events/leave/${eventId}`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
});
const result = yield response.json();
if (result.success) {
window.location.href = `/view.html?event=${eventId}`;
}
else {
alert(`Error: ${(_c = result.error_msg) !== null && _c !== void 0 ? _c : "Unknown error occurred."}`);
}
}
catch (error) {
console.error("Failed to leave:", error);
alert("Failed to leave.");
}
}));
}
})); }));

View File

@@ -35,3 +35,13 @@ export function getMyAccount() {
return data; return data;
}); });
} }
export function getMyRegisteredEventIds() {
return __awaiter(this, void 0, void 0, function* () {
const res = yield fetch("/api/auth/my_events");
if (!res.ok) {
throw Error("Użytkownik niezalogowany!");
}
const events = yield res.json();
return events.map((event) => event.eventId);
});
}

View File

@@ -80,6 +80,7 @@
<script type="module" src="/js/eventModify.js"></script> <script type="module" src="/js/eventModify.js"></script>
<script type="module" src="/js/generalUseHelpers.js"></script> <script type="module" src="/js/generalUseHelpers.js"></script>
<script type="module" src="/js/auth.js"></script>
</body> </body>

View File

@@ -1,4 +1,4 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="pl"> <html lang="pl">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
@@ -64,6 +64,7 @@
<h4 id="descText"></h4><br /> <h4 id="descText"></h4><br />
<button id="applyBtn" class="button hidden-before-load"><span>Apply</span><span>&#11166;</span></button> <button id="applyBtn" class="button hidden-before-load"><span>Apply</span><span>&#11166;</span></button>
<button id="leaveBtn" class="button hidden-before-load"><span>Leave</span><span>&#11166;</span></button>
<button id="editBtn" class="button hidden-before-load"><span>Modify</span><span>&#11166;</span></button> <button id="editBtn" class="button hidden-before-load"><span>Modify</span><span>&#11166;</span></button>
<button id="removeBtn" class="button hidden-before-load" style="background-color: red;"><span>Remove permanently</span><span>&#11166;</span></button> <button id="removeBtn" class="button hidden-before-load" style="background-color: red;"><span>Remove permanently</span><span>&#11166;</span></button>