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

Dev #2

Open
wants to merge 22 commits into
base: other
Choose a base branch
from
Open
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
Binary file added .DS_Store
Binary file not shown.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
frontend/leettrack/src/firebaseConfig.js
frontend/leettrack/src/supabaseClient.js
frontend/leettrack/.gitignore
backend/.env
frotnend/leetrack/.env
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{
}
143 changes: 142 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,142 @@
# leettrack
# AlgoTrackr

AlgoTrackr is a personal LeetCode performance tracker that allows users to track their coding session timing, accuracy, and self-assessment of particular topics. It is designed for local deployment, making it easy to clone and run without external dependencies.

## Features
- **Session Tracking**: Records session time, accuracy, and mood.
- **Statistics Dashboard**: View historical performance trends.
- **Local Deployment**: Fully self-contained with local Postgres database support.
- **Customizable**: Modify and extend for personal use.

---

## Prerequisites
1. [Go](https://golang.org/dl/) (minimum version 1.18)
2. [Node.js](https://nodejs.org/) (minimum version 16)
3. [Postgres](https://www.postgresql.org/download/) (minimum version 14)

---

## Installation and Setup

### Step 1: Clone the Repository
```bash
git clone https://github.com/your-username/algotrackr.git
cd algotrackr
```

### Step 2: Set Up the Backend
1. Navigate to the backend directory:
```bash
cd backend
```

2. Install dependencies:
```bash
go mod tidy
```

3. Configure the database connection in `main.go`:
```go
db, err = sql.Open("postgres", "user=your_user password=your_password dbname=algotrackr sslmode=disable")
```
Replace `your_user`, `your_password`, and `algotrackr` with your Postgres credentials and desired database name.

4. Run the backend:
```bash
go run main.go
```
The backend will run on `http://localhost:8080` by default.

---

### Step 3: Set Up the Frontend
1. Navigate to the frontend directory:
```bash
cd ../frontend/leettrack
```

2. Install dependencies:
```bash
npm install
```

3. Update the `.env` file:
```env
REACT_APP_API_URL=http://localhost:8080
```

4. Run the frontend:
```bash
npm start
```
The frontend will run on `http://localhost:3000` by default.

---

### Step 4: Set Up Postgres
1. Install Postgres:
- **Linux**: Use your package manager (e.g., `sudo apt install postgresql`)
- **macOS**: Use Homebrew (`brew install postgresql`)
- **Windows**: Download the installer from the [official website](https://www.postgresql.org/download/).

2. Start the Postgres service:
```bash
# For Linux/macOS
sudo service postgresql start

# For Windows, start from the Services app
```

3. Create a database:
```bash
psql -U postgres
CREATE DATABASE algotrackr;
CREATE USER your_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE algotrackr TO your_user;
\q
```

4. Initialize the database schema:
```bash
psql -U your_user -d algotrackr -f backend/schema.sql
```
Replace `your_user` with your Postgres username.

---

## Running the Application
1. Start the backend:
```bash
cd backend
go run main.go
```

2. Start the frontend:
```bash
cd frontend/leettrack
npm start
```

3. Open your browser and navigate to:
```
http://localhost:3000
```

---

## Customization
Feel free to modify the project to fit your needs:
- **Frontend**: Update React components in the `src` directory.
- **Backend**: Extend the API or change the logic in the `backend` folder.
- **Database**: Modify the schema to add new features.

---

## Contributing
Contributions are welcome! Please submit a pull request or open an issue if you encounter any bugs or have feature suggestions.

---

## License
This project is licensed under the MIT License. See the `LICENSE` file for details.
73 changes: 52 additions & 21 deletions backend/calculations/calculations.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
package calculations

import (
"log"

"github.com/lib/pq"
"gorm.io/gorm"
)

type TopicScore struct {
Topic string `json: topic`
AvgScore int `json:avgscore`
}

func FilterByTopic(db *gorm.DB, topic string) (float64, error) {
var averageScore float64
err := db.Raw(`
SELECT AVG(score)
FROM sessions
WHERE topics @>
jsonb_build_array(?)
`,
topic).Scan(&averageScore).Error
SELECT AVG(score)
FROM sessions
WHERE ? = ANY(topics) AND userid = ?
ORDER BY created_at DESC
`, topic).Scan(&averageScore).Error
return averageScore, err
}

Expand All @@ -29,13 +35,11 @@ func GetTopNTopicsByAverageScore(db *gorm.DB, n int, weakest bool) (pq.StringArr
}

query := `
SELECT topic, AVG(score) as
avg_score
SELECT topic, AVG(score) as avg_score
FROM (
SELECT
jsonb_array_elements_text(topics) AS
topic, score
SELECT unnest(topics) AS topic, score
FROM sessions
WHERE userid = ?
) AS subquery
GROUP BY topic
ORDER BY avg_score ` + order + `
Expand All @@ -55,14 +59,41 @@ topic, score
return topics, nil
}

func FilterByAverageTimeSpent(db *gorm.DB, topic string) (float64, error) {
var averageTimeSpent float64
err := db.Raw(`
SELECT AVG(timeSpent
FROM sessions
WHERE topics @>
jsonb_build_array(?))
`,
topic).Scan(&averageTimeSpent).Error
return averageTimeSpent, err
func GetStats(db *gorm.DB) ([]TopicScore, error) {
var scores []TopicScore

log.Println("Executing GetStats")

query := `
SELECT
topic AS "Topic",
ROUND(AVG(score))::INTEGER AS "AvgScore"
FROM
(
SELECT
UNNEST(topics) AS topic,
score
FROM
sessions
ORDER BY created_at DESC
) AS topic_scores
GROUP BY
topic
ORDER BY
topic ASC;

`

err := db.Raw(query).Scan(&scores).Error

if err != nil {
log.Println("Query Error:", err)
return nil, err
}

if len(scores) == 0 {
log.Println("No results found")
}

return scores, nil
}
4 changes: 2 additions & 2 deletions backend/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ require (
golang.org/x/arch v0.9.0 // indirect
golang.org/x/crypto v0.25.0 // indirect
golang.org/x/net v0.27.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.23.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/text v0.17.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/postgres v1.5.9 // indirect
Expand Down
4 changes: 4 additions & 0 deletions backend/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ golang.org/x/net v0.27.0 h1:5K3Njcw06/l2y9vpGCSdcxWOYHOUk3dVNGDXN+FvAys=
golang.org/x/net v0.27.0/go.mod h1:dDi0PyhWNoiUOrAS8uXv/vnScO4wnHQO4mj9fn/RytE=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
Expand All @@ -99,6 +101,8 @@ golang.org/x/sys v0.23.0 h1:YfKFowiIMvtgl1UERQoTPPToxltDeZfbj4H7dVUCwmM=
golang.org/x/sys v0.23.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg=
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
64 changes: 29 additions & 35 deletions backend/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"leettrack/calculations"
"leettrack/models"
"log"
Expand All @@ -15,48 +16,38 @@ import (

func main() {

dsn := "host=localhost user=postgres dbname=db password=password port=5432 sslmode=disable"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

db, err := gorm.Open(postgres.Open("host=localhost user=algouser password=password dbname=algotrackr port=5432 sslmode=disable"), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connecct to database:", err)
}

db.AutoMigrate((&models.Session{}))

r := gin.Default()

db.AutoMigrate(&models.Session{})

r.Use(cors.New(cors.Config{
AllowOrigins: []string{"http://localhost:3000"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
AllowCredentials: true,
}))

r.POST(
"/sessions",
func(c *gin.Context) {
var session models.Session
if err := c.ShouldBindJSON(&session); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error()})
return
}
r.POST("/sessions", func(c *gin.Context) {
var session models.Session
if err := c.ShouldBindJSON(&session); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error()})
return
}

if err := db.Create(&session).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, session)
},
)
log.Println(session)

r.DELETE("/clear-database", func(c *gin.Context) {
if err := db.Exec("DELETE FROM sessions").Error; err != nil {
if err := db.Create(&session).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Database cleared"})

c.JSON(http.StatusOK, session)
})
r.GET(
"/sessions",
Expand Down Expand Up @@ -105,25 +96,28 @@ func main() {
weakest := c.Query("weakest") == "true"

topics, err := calculations.GetTopNTopicsByAverageScore(db, n, weakest)

if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}

c.JSON(http.StatusOK, gin.H{"topics": []string(topics)})
c.JSON(http.StatusOK, gin.H{"topics": topics})
},
)

r.GET("/average-time-spent", func(c *gin.Context) {
topic := c.Query("topic")
avgTimeSpent, err := calculations.FilterByAverageTimeSpent(db, topic)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"average_time_spent": avgTimeSpent})
})
r.GET(
"/stats",
func(c *gin.Context) {
scores, err := calculations.GetStats(db)
fmt.Println(scores)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}

c.JSON(http.StatusOK, gin.H{"scores": scores})
},
)

r.Run()
}
Loading