mirror of
https://github.com/TheRealOwenRees/echecsfrance.git
synced 2026-07-23 04:26:57 +00:00
Reorganise code - use src folder
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import { addTournament } from "./procedures/addTournament";
|
||||
import { contactUs } from "./procedures/contactUs";
|
||||
import { fetchTournamentResults } from "./procedures/fetchTournamentResults";
|
||||
import { router } from "./trpc";
|
||||
|
||||
export const appRouter = router({
|
||||
contactUs,
|
||||
addTournament,
|
||||
fetchTournamentResults,
|
||||
});
|
||||
|
||||
export type AppRouter = typeof appRouter;
|
||||
@@ -0,0 +1,81 @@
|
||||
import { format } from "date-fns";
|
||||
|
||||
import clientPromise from "@/lib/mongodb";
|
||||
import { addTournamentSchema } from "@/schemas";
|
||||
import { TournamentData } from "@/types";
|
||||
import { TimeControl } from "@/types";
|
||||
import { errorLog } from "@/utils/logger";
|
||||
|
||||
import { publicProcedure } from "../trpc";
|
||||
|
||||
const tcMap: Record<TimeControl, TournamentData["time_control"]> = {
|
||||
[TimeControl.Classic]: "Cadence Lente",
|
||||
[TimeControl.Rapid]: "Rapide",
|
||||
[TimeControl.Blitz]: "Blitz",
|
||||
[TimeControl.Other]: "Other",
|
||||
};
|
||||
|
||||
export const addTournament = publicProcedure
|
||||
.input(addTournamentSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
try {
|
||||
const client = await clientPromise;
|
||||
const db = client.db("tournamentsFranceDB").collection("tournaments");
|
||||
|
||||
const { name, email, message, tournament } = input;
|
||||
|
||||
const tournamentData: Omit<TournamentData, "_id"> = {
|
||||
...tournament,
|
||||
date: format(tournament.date, "dd/MM/yyyy"),
|
||||
time_control: tcMap[tournament.time_control],
|
||||
coordinates: tournament.coordinates as [number, number],
|
||||
entry_method: "manual",
|
||||
pending: true,
|
||||
status: "scheduled",
|
||||
};
|
||||
|
||||
const result = await db.insertOne(tournamentData);
|
||||
|
||||
if (result.insertedId) {
|
||||
const { tournament, country, date, time_control } = tournamentData;
|
||||
|
||||
if (
|
||||
typeof process.env.DISCORD_WEBHOOK_ADD_TOURNAMENT_URL === "string"
|
||||
) {
|
||||
await fetch(
|
||||
process.env.DISCORD_WEBHOOK_ADD_TOURNAMENT_URL as string,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
embeds: [
|
||||
{
|
||||
title: "Tournament Submitted",
|
||||
fields: [
|
||||
{ name: "Tournament", value: tournament },
|
||||
{ name: "Country", value: country },
|
||||
{ name: "Date", value: date },
|
||||
{
|
||||
name: "Time Control",
|
||||
value: time_control,
|
||||
},
|
||||
{ name: "Sender", value: name },
|
||||
{ name: "Sender Email", value: email },
|
||||
{ name: "Message", value: message ?? "" },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
errorLog(error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import NodeMailer from "nodemailer";
|
||||
|
||||
import { contactUsSchema } from "@/schemas";
|
||||
import { errorLog, infoLog } from "@/utils/logger";
|
||||
|
||||
import { publicProcedure } from "../trpc";
|
||||
|
||||
export const contactUs = publicProcedure
|
||||
.input(contactUsSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
try {
|
||||
const { email, subject, message } = input;
|
||||
|
||||
const mailContent = {
|
||||
from: email,
|
||||
to: process.env.GMAIL_USER,
|
||||
subject: `${subject} from ${email}`,
|
||||
text: message,
|
||||
html: `<p>${message}</p>`,
|
||||
};
|
||||
|
||||
const transporter = NodeMailer.createTransport({
|
||||
service: "gmail",
|
||||
auth: {
|
||||
user: process.env.GMAIL_USER,
|
||||
pass: process.env.GMAIL_PASS,
|
||||
},
|
||||
});
|
||||
|
||||
const mailInfo = await transporter.sendMail(mailContent);
|
||||
infoLog(mailInfo);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
errorLog(error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { fetchTournamentResultsSchema } from "@/schemas";
|
||||
import { errorLog } from "@/utils/logger";
|
||||
|
||||
import { publicProcedure } from "../trpc";
|
||||
|
||||
const scrapedSchema = z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
elo: z.string(),
|
||||
results: z.array(
|
||||
z.object({
|
||||
colour: z.enum(["B", "N", ""]),
|
||||
result: z.string(),
|
||||
opponent_name: z.string().nullable(),
|
||||
opponent_elo: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const outputSchema = z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
elo: z.number(),
|
||||
estimated: z.boolean(),
|
||||
national: z.boolean(),
|
||||
results: z.array(
|
||||
z.object({
|
||||
colour: z.enum(["white", "black", ""]),
|
||||
result: z.number().nullable(),
|
||||
lostByForfeit: z.boolean(),
|
||||
wonByForfeit: z.boolean(),
|
||||
opponent: z.string().nullable(),
|
||||
elo: z.number().nullable(),
|
||||
estimated: z.boolean(),
|
||||
national: z.boolean(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const getEloDetails = (elo: string | null) => {
|
||||
if (elo === null || elo === "") {
|
||||
return { elo: 0, estimated: false, national: false };
|
||||
}
|
||||
return {
|
||||
elo: parseInt(elo),
|
||||
estimated: elo.endsWith("E"),
|
||||
national: elo.endsWith("N"),
|
||||
};
|
||||
};
|
||||
|
||||
const getResultDetails = (
|
||||
results: z.infer<typeof scrapedSchema>[number]["results"][number],
|
||||
) => {
|
||||
if (results.opponent_name === null) {
|
||||
return { result: 0, lostByForfeit: true, wonByForfeit: false };
|
||||
}
|
||||
|
||||
if (results.result === "<") {
|
||||
return { result: 0, lostByForfeit: true, wonByForfeit: false };
|
||||
}
|
||||
|
||||
if (results.result === ">") {
|
||||
return { result: 1, lostByForfeit: false, wonByForfeit: true };
|
||||
}
|
||||
|
||||
return {
|
||||
result: parseFloat(results.result),
|
||||
lostByForfeit: false,
|
||||
wonByForfeit: false,
|
||||
};
|
||||
};
|
||||
|
||||
const reportFetchError = async (url: string, error: any) => {
|
||||
if (typeof process.env.DISCORD_WEBHOOK_ERROR_LOGS_URL === "string") {
|
||||
await fetch(process.env.DISCORD_WEBHOOK_ERROR_LOGS_URL as string, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
embeds: [
|
||||
{
|
||||
title: "Error Fetching Tournament Results",
|
||||
fields: [
|
||||
{ name: "url", value: url },
|
||||
{
|
||||
name: "error.message",
|
||||
value: "message" in error ? error.message : "",
|
||||
},
|
||||
{ name: "error", value: JSON.stringify(error, null, 2) },
|
||||
],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const fetchTournamentResults = publicProcedure
|
||||
.input(fetchTournamentResultsSchema)
|
||||
.output(outputSchema)
|
||||
.query(async ({ input }) => {
|
||||
try {
|
||||
// Depending on which page the user copied the URL from, we need to extract the tournament ID
|
||||
|
||||
// http://echecs.asso.fr/FicheTournoi.aspx?Ref=59975
|
||||
// http://echecs.asso.fr/Resultats.aspx?URL=Tournois/Id/59975/59975&Action=Ls
|
||||
|
||||
const tournamentId =
|
||||
input.url.match(/Ref=(\d+)/)?.[1] ?? input.url.match(/Id\/(\d+)/)?.[1];
|
||||
if (!tournamentId) {
|
||||
throw new Error("ERR_NO_TOURNAMENT_ID");
|
||||
}
|
||||
|
||||
const headers = new Headers();
|
||||
const apiKey = process.env.RESULTS_API_KEY;
|
||||
|
||||
if (apiKey) {
|
||||
headers.append("api-key", apiKey);
|
||||
}
|
||||
|
||||
const rawResults = await fetch(
|
||||
`${process.env.RESULTS_SCRAPER_URL}${tournamentId}`,
|
||||
{
|
||||
headers: headers,
|
||||
},
|
||||
);
|
||||
|
||||
const results = await rawResults.json();
|
||||
|
||||
if ("detail" in results && results.detail === "Not found") {
|
||||
throw new Error("ERR_TOURNAMENT_NOT_FOUND");
|
||||
}
|
||||
|
||||
const parsedResults = scrapedSchema.parse(results);
|
||||
return parsedResults.map<z.infer<typeof outputSchema>[number]>(
|
||||
(player) => ({
|
||||
id: player.id,
|
||||
name: player.name,
|
||||
...getEloDetails(player.elo),
|
||||
results: player.results.map((result) => ({
|
||||
colour:
|
||||
result.colour === "B"
|
||||
? "white"
|
||||
: result.colour === "N"
|
||||
? "black"
|
||||
: "",
|
||||
opponent: result.opponent_name,
|
||||
...getResultDetails(result),
|
||||
...getEloDetails(result.opponent_elo),
|
||||
})),
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
reportFetchError(input.url, error);
|
||||
errorLog(JSON.stringify(error, null, 2));
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import { initTRPC } from "@trpc/server";
|
||||
import superjson from "superjson";
|
||||
import { z } from "zod";
|
||||
|
||||
const t = initTRPC.create({
|
||||
transformer: superjson,
|
||||
});
|
||||
|
||||
// Base router and procedure helpers
|
||||
export const router = t.router;
|
||||
export const publicProcedure = t.procedure;
|
||||
Reference in New Issue
Block a user