Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Fix setup bugs #55

Merged
merged 1 commit into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions app/src/app/(general)/LatestGamesTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,14 @@ export const LatestGamesTable = ({ games }: LatestGamesTableProps) => {
getCoreRowModel: getCoreRowModel()
})

if (games.length === 0) {
return (
<div className='h-72 w-full flex items-center justify-center'>
<span>No game found yet</span>
</div>
)
}

return (
<div className='h-72 w-full overflow-scroll p-0'>
<table className='w-full'>
Expand Down
4 changes: 3 additions & 1 deletion app/src/app/setup/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { LogoutButton } from '@/components/auth/LogoutButton'
import { cn } from '@/lib/utils'
import React from 'react'

Expand All @@ -7,11 +8,12 @@ export default function SetupLayout({
children: React.ReactNode
}) {
return (
<div className='flex h-screen w-full items-center justify-center bg-background text-white'>
<div className='flex flex-col gap-40 h-screen w-full items-center justify-center bg-background text-white'>
<div className={cn('w-3/4 md:w-1/2 m-h-1/2 bg-foreground ',
'border-l-4 border-r-0 border-t-0 border-b-0 border-primary rounded-none p-5')}>
{children}
</div>
<LogoutButton />
</div>
)
}
2 changes: 1 addition & 1 deletion app/src/app/setup/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export default async function SetupPage() {
</h1>
<p>
Welcome to Chess Tactics Manager !
Here you can set up your account.
Here you can set up your chess account.
</p>
<SetupForm />
</>
Expand Down
96 changes: 0 additions & 96 deletions app/src/lib/chess/lichess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,99 +17,3 @@ export const triggerLichessSync = async (accountId: string) => {

await createLichessSynchonizerTask(accountId)
}

export const updateLichessAccount = async (accountId: string) => {
console.log('Updating lichess account', accountId)
const account = await prisma.chessAccount.findUnique({
where: {
id: accountId
}
})

if (!account) {
console.log('Account not found')
return null
}

await prisma.chessAccount.update({
where: {
id: accountId
},
data: {
isFetching: true
}
})

console.log('Fetching lichess games for', account.username)

const response = await fetch(
`https://lichess.org/api/games/user/${account.username}?clocks=true&opening=true&max=100`,
{
headers: {
Accept: 'application/x-ndjson'
}
}
)
const responseText = await response.text()
const games = (responseText.match(/.+/g) ?? []).map((text) =>
JSON.parse(text)
)

for (const game of games) {
console.log('Creating game', game.id)

const gameExist = await prisma.game.findUnique({
where: {
id: game.id
}
})

if (gameExist) {
console.log('Game already exists')
continue
}

const whitePlayer = game.players.white
const blackPlayer = game.players.black

if (!whitePlayer?.user || !blackPlayer?.user) {
console.log('Skipping game', game.id)
continue
}

await prisma.game.create({
data: {
id: game.id,
pgn: game.moves,
whitePlayer: whitePlayer.user.id,
whiteChessAccountId:
whitePlayer.user.id === account.username ? accountId : null,
whiteRating: whitePlayer.rating,
blackPlayer: blackPlayer.user.id,
blackChessAccountId:
blackPlayer.user.id === account.username ? accountId : null,
blackRating: blackPlayer.rating,
winner: game.winner || 'draw',
status: game.status,
rated: game.rated,
category: game.speed,
clocks: game.clocks,
opening: game.opening.name,
date: new Date(game.createdAt)
}
})
console.log('Game created')
}

await prisma.chessAccount.update({
where: {
id: accountId
},
data: {
lastFetch: new Date(),
isFetching: false
}
})

return games
}
21 changes: 15 additions & 6 deletions app/src/pages/api/setup/account.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use server'

import { isEmpty, isNil } from 'lodash'
import prisma from '@/lib/database'
import { NextApiRequest, NextApiResponse } from 'next'
import { decode } from 'next-auth/jwt'
Expand Down Expand Up @@ -46,16 +47,15 @@ export default async function handler(
secret: process.env.NEXTAUTH_SECRET!,
})

console.log('decodedUser', decodedUser)

if (!decodedUser || !decodedUser.email) {
res.status(403).json({ success: false })
return
}

const { lichessUsername, chesscomUsername } = req.body

if (lichessUsername === undefined && chesscomUsername === undefined) {
if ((isNil(lichessUsername) || isEmpty(lichessUsername)) &&
(isNil(chesscomUsername) || isEmpty(chesscomUsername))) {
res.status(400).json({ success: false })
return
}
Expand All @@ -71,17 +71,26 @@ export default async function handler(
return
}

if (lichessUsername !== undefined) {
if (!isNil(lichessUsername) && !isEmpty(lichessUsername)) {
await prisma.chessAccount.create({
data: {
provider: 'lichess',
username: lichessUsername,
userId: user.id
},
})
}
}

if (!isNil(chesscomUsername) && !isEmpty(chesscomUsername)) {
await prisma.chessAccount.create({
data: {
provider: 'chesscom',
username: chesscomUsername,
userId: user.id
},
})
}


res.status(200).json({ success: true })
} else {
res.status(400).json({ success: false })
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- DropIndex
DROP INDEX "ChessAccount_userId_key";
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- DropIndex
DROP INDEX "ChessAccount_provider_username_key";
4 changes: 1 addition & 3 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ model User {

model ChessAccount {
id String @id @default(cuid())
userId String @unique
userId String
provider String
username String
isFetching Boolean @default(false)
Expand All @@ -72,8 +72,6 @@ model ChessAccount {
gamesAsBlack Game[] @relation("BlackChessAccount")

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

@@unique([provider, username])
}

enum GameCategory {
Expand Down
Loading