Compare commits
17 Commits
ef86deb222
...
19/post-al
| Author | SHA1 | Date | |
|---|---|---|---|
| b2f532fa22 | |||
| b56738653d | |||
| 5d803bb01c | |||
| 2620d6ee47 | |||
| 74536bd49d | |||
| 9cb71d53cf | |||
| b5aae3be3d | |||
| 238aedb5c9 | |||
| d1774c1ce0 | |||
| 8fedac21bb | |||
|
|
361baac8f3 | ||
|
|
0007f10ae3 | ||
|
|
b48d082edd | ||
|
|
bfc1d135de | ||
|
|
0749d8ce7a | ||
| 1589bc9422 | |||
| 790ee3c622 |
@@ -1,2 +1,9 @@
|
||||
# Allowance Planner 2000
|
||||
An improved Allowance Planner app.
|
||||
An improved Allowance Planner app.
|
||||
|
||||
## Running backend
|
||||
In order to run the backend, go to the `backend directory and run:
|
||||
|
||||
```bash
|
||||
$ go run .
|
||||
```
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
TestGoalName = "Test Goal"
|
||||
TestAllowanceName = "Test History"
|
||||
)
|
||||
|
||||
func startServer(t *testing.T) *httpexpect.Expect {
|
||||
@@ -49,56 +49,58 @@ func TestGetUserBadId(t *testing.T) {
|
||||
e.GET("/user/bad-id").Expect().Status(400)
|
||||
}
|
||||
|
||||
func TestGetUserGoalsWhenNoGoalsPresent(t *testing.T) {
|
||||
func TestGetUserAllowanceWhenNoAllowancePresent(t *testing.T) {
|
||||
e := startServer(t)
|
||||
result := e.GET("/user/1/goals").Expect().Status(200).JSON().Array()
|
||||
result.Length().IsEqual(0)
|
||||
result := e.GET("/user/1/allowance").Expect().Status(200).JSON().Array()
|
||||
result.Length().IsEqual(1)
|
||||
item := result.Value(0).Object()
|
||||
item.Value("id").IsEqual(0)
|
||||
}
|
||||
|
||||
func TestGetUserGoals(t *testing.T) {
|
||||
func TestGetUserAllowance(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Create a new goal
|
||||
// Create a new allowance
|
||||
requestBody := map[string]interface{}{
|
||||
"name": TestGoalName,
|
||||
"name": TestAllowanceName,
|
||||
"target": 5000,
|
||||
"weight": 10,
|
||||
}
|
||||
e.POST("/user/1/goals").WithJSON(requestBody).Expect().Status(201)
|
||||
e.POST("/user/1/allowance").WithJSON(requestBody).Expect().Status(201)
|
||||
|
||||
// Validate goal
|
||||
result := e.GET("/user/1/goals").Expect().Status(200).JSON().Array()
|
||||
result.Length().IsEqual(1)
|
||||
item := result.Value(0).Object()
|
||||
// Validate allowance
|
||||
result := e.GET("/user/1/allowance").Expect().Status(200).JSON().Array()
|
||||
result.Length().IsEqual(2)
|
||||
item := result.Value(1).Object()
|
||||
item.Value("id").IsEqual(1)
|
||||
item.Value("name").IsEqual(TestGoalName)
|
||||
item.Value("name").IsEqual(TestAllowanceName)
|
||||
item.Value("target").IsEqual(5000)
|
||||
item.Value("weight").IsEqual(10)
|
||||
item.Value("progress").IsEqual(0)
|
||||
item.NotContainsKey("user_id")
|
||||
}
|
||||
|
||||
func TestGetUserGoalsNoUser(t *testing.T) {
|
||||
func TestGetUserAllowanceNoUser(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.GET("/user/999/goals").Expect().Status(404)
|
||||
e.GET("/user/999/allowance").Expect().Status(404)
|
||||
}
|
||||
|
||||
func TestGetUserGoalsBadId(t *testing.T) {
|
||||
func TestGetUserAllowanceBadId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.GET("/user/bad-id/goals").Expect().Status(400)
|
||||
e.GET("/user/bad-id/allowance").Expect().Status(400)
|
||||
}
|
||||
|
||||
func TestCreateUserGoal(t *testing.T) {
|
||||
func TestCreateUserAllowance(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Create a new goal
|
||||
// Create a new allowance
|
||||
requestBody := map[string]interface{}{
|
||||
"name": TestGoalName,
|
||||
"name": TestAllowanceName,
|
||||
"target": 5000,
|
||||
"weight": 10,
|
||||
}
|
||||
|
||||
response := e.POST("/user/1/goals").
|
||||
response := e.POST("/user/1/allowance").
|
||||
WithJSON(requestBody).
|
||||
Expect().
|
||||
Status(201).
|
||||
@@ -106,40 +108,40 @@ func TestCreateUserGoal(t *testing.T) {
|
||||
|
||||
// Verify the response has an ID
|
||||
response.ContainsKey("id")
|
||||
goalId := response.Value("id").Number().Raw()
|
||||
allowanceId := response.Value("id").Number().Raw()
|
||||
|
||||
// Verify the goal exists in the list of goals
|
||||
goals := e.GET("/user/1/goals").
|
||||
// Verify the allowance exists in the list of allowances
|
||||
allowances := e.GET("/user/1/allowance").
|
||||
Expect().
|
||||
Status(200).
|
||||
JSON().Array()
|
||||
|
||||
goals.Length().IsEqual(1)
|
||||
allowances.Length().IsEqual(2)
|
||||
|
||||
goal := goals.Value(0).Object()
|
||||
goal.Value("id").IsEqual(goalId)
|
||||
goal.Value("name").IsEqual(TestGoalName)
|
||||
goal.Value("target").IsEqual(5000)
|
||||
goal.Value("weight").IsEqual(10)
|
||||
goal.Value("progress").IsEqual(0)
|
||||
allowance := allowances.Value(1).Object()
|
||||
allowance.Value("id").IsEqual(allowanceId)
|
||||
allowance.Value("name").IsEqual(TestAllowanceName)
|
||||
allowance.Value("target").IsEqual(5000)
|
||||
allowance.Value("weight").IsEqual(10)
|
||||
allowance.Value("progress").IsEqual(0)
|
||||
}
|
||||
|
||||
func TestCreateUserGoalNoUser(t *testing.T) {
|
||||
func TestCreateUserAllowanceNoUser(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
requestBody := map[string]interface{}{
|
||||
"name": TestGoalName,
|
||||
"name": TestAllowanceName,
|
||||
"target": 5000,
|
||||
"weight": 10,
|
||||
}
|
||||
|
||||
e.POST("/user/999/goals").
|
||||
e.POST("/user/999/allowance").
|
||||
WithJSON(requestBody).
|
||||
Expect().
|
||||
Status(404)
|
||||
}
|
||||
|
||||
func TestCreateUserGoalInvalidInput(t *testing.T) {
|
||||
func TestCreateUserAllowanceInvalidInput(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Test with empty name
|
||||
@@ -149,7 +151,7 @@ func TestCreateUserGoalInvalidInput(t *testing.T) {
|
||||
"weight": 10,
|
||||
}
|
||||
|
||||
e.POST("/user/1/goals").
|
||||
e.POST("/user/1/allowance").
|
||||
WithJSON(requestBody).
|
||||
Expect().
|
||||
Status(400)
|
||||
@@ -159,76 +161,81 @@ func TestCreateUserGoalInvalidInput(t *testing.T) {
|
||||
"target": 5000,
|
||||
}
|
||||
|
||||
e.POST("/user/1/goals").
|
||||
e.POST("/user/1/allowance").
|
||||
WithJSON(invalidRequest).
|
||||
Expect().
|
||||
Status(400)
|
||||
}
|
||||
|
||||
func TestCreateUserGoalBadId(t *testing.T) {
|
||||
func TestCreateUserAllowanceBadId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
requestBody := map[string]interface{}{
|
||||
"name": TestGoalName,
|
||||
"name": TestAllowanceName,
|
||||
"target": 5000,
|
||||
"weight": 10,
|
||||
}
|
||||
|
||||
e.POST("/user/bad-id/goals").
|
||||
e.POST("/user/bad-id/allowance").
|
||||
WithJSON(requestBody).
|
||||
Expect().
|
||||
Status(400)
|
||||
}
|
||||
|
||||
func TestDeleteUserGoal(t *testing.T) {
|
||||
func TestDeleteUserAllowance(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Create a new goal to delete
|
||||
// Create a new allowance to delete
|
||||
createRequest := map[string]interface{}{
|
||||
"name": TestGoalName,
|
||||
"name": TestAllowanceName,
|
||||
"target": 1000,
|
||||
"weight": 5,
|
||||
}
|
||||
response := e.POST("/user/1/goals").
|
||||
response := e.POST("/user/1/allowance").
|
||||
WithJSON(createRequest).
|
||||
Expect().
|
||||
Status(201).
|
||||
JSON().Object()
|
||||
|
||||
goalId := response.Value("id").Number().Raw()
|
||||
allowanceId := response.Value("id").Number().Raw()
|
||||
|
||||
// Delete the goal
|
||||
e.DELETE("/user/1/goal/" + strconv.Itoa(int(goalId))).
|
||||
// Delete the allowance
|
||||
e.DELETE("/user/1/allowance/" + strconv.Itoa(int(allowanceId))).
|
||||
Expect().
|
||||
Status(200).
|
||||
JSON().Object().Value("message").IsEqual("Goal deleted successfully")
|
||||
JSON().Object().Value("message").IsEqual("History deleted successfully")
|
||||
|
||||
// Verify the goal no longer exists
|
||||
goals := e.GET("/user/1/goals").
|
||||
// Verify the allowance no longer exists
|
||||
allowances := e.GET("/user/1/allowance").
|
||||
Expect().
|
||||
Status(200).
|
||||
JSON().Array()
|
||||
goals.Length().IsEqual(0)
|
||||
allowances.Length().IsEqual(1)
|
||||
}
|
||||
|
||||
func TestDeleteUserGoalNotFound(t *testing.T) {
|
||||
func TestDeleteUserRestAllowance(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.DELETE("/user/1/allowance/0").Expect().Status(400)
|
||||
}
|
||||
|
||||
func TestDeleteUserAllowanceNotFound(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Attempt to delete a non-existent goal
|
||||
e.DELETE("/user/1/goal/999").
|
||||
// Attempt to delete a non-existent allowance
|
||||
e.DELETE("/user/1/allowance/999").
|
||||
Expect().
|
||||
Status(404).
|
||||
JSON().Object().Value("error").IsEqual("Goal not found")
|
||||
JSON().Object().Value("error").IsEqual("History not found")
|
||||
}
|
||||
|
||||
func TestDeleteUserGoalInvalidId(t *testing.T) {
|
||||
func TestDeleteUserAllowanceInvalidId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Attempt to delete a goal with an invalid ID
|
||||
e.DELETE("/user/1/goal/invalid-id").
|
||||
// Attempt to delete an allowance with an invalid ID
|
||||
e.DELETE("/user/1/allowance/invalid-id").
|
||||
Expect().
|
||||
Status(400).
|
||||
JSON().Object().Value("error").IsEqual("Invalid goal ID")
|
||||
JSON().Object().Value("error").IsEqual("Invalid allowance ID")
|
||||
}
|
||||
|
||||
func TestCreateTask(t *testing.T) {
|
||||
@@ -248,7 +255,16 @@ func TestCreateTask(t *testing.T) {
|
||||
|
||||
// Verify the response has an ID
|
||||
response.ContainsKey("id")
|
||||
taskId := response.Value("id").Number().Raw()
|
||||
response.Value("id").Number().IsEqual(1)
|
||||
|
||||
e.GET("/tasks").Expect().Status(200).JSON().Array().Length().IsEqual(1)
|
||||
|
||||
// Get task
|
||||
result := e.GET("/task/1").Expect().Status(200).JSON().Object()
|
||||
result.Value("id").IsEqual(1)
|
||||
result.Value("name").IsEqual("Test Task")
|
||||
result.Value("reward").IsEqual(100)
|
||||
result.Value("assigned").IsNull()
|
||||
|
||||
// Create a new task with assigned user
|
||||
assignedUserId := 1
|
||||
@@ -265,7 +281,37 @@ func TestCreateTask(t *testing.T) {
|
||||
JSON().Object()
|
||||
|
||||
responseWithUser.ContainsKey("id")
|
||||
responseWithUser.Value("id").Number().NotEqual(taskId) // Ensure different ID
|
||||
responseWithUser.Value("id").Number().IsEqual(2)
|
||||
}
|
||||
|
||||
func TestDeleteTask(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Create a new task without assigned user
|
||||
requestBody := map[string]interface{}{
|
||||
"name": "Test Task",
|
||||
"reward": 100,
|
||||
}
|
||||
|
||||
response := e.POST("/tasks").
|
||||
WithJSON(requestBody).
|
||||
Expect().
|
||||
Status(201). // Expect Created status
|
||||
JSON().Object()
|
||||
|
||||
// Verify the response has an ID
|
||||
response.ContainsKey("id")
|
||||
taskId := response.Value("id").Number().Raw()
|
||||
|
||||
// Delete the task
|
||||
e.DELETE("/task/" + strconv.Itoa(int(taskId))).Expect().Status(200)
|
||||
// Verify the task no longer exists
|
||||
e.GET("/task/" + strconv.Itoa(int(taskId))).Expect().Status(404)
|
||||
}
|
||||
|
||||
func TestDeleteTaskNotFound(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.DELETE("/task/1").Expect().Status(404)
|
||||
}
|
||||
|
||||
func TestCreateTaskNoName(t *testing.T) {
|
||||
@@ -315,15 +361,15 @@ func TestGetTaskWhenNoTasks(t *testing.T) {
|
||||
result.Length().IsEqual(0)
|
||||
}
|
||||
|
||||
func createTestTask(e *httpexpect.Expect) {
|
||||
func createTestTaskWithAmount(e *httpexpect.Expect, amount int) int {
|
||||
requestBody := map[string]interface{}{
|
||||
"name": "Test Task",
|
||||
"reward": 100,
|
||||
"reward": amount,
|
||||
}
|
||||
e.POST("/tasks").WithJSON(requestBody).Expect().Status(201)
|
||||
return int(e.POST("/tasks").WithJSON(requestBody).Expect().Status(201).JSON().Object().Value("id").Number().Raw())
|
||||
}
|
||||
|
||||
func TestGetTaskSWhenTasks(t *testing.T) {
|
||||
func TestGetTasksWhenTasks(t *testing.T) {
|
||||
e := startServer(t)
|
||||
createTestTask(e)
|
||||
|
||||
@@ -391,9 +437,9 @@ func TestPutTaskInvalidTaskId(t *testing.T) {
|
||||
func TestPostAllowance(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
e.POST("/user/1/allowance").WithJSON(PostAllowance{Allowance: 100}).Expect().Status(200)
|
||||
e.POST("/user/1/allowance").WithJSON(PostAllowance{Allowance: 20}).Expect().Status(200)
|
||||
e.POST("/user/1/allowance").WithJSON(PostAllowance{Allowance: -10}).Expect().Status(200)
|
||||
e.POST("/user/1/history").WithJSON(PostHistory{Allowance: 100}).Expect().Status(200)
|
||||
e.POST("/user/1/history").WithJSON(PostHistory{Allowance: 20}).Expect().Status(200)
|
||||
e.POST("/user/1/history").WithJSON(PostHistory{Allowance: -10}).Expect().Status(200)
|
||||
|
||||
response := e.GET("/user/1").Expect().Status(200).JSON().Object()
|
||||
response.Value("allowance").Number().IsEqual(100 + 20 - 10)
|
||||
@@ -402,16 +448,16 @@ func TestPostAllowance(t *testing.T) {
|
||||
func TestPostAllowanceInvalidUserId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
e.POST("/user/999/allowance").WithJSON(PostAllowance{Allowance: 100}).Expect().
|
||||
e.POST("/user/999/history").WithJSON(PostHistory{Allowance: 100}).Expect().
|
||||
Status(404)
|
||||
}
|
||||
|
||||
func TestGetHistory(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
e.POST("/user/1/allowance").WithJSON(PostAllowance{Allowance: 100}).Expect().Status(200)
|
||||
e.POST("/user/1/allowance").WithJSON(PostAllowance{Allowance: 20}).Expect().Status(200)
|
||||
e.POST("/user/1/allowance").WithJSON(PostAllowance{Allowance: -10}).Expect().Status(200)
|
||||
e.POST("/user/1/history").WithJSON(PostHistory{Allowance: 100}).Expect().Status(200)
|
||||
e.POST("/user/1/history").WithJSON(PostHistory{Allowance: 20}).Expect().Status(200)
|
||||
e.POST("/user/1/history").WithJSON(PostHistory{Allowance: -10}).Expect().Status(200)
|
||||
|
||||
response := e.GET("/user/1/history").Expect().Status(200).JSON().Array()
|
||||
response.Length().IsEqual(3)
|
||||
@@ -421,8 +467,243 @@ func TestGetHistory(t *testing.T) {
|
||||
response.Value(2).Object().Value("allowance").Number().IsEqual(-10)
|
||||
}
|
||||
|
||||
func TestGetUserAllowanceById(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Create a new allowance
|
||||
requestBody := map[string]interface{}{
|
||||
"name": TestAllowanceName,
|
||||
"target": 5000,
|
||||
"weight": 10,
|
||||
}
|
||||
resp := e.POST("/user/1/allowance").WithJSON(requestBody).Expect().Status(201).JSON().Object()
|
||||
allowanceId := int(resp.Value("id").Number().Raw())
|
||||
|
||||
// Retrieve the created allowance by ID
|
||||
result := e.GET("/user/1/allowance/" + strconv.Itoa(allowanceId)).Expect().Status(200).JSON().Object()
|
||||
result.Value("id").IsEqual(allowanceId)
|
||||
result.Value("name").IsEqual(TestAllowanceName)
|
||||
result.Value("target").IsEqual(5000)
|
||||
result.Value("weight").IsEqual(10)
|
||||
result.Value("progress").IsEqual(0)
|
||||
}
|
||||
|
||||
func TestGetUserByAllowanceIdInvalidAllowance(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.GET("/user/1/allowance/9999").Expect().Status(404)
|
||||
}
|
||||
|
||||
func TestGetUserByAllowanceByIdInvalidUserId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.GET("/user/999/allowance/1").Expect().Status(404)
|
||||
}
|
||||
|
||||
func TestGetUserByAllowanceByIdBadUserId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.GET("/user/bad/allowance/1").Expect().Status(400)
|
||||
}
|
||||
|
||||
func TestGetUserByAllowanceByIdBadAllowanceId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.GET("/user/1/allowance/bad").Expect().Status(400)
|
||||
}
|
||||
|
||||
func TestPutAllowanceById(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
// Create a new allowance
|
||||
requestBody := map[string]interface{}{
|
||||
"name": TestAllowanceName,
|
||||
"target": 5000,
|
||||
"weight": 10,
|
||||
}
|
||||
resp := e.POST("/user/1/allowance").WithJSON(requestBody).Expect().Status(201).JSON().Object()
|
||||
allowanceId := int(resp.Value("id").Number().Raw())
|
||||
|
||||
// Update the allowance
|
||||
updateRequest := map[string]interface{}{
|
||||
"name": "Updated Allowance",
|
||||
"target": 6000,
|
||||
"weight": 15,
|
||||
}
|
||||
e.PUT("/user/1/allowance/" + strconv.Itoa(allowanceId)).WithJSON(updateRequest).Expect().Status(200)
|
||||
|
||||
// Verify the allowance is updated
|
||||
result := e.GET("/user/1/allowance/" + strconv.Itoa(allowanceId)).Expect().Status(200).JSON().Object()
|
||||
result.Value("id").IsEqual(allowanceId)
|
||||
result.Value("name").IsEqual("Updated Allowance")
|
||||
result.Value("target").IsEqual(6000)
|
||||
result.Value("weight").IsEqual(15)
|
||||
}
|
||||
|
||||
func TestCompleteTask(t *testing.T) {
|
||||
e := startServer(t)
|
||||
taskId := createTestTaskWithAmount(e, 101)
|
||||
|
||||
e.GET("/tasks").Expect().Status(200).JSON().Array().Length().IsEqual(1)
|
||||
|
||||
// Update rest allowance
|
||||
e.PUT("/user/1/allowance/0").WithJSON(UpdateAllowanceRequest{
|
||||
Weight: 25,
|
||||
}).Expect().Status(200)
|
||||
// Create two allowance goals
|
||||
e.POST("/user/1/allowance").WithJSON(CreateAllowanceRequest{
|
||||
Name: "Test Allowance 1",
|
||||
Target: 1000,
|
||||
Weight: 50,
|
||||
}).Expect().Status(201)
|
||||
e.POST("/user/1/allowance").WithJSON(CreateAllowanceRequest{
|
||||
Name: "Test Allowance 1",
|
||||
Target: 1000,
|
||||
Weight: 25,
|
||||
}).Expect().Status(201)
|
||||
|
||||
// Complete the task
|
||||
e.POST("/task/" + strconv.Itoa(taskId) + "/complete").Expect().Status(200)
|
||||
|
||||
// Verify the task is marked as completed
|
||||
e.GET("/task/" + strconv.Itoa(taskId)).Expect().Status(404)
|
||||
|
||||
// Verify the allowances are updated for user 1
|
||||
allowances := e.GET("/user/1/allowance").Expect().Status(200).JSON().Array()
|
||||
allowances.Length().IsEqual(3)
|
||||
allowances.Value(0).Object().Value("id").Number().IsEqual(0)
|
||||
allowances.Value(0).Object().Value("progress").Number().IsEqual(26)
|
||||
allowances.Value(1).Object().Value("id").Number().IsEqual(1)
|
||||
allowances.Value(1).Object().Value("progress").Number().IsEqual(50)
|
||||
allowances.Value(2).Object().Value("id").Number().IsEqual(2)
|
||||
allowances.Value(2).Object().Value("progress").Number().IsEqual(25)
|
||||
|
||||
// And also for user 2
|
||||
allowances = e.GET("/user/2/allowance").Expect().Status(200).JSON().Array()
|
||||
allowances.Length().IsEqual(1)
|
||||
allowances.Value(0).Object().Value("id").Number().IsEqual(0)
|
||||
allowances.Value(0).Object().Value("progress").Number().IsEqual(101)
|
||||
|
||||
for userId := 1; userId <= 2; userId++ {
|
||||
userIdStr := strconv.Itoa(userId)
|
||||
// Ensure the history got updated
|
||||
history := e.GET("/user/" + userIdStr + "/history").Expect().Status(200).JSON().Array()
|
||||
history.Length().IsEqual(1)
|
||||
history.Value(0).Object().Value("allowance").Number().IsEqual(101)
|
||||
history.Value(0).Object().Value("timestamp").String().AsDateTime().InRange(getDelta(time.Now(), 2.0))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteTaskAllowanceWeightsSumTo0(t *testing.T) {
|
||||
e := startServer(t)
|
||||
taskId := createTestTaskWithAmount(e, 101)
|
||||
|
||||
e.GET("/tasks").Expect().Status(200).JSON().Array().Length().IsEqual(1)
|
||||
|
||||
// Update rest allowance
|
||||
e.PUT("/user/1/allowance/0").WithJSON(UpdateAllowanceRequest{
|
||||
Weight: 0,
|
||||
}).Expect().Status(200)
|
||||
// Create an allowance goal
|
||||
createTestAllowance(e, "Test Allowance 1", 1000, 0)
|
||||
|
||||
// Complete the task
|
||||
e.POST("/task/" + strconv.Itoa(taskId) + "/complete").Expect().Status(200)
|
||||
|
||||
// Verify the task is marked as completed
|
||||
e.GET("/task/" + strconv.Itoa(taskId)).Expect().Status(404)
|
||||
|
||||
// Verify the allowances are updated for user 1
|
||||
allowances := e.GET("/user/1/allowance").Expect().Status(200).JSON().Array()
|
||||
allowances.Length().IsEqual(2)
|
||||
allowances.Value(0).Object().Value("id").Number().IsEqual(0)
|
||||
allowances.Value(0).Object().Value("progress").Number().IsEqual(101)
|
||||
allowances.Value(1).Object().Value("id").Number().IsEqual(1)
|
||||
allowances.Value(1).Object().Value("progress").Number().IsEqual(0)
|
||||
}
|
||||
|
||||
func TestCompleteTaskInvalidId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.POST("/task/999/complete").Expect().Status(404)
|
||||
}
|
||||
|
||||
func TestCompleteAllowance(t *testing.T) {
|
||||
e := startServer(t)
|
||||
createTestTaskWithAmount(e, 100)
|
||||
createTestAllowance(e, "Test Allowance 1", 100, 50)
|
||||
|
||||
// Complete the task
|
||||
e.POST("/task/1/complete").Expect().Status(200)
|
||||
|
||||
// Complete allowance goal
|
||||
e.POST("/user/1/allowance/1/complete").Expect().Status(200)
|
||||
|
||||
// Verify the allowance no longer exists
|
||||
e.GET("/user/1/allowance/1").Expect().Status(404)
|
||||
|
||||
// Verify history is updated
|
||||
history := e.GET("/user/1/history").Expect().Status(200).JSON().Array()
|
||||
history.Length().IsEqual(2)
|
||||
history.Value(0).Object().Value("allowance").Number().IsEqual(100)
|
||||
history.Value(0).Object().Value("timestamp").String().AsDateTime().InRange(getDelta(time.Now(), 2.0))
|
||||
history.Value(1).Object().Value("allowance").Number().IsEqual(-100)
|
||||
history.Value(1).Object().Value("timestamp").String().AsDateTime().InRange(getDelta(time.Now(), 2.0))
|
||||
}
|
||||
|
||||
func TestCompleteAllowanceInvalidUserId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.POST("/user/999/allowance/1/complete").Expect().Status(404)
|
||||
}
|
||||
|
||||
func TestCompleteAllowanceInvalidAllowanceId(t *testing.T) {
|
||||
e := startServer(t)
|
||||
e.POST("/user/1/allowance/999/complete").Expect().Status(404)
|
||||
}
|
||||
|
||||
func TestPutBulkAllowance(t *testing.T) {
|
||||
e := startServer(t)
|
||||
|
||||
createTestAllowance(e, "Test Allowance 1", 1000, 1)
|
||||
createTestAllowance(e, "Test Allowance 2", 1000, 2)
|
||||
|
||||
// Bulk edit
|
||||
request := []map[string]interface{}{
|
||||
{
|
||||
"id": 1,
|
||||
"weight": 5,
|
||||
},
|
||||
{
|
||||
"id": 0,
|
||||
"weight": 99,
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"weight": 10,
|
||||
},
|
||||
}
|
||||
e.PUT("/user/1/allowance").WithJSON(request).Expect().Status(200)
|
||||
|
||||
// Verify the allowances are updated
|
||||
allowances := e.GET("/user/1/allowance").Expect().Status(200).JSON().Array()
|
||||
allowances.Length().IsEqual(3)
|
||||
allowances.Value(0).Object().Value("id").Number().IsEqual(0)
|
||||
allowances.Value(0).Object().Value("weight").Number().IsEqual(99)
|
||||
allowances.Value(1).Object().Value("id").Number().IsEqual(1)
|
||||
allowances.Value(1).Object().Value("weight").Number().IsEqual(5)
|
||||
allowances.Value(2).Object().Value("id").Number().IsEqual(2)
|
||||
allowances.Value(2).Object().Value("weight").Number().IsEqual(10)
|
||||
}
|
||||
|
||||
func getDelta(base time.Time, delta float64) (time.Time, time.Time) {
|
||||
start := base.Add(-time.Duration(delta) * time.Second)
|
||||
end := base.Add(time.Duration(delta) * time.Second)
|
||||
return start, end
|
||||
}
|
||||
|
||||
func createTestAllowance(e *httpexpect.Expect, name string, target int, weight float64) {
|
||||
e.POST("/user/1/allowance").WithJSON(CreateAllowanceRequest{
|
||||
Name: name,
|
||||
Target: target,
|
||||
Weight: weight,
|
||||
}).Expect().Status(201)
|
||||
}
|
||||
|
||||
func createTestTask(e *httpexpect.Expect) int {
|
||||
return createTestTaskWithAmount(e, 100)
|
||||
}
|
||||
|
||||
265
backend/db.go
265
backend/db.go
@@ -67,27 +67,53 @@ func (db *Db) UserExists(userId int) (bool, error) {
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (db *Db) GetUserGoals(userId int) ([]Goal, error) {
|
||||
goals := make([]Goal, 0)
|
||||
func (db *Db) GetUserAllowances(userId int) ([]Allowance, error) {
|
||||
allowances := make([]Allowance, 0)
|
||||
var err error
|
||||
|
||||
for row := range db.db.Query("select id, name, target, progress, weight from goals where user_id = ?").
|
||||
totalAllowance := Allowance{}
|
||||
err = db.db.Query("select balance, weight from users where id = ?").Bind(userId).ScanSingle(&totalAllowance.Progress, &totalAllowance.Weight)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
allowances = append(allowances, totalAllowance)
|
||||
|
||||
for row := range db.db.Query("select id, name, target, balance, weight from allowances where user_id = ?").
|
||||
Bind(userId).Range(&err) {
|
||||
goal := Goal{}
|
||||
err = row.Scan(&goal.ID, &goal.Name, &goal.Target, &goal.Progress, &goal.Weight)
|
||||
allowance := Allowance{}
|
||||
err = row.Scan(&allowance.ID, &allowance.Name, &allowance.Target, &allowance.Progress, &allowance.Weight)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
goals = append(goals, goal)
|
||||
allowances = append(allowances, allowance)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return goals, nil
|
||||
return allowances, nil
|
||||
}
|
||||
|
||||
func (db *Db) CreateGoal(userId int, goal *CreateGoalRequest) (int, error) {
|
||||
// Check if user exists before attempting to create a goal
|
||||
func (db *Db) GetUserAllowanceById(userId int, allowanceId int) (*Allowance, error) {
|
||||
allowance := &Allowance{}
|
||||
if allowanceId == 0 {
|
||||
err := db.db.Query("select balance, weight from users where id = ?").
|
||||
Bind(userId).ScanSingle(&allowance.Progress, &allowance.Weight)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
err := db.db.Query("select id, name, target, balance, weight from allowances where user_id = ? and id = ?").
|
||||
Bind(userId, allowanceId).
|
||||
ScanSingle(&allowance.ID, &allowance.Name, &allowance.Target, &allowance.Progress, &allowance.Weight)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return allowance, nil
|
||||
}
|
||||
|
||||
func (db *Db) CreateAllowance(userId int, allowance *CreateAllowanceRequest) (int, error) {
|
||||
// Check if user exists before attempting to create an allowance
|
||||
exists, err := db.UserExists(userId)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
@@ -102,9 +128,9 @@ func (db *Db) CreateGoal(userId int, goal *CreateGoalRequest) (int, error) {
|
||||
}
|
||||
defer tx.MustRollback()
|
||||
|
||||
// Insert the new goal
|
||||
err = tx.Query("insert into goals (user_id, name, target, progress, weight) values (?, ?, ?, 0, ?)").
|
||||
Bind(userId, goal.Name, goal.Target, goal.Weight).
|
||||
// Insert the new allowance
|
||||
err = tx.Query("insert into allowances (user_id, name, target, weight) values (?, ?, ?, ?)").
|
||||
Bind(userId, allowance.Name, allowance.Target, allowance.Weight).
|
||||
Exec()
|
||||
|
||||
if err != nil {
|
||||
@@ -127,21 +153,21 @@ func (db *Db) CreateGoal(userId int, goal *CreateGoalRequest) (int, error) {
|
||||
return lastId, nil
|
||||
}
|
||||
|
||||
func (db *Db) DeleteGoal(userId int, goalId int) error {
|
||||
// Check if the goal exists for the user
|
||||
func (db *Db) DeleteAllowance(userId int, allowanceId int) error {
|
||||
// Check if the allowance exists for the user
|
||||
count := 0
|
||||
err := db.db.Query("select count(*) from goals where id = ? and user_id = ?").
|
||||
Bind(goalId, userId).ScanSingle(&count)
|
||||
err := db.db.Query("select count(*) from allowances where id = ? and user_id = ?").
|
||||
Bind(allowanceId, userId).ScanSingle(&count)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return errors.New("goal not found")
|
||||
return errors.New("allowance not found")
|
||||
}
|
||||
|
||||
// Delete the goal
|
||||
err = db.db.Query("delete from goals where id = ? and user_id = ?").
|
||||
Bind(goalId, userId).Exec()
|
||||
// Delete the allowance
|
||||
err = db.db.Query("delete from allowances where id = ? and user_id = ?").
|
||||
Bind(allowanceId, userId).Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -149,6 +175,107 @@ func (db *Db) DeleteGoal(userId int, goalId int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (db *Db) CompleteAllowance(userId int, allowanceId int) error {
|
||||
tx, err := db.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.MustRollback()
|
||||
|
||||
// Get the cost of the allowance
|
||||
var cost int
|
||||
err = tx.Query("select balance from allowances where id = ? and user_id = ?").
|
||||
Bind(allowanceId, userId).ScanSingle(&cost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete the allowance
|
||||
err = tx.Query("delete from allowances where id = ? and user_id = ?").
|
||||
Bind(allowanceId, userId).Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add a history entry
|
||||
err = tx.Query("insert into history (user_id, timestamp, amount) values (?, ?, ?)").
|
||||
Bind(userId, time.Now().Unix(), -cost).
|
||||
Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (db *Db) UpdateUserAllowance(userId int, allowance *UpdateAllowanceRequest) error {
|
||||
tx, err := db.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.MustRollback()
|
||||
|
||||
err = tx.Query("update users set weight=? where id = ?").
|
||||
Bind(allowance.Weight, userId).
|
||||
Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (db *Db) UpdateAllowance(userId int, allowanceId int, allowance *UpdateAllowanceRequest) error {
|
||||
// Check if the allowance exists for the user
|
||||
count := 0
|
||||
err := db.db.Query("select count(*) from allowances where id = ? and user_id = ?").
|
||||
Bind(allowanceId, userId).ScanSingle(&count)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return errors.New("allowance not found")
|
||||
}
|
||||
|
||||
tx, err := db.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.MustRollback()
|
||||
|
||||
err = tx.Query("update allowances set name=?, target=?, weight=? where id = ? and user_id = ?").
|
||||
Bind(allowance.Name, allowance.Target, allowance.Weight, allowanceId, userId).
|
||||
Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (db *Db) BulkUpdateAllowance(userId int, allowances []BulkUpdateAllowanceRequest) error {
|
||||
tx, err := db.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.MustRollback()
|
||||
|
||||
for _, allowance := range allowances {
|
||||
if allowance.ID == 0 {
|
||||
err = tx.Query("update users set weight=? where id = ?").
|
||||
Bind(allowance.Weight, userId).
|
||||
Exec()
|
||||
} else {
|
||||
err = tx.Query("update allowances set weight=? where id = ? and user_id = ?").
|
||||
Bind(allowance.Weight, allowance.ID, userId).
|
||||
Exec()
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (db *Db) CreateTask(task *CreateTaskRequest) (int, error) {
|
||||
tx, err := db.db.Begin()
|
||||
if err != nil {
|
||||
@@ -210,6 +337,21 @@ func (db *Db) GetTask(id int) (Task, error) {
|
||||
return task, nil
|
||||
}
|
||||
|
||||
func (db *Db) DeleteTask(id int) error {
|
||||
tx, err := db.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.MustRollback()
|
||||
|
||||
err = tx.Query("delete from tasks where id = ?").Bind(id).Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (db *Db) HasTask(id int) (bool, error) {
|
||||
count := 0
|
||||
err := db.db.Query("select count(*) from tasks where id = ?").
|
||||
@@ -236,7 +378,82 @@ func (db *Db) UpdateTask(id int, task *CreateTaskRequest) error {
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (db *Db) AddAllowance(userId int, allowance *PostAllowance) error {
|
||||
func (db *Db) CompleteTask(taskId int) error {
|
||||
tx, err := db.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.MustRollback()
|
||||
|
||||
var reward int
|
||||
err = tx.Query("select reward from tasks where id = ?").Bind(taskId).ScanSingle(&reward)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for userRow := range tx.Query("select id, weight from users").Range(&err) {
|
||||
var userId int
|
||||
var userWeight float64
|
||||
err = userRow.Scan(&userId, &userWeight)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Add the history entry
|
||||
err = tx.Query("insert into history (user_id, timestamp, amount) values (?, ?, ?)").
|
||||
Bind(userId, time.Now().Unix(), reward).
|
||||
Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Calculate the sums of all weights
|
||||
var sumOfWeights float64
|
||||
err = tx.Query("select sum(weight) from allowances where user_id = ? and weight > 0").Bind(userId).ScanSingle(&sumOfWeights)
|
||||
sumOfWeights += userWeight
|
||||
|
||||
remainingReward := reward
|
||||
|
||||
if sumOfWeights > 0 {
|
||||
// Distribute the reward to the allowances
|
||||
for allowanceRow := range tx.Query("select id, weight from allowances where user_id = ? and weight > 0").Bind(userId).Range(&err) {
|
||||
var allowanceId int
|
||||
var allowanceWeight float64
|
||||
err = allowanceRow.Scan(&allowanceId, &allowanceWeight)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Calculate the amount to add to the allowance
|
||||
amount := int((allowanceWeight / sumOfWeights) * float64(remainingReward))
|
||||
sumOfWeights -= allowanceWeight
|
||||
err = tx.Query("update allowances set balance = balance + ? where id = ? and user_id = ?").
|
||||
Bind(amount, allowanceId, userId).Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
remainingReward -= amount
|
||||
}
|
||||
}
|
||||
|
||||
// Add the remaining reward to the user
|
||||
err = tx.Query("update users set balance = balance + ? where id = ?").
|
||||
Bind(remainingReward, userId).Exec()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove the task
|
||||
err = tx.Query("delete from tasks where id = ?").Bind(taskId).Exec()
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (db *Db) AddHistory(userId int, allowance *PostHistory) error {
|
||||
tx, err := db.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -252,13 +469,13 @@ func (db *Db) AddAllowance(userId int, allowance *PostAllowance) error {
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func (db *Db) GetHistory(userId int) ([]Allowance, error) {
|
||||
history := make([]Allowance, 0)
|
||||
func (db *Db) GetHistory(userId int) ([]History, error) {
|
||||
history := make([]History, 0)
|
||||
var err error
|
||||
|
||||
for row := range db.db.Query("select amount, `timestamp` from history where user_id = ? order by `timestamp` desc").
|
||||
Bind(userId).Range(&err) {
|
||||
allowance := Allowance{}
|
||||
allowance := History{}
|
||||
var timestamp int64
|
||||
err = row.Scan(&allowance.Allowance, ×tamp)
|
||||
if err != nil {
|
||||
|
||||
@@ -13,12 +13,12 @@ type UserWithAllowance struct {
|
||||
Allowance int `json:"allowance"`
|
||||
}
|
||||
|
||||
type Allowance struct {
|
||||
type History struct {
|
||||
Allowance int `json:"allowance"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
}
|
||||
|
||||
type PostAllowance struct {
|
||||
type PostHistory struct {
|
||||
Allowance int `json:"allowance"`
|
||||
}
|
||||
|
||||
@@ -30,18 +30,29 @@ type Task struct {
|
||||
Assigned *int `json:"assigned"` // Pointer to allow null
|
||||
}
|
||||
|
||||
type Goal struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Target int `json:"target"`
|
||||
Progress int `json:"progress"`
|
||||
Weight int `json:"weight"`
|
||||
type Allowance struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Target int `json:"target"`
|
||||
Progress int `json:"progress"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type CreateGoalRequest struct {
|
||||
Name string `json:"name"`
|
||||
Target int `json:"target"`
|
||||
Weight int `json:"weight"`
|
||||
type CreateAllowanceRequest struct {
|
||||
Name string `json:"name"`
|
||||
Target int `json:"target"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type UpdateAllowanceRequest struct {
|
||||
Name string `json:"name"`
|
||||
Target int `json:"target"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type BulkUpdateAllowanceRequest struct {
|
||||
ID int `json:"id"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
type CreateGoalResponse struct {
|
||||
|
||||
@@ -3,7 +3,7 @@ module allowance_planner
|
||||
go 1.24.2
|
||||
|
||||
require (
|
||||
gitea.seeseepuff.be/seeseemelk/mysqlite v0.12.0
|
||||
gitea.seeseepuff.be/seeseemelk/mysqlite v0.14.0
|
||||
github.com/gavv/httpexpect/v2 v2.17.0
|
||||
github.com/gin-contrib/cors v1.7.5
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
@@ -68,9 +68,9 @@ require (
|
||||
gopkg.in/fsnotify.v1 v1.4.7 // indirect
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.65.6 // indirect
|
||||
modernc.org/libc v1.65.7 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.10.0 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
modernc.org/sqlite v1.37.0 // indirect
|
||||
moul.io/http2curl/v2 v2.3.0 // indirect
|
||||
zombiezen.com/go/sqlite v1.4.0 // indirect
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
gitea.seeseepuff.be/seeseemelk/mysqlite v0.12.0 h1:kl0VFgvm52UKxJhZpf1hvucxZdOoXY50g/VmzsWH+/8=
|
||||
gitea.seeseepuff.be/seeseemelk/mysqlite v0.12.0/go.mod h1:cgswydOxJjMlNwfcBIXnKjr47LwXnMT9BInkiHb0tXE=
|
||||
gitea.seeseepuff.be/seeseemelk/mysqlite v0.13.0 h1:nqSXu5i5fHB1rrx/kfi8Phn/J6eFa2yh02FiGc9U1yg=
|
||||
gitea.seeseepuff.be/seeseemelk/mysqlite v0.13.0/go.mod h1:cgswydOxJjMlNwfcBIXnKjr47LwXnMT9BInkiHb0tXE=
|
||||
gitea.seeseepuff.be/seeseemelk/mysqlite v0.14.0 h1:aRItVfUj48fBmuec7rm/jY9KCfvHW2VzJfItVk4t8sw=
|
||||
gitea.seeseepuff.be/seeseemelk/mysqlite v0.14.0/go.mod h1:cgswydOxJjMlNwfcBIXnKjr47LwXnMT9BInkiHb0tXE=
|
||||
github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 h1:ZBbLwSJqkHBuFDA6DUhhse0IGJ7T5bemHyNILUjvOq4=
|
||||
github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2/go.mod h1:VSw57q4QFiWDbRnjdX8Cb3Ow0SFncRw+bA/ofY6Q83w=
|
||||
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
|
||||
@@ -216,10 +220,14 @@ modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/libc v1.65.6 h1:OhJUhmuJ6MVZdqL5qmnd0/my46DKGFhSX4WOR7ijfyE=
|
||||
modernc.org/libc v1.65.6/go.mod h1:MOiGAM9lrMBT9L8xT1nO41qYl5eg9gCp9/kWhz5L7WA=
|
||||
modernc.org/libc v1.65.7 h1:Ia9Z4yzZtWNtUIuiPuQ7Qf7kxYrxP1/jeHZzG8bFu00=
|
||||
modernc.org/libc v1.65.7/go.mod h1:011EQibzzio/VX3ygj1qGFt5kMjP0lHb0qCW5/D/pQU=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.10.0 h1:fzumd51yQ1DxcOxSO+S6X7+QTuVU+n8/Aj7swYjFfC4=
|
||||
modernc.org/memory v1.10.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
|
||||
311
backend/main.go
311
backend/main.go
@@ -76,7 +76,7 @@ func getUser(c *gin.Context) {
|
||||
c.IndentedJSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
func getUserGoals(c *gin.Context) {
|
||||
func getUserAllowance(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
@@ -97,16 +97,59 @@ func getUserGoals(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
goals, err := db.GetUserGoals(userId)
|
||||
allowances, err := db.GetUserAllowances(userId)
|
||||
if err != nil {
|
||||
log.Printf("Error getting user goals: %v", err)
|
||||
log.Printf("Error getting user allowance: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
c.IndentedJSON(http.StatusOK, goals)
|
||||
c.IndentedJSON(http.StatusOK, allowances)
|
||||
}
|
||||
|
||||
func createUserGoal(c *gin.Context) {
|
||||
func getUserAllowanceById(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
allowanceIdStr := c.Param("allowanceId")
|
||||
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
log.Printf(ErrInvalidUserID+": %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": ErrInvalidUserID})
|
||||
return
|
||||
}
|
||||
|
||||
allowanceId, err := strconv.Atoi(allowanceIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid allowance ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid allowance ID"})
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := db.UserExists(userId)
|
||||
if err != nil {
|
||||
log.Printf(ErrCheckingUserExist, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": ErrUserNotFound})
|
||||
return
|
||||
}
|
||||
|
||||
allowance, err := db.GetUserAllowanceById(userId, allowanceId)
|
||||
if errors.Is(err, mysqlite.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Allowance not found"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("Error getting allowance: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
c.IndentedJSON(http.StatusOK, allowance)
|
||||
}
|
||||
|
||||
func createUserAllowance(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
@@ -116,7 +159,7 @@ func createUserGoal(c *gin.Context) {
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var goalRequest CreateGoalRequest
|
||||
var goalRequest CreateAllowanceRequest
|
||||
if err := c.ShouldBindJSON(&goalRequest); err != nil {
|
||||
log.Printf("Error parsing request body: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
|
||||
@@ -125,12 +168,12 @@ func createUserGoal(c *gin.Context) {
|
||||
|
||||
// Validate request
|
||||
if goalRequest.Name == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Goal name cannot be empty"})
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Allowance name cannot be empty"})
|
||||
return
|
||||
}
|
||||
|
||||
// Create goal in database
|
||||
goalId, err := db.CreateGoal(userId, &goalRequest)
|
||||
goalId, err := db.CreateAllowance(userId, &goalRequest)
|
||||
if err != nil {
|
||||
log.Printf("Error creating goal: %v", err)
|
||||
if err.Error() == "user does not exist" {
|
||||
@@ -146,9 +189,8 @@ func createUserGoal(c *gin.Context) {
|
||||
c.IndentedJSON(http.StatusCreated, response)
|
||||
}
|
||||
|
||||
func deleteUserGoal(c *gin.Context) {
|
||||
func bulkPutUserAllowance(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
goalIdStr := c.Param("goalId")
|
||||
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
@@ -157,13 +199,6 @@ func deleteUserGoal(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
goalId, err := strconv.Atoi(goalIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid goal ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid goal ID"})
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := db.UserExists(userId)
|
||||
if err != nil {
|
||||
log.Printf(ErrCheckingUserExist, err)
|
||||
@@ -175,18 +210,162 @@ func deleteUserGoal(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
err = db.DeleteGoal(userId, goalId)
|
||||
var allowanceRequest []BulkUpdateAllowanceRequest
|
||||
if err := c.ShouldBindJSON(&allowanceRequest); err != nil {
|
||||
log.Printf("Error parsing request body: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
err = db.BulkUpdateAllowance(userId, allowanceRequest)
|
||||
if err != nil {
|
||||
if err.Error() == "goal not found" {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Goal not found"})
|
||||
log.Printf("Error updating allowance: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
c.IndentedJSON(http.StatusOK, gin.H{"message": "Allowance updated successfully"})
|
||||
}
|
||||
|
||||
func deleteUserAllowance(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
allowanceIdStr := c.Param("allowanceId")
|
||||
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
log.Printf(ErrInvalidUserID+": %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": ErrInvalidUserID})
|
||||
return
|
||||
}
|
||||
|
||||
allowanceId, err := strconv.Atoi(allowanceIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid allowance ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid allowance ID"})
|
||||
return
|
||||
}
|
||||
|
||||
if allowanceId == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Allowance id zero cannot be deleted"})
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := db.UserExists(userId)
|
||||
if err != nil {
|
||||
log.Printf(ErrCheckingUserExist, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": ErrUserNotFound})
|
||||
return
|
||||
}
|
||||
|
||||
err = db.DeleteAllowance(userId, allowanceId)
|
||||
if err != nil {
|
||||
if err.Error() == "allowance not found" {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "History not found"})
|
||||
} else {
|
||||
log.Printf("Error deleting goal: %v", err)
|
||||
log.Printf("Error deleting allowance: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
c.IndentedJSON(http.StatusOK, gin.H{"message": "Goal deleted successfully"})
|
||||
c.IndentedJSON(http.StatusOK, gin.H{"message": "History deleted successfully"})
|
||||
}
|
||||
|
||||
func putUserAllowance(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
allowanceIdStr := c.Param("allowanceId")
|
||||
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
log.Printf(ErrInvalidUserID+": %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": ErrInvalidUserID})
|
||||
return
|
||||
}
|
||||
|
||||
allowanceId, err := strconv.Atoi(allowanceIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid allowance ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid allowance ID"})
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := db.UserExists(userId)
|
||||
if err != nil {
|
||||
log.Printf(ErrCheckingUserExist, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": ErrUserNotFound})
|
||||
return
|
||||
}
|
||||
|
||||
var allowanceRequest UpdateAllowanceRequest
|
||||
if err := c.ShouldBindJSON(&allowanceRequest); err != nil {
|
||||
log.Printf("Error parsing request body: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if allowanceId == 0 {
|
||||
err = db.UpdateUserAllowance(userId, &allowanceRequest)
|
||||
} else {
|
||||
err = db.UpdateAllowance(userId, allowanceId, &allowanceRequest)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("Error updating allowance: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
c.IndentedJSON(http.StatusOK, gin.H{"message": "Allowance updated successfully"})
|
||||
}
|
||||
|
||||
func completeAllowance(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
allowanceIdStr := c.Param("allowanceId")
|
||||
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
log.Printf(ErrInvalidUserID+": %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": ErrInvalidUserID})
|
||||
return
|
||||
}
|
||||
|
||||
allowanceId, err := strconv.Atoi(allowanceIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid allowance ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid allowance ID"})
|
||||
return
|
||||
}
|
||||
|
||||
exists, err := db.UserExists(userId)
|
||||
if err != nil {
|
||||
log.Printf(ErrCheckingUserExist, err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
if !exists {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": ErrUserNotFound})
|
||||
return
|
||||
}
|
||||
|
||||
err = db.CompleteAllowance(userId, allowanceId)
|
||||
if errors.Is(err, mysqlite.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Allowance not found"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("Error completing allowance: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
c.IndentedJSON(http.StatusOK, gin.H{"message": "Allowance completed successfully"})
|
||||
}
|
||||
|
||||
func createTask(c *gin.Context) {
|
||||
@@ -290,7 +469,61 @@ func putTask(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Task updated successfully"})
|
||||
}
|
||||
|
||||
func postAllowance(c *gin.Context) {
|
||||
func deleteTask(c *gin.Context) {
|
||||
taskIdStr := c.Param("taskId")
|
||||
taskId, err := strconv.Atoi(taskIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid task ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid task ID"})
|
||||
return
|
||||
}
|
||||
|
||||
hasTask, err := db.HasTask(taskId)
|
||||
if err != nil {
|
||||
log.Printf("Error checking task existence: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
if !hasTask {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Task not found"})
|
||||
return
|
||||
}
|
||||
|
||||
err = db.DeleteTask(taskId)
|
||||
if err != nil {
|
||||
log.Printf("Error deleting task: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Task deleted successfully"})
|
||||
}
|
||||
|
||||
func completeTask(c *gin.Context) {
|
||||
taskIdStr := c.Param("taskId")
|
||||
taskId, err := strconv.Atoi(taskIdStr)
|
||||
if err != nil {
|
||||
log.Printf("Invalid task ID: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid task ID"})
|
||||
return
|
||||
}
|
||||
|
||||
err = db.CompleteTask(taskId)
|
||||
if errors.Is(err, mysqlite.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Task not found"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("Error completing task: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Task completed successfully"})
|
||||
}
|
||||
|
||||
func postHistory(c *gin.Context) {
|
||||
userIdStr := c.Param("userId")
|
||||
userId, err := strconv.Atoi(userIdStr)
|
||||
if err != nil {
|
||||
@@ -299,8 +532,8 @@ func postAllowance(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var allowanceRequest PostAllowance
|
||||
if err := c.ShouldBindJSON(&allowanceRequest); err != nil {
|
||||
var historyRequest PostHistory
|
||||
if err := c.ShouldBindJSON(&historyRequest); err != nil {
|
||||
log.Printf("Error parsing request body: %v", err)
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
|
||||
return
|
||||
@@ -317,13 +550,13 @@ func postAllowance(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
err = db.AddAllowance(userId, &allowanceRequest)
|
||||
err = db.AddHistory(userId, &historyRequest)
|
||||
if err != nil {
|
||||
log.Printf("Error updating allowance: %v", err)
|
||||
log.Printf("Error updating history: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": ErrInternalServerError})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Allowance updated successfully"})
|
||||
c.JSON(http.StatusOK, gin.H{"message": "History updated successfully"})
|
||||
}
|
||||
|
||||
func getHistory(c *gin.Context) {
|
||||
@@ -354,18 +587,26 @@ func start(ctx context.Context, config *ServerConfig) {
|
||||
defer db.db.MustClose()
|
||||
|
||||
router := gin.Default()
|
||||
router.Use(cors.Default())
|
||||
router.Use(cors.New(cors.Config{
|
||||
AllowOrigins: []string{"*"},
|
||||
}))
|
||||
router.GET("/api/users", getUsers)
|
||||
router.GET("/api/user/:userId", getUser)
|
||||
router.POST("/api/user/:userId/allowance", postAllowance)
|
||||
router.POST("/api/user/:userId/history", postHistory)
|
||||
router.GET("/api/user/:userId/history", getHistory)
|
||||
router.GET("/api/user/:userId/goals", getUserGoals)
|
||||
router.POST("/api/user/:userId/goals", createUserGoal)
|
||||
router.DELETE("/api/user/:userId/goal/:goalId", deleteUserGoal)
|
||||
router.GET("/api/user/:userId/allowance", getUserAllowance)
|
||||
router.POST("/api/user/:userId/allowance", createUserAllowance)
|
||||
router.PUT("/api/user/:userId/allowance", bulkPutUserAllowance)
|
||||
router.GET("/api/user/:userId/allowance/:allowanceId", getUserAllowanceById)
|
||||
router.DELETE("/api/user/:userId/allowance/:allowanceId", deleteUserAllowance)
|
||||
router.PUT("/api/user/:userId/allowance/:allowanceId", putUserAllowance)
|
||||
router.POST("/api/user/:userId/allowance/:allowanceId/complete", completeAllowance)
|
||||
router.POST("/api/tasks", createTask)
|
||||
router.GET("/api/tasks", getTasks)
|
||||
router.GET("/api/task/:taskId", getTask)
|
||||
router.PUT("/api/task/:taskId", putTask)
|
||||
router.DELETE("/api/task/:taskId", deleteTask)
|
||||
router.POST("/api/task/:taskId/complete", completeTask)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: config.Addr,
|
||||
@@ -400,5 +641,9 @@ func main() {
|
||||
Datasource: os.Getenv("DB_PATH"),
|
||||
Addr: ":8080",
|
||||
}
|
||||
if config.Datasource == "" {
|
||||
config.Datasource = "allowance_planner.db3"
|
||||
log.Printf("Warning: No DB_PATH set, using default of %s", config.Datasource)
|
||||
}
|
||||
start(context.Background(), &config)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
create table users
|
||||
(
|
||||
id integer primary key,
|
||||
name text not null
|
||||
name text not null,
|
||||
weight real not null default 0.0,
|
||||
balance integer not null default 0
|
||||
) strict;
|
||||
|
||||
create table history
|
||||
@@ -12,13 +14,13 @@ create table history
|
||||
amount integer not null
|
||||
);
|
||||
|
||||
create table goals
|
||||
create table allowances
|
||||
(
|
||||
id integer primary key,
|
||||
user_id integer not null,
|
||||
name text not null,
|
||||
target integer not null,
|
||||
progress integer not null,
|
||||
balance integer not null default 0,
|
||||
weight real not null
|
||||
);
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ paths:
|
||||
404:
|
||||
description: The users could not be found.
|
||||
|
||||
/user/{userId}/allowance:
|
||||
/user/{userId}/history:
|
||||
get:
|
||||
summary: Gets the allowance history of a user
|
||||
parameters:
|
||||
@@ -114,7 +114,7 @@ paths:
|
||||
400:
|
||||
description: The allowance could not be updated.
|
||||
|
||||
/user/{userId}/goals:
|
||||
/user/{userId}/allowance:
|
||||
get:
|
||||
summary: Gets all goals
|
||||
parameters:
|
||||
@@ -201,7 +201,7 @@ paths:
|
||||
404:
|
||||
description: The goals could not be found.
|
||||
|
||||
/user/{userId}/goal/{goalId}:
|
||||
/user/{userId}/allowance/{goalId}:
|
||||
get:
|
||||
summary: Gets information about a goal
|
||||
parameters:
|
||||
@@ -284,7 +284,7 @@ paths:
|
||||
404:
|
||||
description: The goal could not be found.
|
||||
|
||||
/user/{userId}/goal/{goalId}/complete:
|
||||
/user/{userId}/allowance/{goalId}/complete:
|
||||
post:
|
||||
summary: Completes a goal.
|
||||
description: Completes a goal. This will subtract this goal's value from the user's allowance and then remove the goal.
|
||||
|
||||
@@ -13,7 +13,6 @@ export class AppComponent {
|
||||
this.storageService.init().then(() => {
|
||||
this.storageService.getCurrentUserId().then((userId) => {
|
||||
if (userId !== undefined && userId !== null) {
|
||||
console.log('userId: ', userId);
|
||||
this.router.navigate(['/tabs/allowance', userId]);
|
||||
}
|
||||
});
|
||||
|
||||
6
frontend/allowance-planner-v2/src/app/models/task.ts
Normal file
6
frontend/allowance-planner-v2/src/app/models/task.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export interface Task {
|
||||
id: number;
|
||||
name: string;
|
||||
reward: number;
|
||||
assigned: number;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<ion-header [translucent]="true">
|
||||
<ion-header [translucent]="true" class="ion-no-border">
|
||||
<ion-toolbar>
|
||||
<ion-title>
|
||||
Allowance
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<ion-header [translucent]="true">
|
||||
<ion-header [translucent]="true" class="ion-no-border">
|
||||
<ion-toolbar>
|
||||
<ion-title>
|
||||
History
|
||||
|
||||
@@ -5,14 +5,22 @@ import { FormsModule } from '@angular/forms';
|
||||
import { TasksPage } from './tasks.page';
|
||||
|
||||
import { TasksPageRoutingModule } from './tasks-routing.module';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { TaskService } from 'src/app/services/task.service';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
IonicModule,
|
||||
CommonModule,
|
||||
FormsModule,
|
||||
TasksPageRoutingModule
|
||||
TasksPageRoutingModule,
|
||||
MatIconModule,
|
||||
],
|
||||
declarations: [TasksPage]
|
||||
declarations: [TasksPage],
|
||||
providers: [
|
||||
provideHttpClient(),
|
||||
TaskService
|
||||
]
|
||||
})
|
||||
export class TasksPageModule {}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<ion-header [translucent]="true">
|
||||
<ion-header [translucent]="true" class="ion-no-border">
|
||||
<ion-toolbar>
|
||||
<ion-title>
|
||||
Tasks
|
||||
@@ -7,4 +7,17 @@
|
||||
</ion-header>
|
||||
|
||||
<ion-content>
|
||||
<div class="icon">
|
||||
<mat-icon>filter_alt</mat-icon>
|
||||
</div>
|
||||
<div class="list">
|
||||
<div class="task" *ngFor="let task of tasks">
|
||||
<button>Done</button>
|
||||
<div class="name">{{ task.name }}</div>
|
||||
<div
|
||||
class="reward"
|
||||
[ngClass]="{ 'negative': task.reward < 0 }"
|
||||
>{{ task.reward.toFixed(2) }} SP</div>
|
||||
</div>
|
||||
</div>
|
||||
</ion-content>
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
.icon {
|
||||
padding: 5px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
color: var(--ion-color-primary);
|
||||
}
|
||||
|
||||
mat-icon {
|
||||
font-size: 35px;
|
||||
width: 35px;
|
||||
height: 35px;
|
||||
}
|
||||
|
||||
.list {
|
||||
border-top: 1px solid var(--line-color);
|
||||
}
|
||||
|
||||
.task {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid var(--line-color);
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.name {
|
||||
margin-left: 10px;
|
||||
color: var(--font-color);
|
||||
}
|
||||
|
||||
.reward {
|
||||
margin-left: auto;
|
||||
margin-right: 15px;
|
||||
color: var(--positive-amount-color);
|
||||
}
|
||||
|
||||
.negative {
|
||||
color: var(--negative-amount-color);
|
||||
}
|
||||
|
||||
button {
|
||||
width: 57px;
|
||||
height: 30px;
|
||||
border-radius: 10px;
|
||||
color: white;
|
||||
background: var(--confirm-button-color);
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { TaskService } from 'src/app/services/task.service';
|
||||
import { Task } from 'src/app/models/task';
|
||||
|
||||
@Component({
|
||||
selector: 'app-tasks',
|
||||
@@ -6,8 +8,17 @@ import { Component } from '@angular/core';
|
||||
styleUrls: ['tasks.page.scss'],
|
||||
standalone: false,
|
||||
})
|
||||
export class TasksPage {
|
||||
export class TasksPage implements OnInit {
|
||||
public tasks: Array<Task> = [];
|
||||
|
||||
constructor() {}
|
||||
constructor(
|
||||
private taskService: TaskService
|
||||
) {}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.taskService.getTaskList().subscribe(tasks => {
|
||||
this.tasks = tasks;
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Task } from '../models/task';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class TaskService {
|
||||
private url = 'http://localhost:8080/api'
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
getTaskList(): Observable<Array<Task>> {
|
||||
return this.http.get<Task[]>(`${this.url}/tasks`);
|
||||
}
|
||||
}
|
||||
@@ -35,3 +35,11 @@
|
||||
/* @import "@ionic/angular/css/palettes/dark.always.css"; */
|
||||
/* @import "@ionic/angular/css/palettes/dark.class.css"; */
|
||||
@import "@ionic/angular/css/palettes/dark.system.css";
|
||||
|
||||
ion-title {
|
||||
color: var(--ion-color-primary);
|
||||
}
|
||||
|
||||
ion-header {
|
||||
border-bottom: 1px solid var(--line-color);
|
||||
}
|
||||
@@ -4,6 +4,11 @@
|
||||
--ion-color-primary: #9C4BE4;
|
||||
--ion-color-secondary: #F5E9FF;
|
||||
--ion-background-color: #F3F3F3;
|
||||
--font-color: #7B7B7B;
|
||||
--confirm-button-color: #58A66F;
|
||||
--positive-amount-color: #7DCB7D;
|
||||
--negative-amount-color: #C55454;
|
||||
--line-color: #CACACA;
|
||||
|
||||
--ion-font-family: 'Myfont';
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user