mirror of
https://github.com/GCMatters/hermes.git
synced 2026-02-04 21:50:12 +01:00
Compare commits
8 Commits
MyBranchKa
...
26635b4e88
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
26635b4e88 | ||
|
|
7e3759927f | ||
|
|
b440a0334c | ||
|
|
69895f4f35 | ||
|
|
5d362e2a39 | ||
|
|
a81a57654c | ||
|
|
48184cd8b6 | ||
|
|
f2ccde2ea6 |
11
WebApp/DTOs/EventRegistrationDto.cs
Normal file
11
WebApp/DTOs/EventRegistrationDto.cs
Normal 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
|
||||
);
|
||||
@@ -18,7 +18,6 @@ namespace WebApp.Endpoints
|
||||
var group = app.MapGroup("api/auth")
|
||||
.WithParameterValidation();
|
||||
|
||||
// POST /api/auth/login
|
||||
group.MapPost("/login", async (LoginDto dto, ApplicationDbContext context, GeneralUseHelpers guh) =>
|
||||
{
|
||||
var user = await context.WebUsers.FirstOrDefaultAsync(u => u.Email == dto.Email);
|
||||
@@ -39,7 +38,6 @@ namespace WebApp.Endpoints
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/auth/logout
|
||||
group.MapPost("/logout", async (HttpContext httpContext, GeneralUseHelpers guh) =>
|
||||
{
|
||||
var token = await guh.GetTokenFromHTTPContext(httpContext);
|
||||
@@ -56,7 +54,6 @@ namespace WebApp.Endpoints
|
||||
return Results.Ok(new { success = true });
|
||||
});
|
||||
|
||||
// GET /api/auth/my_account
|
||||
group.MapGet("/my_account", async (HttpContext httpContext, GeneralUseHelpers guh) =>
|
||||
{
|
||||
var token = await guh.GetTokenFromHTTPContext(httpContext);
|
||||
@@ -80,7 +77,6 @@ namespace WebApp.Endpoints
|
||||
})
|
||||
.WithName(GetUserEndpointName);
|
||||
|
||||
// GET /api/auth/my_events
|
||||
group.MapGet("/my_events", async (HttpContext httpContext, GeneralUseHelpers guh, ApplicationDbContext context) =>
|
||||
{
|
||||
var token = await guh.GetTokenFromHTTPContext(httpContext);
|
||||
@@ -99,9 +95,16 @@ namespace WebApp.Endpoints
|
||||
|
||||
if(!user.IsOrganisation)
|
||||
{
|
||||
var events = await context.EventRegistrations
|
||||
|
||||
var eventIds = await context.EventRegistrations
|
||||
.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();
|
||||
|
||||
return Results.Ok(events);
|
||||
@@ -126,14 +129,13 @@ namespace WebApp.Endpoints
|
||||
|
||||
});
|
||||
|
||||
// POST /api/auth/add_skill
|
||||
group.MapPost("/add_skill", async (SingleSkillDto dto, HttpContext httpContext, ApplicationDbContext context, GeneralUseHelpers guh) =>
|
||||
{
|
||||
// Uzyskaj użytkownika z tokenu
|
||||
Token? token = await guh.GetTokenFromHTTPContext(httpContext);
|
||||
User? user = await guh.GetUserFromToken(token);
|
||||
|
||||
// Tylko wolontariusze powinni móc dodawać swoje skille
|
||||
// Tylko wolontariusze powinno móc dodawać swoje skille
|
||||
if (user == null || user.IsOrganisation) {
|
||||
return Results.Json(new { message = "Unauthorized" }, statusCode: 401);
|
||||
}
|
||||
@@ -163,14 +165,14 @@ namespace WebApp.Endpoints
|
||||
return Results.Json(new { message = "Skill added successfully!" }, statusCode: 201);
|
||||
});
|
||||
|
||||
// POST /api/auth/remove_skill
|
||||
|
||||
group.MapPost("/remove_skill", async (SingleSkillDto dto, HttpContext httpContext, ApplicationDbContext context, GeneralUseHelpers guh) =>
|
||||
{
|
||||
// Uzyskaj użytkownika z tokenu
|
||||
Token? token = await guh.GetTokenFromHTTPContext(httpContext);
|
||||
User? user = await guh.GetUserFromToken(token);
|
||||
|
||||
// Tylko wolontariusze powinni móc usuwać swoje skille
|
||||
// Tylko wolontariusze powinien móc usuwac swoje skille
|
||||
if (user == null || user.IsOrganisation)
|
||||
{
|
||||
return Results.Json(new { message = "Unauthorized" }, statusCode: 401);
|
||||
@@ -183,28 +185,28 @@ namespace WebApp.Endpoints
|
||||
return Results.Json(new { message = "Skill not found" }, statusCode: 404);
|
||||
}
|
||||
|
||||
// Sprawdzamy, czy ten użytkownik ma już taki skill. Jeżeli nie ma, to nie ma sensu usuwać czegoś, czego nie ma.
|
||||
// Sprawdzamy, czy ten użytkownik ma już taki skill. Jeżeli nie ma, nie ma sensu usuwac go kilkukrotnie.
|
||||
VolunteerSkill? vs = await context.VolunteerSkills.FirstOrDefaultAsync(v => v.UserId == user.UserId && v.SkillId == dto.Skill);
|
||||
if (vs is not null)
|
||||
{
|
||||
// Ma - zatem musimy usunąć otrzymany VolunteerSkill z bazy
|
||||
// Nie ma - zatem musimy dodać nowy VolunteerSkill do bazy
|
||||
VolunteerSkill newVs = dto.ToVolunteerSkillEntity(user.UserId);
|
||||
|
||||
|
||||
await context.VolunteerSkills.Where(v => v.SkillId == dto.Skill)
|
||||
.ExecuteDeleteAsync();
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
// Nie ma - (ta para UserId <-> SkillId nie istnieje w bazie). Zwracamy błąd.
|
||||
// Ma - (ta para UserId <-> SkillId już istnieje w bazie) użytkownik już ma ten skill
|
||||
return Results.Json(new { message = "You don't have this skill" }, statusCode: 400);
|
||||
}
|
||||
|
||||
return Results.Json(new { message = "Skill deleted successfully!" }, statusCode: 201);
|
||||
});
|
||||
|
||||
// GET /api/auth/skills
|
||||
group.MapGet("/skills", async (HttpContext httpContext, ApplicationDbContext context, GeneralUseHelpers guh) =>
|
||||
group.MapGet("/get_skills", async (HttpContext httpContext, ApplicationDbContext context, GeneralUseHelpers guh) =>
|
||||
{
|
||||
// Uzyskaj użytkownika z tokenu
|
||||
Token? token = await guh.GetTokenFromHTTPContext(httpContext);
|
||||
|
||||
135
WebApp/Endpoints/EventRegistrationEndpoints.cs
Normal file
135
WebApp/Endpoints/EventRegistrationEndpoints.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using WebApp.Data;
|
||||
using WebApp.DTOs;
|
||||
@@ -134,7 +134,7 @@ namespace WebApp.Endpoints
|
||||
// Uzyskaj organizację z tokenu
|
||||
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
|
||||
Organisation? org = await guhf.GetOrganisationFromToken(token);
|
||||
if (org is null) return Results.Unauthorized();
|
||||
if (org is null) return Results.StatusCode(403);
|
||||
|
||||
// Sprawdź, czy organizacja ma prawo
|
||||
// do usunięcia tego (EventId = id) eventu.
|
||||
@@ -161,6 +161,7 @@ namespace WebApp.Endpoints
|
||||
List<EventSummaryDto> SearchResults = [];
|
||||
|
||||
|
||||
|
||||
List<Event> AllEvents = await dbContext.Events.ToListAsync();
|
||||
if (sort is null || sort.ToUpper() != "ASC")
|
||||
{
|
||||
@@ -222,91 +223,6 @@ namespace WebApp.Endpoints
|
||||
return Results.Ok(SearchResults);
|
||||
});
|
||||
|
||||
// POST /events/1/add_skill
|
||||
group.MapPost("/{id}/add_skill/",
|
||||
async (int id, SingleSkillDto dto, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
|
||||
{
|
||||
Event? Eve = await dbContext.Events.FindAsync(id);
|
||||
|
||||
if (Eve is null) return Results.Json(new { message = "Event not found" }, statusCode: 404);
|
||||
|
||||
// Sprawdź, czy token należy do organizacji, a jeżeli tak, to do której.
|
||||
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
|
||||
Organisation? org = await guhf.GetOrganisationFromToken(token);
|
||||
|
||||
// Jeśli token należy do organizacji, która utworzyła to wydarzenie,
|
||||
// to zwróć także EventRegistrations. W przeciwnym razie usuń to pole
|
||||
// przed jego wysłaniem!
|
||||
if (org is null || org.OrganisationId != Eve.OrganisationId) return Results.Unauthorized();
|
||||
|
||||
// Szukamy skilla w bazie o ID takim, jak w otrzymanym DTO
|
||||
Skill? skill = await dbContext.Skills.FindAsync(dto.Skill);
|
||||
if (skill is null)
|
||||
{
|
||||
return Results.Json(new { message = "Skill not found" }, statusCode: 404);
|
||||
}
|
||||
|
||||
// Sprawdzamy, czy to wydarzenie nie ma już takiego skilla. Jeżeli ma, nie ma sensu dodawać go kilkukrotnie.
|
||||
EventSkill? es = await dbContext.EventSkills.FirstOrDefaultAsync(e => e.EventId == id && e.SkillId == dto.Skill);
|
||||
if (es is null)
|
||||
{
|
||||
// Nie ma - zatem musimy dodać nowy EventSkill do bazy
|
||||
EventSkill newEs = dto.ToEventSkillEntity(Eve.EventId);
|
||||
dbContext.EventSkills.Add(newEs);
|
||||
await dbContext.SaveChangesAsync();
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
// Ma - (ta para EventId <-> SkillId już istnieje w bazie); ten Event posiada już ten skill
|
||||
return Results.Json(new { message = "Skill already assinged to this event!" }, statusCode: 400);
|
||||
}
|
||||
|
||||
return Results.Json(new { message = "Skill added to event successfully!" }, statusCode: 201);
|
||||
|
||||
});
|
||||
|
||||
// POST /events/1/renive_skill
|
||||
group.MapPost("/{id}/remove_skill/",
|
||||
async (int id, SingleSkillDto dto, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
|
||||
{
|
||||
Event? Eve = await dbContext.Events.FindAsync(id);
|
||||
|
||||
if (Eve is null) return Results.Json(new { message = "Event not found" }, statusCode: 404);
|
||||
|
||||
// Sprawdź, czy token należy do organizacji, a jeżeli tak, to do której.
|
||||
Token? token = await guhf.GetTokenFromHTTPContext(httpContext);
|
||||
Organisation? org = await guhf.GetOrganisationFromToken(token);
|
||||
|
||||
// Jeśli token należy do organizacji, która utworzyła to wydarzenie,
|
||||
// to zwróć także EventRegistrations. W przeciwnym razie usuń to pole
|
||||
// przed jego wysłaniem!
|
||||
if (org is null || org.OrganisationId != Eve.OrganisationId) return Results.Unauthorized();
|
||||
|
||||
// Szukamy skilla w bazie o ID takim, jak w otrzymanym DTO
|
||||
Skill? skill = await dbContext.Skills.FindAsync(dto.Skill);
|
||||
if (skill is null)
|
||||
{
|
||||
return Results.Json(new { message = "Skill not found" }, statusCode: 404);
|
||||
}
|
||||
|
||||
// Sprawdzamy, czy to wydarzenie nie ma już takiego skilla. Jeżeli nie ma, to nie ma sensu kasować czegoś, czego nie ma.
|
||||
EventSkill? es = await dbContext.EventSkills.FirstOrDefaultAsync(e => e.EventId == id && e.SkillId == dto.Skill);
|
||||
if (es is not null)
|
||||
{
|
||||
// Ma - zatem musimy usunąć ten EventSkill z bazy
|
||||
await dbContext.EventSkills.Where(e => e.SkillId == dto.Skill)
|
||||
.ExecuteDeleteAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Nie ma - (ta para EventId <-> SkillId nie istnieje w bazie); ten Event nie posiada tego skill'a
|
||||
return Results.Json(new { message = "This skill isn't assinged to this event!" }, statusCode: 400);
|
||||
}
|
||||
|
||||
return Results.Json(new { message = "Skill removed from event successfully!" }, statusCode: 201);
|
||||
});
|
||||
|
||||
return group;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using WebApp.Data;
|
||||
using WebApp.Mapping;
|
||||
|
||||
namespace WebApp.Endpoints;
|
||||
|
||||
public static class SkillsEndpoints
|
||||
{
|
||||
const string GetSkillEndpointName = "GetSkill";
|
||||
|
||||
public static RouteGroupBuilder MapSkillsEndpoints(this WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("api/skills").WithParameterValidation();
|
||||
|
||||
// GET /skills
|
||||
group.MapGet("/",
|
||||
async (ApplicationDbContext dbContext) =>
|
||||
await dbContext.Skills
|
||||
.OrderBy(Sk => Sk.SkillId)
|
||||
.Select(Sk => Sk.ToSkillSummaryDto()) // SkillSummaryDto
|
||||
.AsNoTracking()
|
||||
.ToListAsync());
|
||||
|
||||
return group;
|
||||
}
|
||||
}
|
||||
17
WebApp/Mapping/EventRegistrationMapping.cs
Normal file
17
WebApp/Mapping/EventRegistrationMapping.cs
Normal 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
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
using WebApp.DTOs;
|
||||
using WebApp.Entities;
|
||||
|
||||
namespace WebApp.Mapping;
|
||||
|
||||
public static class EventSkillMapping
|
||||
{
|
||||
public static EventSkill ToEventSkillEntity(this SingleSkillDto SSDto, int eid)
|
||||
{
|
||||
return new EventSkill()
|
||||
{
|
||||
EventId = eid,
|
||||
SkillId = SSDto.Skill,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,17 @@
|
||||
using WebApp.DTOs;
|
||||
using WebApp.DTOs;
|
||||
using WebApp.Entities;
|
||||
|
||||
namespace WebApp.Mapping;
|
||||
|
||||
public static class VolunteerSkillMapping
|
||||
namespace WebApp.Mapping
|
||||
{
|
||||
public static VolunteerSkill ToVolunteerSkillEntity(this SingleSkillDto SSDto, int uid)
|
||||
public static class VolunteerSkillMapping
|
||||
{
|
||||
return new VolunteerSkill()
|
||||
public static VolunteerSkill ToVolunteerSkillEntity(this SingleSkillDto SSDto, int uid)
|
||||
{
|
||||
UserId = uid,
|
||||
SkillId = SSDto.Skill,
|
||||
};
|
||||
return new VolunteerSkill()
|
||||
{
|
||||
UserId = uid,
|
||||
SkillId = SSDto.Skill,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,6 @@ app.UseRouting(); // Enables routing to match incoming request to endpoints
|
||||
app.MapEventsEndpoints();
|
||||
app.MapOrganizationsEndpoints();
|
||||
app.MapAuthEndpoints();
|
||||
app.MapSkillsEndpoints();
|
||||
app.MapEventsRegistrationEndpoints();
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -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 urlParams = new URLSearchParams(queryString);
|
||||
@@ -9,6 +9,8 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
var container = document.getElementById("mainContainer");
|
||||
const modifyBtn = document.getElementById("editBtn");
|
||||
const removeBtn = document.getElementById("removeBtn");
|
||||
const applyBtn = document.getElementById("applyBtn");
|
||||
const leaveBtn = document.getElementById("leaveBtn");
|
||||
var org_id: number = -1;
|
||||
|
||||
try {
|
||||
@@ -28,11 +30,11 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
try {
|
||||
if (eventId) thisEvent = await getEvent(eventId);
|
||||
} 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 (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 {
|
||||
|
||||
const titleText = document.getElementById( "titleText") as HTMLElement;
|
||||
@@ -51,13 +53,20 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
organizerText.innerHTML = "Organized by: " + thisEvent.organisationName;
|
||||
|
||||
if (org_id == thisEvent.organisationId) {
|
||||
// U¿ytkownik jest organizacj¹, która
|
||||
// stworzy³a to wydarzenie
|
||||
// Użytkownik jest organizacją, która
|
||||
// stworzyła to wydarzenie
|
||||
unhideElementById(document, "editBtn");
|
||||
unhideElementById(document, "removeBtn");
|
||||
} else if (org_id == -1) {
|
||||
// U¿ytkownik jest wolontariuszem
|
||||
unhideElementById(document, "applyBtn");
|
||||
// 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, "mainContainer");
|
||||
@@ -76,7 +85,7 @@ document.addEventListener("DOMContentLoaded", async () => {
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
// Wysy³a ¿¹danie DELETE do API
|
||||
// Wysyła żądanie DELETE do API
|
||||
const response = await fetch(`/api/events/${eventId}`, {
|
||||
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.")
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
@@ -36,9 +36,20 @@ export async function getEvent(id: string): Promise<EventData> {
|
||||
export async function getMyAccount(): Promise<MyAccount> {
|
||||
const res = await fetch("/api/auth/my_account");
|
||||
if (!res.ok) {
|
||||
throw Error("U¿ytkownik niezalogowany!");
|
||||
throw Error("U<EFBFBD>ytkownik niezalogowany!");
|
||||
}
|
||||
const data = await res.json();
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
||||
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 urlParams = new URLSearchParams(queryString);
|
||||
const eventId = urlParams.get('event');
|
||||
@@ -15,6 +15,8 @@ document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, vo
|
||||
var container = document.getElementById("mainContainer");
|
||||
const modifyBtn = document.getElementById("editBtn");
|
||||
const removeBtn = document.getElementById("removeBtn");
|
||||
const applyBtn = document.getElementById("applyBtn");
|
||||
const leaveBtn = document.getElementById("leaveBtn");
|
||||
var org_id = -1;
|
||||
try {
|
||||
var user = yield getMyAccount();
|
||||
@@ -36,7 +38,7 @@ document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, vo
|
||||
}
|
||||
catch (err) {
|
||||
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 (container !== null)
|
||||
@@ -63,7 +65,14 @@ document.addEventListener("DOMContentLoaded", () => __awaiter(void 0, void 0, vo
|
||||
}
|
||||
else if (org_id == -1) {
|
||||
// Użytkownik jest wolontariuszem
|
||||
unhideElementById(document, "applyBtn");
|
||||
const registeredIds = yield getMyRegisteredEventIds();
|
||||
const isRegistered = registeredIds.includes(Number(eventId));
|
||||
if (isRegistered) {
|
||||
unhideElementById(document, "leaveBtn");
|
||||
}
|
||||
else {
|
||||
unhideElementById(document, "applyBtn");
|
||||
}
|
||||
}
|
||||
unhideElementById(document, "mainContainer");
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
}));
|
||||
}
|
||||
}));
|
||||
|
||||
@@ -35,3 +35,13 @@ export function getMyAccount() {
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
@@ -68,16 +68,12 @@
|
||||
<input type="password" id="password" class="form-control input-field" required />
|
||||
</div>
|
||||
|
||||
<br />
|
||||
<br/>
|
||||
|
||||
<button id="logInBtn" class="button" type="submit">
|
||||
<span>Log in</span>
|
||||
<span>⮞</span>
|
||||
</button>
|
||||
<button id="signUpBtn" class="button" type="button" onclick="alert('Coming soon!')">
|
||||
<span>Sign up</span>
|
||||
<span>⮞</span>
|
||||
</button>
|
||||
<p id="message" style="color: red;"></p>
|
||||
|
||||
</form>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!DOCTYPE html>
|
||||
<html lang="pl">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
@@ -64,6 +64,7 @@
|
||||
<h4 id="descText"></h4><br />
|
||||
|
||||
<button id="applyBtn" class="button hidden-before-load"><span>Apply</span><span>⮞</span></button>
|
||||
<button id="leaveBtn" class="button hidden-before-load"><span>Leave</span><span>⮞</span></button>
|
||||
<button id="editBtn" class="button hidden-before-load"><span>Modify</span><span>⮞</span></button>
|
||||
<button id="removeBtn" class="button hidden-before-load" style="background-color: red;"><span>Remove permanently</span><span>⮞</span></button>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user