-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.go
1516 lines (1181 loc) · 37.1 KB
/
view.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
"database/sql"
"fmt"
"html/template"
"net/http"
"bytes"
"encoding/json"
"os"
"net/smtp"
"regexp"
"strconv"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/joho/godotenv"
"golang.org/x/crypto/bcrypt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
"log"
"time"
"strings"
)
var db *sql.DB
var err error
var collection *mongo.Collection
func init() {
err := godotenv.Load()
if err != nil {
panic("Error loading .env file")
}
// Initialize the database connection
initDB()
initmongoDB()
}
func initDB() {
// Read environment variables
dbUser := os.Getenv("DB_USER")
dbPass := os.Getenv("DB_PASS")
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
dbDatabase := os.Getenv("DB_NAME")
fmt.Println("DB User:", dbUser)
fmt.Println("DB Pass:", dbPass)
fmt.Println("DB Host:", dbHost)
fmt.Println("DB Port:", dbPort)
// Connect to the MySQL database
dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPass, dbHost, dbPort, dbDatabase)
db, err = sql.Open("mysql", dataSourceName)
if err != nil {
fmt.Println("Error:", err)
panic(err)
}
// Check the connection
err = db.Ping()
if err != nil {
fmt.Println("Error connecting to the database:", err)
panic(err)
}
fmt.Println("Connected to MySQL database!")
}
func initmongoDB() {
// Set client options
connection_string := os.Getenv("CONNECTION_STRING")
clientOptions := options.Client().ApplyURI(connection_string)
// Connect to MongoDB
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
// log.Fatal(err)
fmt.Println("Error:", err)
return
}
collection = client.Database("Student_inventory_list").Collection("Item_list")
// Check the connection
err = client.Ping(context.Background(), readpref.Primary())
if err != nil {
// log.Fatal(err)
fmt.Println("Error:", err)
return
}
fmt.Println("Connected to MongoDB!")
}
func home_before_login(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("templates/home_before_login.html")
if err != nil {
log.Printf("Error parsing template: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer func() {
if err := recover(); err != nil {
log.Printf("Panic during template execution: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
if err := t.Execute(w, nil); err != nil {
log.Printf("Error executing template: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
func home_after_login(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("templates/home_after_login.html")
t.Execute(w, nil)
}
func club_option(w http.ResponseWriter, r *http.Request) {
join_output, err := db.Query("SELECT club_id, club, Info, Img_link FROM clubs")
// fmt.Println(join_output)
if err != nil {
// Handle the error (log it or return an error response)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer join_output.Close()
id_arr := []string{}
club_arr := []string{}
info_arr := []string{}
photolink_arr := []string{}
for join_output.Next() {
var id string
var club string
var info string
var link string
err = join_output.Scan(&id, &club, &info, &link)
if err != nil {
panic(err.Error())
}
id_arr = append(id_arr, id)
club_arr = append(club_arr, club)
info_arr = append(info_arr, info)
photolink_arr = append(photolink_arr, link)
}
fmt.Println("ID:", id_arr)
fmt.Println("Club:", club_arr)
fmt.Println("Info:", info_arr)
// fmt.Println("Photo Link:", photolink_arr)
temp := club_info{
Club_id: id_arr,
Club: club_arr,
Info: info_arr,
Link: photolink_arr,
}
// Convert the struct to JSON
jsonData, err := json.Marshal(temp)
if err != nil {
// Handle the error
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Render the template with the JSON data
t, _ := template.ParseFiles("templates/club1.html")
t.Execute(w, template.JS(jsonData))
}
func cart(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("templates/cart.html")
t.Execute(w, nil)
}
func update(w http.ResponseWriter, r *http.Request) {
var updateItem Item
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&updateItem); err != nil {
http.Error(w, "Failed to decode JSON", http.StatusBadRequest)
return
}
club_id := updateItem.Club_id
club := updateItem.Club
name := updateItem.Name
return_date := updateItem.Return
id := updateItem.ID
username := updateItem.Username
email := db.QueryRow("SELECT email FROM clubs WHERE club_id=?", club_id)
filter := bson.M{"username": username, "club_info.club": club}
var email_id string
if err := email.Scan(&email_id); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// If the error is of any other type, send a 500 status
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
email_item_arr := []email_Item{}
for idx, itemID := range updateItem.ItemID {
fmt.Println("Item ID:", itemID)
fmt.Println("Quantity:", updateItem.Quantity[idx])
get_item := db.QueryRow("SELECT item FROM items WHERE item_id=?", itemID)
var setitem string
if err := get_item.Scan(&setitem); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
value := db.QueryRow("SELECT quantity FROM items WHERE item_id=?", itemID)
// Update the quantity of the item in the database
var val int
if err := value.Scan(&val); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
updated_value := val - updateItem.Quantity[idx]
temp := email_Item{
Name: setitem,
Quantity: updateItem.Quantity[idx],
Left: updated_value,
}
email_item_arr = append(email_item_arr, temp)
_, err := db.Exec("UPDATE items SET quantity=? WHERE item_id=?", updated_value, itemID)
if err != nil {
// If there is an issue with the database, return a 500 error
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
fmt.Println("Item ID:", updateItem.ItemID)
fmt.Println("Quantity:", updateItem.Quantity)
update := bson.M{
"$set": bson.M{
"club_info.$.borrow_status": "Yes",
},
"$push": bson.M{
"club_info.$.items": bson.M{
"name": setitem,
"quantity": updateItem.Quantity[idx],
"return_date": return_date,
},
},
}
updateResult, err := collection.UpdateOne(context.Background(), filter, update)
if err != nil {
// log.Fatal(err)
fmt.Println("Error:", err)
return
}
fmt.Printf("Matched %v document and modified %v document.\n", updateResult.MatchedCount, updateResult.ModifiedCount)
}
fmt.Println("email_item_arr:", email_item_arr)
send_email(email_id, club_id, name, return_date, club, id, email_item_arr)
}
func send_email(email_id string, club_id string, name string, return_date string, club string, id string, items []email_Item) {
// Send an email to the club
// sender data
from := os.Getenv("EMAIL")
password := os.Getenv("PASSWORD")
fmt.Println("Email:", from)
// fmt.Println("Password:", password)
// receiver email address
to := []string{
email_id, // could be more than one receiver email addresses separated by comma
}
fmt.Println("Email ID:", to)
// smtp - Simple Mail Transfer Protocol
host := "smtp.gmail.com"
port := "587"
auth := smtp.PlainAuth("", from, password, host)
t, _ := template.ParseFiles("templates/email_template.html")
var body bytes.Buffer
mimeHeaders := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
body.Write([]byte(fmt.Sprintf("Subject: Item borrowed by student \n%s\n\n", mimeHeaders)))
// Prepare data for template
data := struct {
Name string
ReturnDate string
Club string
Id string
Items []email_Item
}{
Name: name,
ReturnDate: return_date,
Club: club,
Id: id,
Items: items,
}
t.Execute(&body, data)
err := smtp.SendMail(host+":"+port, auth, from, to, body.Bytes())
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Email Sent!")
}
func inventory(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method)
t, _ := template.ParseFiles("templates/inventory.html")
vars := mux.Vars(r)
id := vars["ID"]
fmt.Println("ID:", id)
result := db.QueryRow("SELECT club FROM clubs WHERE club_id=?", id)
var club string
if err := result.Scan(&club); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// If the error is of any other type, send a 500 status
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
fmt.Println("Club:", club)
join_output, err := db.Query("SELECT items.item_id, items.item, items.quantity, items.club_id FROM items INNER JOIN clubs ON clubs.club_id=items.club_id WHERE items.club_id=?", id)
// fmt.Println(join_output)
if err != nil {
// Handle the error (log it or return an error response)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
defer join_output.Close()
join_arr := []string{}
join_arr_id := []string{}
join_arr_quantity := []int{}
for join_output.Next() {
var item_id string
var item string
var quantity int
var club_id string
err = join_output.Scan(&item_id, &item, &quantity, &club_id)
if err != nil {
panic(err.Error())
}
join_arr = append(join_arr, item)
join_arr_quantity = append(join_arr_quantity, quantity)
join_arr_id = append(join_arr_id, item_id)
}
fmt.Println("Items:", join_arr)
fmt.Println("Quantity:", join_arr_quantity)
temp := item_info{
Item_id: join_arr_id,
Club: club,
Club_id: id,
Items: join_arr,
Quantity: join_arr_quantity,
}
// Convert the struct to JSON
jsonData, err := json.Marshal(temp)
if err != nil {
// Handle the error
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Render the template with the JSON data
t.Execute(w, template.JS(jsonData))
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // get request method
if r.Method == "GET" {
// Serve the login page
http.ServeFile(w, r, "templates/signin.html")
return
}
r.ParseForm()
// logic part of log in
loginUsername := r.FormValue("username")
loginPassword := r.FormValue("password")
fmt.Println("username:", loginUsername)
fmt.Println("password:", loginPassword)
// Get the existing entry present in the database for the given username
result := db.QueryRow("SELECT password FROM student WHERE username=?", loginUsername)
result1 := db.QueryRow("SELECT name FROM student WHERE username=?", loginUsername)
// Declare a variable to store the retrieved hashed password
var hashedPassword string
var name string
if err := result1.Scan(&name); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
w.Write([]byte("unsuccessfull"))
// http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// If the error is of any other type, send a 500 status
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
fmt.Println("Name:", name)
// Scan the result into the hashedPassword variable
if err := result.Scan(&hashedPassword); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
w.Write([]byte("unsuccessfull"))
// http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// If the error is of any other type, send a 500 status
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Compare the stored hashed password with the hashed version of the password that was received
if err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(loginPassword)); err != nil {
// If the two passwords don't match, return a 401 status
fmt.Println("unsuccessfull")
w.Write([]byte("unsuccessfull"))
// http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
fmt.Println("success")
// If we reach this point, that means the user's password was correct, and they are authorized
// Send a success response to the client
institute_id := db.QueryRow("SELECT Institute_id FROM student WHERE username=?", loginUsername)
var id string
if err := institute_id.Scan(&id); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
w.Write([]byte("unsuccessfull"))
// http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// If the error is of any other type, send a 500 status
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
temp := user{
Username: name,
ID: id,
}
// Convert the struct to JSON
jsonData, err := json.Marshal(temp)
if err != nil {
// Handle the error
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
fmt.Println("Name:", name)
w.Write([]byte(jsonData))
}
func signup(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // get request method
if r.Method == "GET" {
t, _ := template.ParseFiles("templates/signup.html")
t.Execute(w, nil)
} else {
r.ParseForm()
// logic part of sign up
var username = r.FormValue("username")
var password = r.FormValue("password")
var confirm_password = r.FormValue("confirm-password")
var name = r.FormValue("name")
var id = r.FormValue("id")
// uppercase the id
id = strings.ToUpper(id)
fmt.Println("username:", username)
fmt.Println("password:", password)
fmt.Println("confirm-password:", confirm_password)
fmt.Println("name:", name)
fmt.Println("id:", id)
// Check if username already exists
result := db.QueryRow("SELECT username FROM student WHERE username=?", username)
var existingUsername string
err := result.Scan(&existingUsername)
if err == nil {
// Username already exists
fmt.Println("Username already exists")
w.Write([]byte("username"))
return
} else if err != sql.ErrNoRows {
// If the error is of any other type, send a 500 status
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
if password != confirm_password {
// Passwords do not match
w.Write([]byte("password"))
http.Redirect(w, r, "/signup/", http.StatusSeeOther)
return
}
// Hash the password
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(password), 8)
// Insert the new user into the database
insert, err := db.Prepare("INSERT INTO student (username, name, password, Institute_id) VALUES (?, ?, ?, ?)")
if err != nil {
panic(err.Error())
}
defer insert.Close()
// Execute the prepared statement with form values
_, err = insert.Exec(username, name, hashedPassword, id)
if err != nil {
panic(err.Error())
}
fmt.Println("Record inserted successfully")
w.Write([]byte("success"))
all_club, _ := db.Query("SELECT club_id, club FROM clubs")
var club_data []Club_present
for all_club.Next() {
var club_id string
var club string
err = all_club.Scan(&club_id, &club)
if err != nil {
panic(err.Error())
}
temp := Club_present{
Club_id: club_id,
Club: club,
Items: []BorrowedItem{},
}
club_data = append(club_data, temp)
}
// Insert a new document into the collection.
user := student{Username: username, Name: name, InstituteID: id, Club_info: club_data}
fmt.Println("user:", user)
insertResult, err := collection.InsertOne(context.Background(), user)
if err != nil {
// log.Fatal(err)
fmt.Println("Error:", err)
return
}
fmt.Println("Inserted a single document: ", insertResult.InsertedID)
// Fetch the inserted document from the collection
var insertedUser student
filter := bson.M{"_id": insertResult.InsertedID}
err = collection.FindOne(context.Background(), filter).Decode(&insertedUser)
if err != nil {
// log.Fatal(err)
fmt.Println("Error:", err)
return
}
// Print the entire inserted document
fmt.Println("Inserted User:", insertedUser)
}
}
func thank_page(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("templates/thank.html")
t.Execute(w, nil)
}
func borrow_list(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // get request method
if r.Method == "GET" {
result, _ := db.Query("SELECT club_id, club FROM clubs")
var club []string
for result.Next() {
var id string
var name string
err = result.Scan(&id, &name)
if err != nil {
panic(err.Error())
}
// temp := coordinator{
// club_name: name,
// club_id: id,
// }
club = append(club, name)
}
data := struct {
Items []string
}{
Items: club,
}
fmt.Println("Club:", club)
jsonData, err := json.Marshal(data)
if err != nil {
// Handle the error
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
t, _ := template.ParseFiles("templates/Borrow_list.html")
t.Execute(w, template.JS(jsonData))
} else if r.Method == "POST" {
r.ParseForm()
var club = r.FormValue("club")
var username = r.FormValue("username")
fmt.Println("club:", club)
filter := bson.M{"username": username, "club_info.club": club, "club_info.borrow_status": "Yes"}
var student student
err := collection.FindOne(context.Background(), filter).Decode(&student)
if err != nil {
// log.Fatal(err)
var status Status
status.Status = "unsuccessfull"
jsonData, err := json.Marshal(status)
w.Write([]byte(jsonData))
fmt.Println("Error:", err)
return
}
fmt.Println("Student:", student)
temp := student.Club_info
fmt.Println("Temp:", temp)
var items []BorrowedItem
for _, item := range temp {
if item.Club == club {
items = item.Items
}
}
fmt.Println("Items:", items)
// Convert the struct to JSON
jsonData, err := json.Marshal(items)
if err != nil {
// Handle the error
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Write([]byte(jsonData))
}
}
func delete_items(w http.ResponseWriter, r *http.Request) {
fmt.Println("method:", r.Method) // get request method
// r.ParseForm()
decoder := json.NewDecoder(r.Body)
var deleteItemsRequest DeleteItemsRequest
err := decoder.Decode(&deleteItemsRequest)
if err != nil {
http.Error(w, "Error decoding JSON request", http.StatusBadRequest)
return
}
item := deleteItemsRequest.Item
quantity := deleteItemsRequest.Quantity
returnDate := deleteItemsRequest.ReturnDate
username := deleteItemsRequest.Username
club := deleteItemsRequest.Club
id := deleteItemsRequest.ID
fmt.Println("item:", item)
fmt.Println("quantity:", quantity)
fmt.Println("returnDate:", returnDate)
name_id := db.QueryRow("SELECT name FROM student WHERE username=?", username)
var name string
if err := name_id.Scan(&name); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// If the error is of any other type, send a 500 status
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
result := db.QueryRow("SELECT email FROM clubs WHERE club=?", club)
var email_id string
if err := result.Scan(&email_id); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// If the error is of any other type, send a 500 status
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
delete_item_arr := []return_email_Item{}
for idx, itemID := range item {
var delete_item = string(itemID)
var delete_quantity_str = quantity[idx]
var delete_returnDate = string(returnDate[idx])
delete_quantity, _ := strconv.Atoi(delete_quantity_str)
fmt.Println("Item:", delete_item)
fmt.Println("Quantity:", delete_quantity)
fmt.Println("Return Date:", delete_returnDate)
fmt.Println("Username:", username)
fmt.Println("Club:", club)
filter := bson.M{"username": username, "club_info.club": club, "club_info.items.name": delete_item}
update := bson.M{
"$pull": bson.M{
"club_info.$.items": bson.M{
"name": delete_item,
"quantity": delete_quantity,
"return_date": delete_returnDate,
},
},
}
// Execute the $pull operation
_, err := collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
// log.Fatal(err)
fmt.Println("Error:", err)
return
}
filter = bson.M{"username": username}
// Then, check the length of the items array
var result bson.M
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
// log.Fatal(err)
fmt.Println("Error:", err)
return
}
// Check if "club_info" field exists
clubInfo, ok := result["club_info"].(bson.A)
if !ok {
// log.Fatal("Club information not found.")
fmt.Println("Club information not found.")
return
}
// Find the specific club
var targetClub bson.M
for _, c := range clubInfo {
if c.(bson.M)["club"].(string) == club {
targetClub = c.(bson.M)
break
}
}
// Check if the "items" field exists and is an array (bson.A)
item_arr, _ := targetClub["items"].(bson.A)
fmt.Println("Item Array:", item_arr)
fmt.Println("Length:", len(item_arr))
var targetClubIndex int
for i, c := range clubInfo {
if c.(bson.M)["club"].(string) == club {
targetClubIndex = i
break
}
}
if len(item_arr) == 0 {
// If it's 0, set borrow_status to "No"
update = bson.M{
"$set": bson.M{
fmt.Sprintf("club_info.%d.borrow_status", targetClubIndex): "No",
},
}
_, err = collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
// log.Fatal(err)
fmt.Println("Error:", err)
}
}
// Update the quantity of the item in the database
value := db.QueryRow("SELECT quantity FROM items WHERE item=?", delete_item)
var val int
if err := value.Scan(&val); err != nil {
// If an entry with the username does not exist, send an "Unauthorized"(401) status
if err == sql.ErrNoRows {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
updated_value := val + delete_quantity
currentTime := time.Now()
// Time := currentTime.Format("2006-01-02")
compareDate, _ := time.Parse("2006-01-02", delete_returnDate)
var status string
if currentTime.After(compareDate) {
status = "Late"
} else {
status = "Within Time"
}
temp := return_email_Item{
Name: delete_item,
Quantity: delete_quantity,
Left: updated_value,
ReturnDate: delete_returnDate,
Status: status,
}
delete_item_arr = append(delete_item_arr, temp)
_, err = db.Exec("UPDATE items SET quantity=? WHERE item=?", updated_value, delete_item)
if err != nil {
// If there is an issue with the database, return a 500 error
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
fmt.Println("Item ID:", item)
fmt.Println("Quantity:", quantity)
fmt.Println("Return Date:", returnDate)
fmt.Println("Username:", username)
fmt.Println("Club:", club)
}
send_return_email(name, club, id, email_id, delete_item_arr)
}
func send_return_email(username string, club string, id string, email_id string, items []return_email_Item) {
// sender data
from := os.Getenv("EMAIL")
password := os.Getenv("PASSWORD")
fmt.Println("Email:", from)
// fmt.Println("Password:", password)
// receiver email address
to := []string{
email_id, // could be more than one receiver email addresses separated by comma
}
fmt.Println("Email ID:", to)
// smtp - Simple Mail Transfer Protocol
host := "smtp.gmail.com"
port := "587"
auth := smtp.PlainAuth("", from, password, host)
t, _ := template.ParseFiles("templates/return_email_template.html")
var body bytes.Buffer
mimeHeaders := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
body.Write([]byte(fmt.Sprintf("Subject: Item returned by student \n%s\n\n", mimeHeaders)))
// Prepare data for template
data := struct {
Name string
Club string
Id string
Items []return_email_Item
}{
Name: username,
Club: club,
Id: id,
Items: items,
}
t.Execute(&body, data)
err := smtp.SendMail(host+":"+port, auth, from, to, body.Bytes())
if err != nil {