Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
72bd84d354 | ||
|
|
10dc621cac | ||
|
|
bee6c0093e | ||
|
|
cd9685fdf7 | ||
|
|
0c017082ee | ||
|
|
0338189ffa | ||
|
|
a092e82f7f | ||
|
|
fede9ff793 | ||
|
|
2914859505 | ||
|
|
ce964edcd4 | ||
|
|
b140869281 | ||
|
|
4c4bad4be0 | ||
|
|
807758d924 | ||
|
|
0d29e1f382 | ||
|
|
c3aaec9798 | ||
|
|
28b92f4eda | ||
|
|
bbe4ecf705 | ||
|
|
40886aa815 | ||
|
|
1bd0da305d | ||
|
|
06e0eea782 | ||
|
|
79acbc377a | ||
|
|
fdd5401b06 | ||
|
|
d7d19ffb2d | ||
|
|
1b643c0bc2 | ||
|
|
0f183559e5 | ||
|
|
46d46c71a6 | ||
|
|
60d87dcf35 | ||
|
|
322821289e | ||
|
|
27d84c3c99 | ||
|
|
cb7298077d | ||
|
|
135066bad2 | ||
|
|
b27da3f095 | ||
|
|
459ddf542a | ||
|
|
e2d085a534 | ||
|
|
61d97ea429 | ||
|
|
1692b77a99 | ||
|
|
9511270b71 | ||
|
|
a98b10c816 | ||
|
|
c025a00415 | ||
|
|
c05e3a3879 | ||
|
|
fa8acec7a8 | ||
|
|
7ed53fc539 | ||
|
|
315f33b3e7 | ||
|
|
3aa4f72b33 | ||
|
|
2071e94516 | ||
|
|
50e672849b | ||
|
|
956fe306e5 | ||
|
|
dcabacdc8c | ||
|
|
8032b79989 | ||
|
|
255ea25edf | ||
|
|
7e85215fcc | ||
|
|
84b8c1ae5e | ||
|
|
ca4020f0ee | ||
|
|
596533753c | ||
|
|
e97f185e22 | ||
|
|
fdd489345d | ||
|
|
724b61cc2e | ||
|
|
b456a02178 | ||
|
|
41e7ca4f87 | ||
|
|
ae88f5d149 | ||
|
|
421943d5d4 | ||
|
|
8ee6c40bde | ||
|
|
c83f05674e | ||
|
|
e8c3272677 | ||
|
|
974c512cd1 | ||
|
|
f177e8cef7 | ||
|
|
55ca35034e | ||
|
|
2ef9c71f59 | ||
|
|
f402b27222 | ||
|
|
7bd33decc9 | ||
|
|
456dab3d6f | ||
|
|
27eb0937c7 | ||
|
|
eb065c4142 | ||
|
|
22d41d04dc | ||
|
|
dd0cd7d76c | ||
|
|
52e1c0fb5b | ||
|
|
f8ff2cf90e | ||
|
|
66112d4158 | ||
|
|
39400b371a | ||
|
|
9d44f98ff1 | ||
|
|
c054e3f065 | ||
|
|
b708f1d815 | ||
|
|
471d1c94a0 | ||
|
|
f37e677dbf |
No files matched your search
@@ -1,6 +0,0 @@
|
||||
mongoURI=mongodb://localhost:27017
|
||||
dbo=school
|
||||
secret=<your 256 bit secret>
|
||||
PORT=8000
|
||||
SYSTEM_EMAIL=<your system email>
|
||||
SYSTEM_PASSWORD=<your system password>
|
||||
+3
-3
@@ -1,6 +1,9 @@
|
||||
# Environment
|
||||
.env
|
||||
|
||||
# Vendor
|
||||
/vendor/*
|
||||
|
||||
# Pycache
|
||||
/test/__pycache__/*
|
||||
/test/util/__pycache__/*
|
||||
@@ -11,6 +14,3 @@
|
||||
|
||||
# Test output
|
||||
/test/output/*
|
||||
|
||||
# Sample Data
|
||||
/test/sample_data/*
|
||||
@@ -1,13 +0,0 @@
|
||||
<!-- CONTRIBUTING -->
|
||||
## Contributing
|
||||
|
||||
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
|
||||
|
||||
If you have a suggestion that would make this better, please create a pull request. You can also simply open an issue with the tag "enhancement".
|
||||
Don't forget to give the project a star! Thanks again!
|
||||
|
||||
1. Clone the Project
|
||||
2. Create your Feature Branch (`git checkout -b update/AmazingFeature`)
|
||||
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
|
||||
4. Push to the Branch (`git push origin update/AmazingFeature`)
|
||||
5. Open a Pull Request
|
||||
+1357
File diff suppressed because it is too large.
Load diff
@@ -2,9 +2,18 @@
|
||||
|
||||
The backend API for a school management system accessible by staff and students.
|
||||
|
||||
<a href="https://github.com/SowinskiBraeden/school-management-api"><strong>Explore the docs »</strong></a>
|
||||
<br>
|
||||
<br>
|
||||
***Explore the docs »***
|
||||
* [Getting Started](#getting-started)
|
||||
* [Usage/Documenation](#usage)
|
||||
* [License](#license)
|
||||
* [Contact](#contact)
|
||||
|
||||
### Built With
|
||||
|
||||
* [Golang](https://go.dev/)
|
||||
* [GoFiber](https://gofiber.io/)
|
||||
* [GoMongo Driver](https://docs.mongodb.com/drivers/go/current/)
|
||||
* [golang-jwt](https://github.com/golang-jwt/jwt)
|
||||
|
||||
## About The Project
|
||||
|
||||
@@ -14,22 +23,31 @@ this on as a full project to work on for my Software Engineering class and is no
|
||||
work on this till completion, starting with this API, and then the front end, learning new tricks and languages
|
||||
along the way.
|
||||
|
||||
I highly recommend looking at the testing for [schedule generation](/test/scheduleGenerator), [version 3](/test/scheduleGenerator/generator_v3.py)
|
||||
Developing the API has has me face many challenges. With me developing my techniques in Go, and increasing my
|
||||
ability to work with Go frameworks. Understanding the workflow of packages and the Go ecosystem.
|
||||
|
||||
I started by developing authentication; a solid footing to the project, without the authentication of users,
|
||||
the rest of the project would fail to work. As the purpose of this API handles sensitive data on students.
|
||||
|
||||
Once the authentication was complete, I took to working on majority of the user data handling. Such as
|
||||
setting, updating and or deleting user attributes. Building a few more key authentication features only
|
||||
allowing the proper authenticated user, an admin, perfom many of the actions.
|
||||
|
||||
Once this was complete I started work on conceptualizing the next major step of the API. Course management,
|
||||
including course selection, schedule generation, etc. This can be viewed in this [request](https://github.com/SowinskiBraeden/school-management-api/issues/5).
|
||||
To start off on this new set of features, I decided to tackle the largest and most complex problem,
|
||||
schedule generation. This algorithm generates a master timetable as well as updates the student schedule.
|
||||
All the while keeping track of any errors for admins to handle personally. This can be found in `testing`,
|
||||
The [schedule generation](/test/scheduleGenerator) file is of the latest version, version 3. Though this has
|
||||
been moved to its own [repository](https://github.com/SowinskiBraeden/ScheduleGeneratorApp).
|
||||
|
||||
## Related Work
|
||||
|
||||
After the majority completion of vital api functionalities such as the ability to update information, create new
|
||||
information, generate information, delete information, authentication etc. I have created a new repository
|
||||
for the next frontier of this project. I am now concurrently working on the [School Management Website](https://github.com/SowinskiBraeden/school-management).
|
||||
for the next frontier of this project. I am now concurrently working on the [School Management Website](https://github.com/SowinskiBraeden/school-management-vue).
|
||||
|
||||
The School Management Website. is going to be written using the [Vue.js](https://vuejs.org/) framework. Vue.js is a popular framwork for working on frontend UI programs. I am currently unfamiliar with the framework but plan on learning the framework to use it more in the future.
|
||||
<br>
|
||||
|
||||
### Built With
|
||||
|
||||
* [Golang](https://go.dev/)
|
||||
* [GoFiber](https://gofiber.io/)
|
||||
* [GoMongo Driver](https://docs.mongodb.com/drivers/go/current/)
|
||||
The School Management Website, is going to be written using the [Vue.js](https://vuejs.org/) framework as there were issues trying to use Next.js in an [older test](https://github.com/SowinskiBraeden/school-management).
|
||||
|
||||
## Getting Started
|
||||
|
||||
@@ -82,12 +100,7 @@ The systems is easy to start and your local machine. Eliminating any long unforg
|
||||
|
||||
The usage for this API is in the name, school management, it's not an easy task in the areas I live near. Overcrowded schools are far too common and the need for a better school management system is there. The current systems issued by the government work but are poor and outdated.
|
||||
|
||||
|
||||
<!-- CONTRIBUTING -->
|
||||
## Contributing
|
||||
|
||||
Please refer to [CONTRIBUTING](CONTRIBUTING.md) for contributing to the project.
|
||||
|
||||
To see a full list of features and how to use the system, read the [documentation](DOCUMENTATION.md)
|
||||
|
||||
|
||||
<!-- LICENSE -->
|
||||
@@ -99,6 +112,6 @@ Distributed under the MIT License. See [LICENSE](LICENSE) for more information.
|
||||
<!-- CONTACT -->
|
||||
## Contact
|
||||
|
||||
Braeden Sowinski - [@BraedenSowinski](https://twitter.com/BraedenSowinski) - sowinskibraeden@gmail.com
|
||||
Braeden Sowinski - [@BraedenSowinski](https://twitter.com/BraedenSowinski) - sowinskibraeden@gmail.com - McDazzzled#5307 on Discord
|
||||
|
||||
Project Link: [https://github.com/SowinskiBraeden/school-management-api](https://github.com/SowinskiBraeden/school-management-api)
|
||||
+596
-222
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,78 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/smtp"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Server string
|
||||
Port int
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
var config Config = Config{
|
||||
Server: "smtp.gmail.com",
|
||||
Port: 587,
|
||||
Email: os.Getenv("SYSTEM_EMAIL"),
|
||||
Password: os.Getenv("SYSTEM_PASSWORD"),
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
to []string
|
||||
subject string
|
||||
body string
|
||||
}
|
||||
|
||||
const (
|
||||
MIME = "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
|
||||
)
|
||||
|
||||
func NewRequest(to []string, subject string) *Request {
|
||||
return &Request{
|
||||
to: to,
|
||||
subject: subject,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Request) parseTemplate(fileName string, data interface{}) error {
|
||||
t, err := template.ParseFiles(fileName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
buffer := new(bytes.Buffer)
|
||||
if err = t.Execute(buffer, data); err != nil {
|
||||
return err
|
||||
}
|
||||
r.body = buffer.String()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Request) sendMail() bool {
|
||||
body := "To: " + r.to[0] + "\r\nSubject: " + r.subject + "\r\n" + MIME + "\r\n" + r.body
|
||||
SMTP := fmt.Sprintf("%s:%d", config.Server, config.Port)
|
||||
if err := smtp.SendMail(SMTP, smtp.PlainAuth("", config.Email, config.Password, config.Server), config.Email, r.to, []byte(body)); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (r *Request) Send(templateName string, items interface{}) bool {
|
||||
err := r.parseTemplate(templateName, items)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
return false
|
||||
}
|
||||
if ok := r.sendMail(); ok {
|
||||
log.Printf("Email has been sent to %s\n", r.to)
|
||||
return true
|
||||
} else {
|
||||
log.Printf("Failed to send the email to %s\n", r.to)
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -14,24 +14,22 @@ import (
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var idCollection *mongo.Collection = database.OpenCollection(database.Client, "cids")
|
||||
var IdCollection *mongo.Collection = database.OpenCollection(database.Client, "cids")
|
||||
|
||||
var table = [...]byte{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'}
|
||||
|
||||
func ValidateID(id string) bool { // true: valid id, false: id already in use
|
||||
func ValidateID(id string, userType int) bool { // true: valid id, false: id already in use
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
var foundID models.Id
|
||||
err := idCollection.FindOne(ctx, bson.M{"cid": id}).Decode(&foundID)
|
||||
err := IdCollection.FindOne(ctx, bson.M{"cid": id}).Decode(&foundID)
|
||||
cancel()
|
||||
if err != nil { // If there is no id found create new ID object to be stored and return true (unless insert error then try again)
|
||||
var newID models.Id
|
||||
newID.CID = id
|
||||
newID.ParentType = userType
|
||||
newID.ID = primitive.NewObjectID()
|
||||
_, insertErr := idCollection.InsertOne(context.Background(), newID)
|
||||
if insertErr != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
_, insertErr := IdCollection.InsertOne(context.Background(), newID)
|
||||
return insertErr == nil
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -39,12 +37,9 @@ func ValidateID(id string) bool { // true: valid id, false: id already in use
|
||||
func ValidatePEN(pen string) bool { // true: valid pen, false: pen already in use
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
var foundID models.Id
|
||||
err := studentCollection.FindOne(ctx, bson.M{"schooldata.pen": pen}).Decode(&foundID)
|
||||
err := StudentCollection.FindOne(ctx, bson.M{"school.pen": pen}).Decode(&foundID)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
return err != nil
|
||||
}
|
||||
|
||||
func GenerateID(length int) string {
|
||||
@@ -0,0 +1,461 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
. "github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
"github.com/SowinskiBraeden/school-management-api/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
/*
|
||||
Several of these functions aren't directly for updating admin
|
||||
information, but for admins only to update information of other
|
||||
object types such as lockers, enabling user accounts after being
|
||||
disbaled, etc.
|
||||
*/
|
||||
|
||||
func UpdateLockerCombo(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check locker number is included
|
||||
if data["lockernumber"] == "" || data["newlockercombo"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"lockercombo": data["newlockercombo"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := LockerCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"lockernumber": data["lockernumber"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the locker could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated locker",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateAdminName(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var admin models.Admin
|
||||
findErr := AdminCollection.FindOne(ctx, bson.M{"aid": claims.Issuer}).Decode(&admin)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "admin not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["firstname"] == "" || data["lastname"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"firstname": data["firstname"],
|
||||
"lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"aid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the admin could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated admin",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateAdminEmail(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var admin models.Admin
|
||||
findErr := AdminCollection.FindOne(ctx, bson.M{"aid": claims.Issuer}).Decode(&admin)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "admin not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"email": data["email"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"aid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the admin could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated admin",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateAdminPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var admin models.Admin
|
||||
findErr := AdminCollection.FindOne(ctx, bson.M{"aid": claims.Issuer}).Decode(&admin)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "admin not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["password"] == "" || data["newpassword1"] == "" || data["newpassword2"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
if !admin.ComparePasswords(data["password"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your password is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
if data["newpassword1"] != data["newpassword2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new passwords must match",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"password": admin.HashPassword(data["newpassword1"]),
|
||||
"temppassword": false, // If it were a temp password, its not now
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"aid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the admin password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
subject := "Password Changed"
|
||||
receiver := admin.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/selfPasswordChanged.html", map[string]string{"username": admin.FirstName}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to admins email",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated admin password",
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveStudentsDisabled(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authorized admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.accountdisabled": false,
|
||||
"account.alerted": false,
|
||||
"account.attempts": 0,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student account could not be enabled",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully enabled student account",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveTeachersDisabled(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authorized admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.accountdisabled": false,
|
||||
"account.attempts": 0,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher account could not be enabled",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully enabled teacher account",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
. "github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
func UpdateContactName(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["_id"] == "" || data["firstname"] == "" || data["lastname"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var middlename string = ""
|
||||
|
||||
if data["middlename"] != "" {
|
||||
middlename = data["middlename"]
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"firstname": data["firstname"],
|
||||
"middlename": middlename,
|
||||
"lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactAddress(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["_id"] == "" || data["address"] == "" || data["city"] == "" || data["province"] == "" || data["postal"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"address": data["address"],
|
||||
"city": data["city"],
|
||||
"province": data["province"],
|
||||
"postal": data["postal"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactHomePhone(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id of contact and new priority number is included
|
||||
if data["_id"] == "" || data["newnumber"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"homephone": data["newnumber"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactWorkPhone(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id of contact and new priority number is included
|
||||
if data["_id"] == "" || data["newnumber"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"workphone": data["newnumber"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactEmail(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id of contact and new priority number is included
|
||||
if data["_id"] == "" || data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"email": data["email"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateContactPriority(c *fiber.Ctx) error {
|
||||
var data map[string]interface{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id of contact and new priority number is included
|
||||
if data["_id"] == nil || data["priority"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var priority int = data["priority"].(int)
|
||||
|
||||
if priority > 10 || priority < 1 {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "invalid priority",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"priority": priority,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := ContactCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": data["_id"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated contact",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,979 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
. "github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
"github.com/SowinskiBraeden/school-management-api/models"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
func toBase64(b []byte) string {
|
||||
return base64.StdEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func UpdateStudentName(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and names are included
|
||||
// Middle name is optional
|
||||
if data["uid"] == "" || data["firstname"] == "" || data["lastname"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var updateMiddle bool = false
|
||||
if data["middlename"] != "" {
|
||||
updateMiddle = true
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
var update bson.M
|
||||
if updateMiddle {
|
||||
update = bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.firstname": data["firstname"],
|
||||
"personal.middlename": data["middlename"],
|
||||
"personal.lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
} else {
|
||||
update = bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.firstname": data["firstname"],
|
||||
"personal.lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentGradeLevel(c *fiber.Ctx) error {
|
||||
var data map[string]interface{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authorized admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == nil || data["gradelevel"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.gradelevel": data["gradelevel"].(float64),
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"].(string)},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
})
|
||||
}
|
||||
|
||||
/*
|
||||
Far later on this function is going to be completely automated.
|
||||
Instead of an admin sending a request to update the homeroom of
|
||||
a student or teacher, the system will take the room number of
|
||||
the teacher's or student's Block 2 class from their schedule.
|
||||
|
||||
Though this function would remain for students only, for example
|
||||
a student requests a course change, if its their block 2 the
|
||||
admin would have to alter their homeroom to be the new class
|
||||
number.
|
||||
*/
|
||||
func UpdateStudentHomeroom(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["homeroom"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.homeroom": data["homeroom"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var student models.Student
|
||||
findErr := StudentCollection.FindOne(ctx, bson.M{"school.sid": claims.Issuer}).Decode(&student)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "student not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["password"] == "" || data["newpassword1"] == "" || data["newpassword2"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
if !student.ComparePasswords(data["password"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your password is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
if data["newpassword1"] != data["newpassword2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new password must match",
|
||||
})
|
||||
}
|
||||
|
||||
if student.UsedPassword(data["newpassword1"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new password cannot be the same as a previous password",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.password": student.HashPassword(data["newpassword1"]),
|
||||
"account.temppassword": false, // If it were a temp password, its not now
|
||||
"updated_at": update_time,
|
||||
},
|
||||
"$push": bson.M{
|
||||
"account.hashhistory": student.HashPassword(data["newpassword1"]),
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Alert email the password has changed
|
||||
subject := "Password Changed"
|
||||
receiver := student.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/selfPasswordChanged.html", map[string]string{"username": student.Personal.FirstName}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "failed to send email to student",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student password",
|
||||
})
|
||||
}
|
||||
|
||||
// This is for students to reset their password if they are unable to login
|
||||
func ResetStudentPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included (email must be personal email)
|
||||
if data["uid"] == "" || data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var student models.Student
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"school.sid": data["uid"]}).Decode(&student)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "student not found",
|
||||
})
|
||||
}
|
||||
|
||||
if student.Personal.Email != data["email"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your personal email is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
tempPass := student.GeneratePassword(12, 1, 1, 1)
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.password": student.HashPassword(tempPass),
|
||||
"account.temppassword": true,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Send student personal email temp password
|
||||
subject := "Password Changed"
|
||||
receiver := student.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/passwordChanged.html", map[string]string{"username": student.Personal.FirstName, "password": tempPass}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to students email",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student password",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentLocker(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and locker are included
|
||||
if data["uid"] == "" || data["lockernumber"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var locker models.Locker
|
||||
err := LockerCollection.FindOne(ctx, bson.M{"lockernumber": data["lockernumber"]}).Decode(&locker)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "locker not found",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.locker": locker.ID,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentAddress(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["address"] == "" || data["city"] == "" || data["province"] == "" || data["postal"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.address": data["address"],
|
||||
"personal.city": data["city"],
|
||||
"personal.province": data["province"],
|
||||
"personal.postal": data["postal"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
})
|
||||
}
|
||||
|
||||
// In the case a student gets held back a grade, we need to update their YOG (Year of Graduation)
|
||||
func UpdateStudentYOG(c *fiber.Ctx) error {
|
||||
var data map[string]interface{}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["yog"] == nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var student models.Student
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"school.sid": data["uid"].(string)}).Decode(&student)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "student not found",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.yog": data["yog"].(int),
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"].(string)},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func RemoveStudentContact(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and contact id are included
|
||||
if data["uid"] == "" || data["contactid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var contact models.Contact
|
||||
err := ContactCollection.FindOne(ctx, bson.M{"_id": data["contactid"]}).Decode(&contact)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact not found",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"updated_at": update_time,
|
||||
},
|
||||
"$pull": bson.M{
|
||||
"personal.contacts": contact.ID,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the contact could not be added",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully added contact",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func AddStudentContact(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and contact id are included
|
||||
if data["uid"] == "" || data["contactid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var contact models.Contact
|
||||
err := ContactCollection.FindOne(ctx, bson.M{"_id": data["contactid"]}).Decode(&contact)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "contact not found",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"updated_at": update_time,
|
||||
},
|
||||
"$push": bson.M{
|
||||
"personal.contacts": contact.ID,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the contact could not be added",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully added contact",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentPhoto(c *fiber.Ctx) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
//Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
sid := c.FormValue("sid")
|
||||
if sid == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
// Get student
|
||||
var student models.Student
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"school.sid": sid}).Decode(&student)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
// Collect image
|
||||
file, err := c.FormFile("image")
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be retrieved",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Get student photo
|
||||
var photo models.Photo
|
||||
findErr = ImageCollection.FindOne(context.TODO(), bson.M{"name": student.School.PhotoName}).Decode(&photo)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student image could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
// Save image to local
|
||||
uniqueId := uuid.New()
|
||||
filename := strings.Replace(uniqueId.String(), "-", "", -1)
|
||||
fileExt := strings.Split(file.Filename, ".")[1]
|
||||
image := fmt.Sprintf("%s.%s", filename, fileExt)
|
||||
err = c.SaveFile(file, fmt.Sprintf("./database/images/%s", image))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be saved",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Read the entire file into a byte slice
|
||||
bytes, err := os.ReadFile(fmt.Sprintf("./database/images/%s", image))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be read",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
var base64Encoding string = toBase64(bytes)
|
||||
|
||||
// Update image name and base64 data
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"base64": base64Encoding,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
_, updateErr := ImageCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": photo.ID},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Remove local image
|
||||
os.Remove(fmt.Sprintf("./database/images/%s", image))
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student photo",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateStudentEmail(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
var sid string
|
||||
var verifiedStudent bool
|
||||
verifiedAdmin, _ := AuthenticateUser(c, 3)
|
||||
verifiedStudent, sid = AuthenticateUser(c, 1)
|
||||
// Ensure Authenticated admin sent request
|
||||
if !verifiedAdmin && !verifiedStudent {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin or teacher can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
if verifiedAdmin && data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
} else if verifiedAdmin {
|
||||
sid = data["uid"]
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.email": data["email"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.sid": sid},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated student",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
. "github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
|
||||
"github.com/SowinskiBraeden/school-management-api/models"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/google/uuid"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
/*
|
||||
Far later on this function is going to be completely automated.
|
||||
Instead of an admin sending a request to update the homeroom of
|
||||
a student or teacher, the system will take the room number of
|
||||
the teacher's or student's Block 2 class from their schedule.
|
||||
|
||||
Though this function would remain for students only, for example
|
||||
a student requests a course change, if its their block 2 the
|
||||
admin would have to alter their homeroom to be the new class
|
||||
number.
|
||||
*/
|
||||
func UpdateTeacherHomeroom(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["homeroom"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"school.homeroom": data["homeroom"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
cookie := c.Cookies("jwt")
|
||||
|
||||
token, err := jwt.ParseWithClaims(cookie, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(SecretKey), nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "not authorized",
|
||||
})
|
||||
}
|
||||
|
||||
claims := token.Claims.(*jwt.StandardClaims)
|
||||
|
||||
var teacher models.Teacher
|
||||
findErr := TeacherCollection.FindOne(ctx, bson.M{"school.tid": claims.Issuer}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "teacher not found",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["password"] == "" || data["newpassword1"] == "" || data["newpassword2"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
if !teacher.ComparePasswords(data["password"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your password is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
if data["newpassword1"] != data["newpassword2"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new passwords must match",
|
||||
})
|
||||
}
|
||||
|
||||
if teacher.UsedPassword(data["newpassword1"]) {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your new password cannot be the same as a previous password",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.password": teacher.HashPassword(data["newpassword1"]),
|
||||
"account.temppassword": false, // If it were a temp password, its not now
|
||||
"updated_at": update_time,
|
||||
},
|
||||
"$push": bson.M{
|
||||
"account.hashhistory": teacher.HashPassword(data["newpassword1"]),
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": claims.Issuer},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
subject := "Password Changed"
|
||||
receiver := teacher.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/selfPasswordChanged.html", map[string]string{"username": teacher.Personal.FirstName}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to teachers email",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher password",
|
||||
})
|
||||
}
|
||||
|
||||
func ResetTeacherPassword(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included (email must be personal email)
|
||||
if data["uid"] == "" || data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
var teacher models.Teacher
|
||||
findErr := TeacherCollection.FindOne(context.TODO(), bson.M{"school.tid": data["uid"]}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "teacher not found",
|
||||
})
|
||||
}
|
||||
|
||||
if teacher.Personal.Email != data["email"] {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Your personal email is incorrect",
|
||||
})
|
||||
}
|
||||
|
||||
tempPass := teacher.GeneratePassword(12, 1, 1, 1)
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"account.password": teacher.HashPassword(tempPass),
|
||||
"account.temppassword": true,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
result, updateErr := StudentCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher password could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Send teacher personal email temp password
|
||||
subject := "Password Changed"
|
||||
receiver := teacher.Personal.Email
|
||||
r := NewRequest([]string{receiver}, subject)
|
||||
|
||||
if sent := r.Send("./templates/passwordChanged.html", map[string]string{"username": teacher.Personal.FirstName, "password": tempPass}); !sent {
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Could not send password to teachers email",
|
||||
})
|
||||
}
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher password",
|
||||
"result": result,
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherAddress(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["uid"] == "" || data["address"] == "" || data["city"] == "" || data["province"] == "" || data["postal"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.address": data["address"],
|
||||
"personal.city": data["city"],
|
||||
"personal.province": data["province"],
|
||||
"personal.postal": data["postal"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherPhoto(c *fiber.Ctx) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
//Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
tid := c.FormValue("tid")
|
||||
if tid == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
// Get teacher
|
||||
var teacher models.Teacher
|
||||
findErr := TeacherCollection.FindOne(context.TODO(), bson.M{"school.tid": tid}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
// Collect image
|
||||
file, err := c.FormFile("image")
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be retrieved",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Get student photo
|
||||
var photo models.Photo
|
||||
findErr = ImageCollection.FindOne(context.TODO(), bson.M{"name": teacher.School.PhotoName}).Decode(&photo)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the student image could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
// Save image to local
|
||||
uniqueId := uuid.New()
|
||||
filename := strings.Replace(uniqueId.String(), "-", "", -1)
|
||||
fileExt := strings.Split(file.Filename, ".")[1]
|
||||
image := fmt.Sprintf("%s.%s", filename, fileExt)
|
||||
err = c.SaveFile(file, fmt.Sprintf("./database/images/%s", image))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be saved",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Read the entire file into a byte slice
|
||||
bytes, err := os.ReadFile(fmt.Sprintf("./database/images/%s", image))
|
||||
if err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be read",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
var base64Encoding string = toBase64(bytes)
|
||||
|
||||
// Update image name and base64 data
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"base64": base64Encoding,
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
_, updateErr := ImageCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"_id": photo.ID},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the image could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
// Remove local image
|
||||
os.Remove(fmt.Sprintf("./database/images/%s", image))
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher photo",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherEmail(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
var tid string
|
||||
var verifiedTeacher bool
|
||||
|
||||
verifiedAdmin, _ := AuthenticateUser(c, 3)
|
||||
verifiedTeacher, tid = AuthenticateUser(c, 2)
|
||||
// Ensure Authenticated admin sent request
|
||||
if !verifiedAdmin && !verifiedTeacher {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin or teacher can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
if verifiedAdmin && data["uid"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
} else if verifiedAdmin {
|
||||
tid = data["uid"]
|
||||
}
|
||||
|
||||
// Check required fields are included
|
||||
if data["email"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.email": data["email"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": tid},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher",
|
||||
})
|
||||
}
|
||||
|
||||
func UpdateTeacherName(c *fiber.Ctx) error {
|
||||
var data map[string]string
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
|
||||
if err := c.BodyParser(&data); err != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Failed to parse body",
|
||||
"error": err,
|
||||
})
|
||||
}
|
||||
|
||||
// Ensure Authenticated admin sent request
|
||||
if verified, _ := AuthenticateUser(c, 3); !verified {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "Unauthorized: only an admin can perform this action",
|
||||
})
|
||||
}
|
||||
|
||||
// Check id and names are included
|
||||
if data["uid"] == "" || data["firstname"] == "" || data["lastname"] == "" {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "missing required fields",
|
||||
})
|
||||
}
|
||||
|
||||
// Get teacher
|
||||
var teacher models.Teacher
|
||||
findErr := TeacherCollection.FindOne(ctx, bson.M{"school.tid": data["uid"]}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be found",
|
||||
"error": findErr,
|
||||
})
|
||||
}
|
||||
|
||||
var middlename string = ""
|
||||
|
||||
if data["middlename"] != "" {
|
||||
middlename = data["middlename"]
|
||||
}
|
||||
|
||||
update_time, _ := time.Parse(time.RFC3339, time.Now().Format(time.RFC3339))
|
||||
update := bson.M{
|
||||
"$set": bson.M{
|
||||
"personal.firstname": data["firstname"],
|
||||
"personal.middlename": middlename,
|
||||
"personal.lastname": data["lastname"],
|
||||
"updated_at": update_time,
|
||||
},
|
||||
}
|
||||
|
||||
_, updateErr := TeacherCollection.UpdateOne(
|
||||
ctx,
|
||||
bson.M{"school.tid": data["uid"]},
|
||||
update,
|
||||
)
|
||||
if updateErr != nil {
|
||||
cancel()
|
||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
|
||||
"success": false,
|
||||
"message": "the teacher could not be updated",
|
||||
"error": updateErr,
|
||||
})
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
return c.Status(fiber.StatusOK).JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "successfully updated teacher",
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,20 +1,34 @@
|
||||
module github.com/SowinskiBraeden/school-management-api
|
||||
|
||||
go 1.16
|
||||
go 1.19
|
||||
|
||||
require (
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible
|
||||
github.com/gofiber/fiber/v2 v2.26.0
|
||||
github.com/google/go-cmp v0.5.6 // indirect
|
||||
github.com/gofiber/fiber/v2 v2.36.0
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef
|
||||
github.com/joho/godotenv v1.3.0
|
||||
github.com/stretchr/testify v1.7.0 // indirect
|
||||
go.mongodb.org/mongo-driver v1.7.2
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
|
||||
golang.org/x/sys v0.0.0-20211205182925-97ca703d548d // indirect
|
||||
golang.org/x/text v0.3.7 // indirect
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
|
||||
github.com/joho/godotenv v1.4.0
|
||||
go.mongodb.org/mongo-driver v1.10.1
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/andybalholm/brotli v1.0.4 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/google/go-cmp v0.5.8 // indirect
|
||||
github.com/klauspost/compress v1.15.9 // indirect
|
||||
github.com/montanaflynn/stats v0.6.6 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/stretchr/testify v1.8.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.38.0 // indirect
|
||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.1 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.3 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a // indirect
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab // indirect
|
||||
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 // indirect
|
||||
golang.org/x/text v0.3.8 // indirect
|
||||
)
|
||||
@@ -1,155 +1,97 @@
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/andybalholm/brotli v1.0.2 h1:JKnhI/XQ75uFBTiuzXpzFrUriDPiZjlOSzh6wXogP0E=
|
||||
github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
|
||||
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
|
||||
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/gobuffalo/attrs v0.0.0-20190224210810-a9411de4debd/go.mod h1:4duuawTqi2wkkpB4ePgWMaai6/Kc6WEz83bhFwpHzj0=
|
||||
github.com/gobuffalo/depgen v0.0.0-20190329151759-d478694a28d3/go.mod h1:3STtPUQYuzV0gBVOY3vy6CfMm/ljR4pABfrTeHNLHUY=
|
||||
github.com/gobuffalo/depgen v0.1.0/go.mod h1:+ifsuy7fhi15RWncXQQKjWS9JPkdah5sZvtHc2RXGlg=
|
||||
github.com/gobuffalo/envy v1.6.15/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI=
|
||||
github.com/gobuffalo/envy v1.7.0/go.mod h1:n7DRkBerg/aorDM8kbduw5dN3oXGswK5liaSCx4T5NI=
|
||||
github.com/gobuffalo/flect v0.1.0/go.mod h1:d2ehjJqGOH/Kjqcoz+F7jHTBbmDb38yXA598Hb50EGs=
|
||||
github.com/gobuffalo/flect v0.1.1/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI=
|
||||
github.com/gobuffalo/flect v0.1.3/go.mod h1:8JCgGVbRjJhVgD6399mQr4fx5rRfGKVzFjbj6RE/9UI=
|
||||
github.com/gobuffalo/genny v0.0.0-20190329151137-27723ad26ef9/go.mod h1:rWs4Z12d1Zbf19rlsn0nurr75KqhYp52EAGGxTbBhNk=
|
||||
github.com/gobuffalo/genny v0.0.0-20190403191548-3ca520ef0d9e/go.mod h1:80lIj3kVJWwOrXWWMRzzdhW3DsrdjILVil/SFKBzF28=
|
||||
github.com/gobuffalo/genny v0.1.0/go.mod h1:XidbUqzak3lHdS//TPu2OgiFB+51Ur5f7CSnXZ/JDvo=
|
||||
github.com/gobuffalo/genny v0.1.1/go.mod h1:5TExbEyY48pfunL4QSXxlDOmdsD44RRq4mVZ0Ex28Xk=
|
||||
github.com/gobuffalo/gitgen v0.0.0-20190315122116-cc086187d211/go.mod h1:vEHJk/E9DmhejeLeNt7UVvlSGv3ziL+djtTr3yyzcOw=
|
||||
github.com/gobuffalo/gogen v0.0.0-20190315121717-8f38393713f5/go.mod h1:V9QVDIxsgKNZs6L2IYiGR8datgMhB577vzTDqypH360=
|
||||
github.com/gobuffalo/gogen v0.1.0/go.mod h1:8NTelM5qd8RZ15VjQTFkAW6qOMx5wBbW4dSCS3BY8gg=
|
||||
github.com/gobuffalo/gogen v0.1.1/go.mod h1:y8iBtmHmGc4qa3urIyo1shvOD8JftTtfcKi+71xfDNE=
|
||||
github.com/gobuffalo/logger v0.0.0-20190315122211-86e12af44bc2/go.mod h1:QdxcLw541hSGtBnhUc4gaNIXRjiDppFGaDqzbrBd3v8=
|
||||
github.com/gobuffalo/mapi v1.0.1/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc=
|
||||
github.com/gobuffalo/mapi v1.0.2/go.mod h1:4VAGh89y6rVOvm5A8fKFxYG+wIW6LO1FMTG9hnKStFc=
|
||||
github.com/gobuffalo/packd v0.0.0-20190315124812-a385830c7fc0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4=
|
||||
github.com/gobuffalo/packd v0.1.0/go.mod h1:M2Juc+hhDXf/PnmBANFCqx4DM3wRbgDvnVWeG2RIxq4=
|
||||
github.com/gobuffalo/packr/v2 v2.0.9/go.mod h1:emmyGweYTm6Kdper+iywB6YK5YzuKchGtJQZ0Odn4pQ=
|
||||
github.com/gobuffalo/packr/v2 v2.2.0/go.mod h1:CaAwI0GPIAv+5wKLtv8Afwl+Cm78K/I/VCm/3ptBN+0=
|
||||
github.com/gobuffalo/syncx v0.0.0-20190224160051-33c29581e754/go.mod h1:HhnNqWY95UYwwW3uSASeV7vtgYkT2t16hJgV3AEPUpw=
|
||||
github.com/gofiber/fiber/v2 v2.26.0 h1:Awnfqp3fqbZzV3wZWMRJ6Xo2U8X0Ls68M7tXjx52NcM=
|
||||
github.com/gofiber/fiber/v2 v2.26.0/go.mod h1:7efVWcBOZi1PyMWznnbitjnARPA7nYZxmQXJVod0bo0=
|
||||
github.com/gofiber/fiber/v2 v2.36.0 h1:1qLMe5rhXFLPa2SjK10Wz7WFgLwYi4TYg7XrjztJHqA=
|
||||
github.com/gofiber/fiber/v2 v2.36.0/go.mod h1:tgCr+lierLwLoVHHO/jn3Niannv34WRkQETU8wiL9fQ=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA=
|
||||
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
|
||||
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
|
||||
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
|
||||
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef h1:A9HsByNhogrvm9cWb28sjiS3i7tcKCkflWFEkHfuAgM=
|
||||
github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef/go.mod h1:lADxMC39cJJqL93Duh1xhAs4I2Zs8mKS89XWXFGp9cs=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
|
||||
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
|
||||
github.com/karrick/godirwalk v1.8.0/go.mod h1:H5KPZjojv4lE+QYImBI8xVtrBRgYrIVsaRPx4tDPEn4=
|
||||
github.com/karrick/godirwalk v1.10.3/go.mod h1:RoGL9dQei4vP9ilrpETWE8CLOZ1kiN0LhBygSwrAsHA=
|
||||
github.com/klauspost/compress v1.9.5/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A=
|
||||
github.com/klauspost/compress v1.13.4 h1:0zhec2I8zGnjWcKyLl6i3gPqKANCCn5e9xmviEEeX6s=
|
||||
github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
|
||||
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/klauspost/compress v1.15.9 h1:wKRjX6JRtDdrE9qwa4b/Cip7ACOshUI4smpCQanqjSY=
|
||||
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2/go.mod h1:Ld9puTsIW75CHf65OeIOkyKbteujpZVXDpWK6YGZbxE=
|
||||
github.com/markbates/safe v1.0.1/go.mod h1:nAqgmRi7cY2nqMc92/bSEeQA+R4OheNU2T1kNSCBdG0=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
|
||||
github.com/pelletier/go-toml v1.7.0/go.mod h1:vwGMzjaWMwyfHwgIBhI2YUM4fB6nL6lVAvS1LBMMhTE=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/montanaflynn/stats v0.6.6 h1:Duep6KMIDpY4Yo11iFsvyqJDyfzLF9+sndUKT+v64GQ=
|
||||
github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/sirupsen/logrus v1.4.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
|
||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
|
||||
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasthttp v1.32.0 h1:keswgWzyKyNIIjz2a7JmCYHOOIkRp6HMx9oTV6QrZWY=
|
||||
github.com/valyala/fasthttp v1.32.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus=
|
||||
github.com/valyala/fasthttp v1.38.0 h1:yTjSSNjuDi2PPvXY2836bIwLmiTS2T4T9p1coQshpco=
|
||||
github.com/valyala/fasthttp v1.38.0/go.mod h1:t/G+3rLek+CyY9bnIE+YlMRddxVAAGjhxndDB4i4C0I=
|
||||
github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8=
|
||||
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.0.2 h1:akYIkZ28e6A96dkWNJQu3nmCzH3YfwMPQExUYDaRv7w=
|
||||
github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs=
|
||||
github.com/xdg-go/stringprep v1.0.2 h1:6iq84/ryjjeRmMJwxutI51F2GIPlP5BfTvXHeYjyhBc=
|
||||
github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
|
||||
github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E=
|
||||
github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g=
|
||||
github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs=
|
||||
github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
|
||||
go.mongodb.org/mongo-driver v1.7.2 h1:pFttQyIiJUHEn50YfZgC9ECjITMT44oiN36uArf/OFg=
|
||||
go.mongodb.org/mongo-driver v1.7.2/go.mod h1:Q4oFMbo1+MSNqICAdYMlC/zSTrwCogR4R8NzkI+yfU8=
|
||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a h1:fZHgsYlfvtyqToslyjUt3VOPF4J7aK/3MPcK7xp3PDk=
|
||||
github.com/youmark/pkcs8 v0.0.0-20201027041543-1326539a0a0a/go.mod h1:ul22v+Nro/R083muKhosV54bj5niojjWZvU8xrevuH4=
|
||||
go.mongodb.org/mongo-driver v1.10.1 h1:NujsPveKwHaWuKUer/ceo9DzEe7HIj1SlJ6uvXZG0S4=
|
||||
go.mongodb.org/mongo-driver v1.10.1/go.mod h1:z4XpeoU6w+9Vht+jAFyLgVrD+jGSQQe0+CBWFHNiHt8=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190422162423-af44ce270edf/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
|
||||
golang.org/x/crypto v0.0.0-20200302210943-78000ba7a073/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa h1:zuSxTR4o9y82ebqCUJYNGJbGPo6sKVl54f/TVDObg1c=
|
||||
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190412183630-56d357773e84/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190419153524-e8e3143a4f4a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190531175056-4c3a928424d2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211205182925-97ca703d548d h1:FjkYO/PPp4Wi0EAUOVLxePm7qVW4r4ctbWpURyuOD0E=
|
||||
golang.org/x/sys v0.0.0-20211205182925-97ca703d548d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab h1:2QkjZIsXupsJbJIdSjjUOgWK3aEtzyuh2mPt3l/CkeU=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 h1:Q5284mrmYTpACcm+eAKjKJH48BBwSyfJqmmGDTtT8Vc=
|
||||
golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190329151228-23e29df326fe/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190416151739-9c9e1878f421/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190420181800-aa740d480789/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190531172133-b3315ee88b7d/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
)
|
||||
|
||||
const version string = "\nv0.8.8-Alpha"
|
||||
const version string = "\nv1.1.3-Beta"
|
||||
|
||||
func main() {
|
||||
fmt.Println(version)
|
||||
|
||||
+32
-12
@@ -1,16 +1,24 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/SowinskiBraeden/school-management-api/database"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var AdminCollection *mongo.Collection = database.OpenCollection(database.Client, "admins")
|
||||
|
||||
type Admin struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
FirstName string `json:"firstname" validate:"required"`
|
||||
@@ -24,9 +32,24 @@ type Admin struct {
|
||||
Updated_at time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (a *Admin) GenerateSchoolEmail() string {
|
||||
var email string = strings.ToLower(a.LastName) + "_" + strings.ToLower(string(a.FirstName[0])) + "@surreyschools.ca"
|
||||
// Add check to see if email already exists
|
||||
func (a *Admin) EmailExists(email string) bool {
|
||||
var admin Admin
|
||||
findErr := AdminCollection.FindOne(context.TODO(), bson.M{"account.schoolemail": email}).Decode(&admin)
|
||||
return findErr == nil
|
||||
}
|
||||
|
||||
func (a *Admin) GenerateSchoolEmail(offset int, lastEmail string) string {
|
||||
addr := os.Getenv("SYSTEM_EMAIL_ADDRESS")
|
||||
var email string = strings.ToLower(a.LastName) + "_" + strings.ToLower(string(a.FirstName[0])) + addr
|
||||
if offset > 0 && offset < len([]rune(a.FirstName))-1 {
|
||||
email = lastEmail[:strings.Index(lastEmail, "_")+offset+1] + strings.ToLower(string(a.FirstName[offset])) + addr
|
||||
}
|
||||
if offset == len([]rune(a.FirstName))-1 {
|
||||
email = strings.ToLower(a.LastName) + "_" + strings.ToLower(a.FirstName) + addr
|
||||
}
|
||||
if offset > len([]rune(a.FirstName))-1 {
|
||||
email = strings.ToLower(a.LastName) + "_" + strings.ToLower(a.FirstName) + strconv.Itoa(offset-len([]rune(a.FirstName))) + addr
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
@@ -35,15 +58,12 @@ func (s *Admin) HashPassword(password string) string {
|
||||
return string(hash)
|
||||
}
|
||||
|
||||
func (s *Admin) ComparePasswords(password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(s.Password), []byte(password))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
func (a *Admin) ComparePasswords(password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(a.Password), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (s *Admin) CheckPasswordStrength(password string) bool {
|
||||
func (a *Admin) CheckPasswordStrength(password string) bool {
|
||||
|
||||
var hasUpper bool = false
|
||||
for _, r := range password {
|
||||
@@ -59,14 +79,14 @@ func (s *Admin) CheckPasswordStrength(password string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper {
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper && len(password) >= 8 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Admin) GeneratePassword(passwordLength, minSpecialChar, minNum, minUpperCase int) string {
|
||||
func (a *Admin) GeneratePassword(passwordLength, minSpecialChar, minNum, minUpperCase int) string {
|
||||
var password strings.Builder
|
||||
|
||||
//Set special character
|
||||
|
||||
+3
-2
@@ -15,6 +15,7 @@ import (
|
||||
*/
|
||||
|
||||
type Id struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
CID string `bson:"cid"` // custom id for admin, teahcer or student
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
CID string `json:"cid"` // custom id for admin, teahcer or student
|
||||
ParentType int `json:"parenttype"` // A number representing the user (1: student, 2: teacher, 3: admin)
|
||||
}
|
||||
+26
-28
@@ -3,6 +3,7 @@ package models
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -17,12 +18,12 @@ import (
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
)
|
||||
|
||||
var lockerCollection *mongo.Collection = database.OpenCollection(database.Client, "lockers")
|
||||
var studentCollection *mongo.Collection = database.OpenCollection(database.Client, "students")
|
||||
var LockerCollection *mongo.Collection = database.OpenCollection(database.Client, "lockers")
|
||||
var StudentCollection *mongo.Collection = database.OpenCollection(database.Client, "students")
|
||||
|
||||
type Student struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
PersonalData struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
Personal struct {
|
||||
FirstName string `json:"firstname" validate:"required"`
|
||||
MiddleName string `json:"middlename"`
|
||||
LastName string `json:"lastname" validate:"required"`
|
||||
@@ -34,8 +35,8 @@ type Student struct {
|
||||
Postal string `json:"postal"`
|
||||
DOB string `json:"dob" validate:"required"`
|
||||
Contacts []string `json:"contacts"` // List of contact ID's rather than contact object
|
||||
} `json:"personaldata"`
|
||||
SchoolData struct {
|
||||
} `json:"personal"`
|
||||
School struct {
|
||||
GradeLevel float64 `json:"gradelevel" validate:"required"`
|
||||
SID string `json:"sid"` // Student ID
|
||||
PEN string `json:"ped"` // Personal Education Number
|
||||
@@ -43,21 +44,23 @@ type Student struct {
|
||||
Locker string `json:"-"` // Locker ID
|
||||
YOG int `json:"yog"` // Year of Graduation
|
||||
PhotoName string `json:"photoname"` // name of photo in db
|
||||
} `json:"schooldata"`
|
||||
AccountData struct {
|
||||
} `json:"School"`
|
||||
Account struct {
|
||||
VerifiedEmail bool `json:"verifiedemail"`
|
||||
SchoolEmail string `json:"schoolemail"`
|
||||
Password string `json:"-" validate:"min=10,max=32"`
|
||||
AccountDisabled bool `bson:"accountdisabled"`
|
||||
Alerted bool `bson:"alerted"`
|
||||
TempPassword bool `json:"temppassword"`
|
||||
Attempts int `json:"attempts"` // login attempts max 5
|
||||
HashHistory []string `json:"-"` // List of old hashed passwords (not including auto generated passwords)
|
||||
} `json:"accountdata"`
|
||||
} `json:"Account"`
|
||||
Created_at time.Time `json:"created_at"`
|
||||
Updated_at time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (s *Student) UsedPassword(password string) bool {
|
||||
for _, oldHash := range s.AccountData.HashHistory {
|
||||
for _, oldHash := range s.Account.HashHistory {
|
||||
if oldHash == s.HashPassword(password) {
|
||||
return true
|
||||
}
|
||||
@@ -72,33 +75,28 @@ func (s *Student) HashPassword(password string) string {
|
||||
|
||||
func (s *Student) EmailExists(email string) bool {
|
||||
var student Student
|
||||
findErr := studentCollection.FindOne(context.TODO(), bson.M{"accountdata.schoolemail": email}).Decode(&student)
|
||||
if findErr != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
findErr := StudentCollection.FindOne(context.TODO(), bson.M{"account.schoolemail": email}).Decode(&student)
|
||||
return findErr == nil
|
||||
}
|
||||
|
||||
func (s *Student) GenerateSchoolEmail(offset int, lastEmail string) string {
|
||||
var email string = strings.ToLower(string(s.PersonalData.FirstName[0])) + "." + strings.ToLower(s.PersonalData.LastName) + "@surreyschools.ca"
|
||||
if offset > 0 && offset < len([]rune(s.PersonalData.FirstName))-1 {
|
||||
email = lastEmail[:offset] + strings.ToLower(string(s.PersonalData.FirstName[offset])) + lastEmail[offset:]
|
||||
addr := os.Getenv("SYSTEM_EMAIL_ADDRESS")
|
||||
var email string = strings.ToLower(string(s.Personal.FirstName[0])) + "." + strings.ToLower(s.Personal.LastName) + addr
|
||||
if offset > 0 && offset < len([]rune(s.Personal.FirstName))-1 {
|
||||
email = lastEmail[:offset] + strings.ToLower(string(s.Personal.FirstName[offset])) + lastEmail[offset:] + addr
|
||||
}
|
||||
if offset == len([]rune(s.PersonalData.FirstName))-1 {
|
||||
email = strings.ToLower(s.PersonalData.FirstName) + "." + strings.ToLower(s.PersonalData.LastName) + "@surreyschools.ca"
|
||||
if offset == len([]rune(s.Personal.FirstName))-1 {
|
||||
email = strings.ToLower(s.Personal.FirstName) + "." + strings.ToLower(s.Personal.LastName) + addr
|
||||
}
|
||||
if offset > len([]rune(s.PersonalData.FirstName))-1 {
|
||||
email = strings.ToLower(s.PersonalData.FirstName) + "." + strings.ToLower(s.PersonalData.LastName) + strconv.Itoa(offset-len([]rune(s.PersonalData.FirstName))) + "@surreyschools.ca"
|
||||
if offset > len([]rune(s.Personal.FirstName))-1 {
|
||||
email = strings.ToLower(s.Personal.FirstName) + "." + strings.ToLower(s.Personal.LastName) + strconv.Itoa(offset-len([]rune(s.Personal.FirstName))) + addr
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
func (s *Student) ComparePasswords(password string) bool { //True: passwords match, False: no match
|
||||
valid := bcrypt.CompareHashAndPassword([]byte(s.AccountData.Password), []byte(password))
|
||||
if valid != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
valid := bcrypt.CompareHashAndPassword([]byte(s.Account.Password), []byte(password))
|
||||
return valid == nil
|
||||
}
|
||||
|
||||
func (s *Student) CheckPasswordStrength(password string) bool {
|
||||
@@ -117,7 +115,7 @@ func (s *Student) CheckPasswordStrength(password string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper {
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper && len(password) >= 8 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
|
||||
+24
-27
@@ -3,6 +3,7 @@ package models
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -23,11 +24,11 @@ var (
|
||||
allCharSet = lowerCharSet + upperCharSet + specialCharSet + numberSet
|
||||
)
|
||||
|
||||
var teacherCollection *mongo.Collection = database.OpenCollection(database.Client, "teachers")
|
||||
var TeacherCollection *mongo.Collection = database.OpenCollection(database.Client, "teachers")
|
||||
|
||||
type Teacher struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
PersonalData struct {
|
||||
ID primitive.ObjectID `bson:"_id"`
|
||||
Personal struct {
|
||||
FirstName string `json:"firstname" validate:"required"`
|
||||
MiddleName string `json:"middlename"`
|
||||
LastName string `json:"lastname" validate:"required"`
|
||||
@@ -37,26 +38,27 @@ type Teacher struct {
|
||||
Province string `json:"province"`
|
||||
Postal string `json:"postal"`
|
||||
DOB string `json:"dob" validate:"required"`
|
||||
} `json:"personaldata"`
|
||||
SchoolData struct {
|
||||
} `json:"personal"`
|
||||
School struct {
|
||||
TID string `json:"tid"` // Teacher ID
|
||||
Homeroom string `json:"homeroom"`
|
||||
PhotoName string `json:"photoname"` // name of photo in db
|
||||
} `json:"schooldata"`
|
||||
AccountData struct {
|
||||
} `json:"School"`
|
||||
Account struct {
|
||||
VerifiedEmail bool `json:"verifiedemail"`
|
||||
SchoolEmail string `json:"schoolemail"`
|
||||
Password string `json:"-" validate:"min=10,max=32"`
|
||||
AccountDisabled bool `bson:"accountdisabled"`
|
||||
TempPassword bool `json:"temppassword"`
|
||||
Attempts int `json:"attempts"` // login attempts max 5
|
||||
HashHistory []string `json:"-"` // List of old hashed passwords (not including auto generated passwords)
|
||||
} `json:"accountdata"`
|
||||
} `json:"Account"`
|
||||
Created_at time.Time `json:"created_at"`
|
||||
Updated_at time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (t *Teacher) UsedPassword(password string) bool {
|
||||
for _, oldHash := range t.AccountData.HashHistory {
|
||||
for _, oldHash := range t.Account.HashHistory {
|
||||
if oldHash == t.HashPassword(password) {
|
||||
return true
|
||||
}
|
||||
@@ -71,33 +73,28 @@ func (t *Teacher) HashPassword(password string) string {
|
||||
|
||||
func (t *Teacher) EmailExists(email string) bool {
|
||||
var teacher Teacher
|
||||
findErr := teacherCollection.FindOne(context.TODO(), bson.M{"accountdata.schoolemail": email}).Decode(&teacher)
|
||||
if findErr != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
findErr := TeacherCollection.FindOne(context.TODO(), bson.M{"account.schoolemail": email}).Decode(&teacher)
|
||||
return findErr == nil
|
||||
}
|
||||
|
||||
func (t *Teacher) GenerateSchoolEmail(offset int, lastEmail string) string {
|
||||
var email string = strings.ToLower(t.PersonalData.LastName) + "_" + strings.ToLower(string(t.PersonalData.FirstName[0])) + "@surreyschools.ca"
|
||||
if offset > 0 && offset < len([]rune(t.PersonalData.FirstName))-1 {
|
||||
email = lastEmail[:strings.Index(lastEmail, "_")+offset+1] + strings.ToLower(string(t.PersonalData.FirstName[offset])) + "@surreyschools.ca"
|
||||
addr := os.Getenv("SYSTEM_EMAIL_ADDRESS")
|
||||
var email string = strings.ToLower(t.Personal.LastName) + "_" + strings.ToLower(string(t.Personal.FirstName[0])) + addr
|
||||
if offset > 0 && offset < len([]rune(t.Personal.FirstName))-1 {
|
||||
email = lastEmail[:strings.Index(lastEmail, "_")+offset+1] + strings.ToLower(string(t.Personal.FirstName[offset])) + addr
|
||||
}
|
||||
if offset == len([]rune(t.PersonalData.FirstName))-1 {
|
||||
email = strings.ToLower(t.PersonalData.LastName) + "_" + strings.ToLower(t.PersonalData.FirstName) + "@surreyschools.ca"
|
||||
if offset == len([]rune(t.Personal.FirstName))-1 {
|
||||
email = strings.ToLower(t.Personal.LastName) + "_" + strings.ToLower(t.Personal.FirstName) + addr
|
||||
}
|
||||
if offset > len([]rune(t.PersonalData.FirstName))-1 {
|
||||
email = strings.ToLower(t.PersonalData.LastName) + "_" + strings.ToLower(t.PersonalData.FirstName) + strconv.Itoa(offset-len([]rune(t.PersonalData.FirstName))) + "@surreyschools.ca"
|
||||
if offset > len([]rune(t.Personal.FirstName))-1 {
|
||||
email = strings.ToLower(t.Personal.LastName) + "_" + strings.ToLower(t.Personal.FirstName) + strconv.Itoa(offset-len([]rune(t.Personal.FirstName))) + addr
|
||||
}
|
||||
return email
|
||||
}
|
||||
|
||||
func (t *Teacher) ComparePasswords(password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(t.AccountData.Password), []byte(password))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
err := bcrypt.CompareHashAndPassword([]byte(t.Account.Password), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (t *Teacher) CheckPasswordStrength(password string) bool {
|
||||
@@ -116,7 +113,7 @@ func (t *Teacher) CheckPasswordStrength(password string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper {
|
||||
if strings.ContainsAny(password, specialCharSet) && hasLower && hasUpper && len(password) >= 8 {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 36 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
+36
-30
@@ -2,6 +2,7 @@ package routes
|
||||
|
||||
import (
|
||||
"github.com/SowinskiBraeden/school-management-api/controllers"
|
||||
"github.com/SowinskiBraeden/school-management-api/controllers/update"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
@@ -27,28 +28,28 @@ func Setup(app *fiber.App) {
|
||||
app.Post(routerPrefix+"/student/login", controllers.StudentLogin)
|
||||
|
||||
// Update Student Handler
|
||||
app.Post(routerPrefix+"/student/updateName", controllers.UpdateStudentName)
|
||||
app.Post(routerPrefix+"/student/updateGradeLevel", controllers.UpdateStudentGradeLevel)
|
||||
app.Post(routerPrefix+"/student/updateHomeroom", controllers.UpdateStudentHomeroom)
|
||||
app.Post(routerPrefix+"/student/updateLocker", controllers.UpdateStudentLocker)
|
||||
app.Post(routerPrefix+"/studnet/updateYOG", controllers.UpdateStudentYOG)
|
||||
app.Post(routerPrefix+"/studnet/addContact", controllers.AddStudentContact)
|
||||
app.Post(routerPrefix+"/student/removeContact", controllers.RemoveStudentContact)
|
||||
app.Post(routerPrefix+"/student/updatePassword", controllers.UpdateStudentPassword)
|
||||
app.Post(routerPrefix+"/student/resetPassword", controllers.ResetStudentPassword)
|
||||
app.Post(routerPrefix+"/student/updateAddress", controllers.UpdateStudentAddress)
|
||||
app.Post(routerPrefix+"/student/updatePhoto", controllers.UpdateStudentPhoto)
|
||||
app.Post(routerPrefix+"/student/updateEmail", controllers.UpdateStudentEmail)
|
||||
app.Post(routerPrefix+"/student/updateName", update.UpdateStudentName)
|
||||
app.Post(routerPrefix+"/student/updateGradeLevel", update.UpdateStudentGradeLevel)
|
||||
app.Post(routerPrefix+"/student/updateHomeroom", update.UpdateStudentHomeroom)
|
||||
app.Post(routerPrefix+"/student/updateLocker", update.UpdateStudentLocker)
|
||||
app.Post(routerPrefix+"/studnet/updateYOG", update.UpdateStudentYOG)
|
||||
app.Post(routerPrefix+"/studnet/addContact", update.AddStudentContact)
|
||||
app.Post(routerPrefix+"/student/removeContact", update.RemoveStudentContact)
|
||||
app.Post(routerPrefix+"/student/updatePassword", update.UpdateStudentPassword)
|
||||
app.Post(routerPrefix+"/student/resetPassword", update.ResetStudentPassword)
|
||||
app.Post(routerPrefix+"/student/updateAddress", update.UpdateStudentAddress)
|
||||
app.Post(routerPrefix+"/student/updatePhoto", update.UpdateStudentPhoto)
|
||||
app.Post(routerPrefix+"/student/updateEmail", update.UpdateStudentEmail)
|
||||
|
||||
// Student Contact Handler
|
||||
app.Post(routerPrefix+"/student/createContact", controllers.CreateContact)
|
||||
app.Post(routerPrefix+"/student/contact/updateName", controllers.UpdateContactName)
|
||||
app.Post(routerPrefix+"/student/contact/updateAddress", controllers.UpdateContactAddress)
|
||||
app.Post(routerPrefix+"/student/contact/updateHomePhone", controllers.UpdateContactHomePhone)
|
||||
app.Post(routerPrefix+"/student/contact/updateWorkPhone", controllers.UpdateContactWorkPhone)
|
||||
app.Post(routerPrefix+"/student/contact/updateEmail", controllers.UpdateContactEmail)
|
||||
app.Post(routerPrefix+"/student/contact/updatePriority", controllers.UpdateContactPriority)
|
||||
app.Post(routerPrefix+"/student/contact/deleteContact", controllers.DeleteContact)
|
||||
app.Post(routerPrefix+"/contact/createContact", controllers.CreateContact)
|
||||
app.Post(routerPrefix+"/contact/updateName", update.UpdateContactName)
|
||||
app.Post(routerPrefix+"/contact/updateAddress", update.UpdateContactAddress)
|
||||
app.Post(routerPrefix+"/contact/updateHomePhone", update.UpdateContactHomePhone)
|
||||
app.Post(routerPrefix+"/contact/updateWorkPhone", update.UpdateContactWorkPhone)
|
||||
app.Post(routerPrefix+"/contact/updateEmail", update.UpdateContactEmail)
|
||||
app.Post(routerPrefix+"/contact/updatePriority", update.UpdateContactPriority)
|
||||
app.Post(routerPrefix+"/contact/deleteContact", controllers.DeleteContact)
|
||||
|
||||
// Teacher Authentication Handler
|
||||
app.Get(routerPrefix+"/teacher", controllers.Teacher)
|
||||
@@ -56,13 +57,13 @@ func Setup(app *fiber.App) {
|
||||
app.Post(routerPrefix+"/teacher/login", controllers.TeacherLogin)
|
||||
|
||||
// Teacher Update Handler
|
||||
app.Post(routerPrefix+"/teacher/updatePassword", controllers.UpdateTeacherPassword)
|
||||
app.Post(routerPrefix+"/teacher/updateAddress", controllers.UpdateTeacherAddress)
|
||||
app.Post(routerPrefix+"/teacher/updatePhoto", controllers.UpdateTeacherPhoto)
|
||||
app.Post(routerPrefix+"/teacher/updateName", controllers.UpdateTeacherName)
|
||||
app.Post(routerPrefix+"/teacher/updateHomeroom", controllers.UpdateTeacherHomeroom)
|
||||
app.Post(routerPrefix+"/teacher/updateEmail", controllers.UpdateTeacherEmail)
|
||||
app.Post(routerPrefix+"/teacher/resetPassword", controllers.ResetTeacherPassword)
|
||||
app.Post(routerPrefix+"/teacher/updatePassword", update.UpdateTeacherPassword)
|
||||
app.Post(routerPrefix+"/teacher/updateAddress", update.UpdateTeacherAddress)
|
||||
app.Post(routerPrefix+"/teacher/updatePhoto", update.UpdateTeacherPhoto)
|
||||
app.Post(routerPrefix+"/teacher/updateName", update.UpdateTeacherName)
|
||||
app.Post(routerPrefix+"/teacher/updateHomeroom", update.UpdateTeacherHomeroom)
|
||||
app.Post(routerPrefix+"/teacher/updateEmail", update.UpdateTeacherEmail)
|
||||
app.Post(routerPrefix+"/teacher/resetPassword", update.ResetTeacherPassword)
|
||||
|
||||
// General Routes
|
||||
app.Post(routerPrefix+"/logout", controllers.Logout)
|
||||
@@ -72,10 +73,15 @@ func Setup(app *fiber.App) {
|
||||
app.Post(routerPrefix+"/admin/create", controllers.CreateAdmin)
|
||||
app.Post(routerPrefix+"/admin/login", controllers.AdminLogin)
|
||||
|
||||
// Admin Update Handler
|
||||
app.Post(routerPrefix+"/admin/updateName", update.UpdateAdminName)
|
||||
app.Post(routerPrefix+"/admin/updateEmail", update.UpdateAdminEmail)
|
||||
app.Post(routerPrefix+"/admin/updatePassword", update.UpdateAdminPassword)
|
||||
|
||||
// General Command Handling
|
||||
app.Post(routerPrefix+"/admin/updateLockerCombo", controllers.UpdateLockerCombo)
|
||||
app.Post(routerPrefix+"/admin/renableStudent", controllers.RemoveStudentsDisabled)
|
||||
app.Post(routerPrefix+"/admin/renableTeacher", controllers.RemoveTeachersDisabled)
|
||||
app.Post(routerPrefix+"/admin/updateLockerCombo", update.UpdateLockerCombo)
|
||||
app.Post(routerPrefix+"/admin/enableStudent", update.RemoveStudentsDisabled)
|
||||
app.Post(routerPrefix+"/admin/enableTeacher", update.RemoveTeachersDisabled)
|
||||
|
||||
// Delete Handler
|
||||
app.Post(routerPrefix+"/remove/student", controllers.RemoveStudent)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
dot_import_whitelist = ["github.com/SowinskiBraeden/school-management-api/controllers"]
|
||||
@@ -0,0 +1,83 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width"/>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<title>Account Disabled</title>
|
||||
<style type="text/css">
|
||||
body{
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
min-width: 100%;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
table{
|
||||
margin: 50px 0 50px 0;
|
||||
}
|
||||
.header{
|
||||
height: 40px;
|
||||
text-align: center;
|
||||
text-transform: uppercase;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.content{
|
||||
height: 100px;
|
||||
font-size: 18px;
|
||||
line-height: 30px;
|
||||
}
|
||||
.subscribe{
|
||||
height: 70px;
|
||||
text-align: center;
|
||||
}
|
||||
.button{
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
font-family: sans-serif;
|
||||
font-weight: bold;
|
||||
padding: 0 30px 0 30px;
|
||||
}
|
||||
.button a{
|
||||
color: #FFFFFF;
|
||||
text-decoration: none;
|
||||
}
|
||||
.buttonwrapper{
|
||||
margin: 0 auto;
|
||||
}
|
||||
.footer{
|
||||
text-transform: uppercase;
|
||||
text-align: center;
|
||||
height: 40px;
|
||||
font-size: 14px;
|
||||
font-style: italic;
|
||||
}
|
||||
.footer a{
|
||||
color: #000000;
|
||||
text-decoration: none;
|
||||
font-style: normal;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body bgcolor="#009587">
|
||||
<table bgcolor="#FFFFFF" width="100%" border="0" cellspacing="0" cellpadding="0">
|
||||
<tr class="header">
|
||||
<td style="padding: 40px;">
|
||||
Uh Oh! Account Disabled!
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="content">
|
||||
<td style="padding:10px;">
|
||||
<p>
|
||||
Hi <b>{{ .username }}</b>, <br/>
|
||||
Your account has been disabled due to too many incorrect login attempts, please contact an admin to enable your account.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="footer">
|
||||
<td style="padding: 40px;">
|
||||
This is an automated system email // DO NOT REPLY
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,95 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width"/>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<title>Account Registered</title>
|
||||
<style type="text/css">
|
||||
body{
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
min-width: 100%;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
table{
|
||||
margin: 50px 0 50px 0;
|
||||
}
|
||||
.header{
|
||||
height: 40px;
|
||||
text-align: center;
|
||||
text-transform: uppercase;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.content{
|
||||
height: 100px;
|
||||
font-size: 18px;
|
||||
line-height: 30px;
|
||||
}
|
||||
.subscribe{
|
||||
height: 70px;
|
||||
text-align: center;
|
||||
}
|
||||
.button{
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
font-family: sans-serif;
|
||||
font-weight: bold;
|
||||
padding: 0 30px 0 30px;
|
||||
}
|
||||
.button a{
|
||||
color: #FFFFFF;
|
||||
text-decoration: none;
|
||||
}
|
||||
.buttonwrapper{
|
||||
margin: 0 auto;
|
||||
}
|
||||
.footer{
|
||||
text-transform: uppercase;
|
||||
text-align: center;
|
||||
height: 40px;
|
||||
font-size: 14px;
|
||||
font-style: italic;
|
||||
}
|
||||
.footer a{
|
||||
color: #000000;
|
||||
text-decoration: none;
|
||||
font-style: normal;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body bgcolor="#009587">
|
||||
<table bgcolor="#FFFFFF" width="100%" border="0" cellspacing="0" cellpadding="0">
|
||||
<tr class="header">
|
||||
<td style="padding: 40px;">
|
||||
Account Registered
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="content">
|
||||
<td style="padding:10px;">
|
||||
<p>
|
||||
Hi <b>{{ .username }}</b>, <br/>
|
||||
Your account has been registered into the system. You can now log into your account.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="subscribe">
|
||||
<td style="padding: 20px 0 0 0;">
|
||||
<h3>Your {{ .userType }} ID is:</h3>
|
||||
<table bgcolor="#009587" border="0" cellspacing="0" cellpadding="0" class="buttonwrapper">
|
||||
<tr>
|
||||
<td class="button" height="45">
|
||||
{{ .id }}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="footer">
|
||||
<td style="padding: 40px;">
|
||||
This is an automated system email // DO NOT REPLY
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,95 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width"/>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<title>Password has been changed</title>
|
||||
<style type="text/css">
|
||||
body{
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
min-width: 100%;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
table{
|
||||
margin: 50px 0 50px 0;
|
||||
}
|
||||
.header{
|
||||
height: 40px;
|
||||
text-align: center;
|
||||
text-transform: uppercase;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.content{
|
||||
height: 100px;
|
||||
font-size: 18px;
|
||||
line-height: 30px;
|
||||
}
|
||||
.subscribe{
|
||||
height: 70px;
|
||||
text-align: center;
|
||||
}
|
||||
.button{
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
font-family: sans-serif;
|
||||
font-weight: bold;
|
||||
padding: 0 30px 0 30px;
|
||||
}
|
||||
.button a{
|
||||
color: #FFFFFF;
|
||||
text-decoration: none;
|
||||
}
|
||||
.buttonwrapper{
|
||||
margin: 0 auto;
|
||||
}
|
||||
.footer{
|
||||
text-transform: uppercase;
|
||||
text-align: center;
|
||||
height: 40px;
|
||||
font-size: 14px;
|
||||
font-style: italic;
|
||||
}
|
||||
.footer a{
|
||||
color: #000000;
|
||||
text-decoration: none;
|
||||
font-style: normal;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body bgcolor="#009587">
|
||||
<table bgcolor="#FFFFFF" width="100%" border="0" cellspacing="0" cellpadding="0">
|
||||
<tr class="header">
|
||||
<td style="padding: 40px;">
|
||||
Password Change!
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="content">
|
||||
<td style="padding:10px;">
|
||||
<p>
|
||||
Hi <b>{{ .username }}</b>, <br/>
|
||||
Your password has been changed by the system.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="subscribe">
|
||||
<td style="padding: 20px 0 0 0;">
|
||||
<h3>Your new password is:</h3>
|
||||
<table bgcolor="#009587" border="0" cellspacing="0" cellpadding="0" class="buttonwrapper">
|
||||
<tr>
|
||||
<td class="button" height="45">
|
||||
{{ .password }}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="footer">
|
||||
<td style="padding: 40px;">
|
||||
This is an automated system email // DO NOT REPLY
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,83 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width"/>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<title>Password has been changed</title>
|
||||
<style type="text/css">
|
||||
body{
|
||||
margin: 0 auto;
|
||||
padding: 0;
|
||||
min-width: 100%;
|
||||
font-family: sans-serif;
|
||||
}
|
||||
table{
|
||||
margin: 50px 0 50px 0;
|
||||
}
|
||||
.header{
|
||||
height: 40px;
|
||||
text-align: center;
|
||||
text-transform: uppercase;
|
||||
font-size: 24px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.content{
|
||||
height: 100px;
|
||||
font-size: 18px;
|
||||
line-height: 30px;
|
||||
}
|
||||
.subscribe{
|
||||
height: 70px;
|
||||
text-align: center;
|
||||
}
|
||||
.button{
|
||||
text-align: center;
|
||||
font-size: 18px;
|
||||
font-family: sans-serif;
|
||||
font-weight: bold;
|
||||
padding: 0 30px 0 30px;
|
||||
}
|
||||
.button a{
|
||||
color: #FFFFFF;
|
||||
text-decoration: none;
|
||||
}
|
||||
.buttonwrapper{
|
||||
margin: 0 auto;
|
||||
}
|
||||
.footer{
|
||||
text-transform: uppercase;
|
||||
text-align: center;
|
||||
height: 40px;
|
||||
font-size: 14px;
|
||||
font-style: italic;
|
||||
}
|
||||
.footer a{
|
||||
color: #000000;
|
||||
text-decoration: none;
|
||||
font-style: normal;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body bgcolor="#009587">
|
||||
<table bgcolor="#FFFFFF" width="100%" border="0" cellspacing="0" cellpadding="0">
|
||||
<tr class="header">
|
||||
<td style="padding: 40px;">
|
||||
Password Change!
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="content">
|
||||
<td style="padding:10px;">
|
||||
<p>
|
||||
Hi <b>{{ .username }}</b>, <br/>
|
||||
Your password has been changed by you. If you did not change your password, contact an admin immediatley!
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="footer">
|
||||
<td style="padding: 40px;">
|
||||
This is an automated system email // DO NOT REPLY
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,13 +0,0 @@
|
||||
# Testing
|
||||
|
||||
Hello there! If you are in this part of the codespace, I have cleaned it up compared to the
|
||||
original codespace. The algorithms have been moved out of `tinker.py` into their own python
|
||||
script from version 1 to 3. These are in the `/scheduleGenerator` folder. I suggest to look
|
||||
at the latest work in `v3.py` where the algorithm has come a long way. Using real 2018 course
|
||||
selection data from my school I am able to test the script to its full potential compared to
|
||||
V1 and V2.
|
||||
|
||||
V3 has a entirely different approach from V1 and V2, that you can read about at the top of
|
||||
the function in `v3.py`. The function is broken up into 6 steps, each step is labeled within
|
||||
the function with a comment, giving a brief explination of what that step contributes to the
|
||||
algorithm.
|
||||
@@ -1,21 +0,0 @@
|
||||
import json
|
||||
|
||||
f = open('./output/students.json')
|
||||
students = json.load(f)
|
||||
f.close()
|
||||
|
||||
couldnt_resolve = 0
|
||||
missing_classes = 0
|
||||
acceptable_missing_classes = 0
|
||||
|
||||
for student in students:
|
||||
blocks = [student["schedule"][block] for block in student["schedule"]]
|
||||
conflicts = sum(1 for b in blocks if len(b)>1)
|
||||
if conflicts == 0 and student["classes"] == student["expectedClasses"]: continue
|
||||
if conflicts > 0: couldnt_resolve += 1
|
||||
if (student["expectedClasses"] - 2) <= student["classes"] < student["expectedClasses"]: acceptable_missing_classes += 1
|
||||
if student["classes"] < (student["expectedClasses"] - 2): missing_classes += 1
|
||||
|
||||
print(f"Couldn't resolve : {couldnt_resolve}/{len(students)} - {round((couldnt_resolve/len(students))*100, 2)}%")
|
||||
print(f"Missing classes : {missing_classes}/{len(students)} - {round((missing_classes/len(students))*100, 2)}%")
|
||||
print(f"Acceptable Missing classes : {acceptable_missing_classes}/{len(students)} - {round((acceptable_missing_classes/len(students))*100, 2)}%")
|
||||
@@ -1,197 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from util.courses import mockCourses, activeCourses # Fake courses
|
||||
from util.mockStudents import generateMockStudents # Generate fake students
|
||||
import json
|
||||
|
||||
|
||||
'''
|
||||
Block 1-4 is first semester while
|
||||
block 5-8 is second semester
|
||||
'''
|
||||
|
||||
'''
|
||||
schedule example:
|
||||
schedule: {
|
||||
"block1": "className",
|
||||
"block2": "className",
|
||||
"block3": "className",
|
||||
"block4": "className"
|
||||
"block5": "className",
|
||||
"block6": "className",
|
||||
"block7": "className",
|
||||
"block8": "className"
|
||||
}
|
||||
'''
|
||||
|
||||
'''
|
||||
running example:
|
||||
running: {
|
||||
"block1": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block2": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block3": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block4": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block5": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block6": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block7": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block8": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}}
|
||||
}
|
||||
'''
|
||||
|
||||
# Error 1: No classes in schedule can fit this student
|
||||
# Error 2: No more room in schedule for another class
|
||||
|
||||
minReq, median, classCap, blockClassLimit = 18, 24, 30, 12
|
||||
activeCourses = {}
|
||||
running = {
|
||||
"block1": {},
|
||||
"block2": {},
|
||||
"block3": {},
|
||||
"block4": {},
|
||||
"block5": {},
|
||||
"block6": {},
|
||||
"block7": {},
|
||||
"block8": {}
|
||||
}
|
||||
|
||||
# Currently V1 has an average of 9.4% success rate, with an avverage of 90.6% error rate
|
||||
def generateScheduleV1(mockStudents, mockCourses):
|
||||
# Collect data and calculate schedules
|
||||
for student in mockStudents:
|
||||
# Tally class request
|
||||
for request in student["requests"]:
|
||||
mockCourses[request]["totalrequests"] += 1
|
||||
mockCourses[request]["studentindexes"].append(mockStudents.index(student))
|
||||
# Add course to active list if enough requests
|
||||
if mockCourses[request]["totalrequests"] > minReq and mockCourses[request]["code"] not in activeCourses: activeCourses[mockCourses[request]["code"]] = mockCourses[request]
|
||||
|
||||
for student in mockStudents:
|
||||
alternateOffset = len(student["requests"])-8
|
||||
alternateIndex = 8
|
||||
for i in range(len(student["requests"])-alternateOffset): # Subtract x classes as they are alternatives
|
||||
currentCourse = student["requests"][i]
|
||||
generate = True
|
||||
while generate:
|
||||
# If class is allowed to run
|
||||
if currentCourse in activeCourses:
|
||||
blockIndex = 1
|
||||
courseNum = 1
|
||||
getFreeBlock = True
|
||||
while getFreeBlock:
|
||||
block = f"block{blockIndex}"
|
||||
cname = f"{mockCourses[currentCourse]['name']}-{courseNum}"
|
||||
if cname in running[block]:
|
||||
if student["schedule"][block] == "": # Add student to class
|
||||
if len(running[block][cname]["students"]) < classCap:
|
||||
running[block][cname]["students"].append(student["name"])
|
||||
student["schedule"][block] = cname
|
||||
getFreeBlock = False
|
||||
else: # Find next available class or create new one
|
||||
if blockIndex == 8: # No available classes
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # No more alterantive
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
getFreeBlock = False
|
||||
else:
|
||||
if (mockCourses[currentCourse]["teachers"] - courseNum) > 0:
|
||||
courseNum += 1
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
else:
|
||||
if blockIndex == 8: # No available classes
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
err1 += 1
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # No more alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
getFreeBlock = False
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
else:
|
||||
if blockIndex == 8:
|
||||
# Class does not exists
|
||||
# Create new class in first available slot
|
||||
blockNum = 1
|
||||
while True:
|
||||
newBlock = f"block{blockNum}"
|
||||
if cname not in running[newBlock] and len(running[newBlock]) < blockClassLimit:
|
||||
if student["schedule"][newBlock] == "": # Add student to class
|
||||
running[newBlock][cname] = {
|
||||
"name": mockCourses[currentCourse]["name"],
|
||||
"students": [student["name"]]
|
||||
}
|
||||
student["schedule"][newBlock] = cname
|
||||
break
|
||||
else:
|
||||
if blockNum == 8:
|
||||
# All student classes have been filled
|
||||
break
|
||||
else:
|
||||
blockNum += 1
|
||||
courseNum = 1
|
||||
else:
|
||||
if blockNum == 8:
|
||||
# No room in school for more classes
|
||||
# print(f"\nError 2: No more room in school for another class")
|
||||
break
|
||||
else:
|
||||
if (mockCourses[currentCourse]["teachers"] - courseNum) > 0:
|
||||
courseNum += 1
|
||||
else:
|
||||
blockNum += 1
|
||||
courseNum = 1
|
||||
break
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
break
|
||||
elif currentCourse not in activeCourses:
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # Out of alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
|
||||
return running
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Processing...")
|
||||
|
||||
mockStudents = generateMockStudents(400)
|
||||
timetable = {}
|
||||
timetable["Version"] = 1
|
||||
timetable["timetable"] = generateScheduleV1(mockStudents, mockCourses)
|
||||
|
||||
with open("../output/timetable.json", "w") as outfile:
|
||||
json.dump(timetable, outfile, indent=2)
|
||||
|
||||
print("Done")
|
||||
@@ -1,213 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
from util.courses import mockCourses, activeCourses # Fake courses
|
||||
from util.mockStudents import generateMockStudents # Generate fake students
|
||||
import math
|
||||
import json
|
||||
|
||||
|
||||
'''
|
||||
Block 1-4 is first semester while
|
||||
block 5-8 is second semester
|
||||
'''
|
||||
|
||||
'''
|
||||
schedule example:
|
||||
schedule: {
|
||||
"block1": "className",
|
||||
"block2": "className",
|
||||
"block3": "className",
|
||||
"block4": "className"
|
||||
"block5": "className",
|
||||
"block6": "className",
|
||||
"block7": "className",
|
||||
"block8": "className"
|
||||
}
|
||||
'''
|
||||
|
||||
'''
|
||||
running example:
|
||||
running: {
|
||||
"block1": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block2": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block3": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block4": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block5": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block6": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block7": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}},
|
||||
"block8": {classCode:{"className":name,"students":[student Name]},classCode:{"className":name,"students":[student Name]}}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
minReq, median, classCap, blockClassLimit = 18, 24, 30, 12
|
||||
mockStudents = []
|
||||
activeCourses = {}
|
||||
running = {
|
||||
"block1": {},
|
||||
"block2": {},
|
||||
"block3": {},
|
||||
"block4": {},
|
||||
"block5": {},
|
||||
"block6": {},
|
||||
"block7": {},
|
||||
"block8": {}
|
||||
}
|
||||
|
||||
|
||||
# Currently V2 has an average of 0.35% success rate, with an avverage of 99.65% error rate
|
||||
def generateScheduleV2(mockStudents, mockCourses):
|
||||
# Collect data and calculate schedules
|
||||
for student in mockStudents:
|
||||
# Tally class request
|
||||
for request in student["requests"]:
|
||||
mockCourses[request]["totalrequests"] += 1
|
||||
mockCourses[request]["studentindexes"].append(mockStudents.index(student))
|
||||
# Add course to active list if enough requests
|
||||
if mockCourses[request]["totalrequests"] > minReq and mockCourses[request]["code"] not in activeCourses: activeCourses[mockCourses[request]["code"]] = mockCourses[request]
|
||||
|
||||
# calculate # of times to run class
|
||||
for i in range(len(activeCourses)):
|
||||
index = list(activeCourses)[i]
|
||||
classRunCount = math.floor(activeCourses[index]["totalrequests"] / classCap)
|
||||
# If there is minReq+ requests left, 1 more class could be run
|
||||
if (activeCourses[index]["totalrequests"] % classCap) > minReq: classRunCount += 1
|
||||
activeCourses[index]["classRunCount"] = classRunCount
|
||||
|
||||
newBlockIndex = 1
|
||||
newCourseNum = 1
|
||||
while classRunCount > 0:
|
||||
block = f"block{newBlockIndex}"
|
||||
cname = f"{activeCourses[index]['name']}-{newCourseNum}"
|
||||
if cname not in running[block] and len(running[block]) < blockClassLimit:
|
||||
# Generate class and sub 1 from classRunCount
|
||||
running[block][cname] = {
|
||||
"name": activeCourses[index]["name"],
|
||||
"students": []
|
||||
}
|
||||
classRunCount -= 1
|
||||
else:
|
||||
if newBlockIndex == 8:
|
||||
if (activeCourses[index]["teachers"] - newCourseNum) > 0:
|
||||
newCourseNum += 1
|
||||
newBlockIndex = 1
|
||||
else:
|
||||
# No room in school for more classes
|
||||
# print(f"\nError 2: No more room in school for another class")
|
||||
classRunCount = 0
|
||||
else: newBlockIndex += 1
|
||||
|
||||
for student in mockStudents:
|
||||
alternateOffset = len(student["requests"])-8
|
||||
alternateIndex = 8
|
||||
for i in range(len(student["requests"])-alternateOffset): # Subtract x classes as they are alternatives
|
||||
currentCourse = student["requests"][i]
|
||||
generate = True
|
||||
courseNum = 1
|
||||
while generate:
|
||||
# If class is allowed to run
|
||||
if currentCourse in activeCourses:
|
||||
blockIndex = 1
|
||||
getFreeBlock = True
|
||||
cname = f"{mockCourses[currentCourse]['name']}-{courseNum}"
|
||||
while getFreeBlock:
|
||||
block = f"block{blockIndex}"
|
||||
if cname in running[block]:
|
||||
if student["schedule"][block] == "": # Add student to class
|
||||
if len(running[block][cname]["students"]) < classCap:
|
||||
running[block][cname]["students"].append(student["name"])
|
||||
student["schedule"][block] = cname
|
||||
getFreeBlock = False
|
||||
else: # Find next available class or create new one
|
||||
if blockIndex == 8: # No available classes
|
||||
if (activeCourses[index]["teachers"] - newCourseNum) > 0:
|
||||
newCourseNum += 1
|
||||
newBlockIndex = 1
|
||||
else:
|
||||
# No room in school for more classes
|
||||
# print(f"\nError 2: No more room in school for another class")
|
||||
classRunCount = 0
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # No more alterantive
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
getFreeBlock = False
|
||||
else: blockIndex += 1
|
||||
else:
|
||||
if blockIndex == 8: # No available classes
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # No more alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
getFreeBlock = False
|
||||
else:
|
||||
if (mockCourses[currentCourse]["teachers"] - courseNum) > 0:
|
||||
courseNum += 1
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
else:
|
||||
if blockIndex == 8:
|
||||
# Class does not exists
|
||||
# Resort to alternative
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # Out of alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
break
|
||||
else:
|
||||
if (mockCourses[currentCourse]["teachers"] - courseNum) > 0:
|
||||
courseNum += 1
|
||||
else:
|
||||
blockIndex += 1
|
||||
courseNum = 1
|
||||
break
|
||||
elif currentCourse not in activeCourses:
|
||||
if len(student["requests"]) == 8:
|
||||
# This student never had any alternatives
|
||||
# How to solve?
|
||||
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
else:
|
||||
if alternateIndex <= (len(student["requests"]) - 1):
|
||||
currentCourse = student["requests"][alternateIndex]
|
||||
alternateIndex += 1
|
||||
else: # Out of alternatives
|
||||
# print(f"\nError 1: No more available classes for student {student['name']}")
|
||||
generate = False
|
||||
|
||||
return running
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Processing...")
|
||||
|
||||
mockStudents = generateMockStudents(400)
|
||||
timetable = {}
|
||||
timetable["Version"] = 2
|
||||
timetable["timetable"] = generateScheduleV2(mockStudents, mockCourses)
|
||||
|
||||
with open("../output/timetable.json", "w") as outfile:
|
||||
json.dump(timetable, outfile, indent=2)
|
||||
|
||||
print("Done")
|
||||
@@ -1,613 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
from inspect import currentframe
|
||||
|
||||
from click import pass_context
|
||||
|
||||
# Import from custom utilities
|
||||
from util.mockStudents import getSampleStudents
|
||||
from util.generateCourses import getSampleCourses
|
||||
|
||||
|
||||
'''
|
||||
Block 1-5 is first semester while
|
||||
block 6-10 is second semester
|
||||
|
||||
|
||||
schedule example:
|
||||
schedule: {
|
||||
"block1": "className",
|
||||
"block2": "className",
|
||||
"block3": "className",
|
||||
...
|
||||
}
|
||||
|
||||
|
||||
running example:
|
||||
running: {
|
||||
"block1": {
|
||||
classCode: {
|
||||
"className": name,
|
||||
"students": [student Name]
|
||||
},
|
||||
classCode: {
|
||||
"className": name,
|
||||
"students": [student Name]
|
||||
}
|
||||
},
|
||||
...
|
||||
}
|
||||
'''
|
||||
|
||||
def getLineNumber(): return currentframe().f_back.f_lineno
|
||||
|
||||
# Takes in information to create or add a new conflict
|
||||
# Returns if the particular student has a previous error
|
||||
def newConflict(pupilNum: str, email: str, type: str, code: str, description: str, logs: dict) -> bool:
|
||||
exists = True if pupilNum in logs else False
|
||||
if exists: logs[pupilNum].append({
|
||||
"Pupil #": pupilNum,
|
||||
"Email": email,
|
||||
"Type": type,
|
||||
"Code": code,
|
||||
"Conflict": description
|
||||
})
|
||||
else:
|
||||
logs[pupilNum] = [{
|
||||
"Pupil #": pupilNum,
|
||||
"Email": email,
|
||||
"Type": type,
|
||||
"Code": code,
|
||||
"Conflict": description
|
||||
}]
|
||||
return exists
|
||||
|
||||
minReq, median, classCap = 18, 24, 30
|
||||
activeCourses = {}
|
||||
running = {
|
||||
"block1": {},
|
||||
"block2": {},
|
||||
"block3": {},
|
||||
"block4": {},
|
||||
"block5": {},
|
||||
"block6": {},
|
||||
"block7": {},
|
||||
"block8": {},
|
||||
"block9": {},
|
||||
"block10": {}
|
||||
}
|
||||
|
||||
# These are the codes for Flex (spare) blocks
|
||||
# Semester 1 and 2
|
||||
flex = ["XAT--12A-S", "XAT--12B-S"]
|
||||
|
||||
# V3 differs a lot by V1/2 as it does not focus on fitting the classes
|
||||
# into the time table first.
|
||||
# It starts by trying to get all classes full and give all students a full class list.
|
||||
# Then it starts to attempt to fit all classes into a timetable, making corretions along
|
||||
# the way. Corrections being moving a students class
|
||||
def generateScheduleV3(
|
||||
students: list,
|
||||
courses: dict,
|
||||
blockClassLimit: int=40,
|
||||
studentsDir: str="../output/students.json",
|
||||
conflictsDir: str="../output/conflicts.json"
|
||||
) -> dict[str, dict]:
|
||||
|
||||
def equal(l: list) -> list: # Used to equalize list of numbers
|
||||
q,r = divmod(sum(l),len(l))
|
||||
return [q+1]*r + [q]*(len(l)-r)
|
||||
|
||||
|
||||
# Step 1 - Calculate which classes can run
|
||||
for student in students:
|
||||
# Tally class request
|
||||
for request in (request for request in student["requests"] if not request["alt"] and request["CrsNo"] not in flex):
|
||||
code = request["CrsNo"]
|
||||
courses[code]["Requests"] += 1
|
||||
# Add course to active list if enough requests
|
||||
if courses[code]["Requests"] > minReq and courses[code]["CrsNo"] not in activeCourses:
|
||||
activeCourses[code] = courses[code]
|
||||
|
||||
|
||||
# Step 2 - Generate empty classes
|
||||
allClassRunCounts = []
|
||||
courseRunInfo = {} # Generated now, used in step 4
|
||||
emptyClasses = {} # List of all classes with how many students should be entered during step 3
|
||||
# calculate # of times to run class
|
||||
for i in range(len(activeCourses)):
|
||||
index = list(activeCourses)[i]
|
||||
if index not in emptyClasses: emptyClasses[index] = {}
|
||||
classRunCount = math.floor(activeCourses[index]["Requests"] / median)
|
||||
remaining = activeCourses[index]["Requests"] % median
|
||||
|
||||
# Put # of classRunCount classes in emptyClasses
|
||||
for j in range(classRunCount):
|
||||
emptyClasses[index][f"{index}-{j}"] = {
|
||||
"CrsNo": index,
|
||||
"Description": activeCourses[index]["Description"],
|
||||
"expectedLen": median # Number of students expected in this class / may be altered
|
||||
}
|
||||
|
||||
# If remaining fit in open slots in existing classes
|
||||
if remaining <= classRunCount * (classCap - median):
|
||||
# Equally disperse remaining into existing classes
|
||||
while remaining > 0:
|
||||
for j in range(classRunCount):
|
||||
if remaining == 0: break
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] += 1
|
||||
remaining -= 1
|
||||
|
||||
# If we can create a class using remaining, but no other classes
|
||||
# exists, create class, and do not equalize
|
||||
elif remaining >= minReq:
|
||||
# Create a class using remaining
|
||||
emptyClasses[index][f"{index}-{classRunCount}"] = {
|
||||
"CrsNo": index,
|
||||
"Description": activeCourses[index]["Description"],
|
||||
"expectedLen": remaining
|
||||
}
|
||||
|
||||
classRunCount += 1
|
||||
if classRunCount >= 2:
|
||||
# Equalize (level) class expectedLen's
|
||||
expectedLengths = [emptyClasses[index][f"{index}-{j}"]["expectedLen"] for j in range(classRunCount)]
|
||||
newExpectedLens = equal(expectedLengths)
|
||||
for j in range(len(newExpectedLens)):
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] = newExpectedLens[j]
|
||||
|
||||
# Else if we can't fit remaining in open slots in existing classes
|
||||
# and it is unable to create its own class,
|
||||
# and requiered number to make a class is less than the max number we can provide from existing classes
|
||||
elif minReq - remaining < classRunCount * (median - minReq):
|
||||
# Take 1 from each class till min requirment met
|
||||
for j in range(classRunCount):
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] -= 1
|
||||
remaining += 1
|
||||
if remaining == minReq: break
|
||||
|
||||
# Create a class using remaining
|
||||
emptyClasses[index][f"{index}-{classRunCount}"] = {
|
||||
"CrsNo": index,
|
||||
"Description": activeCourses[index]["Description"],
|
||||
"expectedLen": remaining
|
||||
}
|
||||
|
||||
classRunCount += 1
|
||||
|
||||
# Equalize (level) class expectedLen's
|
||||
expectedLengths = [emptyClasses[index][f"{index}-{j}"]["expectedLen"] for j in range(classRunCount)]
|
||||
newExpectedLens = equal(expectedLengths)
|
||||
for j in range(len(newExpectedLens)):
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] = newExpectedLens[j]
|
||||
|
||||
else:
|
||||
# In the case that the remaining requests are unable to be resolved
|
||||
# Fill as many requests into class as possible, any left that can't fit,
|
||||
# Will need to be ignored so later we can fold them into their alternative
|
||||
# choices
|
||||
for j in range(classRunCount):
|
||||
if emptyClasses[index][f"{index}-{j}"]["expectedLen"] < classCap and remaining > 0:
|
||||
emptyClasses[index][f"{index}-{j}"]["expectedLen"] += 1
|
||||
remaining -= 1
|
||||
|
||||
courseRunInfo[index] = {
|
||||
"Total": classRunCount,
|
||||
"CrsNo": index
|
||||
}
|
||||
allClassRunCounts.append(classRunCount)
|
||||
|
||||
|
||||
# Step 3 Fill emptyClasses with Students
|
||||
selectedCourses = {}
|
||||
tempStudents = list(students)
|
||||
|
||||
while len(tempStudents) > 0:
|
||||
student = tempStudents[random.randint(0, len(tempStudents)-1)]
|
||||
|
||||
alternates = [request for request in student["requests"] if request["alt"]]
|
||||
for request in (request for request in student["requests"] if not request["alt"] and request["CrsNo"] not in flex):
|
||||
course = request["CrsNo"]
|
||||
getAvailableCourse = True
|
||||
isAlt = False
|
||||
while getAvailableCourse:
|
||||
if course in emptyClasses:
|
||||
# if course exists, get first available class
|
||||
for cname in emptyClasses[course]:
|
||||
if cname in selectedCourses:
|
||||
if isAlt and emptyClasses[course][cname]["expectedLen"] < classCap:
|
||||
emptyClasses[course][cname]["expectedLen"] += 1
|
||||
if len(selectedCourses[cname]["students"]) < emptyClasses[course][cname]["expectedLen"]:
|
||||
# Class exists with room for student
|
||||
selectedCourses[cname]["students"].append({
|
||||
"Pupil #": student["Pupil #"],
|
||||
"index": student["studentIndex"]
|
||||
})
|
||||
getAvailableCourse = False
|
||||
break
|
||||
elif len(selectedCourses[cname]["students"]) == emptyClasses[course][cname]["expectedLen"]:
|
||||
# If class is full, and is last class of that course
|
||||
if cname[len(cname)-1] == f"{len(emptyClasses[course])-1}":
|
||||
if len(alternates) > 0:
|
||||
# Use alternate
|
||||
course = alternates[0]["CrsNo"]
|
||||
alternates.remove(alternates[0])
|
||||
isAlt = True
|
||||
break
|
||||
else:
|
||||
# Force break loop, ignore and let an admin
|
||||
# handle options to solve for missing class
|
||||
getAvailableCourse = False
|
||||
break
|
||||
elif cname not in selectedCourses:
|
||||
selectedCourses[cname] = {
|
||||
"students": [{
|
||||
"Pupil #": student["Pupil #"],
|
||||
"index": student["studentIndex"]
|
||||
}],
|
||||
"CrsNo": course,
|
||||
"Description": courses[course]["Description"]
|
||||
}
|
||||
getAvailableCourse = False
|
||||
break
|
||||
|
||||
elif course not in emptyClasses:
|
||||
if len(alternates) > 0:
|
||||
# Use alternate
|
||||
course = alternates[0]["CrsNo"]
|
||||
alternates.remove(alternates[0])
|
||||
isAlt = True
|
||||
else:
|
||||
# Force break loop, ignore and let an admin
|
||||
# handle options to solve for missing class
|
||||
getAvailableCourse = False
|
||||
|
||||
students[student["studentIndex"]]["remainingAlts"] = alternates
|
||||
tempStudents.remove(student)
|
||||
|
||||
|
||||
# Step 4 - Attempt to fit classes into timetable
|
||||
def stepIndex(offset: int, stepType: int) -> int:
|
||||
# stepType 0 is for stepping between first and second semester
|
||||
if stepType == 0:
|
||||
if offset == 0 or offset == -4: return 5
|
||||
else: return -4
|
||||
|
||||
# stepType 1 is for stepping between second and first semester
|
||||
elif stepType == 1:
|
||||
if offset == 0 or offset == 6: return -5
|
||||
else: return 6
|
||||
|
||||
# Return Error if code is altered to cause error
|
||||
else: raise SystemExit(f"Invalid 'stepType' in func 'stepIndex' line {getLineNumber()}")
|
||||
|
||||
while len(allClassRunCounts) > 0:
|
||||
# Get highest resource class (most times run)
|
||||
index = allClassRunCounts.index(min(allClassRunCounts))
|
||||
course = list(courseRunInfo)[index]
|
||||
|
||||
# Tally first and second semester
|
||||
sem1, sem2 = 0, 0
|
||||
sem1List, sem2List = {}, {}
|
||||
for i in range(1, 6):
|
||||
sem1 += len(running[f"block{i}"])
|
||||
sem1List[f"block{i}"] = running[f"block{i}"]
|
||||
for i in range(5, 11):
|
||||
sem2 += len(running[f"block{i}"])
|
||||
sem2List[f"block{i}"] = running[f"block{i}"]
|
||||
|
||||
# If there is more than one class Running
|
||||
if allClassRunCounts[index] > 1:
|
||||
blockIndex = 0 if sem1 <= sem2 else 5
|
||||
stepType = 0 if sem1 <= sem2 else 1
|
||||
offset = 0
|
||||
|
||||
# Spread classes throughout both semesters
|
||||
for i in range(courseRunInfo[course]["Total"]):
|
||||
cname = f"{course}-{i}"
|
||||
classInserted = False
|
||||
while not classInserted:
|
||||
|
||||
blockIndex += offset
|
||||
if len(running[list(running)[blockIndex]]) < blockClassLimit:
|
||||
running[list(running)[blockIndex]][cname] = {
|
||||
"CrsNo": course,
|
||||
"Description": emptyClasses[course][cname]["Description"],
|
||||
"students": selectedCourses[cname]["students"]
|
||||
}
|
||||
allClassRunCounts[index] -= 1
|
||||
classInserted = True
|
||||
|
||||
offset = stepIndex(offset, stepType)
|
||||
|
||||
if blockIndex >= 9:
|
||||
blockIndex = 0 if sem1 <= sem2 else 5
|
||||
offset = 0
|
||||
|
||||
# If the class only runs once, place in semester with least classes
|
||||
elif allClassRunCounts[index] == 1:
|
||||
# Equally disperse into semesters classes
|
||||
semBlocks = []
|
||||
offset = 1
|
||||
|
||||
# If sem1 is less than or equal to sem2, add to sem1
|
||||
if sem1 <= sem2:
|
||||
for block in sem1List:
|
||||
semBlocks.append(len(block))
|
||||
|
||||
# If sem2 is less than sem1, add to sem2
|
||||
elif sem1 > sem2:
|
||||
offset = 5
|
||||
for block in sem2List:
|
||||
semBlocks.append(len(block))
|
||||
|
||||
# Get block with least classes
|
||||
leastBlock = semBlocks.index(min(semBlocks))
|
||||
cname = f"{course}-0"
|
||||
|
||||
running[f"block{leastBlock+offset}"][course] = {
|
||||
"CrsNo": course,
|
||||
"Description": emptyClasses[course][cname]["Description"],
|
||||
"students": selectedCourses[cname]["students"],
|
||||
}
|
||||
|
||||
allClassRunCounts[index] -= 1
|
||||
|
||||
# Remove course when fully inserted
|
||||
if allClassRunCounts[index] == 0:
|
||||
allClassRunCounts.remove(allClassRunCounts[index])
|
||||
courseRunInfo.pop(list(courseRunInfo)[index])
|
||||
|
||||
|
||||
# Step 5 - Fill student schedule
|
||||
for block in running:
|
||||
for cname in running[block]:
|
||||
for student in running[block][cname]["students"]:
|
||||
students[student["index"]]["schedule"][block].append(cname)
|
||||
students[student["index"]]["classes"] += 1
|
||||
|
||||
|
||||
# Step 6 - Evaluate, move students to fix conflicts
|
||||
conflictLogs = {}
|
||||
criticalCount, acceptableCount = 0, 0
|
||||
c_mc_count, c_cr_count, a_mc_count = 0, 0, 0
|
||||
studentsCritical, studentsAcceptable = 0, 0
|
||||
|
||||
for student in students:
|
||||
initialBlocks = [student["schedule"][block] for block in student["schedule"]]
|
||||
conflicts = sum(1 for b in initialBlocks if len(b)>1)
|
||||
hasConflicts = True if conflicts > 0 else False
|
||||
|
||||
# If there is no conflicts
|
||||
# and classes inserted to is equal to expectedClasses
|
||||
# or classes the student is inserted to is missing
|
||||
# no more than two classes:
|
||||
# continue to next student
|
||||
if not hasConflicts and student["classes"] == student["expectedClasses"]: continue
|
||||
elif not hasConflicts and (student["expectedClasses"]-2) <= student["classes"] < student["expectedClasses"]:
|
||||
a_mc_count += 1
|
||||
acceptableCount += 1
|
||||
if not newConflict(student["Pupil #"], "", "Acceptable", "A-MC", "Missing 1-2 Classses", conflictLogs): studentsAcceptable += 1
|
||||
continue
|
||||
|
||||
studentData = {
|
||||
"Pupil #": student["Pupil #"],
|
||||
"index": student["studentIndex"]
|
||||
}
|
||||
|
||||
# If we are unable to solve, we add to exceptions
|
||||
# and keep trying to resolve the rest of the schedule
|
||||
exceptions = []
|
||||
|
||||
while hasConflicts:
|
||||
# Check if conflicts have been resolved
|
||||
blocks = [student["schedule"][block] for block in student["schedule"]]
|
||||
# If there is exceptions, make them look normal in blocks
|
||||
# list to ginore them when looking for clashes, and not to
|
||||
# accidently overwrite while evaluating other classes
|
||||
if len(exceptions) > 0:
|
||||
for i in range(len(blocks)):
|
||||
if i in exceptions: blocks[i] = ['EXPT']
|
||||
conflicts = sum(1 for b in blocks if len(b)>1)
|
||||
|
||||
if conflicts == 0: hasConflicts = False
|
||||
|
||||
elif conflicts > 0:
|
||||
|
||||
blockLens = [len(block) for block in blocks]
|
||||
freeBlocks = [index for index in range(len(blocks)) if len(blocks[index]) == 0]
|
||||
|
||||
clashIndex = blockLens.index(max(blockLens))
|
||||
blockOut = f"block{clashIndex+1}"
|
||||
classIndex = 0
|
||||
done, advancedConflict = False, False
|
||||
|
||||
while not done:
|
||||
classOut = blocks[clashIndex][classIndex]
|
||||
found = False
|
||||
for index in freeBlocks:
|
||||
if found: break
|
||||
if index != clashIndex:
|
||||
blockIn = list(running)[index]
|
||||
for cname in running[blockIn]:
|
||||
if cname[:-2] == classOut[:-2] and len(running[blockIn][cname]["students"]) < classCap:
|
||||
|
||||
# Update records
|
||||
student["schedule"][blockOut].remove(classOut)
|
||||
student["schedule"][blockIn].append(cname)
|
||||
|
||||
running[blockOut][classOut]["students"].remove(studentData)
|
||||
running[blockIn][cname]["students"].append(studentData)
|
||||
|
||||
found = True
|
||||
break
|
||||
|
||||
if not found:
|
||||
if classIndex < len(blocks[clashIndex])-1: classIndex += 1
|
||||
elif classIndex == len(blocks[clashIndex])-1:
|
||||
classIndex = 0
|
||||
advancedConflict = True
|
||||
done = True
|
||||
else:
|
||||
print(f"Fatal error ({getLineNumber()}): Impossible error")
|
||||
continue
|
||||
|
||||
elif found: done = True
|
||||
|
||||
if advancedConflict:
|
||||
attemptResolve = True
|
||||
classOutIndex = 0
|
||||
while attemptResolve:
|
||||
foundSolution = False
|
||||
newClassOut = blocks[clashIndex][classOutIndex]
|
||||
for blockIndex in range(len(running)):
|
||||
if foundSolution: break
|
||||
if blockIndex != clashIndex and blockIndex not in exceptions:
|
||||
for cname in running[list(running)[blockIndex]]:
|
||||
if cname[:-2] == newClassOut[:-2]:
|
||||
blockIn = f"block{blockIndex+1}"
|
||||
if blockIndex in freeBlocks:
|
||||
if len(running[blockIn][cname]["students"]) < classCap:
|
||||
# In the rare or impossible case a student was not inserted to a class
|
||||
# And it weren't full, insert them into the class
|
||||
student["schedule"][blockOut].remove(newClassOut)
|
||||
student["schedule"][blockIn].append(cname)
|
||||
|
||||
running[blockOut][newClassOut]["students"].remove(studentData)
|
||||
running[blockIn][cname]["students"].append(studentData)
|
||||
foundSolution = True
|
||||
break
|
||||
|
||||
elif len(blocks[blockIndex]) == 1:
|
||||
oClassOut = blocks[blockIndex][0]
|
||||
found_oBlockSolution = False
|
||||
for oBlockIndex in range(len(running)):
|
||||
if found_oBlockSolution: break
|
||||
if oBlockIndex != clashIndex and oBlockIndex not in exceptions and oBlockIndex in freeBlocks:
|
||||
for ocname in running[list(running)[oBlockIndex]]:
|
||||
if ocname[:-2] == oClassOut[:-2]:
|
||||
oBlockIn = f"block{oBlockIndex+1}"
|
||||
if len(running[oBlockIn][ocname]["students"]) < classCap:
|
||||
student["schedule"][blockOut].remove(newClassOut)
|
||||
student["schedule"][blockIn].append(cname)
|
||||
student["schedule"][blockIn].remove(oClassOut)
|
||||
student["schedule"][oBlockIn].append(ocname)
|
||||
|
||||
running[blockOut][newClassOut]["students"].remove(studentData)
|
||||
running[blockIn][cname]["students"].append(studentData)
|
||||
running[blockIn][oClassOut]["students"].remove(studentData)
|
||||
running[oBlockIn][ocname]["students"].append(studentData)
|
||||
|
||||
found_oBlockSolution = True
|
||||
break
|
||||
|
||||
|
||||
if not found_oBlockSolution:
|
||||
exceptions.append(clashIndex)
|
||||
criticalCount += 1
|
||||
c_cr_count += 1
|
||||
if not newConflict(student["Pupil #"], "", "Critial", "C-CR", "Couldn't Resolve", conflictLogs): studentsCritical += 1
|
||||
|
||||
foundSolution = True
|
||||
break
|
||||
|
||||
if not foundSolution:
|
||||
if classOutIndex < len(blocks[clashIndex]) - 1: classOutIndex += 1
|
||||
elif classOutIndex == len(blocks[clashIndex]) - 1:
|
||||
if len(student["remainingAlts"]) > 0:
|
||||
exceptions.append(clashIndex)
|
||||
criticalCount += 1
|
||||
c_cr_count += 1
|
||||
if not newConflict(student["Pupil #"], "", "Critical", "C-CR", "Couldn't Resolve", conflictLogs): studentsCritical += 1
|
||||
|
||||
attemptResolve = False
|
||||
# Attempt to use alt
|
||||
elif len(student["remainingAlts"]) == 0:
|
||||
exceptions.append(clashIndex)
|
||||
criticalCount += 1
|
||||
c_cr_count += 1
|
||||
if not newConflict(student["Pupil #"], "", "Critical", "C-CR", "Couldn't Resolve", conflictLogs): studentsCritical += 1
|
||||
|
||||
attemptResolve = False
|
||||
else: print("Impossible - Thanos")
|
||||
elif foundSolution:
|
||||
attemptResolve = False
|
||||
|
||||
else:
|
||||
print(f"Fatal error ({getLineNumber()}): Impossible error")
|
||||
continue
|
||||
|
||||
metSelfRequirements = True if student["classes"] == student["expectedClasses"] else False
|
||||
while not metSelfRequirements:
|
||||
|
||||
if (student["expectedClasses"] - 2) <= student["classes"] < student["expectedClasses"]:
|
||||
a_mc_count += 1
|
||||
acceptableCount += 1
|
||||
if not newConflict(student["Pupil #"], "", "Acceptable", "A-MC", "Missing 1-2 Classses", conflictLogs): studentsAcceptable += 1
|
||||
break
|
||||
|
||||
elif student["classes"] < (student["expectedClasses"] - 2):
|
||||
# Difference between classes inserted to and
|
||||
# expected classes is too great, attempt to fix
|
||||
if student["Pupil #"] in conflictLogs:
|
||||
c_mc_count += 1
|
||||
criticalCount += 1
|
||||
if not newConflict(student["Pupil #"], "", "Critical", "C-MC", "Missing too many Classses", conflictLogs): studentsCritical += 1
|
||||
|
||||
break
|
||||
|
||||
else:
|
||||
print(f"Fatal error ({getLineNumber()}): Impossible error")
|
||||
continue
|
||||
|
||||
finalConflictLogs = {
|
||||
"Conflicts": conflictLogs,
|
||||
"Critical": {
|
||||
"Total": criticalCount,
|
||||
"Students": studentsCritical,
|
||||
"Errors": [{
|
||||
"Total": c_mc_count,
|
||||
"Description": "Missing too many Classes",
|
||||
"Code": "C-MC"
|
||||
}, {
|
||||
"Total": c_cr_count,
|
||||
"Description": "Couldn't Resolve",
|
||||
"Code": "C-CR"
|
||||
}]
|
||||
},
|
||||
"Acceptable": {
|
||||
"Total": acceptableCount,
|
||||
"Students": studentsAcceptable,
|
||||
"Errors": [{
|
||||
"Total": a_mc_count,
|
||||
"Description": "Missing 1-2 Classes",
|
||||
"Code": "A-MC"
|
||||
}]
|
||||
}
|
||||
}
|
||||
|
||||
# Update Student records
|
||||
with open(studentsDir, "w") as outfile:
|
||||
json.dump(students, outfile, indent=2)
|
||||
|
||||
# Log Conflict to records
|
||||
with open(conflictsDir, "w") as outfile:
|
||||
json.dump(finalConflictLogs, outfile, indent=2)
|
||||
|
||||
return running
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Processing...")
|
||||
|
||||
sampleStudents = getSampleStudents(True)
|
||||
samplemockCourses = getSampleCourses(True)
|
||||
timetable = {}
|
||||
timetable["Version"] = 3
|
||||
timetable["timetable"] = generateScheduleV3(sampleStudents, samplemockCourses)
|
||||
|
||||
with open("../output/timetable.json", "w") as outfile:
|
||||
json.dump(timetable, outfile, indent=2)
|
||||
|
||||
print("Done")
|
||||
@@ -1,98 +0,0 @@
|
||||
#!/usr/bin/python3
|
||||
from prettytable import PrettyTable
|
||||
from typing import Tuple
|
||||
import json
|
||||
import sys
|
||||
|
||||
# Import required utilities
|
||||
from util.mockStudents import generateMockStudents, getSampleStudents
|
||||
from util.generateCourses import getSampleCourses
|
||||
from util.courses import mockCourses
|
||||
|
||||
# Import Algorithms
|
||||
from scheduleGenerator.generator_v1 import generateScheduleV1
|
||||
from scheduleGenerator.generator_v2 import generateScheduleV2
|
||||
from scheduleGenerator.generator_v3 import generateScheduleV3
|
||||
|
||||
def errorOutput(students) -> Tuple[PrettyTable, dict, dict]:
|
||||
# Error Table calulation / output
|
||||
f = open('./output/conflicts.json')
|
||||
conflicts = json.load(f)
|
||||
f.close()
|
||||
totalCritical = conflicts["Critical"]["Students"]
|
||||
totalAcceptable = conflicts["Acceptable"]["Students"]
|
||||
|
||||
t = PrettyTable(['Type', 'Error %', 'Success %', 'Student Error Ratio'])
|
||||
|
||||
errorsC = round(totalCritical / len(students) * 100, 2)
|
||||
successC = round(100 - errorsC, 2)
|
||||
errorsA = round(totalAcceptable / len(students) * 100, 2)
|
||||
successA = round(100 - errorsA, 2)
|
||||
|
||||
t.add_row(['Critical', f"{errorsC} %", f"{successC} %", f"{totalCritical}/{len(students)} Students"])
|
||||
t.add_row(['Acceptable', f"{errorsA} %", f"{successA} %", f"{totalAcceptable}/{len(students)} Students"])
|
||||
|
||||
return t, conflicts["Critical"], conflicts["Acceptable"]
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
if len(sys.argv) == 1:
|
||||
print("Missing argument")
|
||||
exit()
|
||||
|
||||
if sys.argv[1].upper() == 'V1':
|
||||
print("Processing...")
|
||||
|
||||
mockStudents = generateMockStudents(400)
|
||||
timetable = {}
|
||||
timetable["Version"] = 1
|
||||
timetable["timetable"] = generateScheduleV1(mockStudents, mockCourses)
|
||||
|
||||
elif sys.argv[1].upper() == 'V2':
|
||||
print("Processing...")
|
||||
|
||||
mockStudents = generateMockStudents(400)
|
||||
timetable = {}
|
||||
timetable["Version"] = 2
|
||||
timetable["timetable"] = generateScheduleV2(mockStudents, mockCourses)
|
||||
|
||||
|
||||
elif sys.argv[1].upper() == 'V3':
|
||||
|
||||
print("Processing...\n")
|
||||
|
||||
sampleStudents = getSampleStudents("./sample_data/course_selection_data.csv", True)
|
||||
samplemockCourses = getSampleCourses("./sample_data/course_selection_data.csv", True)
|
||||
timetable = {}
|
||||
timetable["Version"] = 3
|
||||
timetable["timetable"] = generateScheduleV3(sampleStudents, samplemockCourses, 40, "./output/students.json", "./output/conflicts.json")
|
||||
|
||||
errors, _, _ = errorOutput(sampleStudents)
|
||||
print(errors)
|
||||
|
||||
elif sys.argv[1].upper() == "ERRORS":
|
||||
f = open('./output/students.json')
|
||||
studentData = json.load(f)
|
||||
f.close()
|
||||
errors, critical, acceptable = errorOutput(studentData)
|
||||
print()
|
||||
print(errors)
|
||||
|
||||
print(f"\n{critical['Total']} critical errors")
|
||||
for i in range(len(critical["Errors"])):
|
||||
print(f"x{critical['Errors'][i]['Total']} {critical['Errors'][i]['Code']} Errors: Critical - {critical['Errors'][i]['Description']}")
|
||||
|
||||
print(f"\n{acceptable['Total']} acceptable errors")
|
||||
for i in range(len(acceptable["Errors"])):
|
||||
print(f"x{acceptable['Errors'][i]['Total']} {acceptable['Errors'][i]['Code']} Errors: Critical - {acceptable['Errors'][i]['Description']}")
|
||||
|
||||
exit()
|
||||
|
||||
else:
|
||||
print("Invalid argument")
|
||||
exit()
|
||||
|
||||
with open("./output/timetable.json", "w") as outfile:
|
||||
json.dump(timetable, outfile, indent=2)
|
||||
|
||||
print("\nDone")
|
||||
@@ -1,222 +0,0 @@
|
||||
# Fake sample data
|
||||
|
||||
mockCourses = {
|
||||
"P-CL": {
|
||||
"name": "Pre-Calculus",
|
||||
"code": "P-CL",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"CL": {
|
||||
"name": "Calculus",
|
||||
"code": "CL",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"EN-CW": {
|
||||
"name": "English: Creative Writing",
|
||||
"code": "EN-CW",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"EN-LS": {
|
||||
"name": "English: Literary Studies",
|
||||
"code": "EN-LS",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"EN-C": {
|
||||
"name": "English: Compisition",
|
||||
"code": "EN-C",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"S-J": {
|
||||
"name": "Social Justice",
|
||||
"code": "S-J",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"S-H": {
|
||||
"name": "History",
|
||||
"code": "S-H",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"S-P": {
|
||||
"name": "Psychology",
|
||||
"code": "S-P",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"SC-P": {
|
||||
"name": "Physics",
|
||||
"code": "SC-P",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"SC-B": {
|
||||
"name": "Biology",
|
||||
"code": "SC-B",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"SC-C": {
|
||||
"name": "Chemistry",
|
||||
"code": "SC-C",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"SC-ES": {
|
||||
"name": "Earth Science",
|
||||
"code": "SC-ES",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"M": {
|
||||
"name": "Music",
|
||||
"code": "M",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"CH": {
|
||||
"name": "Choir",
|
||||
"code": "CH",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"DN": {
|
||||
"name": "Dance",
|
||||
"code": "DN",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"CS": {
|
||||
"name": "Computer Science",
|
||||
"code": "CS",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"GD": {
|
||||
"name": "Game Development",
|
||||
"code": "GD",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"WW": {
|
||||
"name": "Woodwork",
|
||||
"code": "WW",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"MW": {
|
||||
"name": "MetwalWork",
|
||||
"code": "MW",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"M-WP": {
|
||||
"name": "Math: Workplace",
|
||||
"code": "M-WP",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"M-F": {
|
||||
"name": "Math: Foundations",
|
||||
"code": "M-F",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"BN": {
|
||||
"name": "Band",
|
||||
"code": "BN",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"TH": {
|
||||
"name": "Theatre",
|
||||
"code": "TH",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
},
|
||||
"VD-P": {
|
||||
"name": "Video Production",
|
||||
"code": "VD-P",
|
||||
"credits": 4,
|
||||
"gradelevel": 11,
|
||||
"totalrequests": 0,
|
||||
"studentindexes": [],
|
||||
"teachers": 3
|
||||
}
|
||||
}
|
||||
|
||||
activeCourses = {}
|
||||
@@ -1,36 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import csv
|
||||
|
||||
realCourses = {}
|
||||
|
||||
# Get all courses from real sample data
|
||||
def getSampleCourses(data_dir, log=False) -> dict:
|
||||
with open(data_dir, newline='') as csvfile:
|
||||
reader = csv.DictReader(csvfile)
|
||||
for row in reader:
|
||||
exists = False
|
||||
for course in realCourses:
|
||||
exists = True if realCourses[course]["CrsNo"] == row["CrsNo"] else False
|
||||
if exists: break
|
||||
if not exists:
|
||||
realCourses[row["CrsNo"]] = {
|
||||
"CrsNo": row["CrsNo"],
|
||||
"Requests": 0,
|
||||
"Description": row["Description"],
|
||||
"Credits": 4,
|
||||
"students": []
|
||||
}
|
||||
|
||||
if log:
|
||||
with open("./output/realCourses.json", "w") as outfile:
|
||||
json.dump(realCourses, outfile, indent=2)
|
||||
|
||||
return realCourses
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
courseSet: dict = getSampleCourses("../sample_data/course_selection_data.csv")
|
||||
|
||||
with open("../output/realCourses.json", "w") as outfile:
|
||||
json.dump(courseSet, outfile, indent=2)
|
||||
@@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
import random
|
||||
import names
|
||||
import json
|
||||
import csv
|
||||
import sys
|
||||
from util.courses import mockCourses
|
||||
|
||||
flex= ["XAT--12A-S", "XAT--12B-S"]
|
||||
|
||||
mockStudents: list[dict] = []
|
||||
|
||||
# Generate n students for mock data
|
||||
def generateMockStudents(n: int) -> list[dict]:
|
||||
for _ in range(n):
|
||||
newStudent = {
|
||||
"name": names.get_full_name(),
|
||||
"requests": [], # list of class codes
|
||||
"schedule": {
|
||||
"block1": "",
|
||||
"block2": "",
|
||||
"block3": "",
|
||||
"block4": "",
|
||||
"block5": "",
|
||||
"block6": "",
|
||||
"block7": "",
|
||||
"block8": ""
|
||||
}
|
||||
}
|
||||
# Get list of random class choices with no repeats
|
||||
# 8 primary choices, 2 secondary choices
|
||||
courseSelection = random.sample(range(0, len(mockCourses)), 10)
|
||||
for courseNum in courseSelection:
|
||||
newStudent["requests"].append(list(mockCourses)[courseNum])
|
||||
mockStudents.append(newStudent)
|
||||
|
||||
return mockStudents
|
||||
|
||||
|
||||
# sort real sample data into usable dictionary
|
||||
def getSampleStudents(data_dir: str, log: bool = False) -> list[dict]:
|
||||
with open(data_dir, newline='') as csvfile:
|
||||
reader = csv.DictReader(csvfile)
|
||||
for row in reader:
|
||||
exists = False
|
||||
for student in mockStudents:
|
||||
exists = True if student["Pupil #"] == row["Pupil #"] else False
|
||||
if exists: break
|
||||
alternate = True if row["Alternate?"] == 'TRUE' else False
|
||||
if exists:
|
||||
if len(mockStudents[student["studentIndex"]]["requests"]) >= 10 and not alternate and row["CrsNo"] not in flex: alternate = True
|
||||
mockStudents[student["studentIndex"]]["requests"].append({
|
||||
"CrsNo": row["CrsNo"],
|
||||
"Description": row["Description"],
|
||||
"alt": alternate
|
||||
})
|
||||
if row["CrsNo"] not in flex and not alternate and mockStudents[student["studentIndex"]]["expectedClasses"] < 10:
|
||||
mockStudents[student["studentIndex"]]["expectedClasses"] += 1
|
||||
else:
|
||||
newStudent = {
|
||||
"Pupil #": row["Pupil #"],
|
||||
"requests": [{
|
||||
"CrsNo": row["CrsNo"],
|
||||
"Description": row["Description"],
|
||||
"alt": alternate
|
||||
}],
|
||||
"schedule": {
|
||||
"block1": [],
|
||||
"block2": [],
|
||||
"block3": [],
|
||||
"block4": [],
|
||||
"block5": [],
|
||||
"block6": [],
|
||||
"block7": [],
|
||||
"block8": [],
|
||||
"block9": [],
|
||||
"block10": []
|
||||
},
|
||||
"expectedClasses": 1,
|
||||
"classes": 0,
|
||||
"remainingAlts": [],
|
||||
"studentIndex": len(mockStudents)
|
||||
}
|
||||
mockStudents.append(newStudent)
|
||||
|
||||
if log:
|
||||
with open("./output/students.json", "w") as outfile:
|
||||
json.dump(mockStudents, outfile, indent=2)
|
||||
|
||||
return mockStudents
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) == 1:
|
||||
print("Missing argument")
|
||||
exit()
|
||||
if sys.argv[1].lower() == 'sample':
|
||||
studentRequests: list[dict] = getSampleStudents("../sample_data/course_selection_data.csv")
|
||||
|
||||
with open("../output/students.json", "w") as outfile:
|
||||
json.dump(studentRequests, outfile, indent=2)
|
||||
elif sys.argv[1].lower() == 'mock':
|
||||
studentRequests: list[dict] = generateMockStudents(400)
|
||||
|
||||
with open("../output/students.json", "w") as outfile:
|
||||
json.dump(studentRequests, outfile, indent=2)
|
||||
else:
|
||||
print("Invalid argument")
|
||||
exit()
|
||||
|
||||
print("done")
|
||||
Reference in new issue
Block a user