-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
1559 lines (1436 loc) · 52.3 KB
/
main.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 (
"fmt"
"net/http"
"strings"
"time"
"github.com/Missuo0o/goBank/model"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/jinzhu/copier"
"gorm.io/gorm"
)
func main() {
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
//r.Use(cors.Default())
db, _ := connectDB()
store := cookie.NewStore([]byte("secret123"))
r.Use(sessions.Sessions("session", store))
// Login API
r.POST("/login", func(c *gin.Context) {
var loginRequest model.User
err := c.ShouldBindJSON(&loginRequest)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if loginRequest.Username == "" || loginRequest.Password == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid r1equest",
})
return
}
var user []model.User
// Check loginRequest.Username and loginRequest.Password
// select * from user where username = loginRequest.Username
db.Model(model.User{}).Where("username = ?", loginRequest.Username).First(&user)
if len(user) == 0 {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Invalid username or password",
})
return
} else {
if checkPasswordHash(loginRequest.Password, user[0].Password) {
session := sessions.Default(c)
session.Set("username", user[0].Username)
session.Set("role", user[0].Role)
_ = session.Save()
c.JSON(http.StatusOK, gin.H{
"message": "Login successful",
"data": gin.H{
"username": user[0].Username,
"role": user[0].Role},
})
} else {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Invalid username or password",
})
return
}
}
})
// User Register API
r.POST("/user/register", func(c *gin.Context) {
var registerRequest model.User
if err := c.ShouldBindJSON(®isterRequest); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if registerRequest.Username == "" || registerRequest.Password == "" || registerRequest.Keyword == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
registerRequest.Password = hashPassword(registerRequest.Password)
registerRequest.Role = "C"
result := db.Create(registerRequest)
if result.Error != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Username already exists",
})
return
} else {
c.JSON(http.StatusOK, gin.H{
"message": "Register successful",
})
}
})
// Logout API
r.POST("/logout", func(c *gin.Context) {
session := sessions.Default(c)
session.Clear()
_ = session.Save()
c.JSON(http.StatusOK, gin.H{
"message": "Logout successful",
})
})
// Open Account API
r.POST("/user/open", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var openAccountRequest OpenAccountRequest
err := c.ShouldBindJSON(&openAccountRequest)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
// select type from account where id = (select id from customer where username = username) and type = typeValue
var accountType string
db.Model(model.Account{}).Select("type").
Where("id = (?)", db.Model(model.Customer{}).
Select("id").Where("username = ?", username)).
Where("type = ?", openAccountRequest.Type).Find(&accountType)
if accountType != "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Account already exists",
})
return
}
var customer model.Customer
var account model.Account
var checking model.Checking
var saving model.Saving
var loan model.Loan
var studentLoan model.StudentLoan
var homeLoan model.HomeLoan
fmt.Print(openAccountRequest)
_ = copier.Copy(&customer, &openAccountRequest)
_ = copier.Copy(&account, &openAccountRequest)
_ = copier.Copy(&checking, &openAccountRequest)
_ = copier.Copy(&saving, &openAccountRequest)
_ = copier.Copy(&loan, &openAccountRequest)
_ = copier.Copy(&studentLoan, &openAccountRequest)
_ = copier.Copy(&homeLoan, &openAccountRequest)
// if select id from customer where username = username is null, then insert into customer
db.Where("username = ?", username).First(&customer)
if customer.ID == 0 {
customer.Username = username.(string)
db.Create(&customer)
}
uniqueNumberString := generateUniqueRandomNumberString(db)
account.Number = uniqueNumberString
checking.Number = uniqueNumberString
saving.Number = uniqueNumberString
loan.Number = uniqueNumberString
studentLoan.Number = uniqueNumberString
homeLoan.Number = uniqueNumberString
account.ID = customer.ID
account.OpenDate = time.Now().Format("2006-01-02 15:04:05")
if account.Fname == "" || account.Lname == "" || account.State == "" || account.City == "" || account.Zip == "" || account.Address == "" || (account.Type != "C" && account.Type != "S" && account.Type != "L") {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
switch requestType := openAccountRequest.Type; requestType {
case "C":
checking.Charge = 10.00
tx := db.Begin()
if err := tx.Create(&account).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
if err := tx.Create(&checking).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
tx.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Account opened successfully",
})
case "S":
saving.Rate = 1.50
tx1 := db.Begin()
if err := tx1.Create(&account).Error; err != nil {
tx1.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
if err := tx1.Create(&saving).Error; err != nil {
tx1.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
tx1.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Account opened successfully",
})
case "L":
if (openAccountRequest.LoanType != "STUDENT" && openAccountRequest.LoanType != "HOME" && openAccountRequest.LoanType != "PERSONAL") || loan.Amount <= 0 || loan.Months <= 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
// SELECT l.type
//FROM loan l
//JOIN account a ON l.number = a.number
//JOIN customer c ON a.id = c.id
//WHERE l.type = 'STUDENT' AND c.username = 'vincent';
var loanType string
db.Model(model.Loan{}).Select("type").
Joins("JOIN account a ON loan.number = a.number").
Joins("JOIN customer c ON a.id = c.id").
Where("loan.type = ? AND c.username = ?", openAccountRequest.LoanType, username).Find(&loanType)
if loanType != "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "LoanAccount already exists",
})
return
}
loan.Rate = 5.00
interest := loan.Amount * loan.Rate * 0.01 * float64(loan.Months)
loan.Payment = (loan.Amount + interest) / float64(loan.Months)
switch openAccountRequest.LoanType {
case "STUDENT":
if openAccountRequest.UniversityName == "" || studentLoan.StudentID == "" || studentLoan.EducationType == "" || studentLoan.ExpectGradDate == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
loan.Type = "STUDENT"
tx2 := db.Begin()
if err := tx2.Create(&account).Error; err != nil {
tx2.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
if err := tx2.Create(&loan).Error; err != nil {
tx2.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
// select * from university where name = openAccountRequest.UniversityName
var university model.University
db.Where("name = ?", openAccountRequest.UniversityName).First(&university)
if university.Id == 0 {
university.Name = openAccountRequest.UniversityName
if err := tx2.Create(&university).Error; err != nil {
tx2.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
}
studentLoan.UniversityID = university.Id
if err := tx2.Create(&studentLoan).Error; err != nil {
tx2.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
tx2.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Account opened successfully",
})
case "HOME":
if homeLoan.HouseBuildYear == "" || homeLoan.InsuranceAccNo == 0 || homeLoan.InsuranceCompanyName == "" || homeLoan.InsuranceCompanyState == "" || homeLoan.InsuranceCompanyCity == "" || homeLoan.InsuranceCompanyZip == "" || homeLoan.InsuranceCompanyAddress == "" || homeLoan.InsuranceCompanyPremium == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request2",
})
return
}
loan.Type = "HOME"
tx3 := db.Begin()
if err := tx3.Create(&account).Error; err != nil {
tx3.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
if err := tx3.Create(&loan).Error; err != nil {
tx3.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
if err := tx3.Create(&homeLoan).Error; err != nil {
tx3.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
tx3.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Account opened successfully",
})
case "PERSONAL":
loan.Type = "PERSONAL"
tx4 := db.Begin()
if err := tx4.Create(&account).Error; err != nil {
tx4.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
if err := tx4.Create(&loan).Error; err != nil {
tx4.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
tx4.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Account opened successfully",
})
}
}
})
// Reset Password API
r.PUT("/user/reset", func(c *gin.Context) {
var resetRequest model.User
err := c.ShouldBindJSON(&resetRequest)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if resetRequest.Username == "" || resetRequest.Password == "" || resetRequest.Keyword == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
// update user set password = hashPassword(resetRequest.Password) where username = resetRequest.Username and keyword = resetRequest.Keyword
result := db.Model(&model.User{}).Where("username = ? AND keyword = ?", resetRequest.Username, resetRequest.Keyword).Update("password", hashPassword(resetRequest.Password))
if result.RowsAffected == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid username or keyword",
})
return
} else {
c.JSON(http.StatusOK, gin.H{
"message": "Password reset successful",
})
}
})
// Transfer API
r.PUT("/user/transfer", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var transferRequest model.TransferHistory
err := c.ShouldBindJSON(&transferRequest)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if transferRequest.FromAccountNumber == 0 || transferRequest.ToAccountNumber == 0 || transferRequest.Amount == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
// select type from account where number = transferRequest.FromAccount
var fromAccountType string
db.Model(model.Account{}).Select("type").Where("number = ?", transferRequest.FromAccountNumber).Find(&fromAccountType)
// select number from account where id = (select id from customer where username = username) and (type = 'C' or type = 'S')
var fromAccountNumber int64
db.Model(model.Account{}).Select("number").Where("id = (?) AND (type = 'C' OR type = 'S')", db.Model(model.Customer{}).Select("id").Where("username = ?", username)).Find(&fromAccountNumber)
if fromAccountType == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "FromAccount does not exist",
})
}
// select type from account where number = transferRequest.ToAccount
var toAccountType string
db.Model(model.Account{}).Select("type").Where("number = ?", transferRequest.ToAccountNumber).Find(&toAccountType)
if toAccountType == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "ToAccount does not exist",
})
}
switch fromAccountType {
case "C":
switch toAccountType {
case "C":
tx := db.Begin()
// update checking set balance = balance - transferRequest.Amount where number = transferRequest.FromAccount and
// balance >= transferRequest.Amount
result := tx.Model(model.Checking{}).Where("number = ? AND balance >= ?", transferRequest.FromAccountNumber,
transferRequest.Amount).Update("balance", gorm.Expr("balance - ?", transferRequest.Amount))
if result.RowsAffected == 0 {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "Insufficient balance",
})
return
}
// update checking set balance = balance + transferRequest.Amount where number = transferRequest.ToAccount
if err := tx.Model(model.Checking{}).Where("number = ?", transferRequest.ToAccountNumber).Update("balance", gorm.Expr("balance + ?", transferRequest.Amount)).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "ToAccount does not exist",
})
return
}
// insert into transfer_history
transferRequest.TransferDate = time.Now().Format("2006-01-02 15:04:05")
transferRequest.AccountType = "C"
if err := tx.Create(&transferRequest).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "Transfer failed",
})
return
}
tx.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Transfer successful",
})
case "S":
tx1 := db.Begin()
// update checking set balance = balance - transferRequest.Amount where number = transferRequest.FromAccount and balance >= transferRequest.Amount
result := tx1.Model(model.Checking{}).Where("number = ? AND balance >= ?", transferRequest.FromAccountNumber, transferRequest.Amount).Update("balance", gorm.Expr("balance - ?", transferRequest.Amount))
if result.RowsAffected == 0 {
tx1.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "Insufficient balance",
})
return
}
// update saving set balance = balance + transferRequest.Amount where number = transferRequest.ToAccount
if err := tx1.Model(model.Saving{}).Where("number = ?", transferRequest.ToAccountNumber).Update("balance", gorm.Expr("balance + ?", transferRequest.Amount)).Error; err != nil {
tx1.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "ToAccount does not exist",
})
return
}
// insert into transfer_history
transferRequest.TransferDate = time.Now().Format("2006-01-02 15:04:05")
transferRequest.AccountType = "S"
if err := tx1.Create(&transferRequest).Error; err != nil {
tx1.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "Transfer failed",
})
return
}
tx1.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Transfer successful",
})
}
case "S":
switch toAccountType {
case "C":
tx2 := db.Begin()
// update saving set balance = balance - transferRequest.Amount where number = transferRequest.FromAccount and balance >= transferRequest.Amount
result := tx2.Model(model.Saving{}).Where("number = ? AND balance >= ?", transferRequest.FromAccountNumber, transferRequest.Amount).Update("balance", gorm.Expr("balance - ?", transferRequest.Amount))
if result.RowsAffected == 0 {
tx2.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "Insufficient balance",
})
return
}
// update checking set balance = balance + transferRequest.Amount where number = transferRequest.ToAccount
if err := tx2.Model(model.Checking{}).Where("number = ?", transferRequest.ToAccountNumber).Update("balance", gorm.Expr("balance + ?", transferRequest.Amount)).Error; err != nil {
tx2.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "ToAccount does not exist",
})
return
}
// insert into transfer_history
transferRequest.TransferDate = time.Now().Format("2006-01-02 15:04:05")
transferRequest.AccountType = "C"
if err := tx2.Create(&transferRequest).Error; err != nil {
tx2.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "Transfer failed",
})
return
}
tx2.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Transfer successful",
})
case "S":
tx3 := db.Begin()
// update saving set balance = balance - transferRequest.Amount where number = transferRequest.FromAccount and balance >= transferRequest.Amount
result := tx3.Model(model.Saving{}).Where("number = ? AND balance >= ?", transferRequest.FromAccountNumber, transferRequest.Amount).Update("balance", gorm.Expr("balance - ?", transferRequest.Amount))
if result.RowsAffected == 0 {
tx3.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "Insufficient balance",
})
return
}
// update saving set balance = balance + transferRequest.Amount where number = transferRequest.ToAccount
if err := tx3.Model(model.Saving{}).Where("number = ?", transferRequest.ToAccountNumber).Update("balance", gorm.Expr("balance + ?", transferRequest.Amount)).Error; err != nil {
tx3.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "ToAccount does not exist",
})
return
}
// insert into transfer_history
transferRequest.TransferDate = time.Now().Format("2006-01-02 15:04:05")
transferRequest.AccountType = "S"
if err := tx3.Create(&transferRequest).Error; err != nil {
tx3.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": "Transfer failed",
})
return
}
tx3.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Transfer successful",
})
}
}
})
// Get Transfer History API
r.GET("/user/transfer", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var transferHistory []model.TransferHistory
// select * from transfer_history where from_account_number in (select number from account where (type = 'C' or type = 'S') and id = (select id from customer where username = username))
db.Where("from_account_number in (?)", db.Model(model.Account{}).Select("number").Where("(type = 'C' OR type = 'S') AND id = (?)", db.Model(model.Customer{}).Select("id").Where("username = ?", username))).Find(&transferHistory)
for i := range transferHistory {
date, _ := time.Parse(time.RFC3339, transferHistory[i].TransferDate)
transferHistory[i].TransferDate = date.Format("2006-01-02 15:04:05")
}
c.JSON(http.StatusOK, gin.H{
"data": transferHistory,
})
})
// Deposit API
r.PUT("/user/deposit", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var depositRequest Deposit
err := c.ShouldBindJSON(&depositRequest)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if depositRequest.Account == 0 || depositRequest.Balance == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
// 判断当前username是否有对应的账户
// select number from account where id in (select id from customer where username = username) and number =depositRequest.Account and (type = 'C' or type = 'S')
var accountNumber []int64
db.Model(model.Account{}).Select("number").Where("id in (?)", db.Model(model.Customer{}).Select("id").Where("username = ?", username)).Where("number = ? AND (type = 'C' OR type = 'S')", depositRequest.Account).Find(&accountNumber)
if len(accountNumber) == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Account does not exist",
})
return
}
// select type from account where number = depositRequest.Account
var accountType string
db.Model(model.Account{}).Select("type").Where("number = ?", depositRequest.Account).Find(&accountType)
if accountType == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Account does not exist",
})
return
}
switch accountType {
case "C":
// update checking set balance = balance + balance where number = depositRequest.AccountNumber
if err := db.Model(model.Checking{}).Where("number = ?", depositRequest.Account).Update("balance", gorm.Expr("balance + ?", depositRequest.Balance)).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Account does not exist",
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Deposit successful",
})
case "S":
// update saving set balance = balance + balance where number = depositRequest.AccountNumber
if err := db.Model(model.Saving{}).Where("number = ?", depositRequest.Account).Update("balance", gorm.Expr("balance + ?", depositRequest.Balance)).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Account does not exist",
})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Deposit successful",
})
}
})
// Get AccountNumber API
r.GET("/user/account", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var accountNumber []NumberType
// select number,type from account where id = (select id from customer where username = username)
db.Model(model.Account{}).Select("number", "type").Where("id = (?)", db.Model(model.Customer{}).Select("id").Where("username = ?", username)).Find(&accountNumber)
c.JSON(http.StatusOK, gin.H{
"data": accountNumber,
})
})
// Get AccountBalance API
r.GET("/user/balance", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var accountBalance []float64
// select balance from checking where number in (select number from account where id = (select id from customer where username = username) and type = 'C')
var checkingBalance float64
db.Model(model.Checking{}).Select("balance").Where("number in (?)", db.Model(model.Account{}).Select("number").Where("id = (?) AND type = 'C'", db.Model(model.Customer{}).Select("id").Where("username = ?", username))).Find(&checkingBalance)
accountBalance = append(accountBalance, checkingBalance)
// select balance from saving where number in (select number from account where id = (select id from customer where username = username) and type = 'S')
var savingBalance float64
db.Model(model.Saving{}).Select("balance").Where("number in (?)", db.Model(model.Account{}).Select("number").Where("id = (?) AND type = 'S'", db.Model(model.Customer{}).Select("id").Where("username = ?", username))).Find(&savingBalance)
accountBalance = append(accountBalance, savingBalance)
c.JSON(http.StatusOK, gin.H{
"data": accountBalance,
})
})
// Get UserInfo API
r.GET("/user/user", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
// select * form customer where username = username
var customer model.Customer
db.Where("username = ?", username).First(&customer)
c.JSON(http.StatusOK, gin.H{
"data": customer,
})
})
// Update UserInfo API
r.PUT("/user/user", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var updateRequest model.Customer
err := c.ShouldBindJSON(&updateRequest)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if updateRequest.Fname == "" || updateRequest.Lname == "" || updateRequest.State == "" || updateRequest.City == "" || updateRequest.Zip == "" || updateRequest.Address == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
// select id from customer where username = username
var id int64
db.Model(model.Customer{}).Select("id").Where("username = ?", username).Find(&id)
tx := db.Begin()
// update customer set fname = updateRequest.Fname, lname = updateRequest.Lname, state = updateRequest.State, city = updateRequest.City, zip = updateRequest.Zip, address = updateRequest.Address where username = username
if err := tx.Model(model.Customer{}).Where("username = ?", username).Omit("username").Omit("id").Updates(&updateRequest).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
// update account set fname = updateRequest.Fname, lname = updateRequest.Lname, state = updateRequest.State, city = updateRequest.City, zip = updateRequest.Zip, address = updateRequest.Address where id = id
if err := tx.Model(model.Account{}).Where("id = ?", id).Omit("id").Updates(&updateRequest).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
tx.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Update successful",
})
})
// Get LoanInfo API
r.GET("/user/loan", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var loanPaymentCount int64
// select * from loan where number in (select number from account where id = (select id from customer where username = username))
var loan []model.Loan
db.Model(model.Loan{}).Where("number in (?)", db.Model(model.Account{}).Select("number").Where("id = (?)", db.Model(model.Customer{}).Select("id").Where("username = ?", username))).Find(&loan)
if len(loan) == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Loan does not exist",
})
return
}
// select count(*) from loan_payment where number = (select number from account where id = (select id from customer where username = username))
db.Raw("select count(*) from loan_payment where number = (select number from account where type = 'L' and id = (select id from customer where username = ?))", username).Scan(&loanPaymentCount)
// select months from loan where number = (select number from account where id = (select id from customer where username = username))
var months int64
db.Raw("select months from loan where number = (select number from account where type = 'L' and id = (select id from customer where username = ?))", username).Scan(&months)
if loanPaymentCount == months {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Loan already paid off",
})
return
}
c.JSON(http.StatusOK, gin.H{
"data": loan,
})
})
// Pay Loan API
r.POST("/user/pay", RoleAuthMiddleware("C"), func(c *gin.Context) {
session := sessions.Default(c)
username := session.Get("username")
var jsonMap map[string]interface{}
err := c.ShouldBindJSON(&jsonMap)
var accountNumber = int64(jsonMap["account"].(float64))
if accountNumber == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
// select * from loan where number in (select number from account where id = (select id from customer where username = username))
var loan []model.Loan
db.Model(model.Loan{}).Where("number in (?)", db.Model(model.Account{}).Select("number").Where("id = (?)", db.Model(model.Customer{}).Select("id").Where("username = ?", username))).Find(&loan)
if len(loan) == 0 {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Loan does not exist",
})
return
}
// select * from loan_payment where number = (select number from account where type = 'L' and id = (select id from customer where username = username))
var loanPayment []model.LoanPayment
db.Model(model.LoanPayment{}).Where("number = (?)", db.Model(model.Account{}).Select("number").Where("type = 'L' AND id = (?)", db.Model(model.Customer{}).Select("id").Where("username = ?", username))).Find(&loanPayment)
for _, payment := range loanPayment {
var currentMonth bool
currentMonth = strings.Contains(payment.PaymentDate, time.Now().Format("2006-01"))
if currentMonth {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Payment already made this month",
})
return
}
}
// select payment from loan where number in (select number from account where id = (select id from customer where username = username))
var payment float64
db.Model(model.Loan{}).Select("payment").Where("number in (?)", db.Model(model.Account{}).Select("number").Where("id = (?)", db.Model(model.Customer{}).Select("id").Where("username = ?", username))).Find(&payment)
// select type from account where number = accountNumber
var accountType string
db.Model(model.Account{}).Select("type").Where("number = ?", accountNumber).Find(&accountType)
// select number from account where id = (select id from customer where username = username) and (type = 'C' or type = 'S')
var AccountNumber []int64
db.Model(model.Account{}).Select("number").Where("id = (?) AND (type = 'C' OR type = 'S')", db.Model(model.Customer{}).Select("id").Where("username = ?", username)).Find(&AccountNumber)
found := false
for _, account := range AccountNumber {
if account == accountNumber {
found = true
break
}
}
if !found {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Account does not exist",
})
}
var loanPaymentRecord model.LoanPayment
loanPaymentRecord.Number = loan[0].Number
loanPaymentRecord.PaymentDate = time.Now().Format("2006-01-02")
loanPaymentRecord.PaymentAmount = payment
switch accountType {
case "C":
// select balance from checking where number = accountNumber
var balance float64
db.Model(model.Checking{}).Select("balance").Where("number = ?", accountNumber).Find(&balance)
if balance < payment {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Insufficient balance",
})
return
}
tx := db.Begin()
// update checking set balance = balance - payment where number = accountNumber
if err := tx.Model(model.Checking{}).Where("number = ?", accountNumber).Update("balance", gorm.Expr("balance - ?", payment)).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
// insert into loan_payment
if err := tx.Create(&loanPaymentRecord).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
tx.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Payment successful",
})
case "S":
// select balance from saving where number = accountNumber
var balance float64
db.Model(model.Saving{}).Select("balance").Where("number = ?", accountNumber).Find(&balance)
if balance < payment {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Insufficient balance",
})
return
}
tx := db.Begin()
// update saving set balance = balance - payment where number = accountNumber
if err := tx.Model(model.Saving{}).Where("number = ?", accountNumber).Update("balance", gorm.Expr("balance - ?", payment)).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
// insert into loan_payment
if err := tx.Create(&loanPaymentRecord).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusBadRequest, gin.H{
"message": err.Error(),
})
return
}
tx.Commit()
c.JSON(http.StatusOK, gin.H{
"message": "Payment successful",
})
}
})
// Admin register API
r.POST("/admin/register", RoleAuthMiddleware("A"), func(c *gin.Context) {
var registerRequest model.User
if err := c.ShouldBindJSON(®isterRequest); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if registerRequest.Username == "" || registerRequest.Password == "" || registerRequest.Role == "" || registerRequest.Keyword == "" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
registerRequest.Password = hashPassword(registerRequest.Password)
if registerRequest.Role != "A" && registerRequest.Role != "C" {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid role",
})
return
}
result := db.Create(registerRequest)
if result.Error != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Username already exists",
})
return
} else {
c.JSON(http.StatusOK, gin.H{
"message": "Register successful",
})
}
})
// Admin OpenAccount API
r.POST("/admin/open", RoleAuthMiddleware("A"), func(c *gin.Context) {
var openAccountRequest OpenAccountRequest
err := c.ShouldBindJSON(&openAccountRequest)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"message": "Invalid request",
})
return
}
if openAccountRequest.Username == "" || openAccountRequest.Fname == "" || openAccountRequest.Lname == "" || openAccountRequest.State == "" || openAccountRequest.City == "" || openAccountRequest.Zip == "" || openAccountRequest.Address == "" || (openAccountRequest.Type != "C" && openAccountRequest.Type != "S" && openAccountRequest.Type != "L") {