Repository navigation
Expand file tree
/
Copy pathgrinfo_api.go
More file actions
1385 lines (1229 loc) · 40.8 KB
/
Copy pathgrinfo_api.go
File metadata and controls
1385 lines (1229 loc) · 40.8 KB
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 (
"database/sql"
"encoding/json"
"fmt"
"hash/fnv"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
)
type GrInfoQuestion struct {
ID int `json:"id"`
Category string `json:"category"`
Dificultate string `json:"dificultate"`
EloRating int `json:"eloRating"`
Enunt string `json:"enunt"`
ExplicatieRaspuns string `json:"explicatieRaspuns"`
GraphData string `json:"graphData"`
Optiuni []string `json:"optiuni"`
RaspunsCorect int `json:"raspunsCorect"`
}
type GrInfoSessionStartRequest struct {
InitialElo float64 `json:"initialElo"`
TotalQuestions int `json:"totalQuestions"`
Category string `json:"category"`
Difficulty string `json:"difficulty"`
}
type GrInfoSessionAnswerRequest struct {
SessionID int `json:"sessionId"`
QuestionID int `json:"questionId"`
IsCorrect bool `json:"isCorrect"`
EloBefore float64 `json:"eloBefore"`
EloAfter float64 `json:"eloAfter"`
}
type GrInfoSessionFinishRequest struct {
SessionID int `json:"sessionId"`
FinalElo float64 `json:"finalElo"`
CorrectAnswers int `json:"correctAnswers"`
TotalQuestions int `json:"totalQuestions"`
}
type GrInfoSecurityIncidentRequest struct {
SessionID int `json:"sessionId"`
IncidentType string `json:"incidentType"`
Description string `json:"description"`
EloPenalty int `json:"eloPenalty"`
}
type GrInfoCompatIncidentRequest struct {
Reason string `json:"reason"`
Category string `json:"category"`
CurrentElo int `json:"currentElo"`
EloPenalty int `json:"eloPenalty"`
}
type GrInfoCompatSessionRequest struct {
SessionID int `json:"sessionId"`
Category string `json:"category"`
Difficulty string `json:"difficulty"`
InitialElo float64 `json:"initialElo"`
FinalElo float64 `json:"finalElo"`
CorrectAnswers int `json:"correctAnswers"`
TotalQuestions int `json:"totalQuestions"`
}
type GrInfoAdminQuestion struct {
ID int `json:"id"`
Category string `json:"category"`
Dificultate string `json:"dificultate"`
EloRating int `json:"eloRating"`
Enunt string `json:"enunt"`
ExplicatieRaspuns string `json:"explicatieRaspuns"`
GraphData string `json:"graphData"`
Optiuni []string `json:"optiuni"`
RaspunsCorect int `json:"raspunsCorect"`
IsActive bool `json:"isActive"`
}
type GrInfoAdminQuestionRequest struct {
Category string `json:"category"`
Dificultate string `json:"dificultate"`
EloRating int `json:"eloRating"`
Enunt string `json:"enunt"`
ExplicatieRaspuns string `json:"explicatieRaspuns"`
GraphData string `json:"graphData"`
Optiuni []string `json:"optiuni"`
RaspunsCorect int `json:"raspunsCorect"`
IsActive bool `json:"isActive"`
}
func initGrInfoTablesAndSeed(db *sql.DB) error {
createSQL := `
CREATE TABLE IF NOT EXISTS grinfo_categories (
id BIGSERIAL PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS grinfo_questions (
id BIGSERIAL PRIMARY KEY,
category_id BIGINT NOT NULL REFERENCES grinfo_categories(id) ON DELETE RESTRICT,
difficulty TEXT NOT NULL CHECK (difficulty IN ('usoara', 'medie', 'grea')),
elo_rating INTEGER NOT NULL,
enunt TEXT NOT NULL,
explicatie_raspuns TEXT NOT NULL,
graph_data JSONB NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS grinfo_question_options (
id BIGSERIAL PRIMARY KEY,
question_id BIGINT NOT NULL REFERENCES grinfo_questions(id) ON DELETE CASCADE,
option_index INTEGER NOT NULL CHECK (option_index BETWEEN 0 AND 3),
option_text TEXT NOT NULL,
is_correct BOOLEAN NOT NULL DEFAULT FALSE,
UNIQUE(question_id, option_index)
);
CREATE TABLE IF NOT EXISTS grinfo_sessions (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
category TEXT NOT NULL DEFAULT 'all',
difficulty TEXT NOT NULL DEFAULT 'all',
initial_elo NUMERIC(6,2) NOT NULL DEFAULT 1000,
final_elo NUMERIC(6,2),
total_questions INTEGER NOT NULL DEFAULT 10,
correct_answers INTEGER NOT NULL DEFAULT 0,
started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
ended_at TIMESTAMPTZ
);
CREATE TABLE IF NOT EXISTS grinfo_session_answers (
id BIGSERIAL PRIMARY KEY,
session_id BIGINT NOT NULL REFERENCES grinfo_sessions(id) ON DELETE CASCADE,
question_id BIGINT NOT NULL REFERENCES grinfo_questions(id) ON DELETE RESTRICT,
is_correct BOOLEAN NOT NULL,
elo_before NUMERIC(6,2) NOT NULL,
elo_after NUMERIC(6,2) NOT NULL,
answered_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS grinfo_security_logs (
id BIGSERIAL PRIMARY KEY,
session_id BIGINT REFERENCES grinfo_sessions(id) ON DELETE CASCADE,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
description TEXT,
elo_penalty INTEGER NOT NULL DEFAULT 50,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_grinfo_questions_category ON grinfo_questions(category_id);
CREATE INDEX IF NOT EXISTS idx_grinfo_questions_elo ON grinfo_questions(elo_rating);
CREATE INDEX IF NOT EXISTS idx_grinfo_questions_active ON grinfo_questions(is_active);
CREATE INDEX IF NOT EXISTS idx_grinfo_sessions_user ON grinfo_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_grinfo_answers_session ON grinfo_session_answers(session_id);
CREATE INDEX IF NOT EXISTS idx_grinfo_security_session ON grinfo_security_logs(session_id);
`
if _, err := db.Exec(createSQL); err != nil {
return err
}
if _, err := db.Exec(`ALTER TABLE grinfo_sessions ADD COLUMN IF NOT EXISTS difficulty TEXT NOT NULL DEFAULT 'all'`); err != nil {
return err
}
if _, err := db.Exec(`ALTER TABLE grinfo_sessions ADD COLUMN IF NOT EXISTS started_at TIMESTAMPTZ NOT NULL DEFAULT NOW()`); err != nil {
return err
}
if _, err := db.Exec(`
INSERT INTO grinfo_categories (slug, name)
VALUES
('orientate', 'Grafuri orientate'),
('neorientate', 'Grafuri neorientate')
ON CONFLICT (slug) DO NOTHING
`); err != nil {
return err
}
if err := seedGrInfoQuestions(db); err != nil {
return err
}
return cleanupInvalidGrInfoSessions(db)
}
func seedGrInfoQuestions(db *sql.DB) error {
// Preserve manually curated datasets. Seed only on first boot when no questions exist.
var existingCount int
if err := db.QueryRow(`SELECT COUNT(*) FROM grinfo_questions`).Scan(&existingCount); err != nil {
return err
}
if existingCount > 0 {
return nil
}
var orientateID, neorientateID int
if err := db.QueryRow(`SELECT id FROM grinfo_categories WHERE slug='orientate'`).Scan(&orientateID); err != nil {
return err
}
if err := db.QueryRow(`SELECT id FROM grinfo_categories WHERE slug='neorientate'`).Scan(&neorientateID); err != nil {
return err
}
var orientateCount, neorientateCount int
if err := db.QueryRow(`
SELECT COUNT(*)
FROM grinfo_questions q
JOIN grinfo_categories c ON c.id = q.category_id
WHERE c.slug='orientate' AND q.is_active=TRUE
`).Scan(&orientateCount); err != nil {
return err
}
if err := db.QueryRow(`
SELECT COUNT(*)
FROM grinfo_questions q
JOIN grinfo_categories c ON c.id = q.category_id
WHERE c.slug='neorientate' AND q.is_active=TRUE
`).Scan(&neorientateCount); err != nil {
return err
}
if orientateCount < 45 {
if err := insertGeneratedQuestions(db, orientateID, "orientate", orientateCount+1, 45); err != nil {
return err
}
}
if neorientateCount < 45 {
if err := insertGeneratedQuestions(db, neorientateID, "neorientate", neorientateCount+1, 45); err != nil {
return err
}
}
return nil
}
func buildGrInfoQuestionContent(category string, index int) (string, int, string, string, [4]string, int, string) {
difficulty := "usoara"
elo := 900 + (index * 12)
if index > 15 {
difficulty = "medie"
elo = 1050 + (index * 14)
}
if index > 30 {
difficulty = "grea"
elo = 1250 + (index * 16)
}
graphData := `{"nodes":[{"id":"n1"},{"id":"n2"},{"id":"n3"}],"edges":[{"source":"n1","target":"n2"},{"source":"n2","target":"n3"}]}`
var questionText string
var explanation string
var options [4]string
correctIndex := 0
pattern := (index - 1) % 6
if category == "orientate" {
switch pattern {
case 0:
questionText = fmt.Sprintf("[Orientate %d] Ce descrie corect un arc într-un graf orientat?", index)
explanation = "Un arc are sens și merge dintr-un nod sursă către un nod destinație."
options = [4]string{
"Leagă două noduri cu sens de la sursă la destinație",
"Leagă două noduri fără direcție",
"Poate exista doar în grafuri complete",
"Nu influențează gradul nodurilor",
}
case 1:
questionText = fmt.Sprintf("[Orientate %d] Ce relație este corectă pentru gradele unui nod?", index)
explanation = "În grafurile orientate, gradul intern și extern descriu intrările și ieșirile unui nod."
options = [4]string{
"Suma gradului intern și extern este gradul total al nodului",
"Gradul intern este mereu egal cu numărul de noduri",
"Gradul extern nu poate fi 0",
"Fiecare nod are exact două arce incidente",
}
case 2:
questionText = fmt.Sprintf("[Orientate %d] Când poate fi aplicată sortarea topologică?", index)
explanation = "Sortarea topologică se aplică doar pe grafuri orientate fără cicluri."
options = [4]string{
"Pe un DAG",
"Pe orice graf orientat, inclusiv cu cicluri",
"Doar pe grafuri neorientate",
"Numai dacă există un singur nod",
}
case 3:
questionText = fmt.Sprintf("[Orientate %d] Ce afirmă corect despre un graf orientat aciclic?", index)
explanation = "Un DAG nu conține cicluri orientate și este des folosit în dependențe și planificare."
options = [4]string{
"Nu conține cicluri orientate",
"Are obligatoriu un ciclu cu toate nodurile",
"Este același lucru cu un graf complet",
"Nu poate avea drumuri",
}
case 4:
questionText = fmt.Sprintf("[Orientate %d] Cum se interpretează matricea de adiacență?", index)
explanation = "În matricea de adiacență pentru grafuri orientate, poziția aij indică existența unui arc i→j."
options = [4]string{
"aij = 1 dacă există un arc de la i la j",
"aij = 1 doar dacă i și j sunt noduri izolate",
"aij reprezintă numărul de componente conexe",
"aij este mereu 0 pe diagonală, indiferent de graf",
}
default:
questionText = fmt.Sprintf("[Orientate %d] Ce este adevărat despre un drum orientat?", index)
explanation = "Un drum orientat urmează sensul arcelor, dintr-un nod inițial către unul final."
options = [4]string{
"Parcurge arcele în sensul lor",
"Ignoră complet direcția arcelor",
"Poate folosi aceeași muchie de două ori fără restricții",
"Este identic cu un ciclu obligatoriu",
}
}
} else {
switch pattern {
case 0:
questionText = fmt.Sprintf("[Neorientate %d] Ce descrie corect o muchie într-un graf neorientat?", index)
explanation = "În grafurile neorientate, muchiile nu au sens și conectează două noduri în mod simetric."
options = [4]string{
"Leagă două noduri fără direcție",
"Are sens doar într-un singur sens",
"Poate lega un nod de el însuși în orice caz",
"Este folosită doar în DAG-uri",
}
case 1:
questionText = fmt.Sprintf("[Neorientate %d] Care este relația corectă pentru suma gradelor?", index)
explanation = "Într-un graf neorientat, suma gradelor tuturor nodurilor este de două ori numărul muchiilor."
options = [4]string{
"Este egală cu 2m",
"Este egală cu n",
"Este mereu 0",
"Este egală cu numărul de componente conexe",
}
case 2:
questionText = fmt.Sprintf("[Neorientate %d] Câte muchii are un arbore cu n noduri?", index)
explanation = "Un arbore cu n noduri are întotdeauna n - 1 muchii."
options = [4]string{
"n - 1 muchii",
"n muchii",
"n + 1 muchii",
"2n muchii",
}
case 3:
questionText = fmt.Sprintf("[Neorientate %d] Câte muchii are un graf complet cu n noduri?", index)
explanation = "Un graf complet neorientat cu n noduri are n(n - 1)/2 muchii."
options = [4]string{
"n(n - 1)/2",
"n - 1",
"n",
"n^2",
}
case 4:
questionText = fmt.Sprintf("[Neorientate %d] Ce afirmă corect despre un graf conex?", index)
explanation = "Conexitatea spune că între orice două noduri există cel puțin un drum."
options = [4]string{
"Între orice două noduri există cel puțin un drum",
"Nu poate conține cicluri",
"Are obligatoriu exact o muchie",
"Este mereu complet",
}
default:
questionText = fmt.Sprintf("[Neorientate %d] Ce este adevărat despre un graf simplu?", index)
explanation = "Un graf simplu nu are bucle și nu are muchii multiple între aceleași noduri."
options = [4]string{
"Nu are bucle și nici muchii multiple",
"Trebuie să fie complet",
"Are obligatoriu bucle pe fiecare nod",
"Poate avea mai multe muchii paralele între aceleași noduri",
}
}
}
shuffledOptions, shuffledCorrectIndex := shuffleGrInfoOptions(category, index, options, correctIndex)
return difficulty, elo, questionText, explanation, shuffledOptions, shuffledCorrectIndex, graphData
}
func shuffleGrInfoOptions(category string, index int, options [4]string, correctIndex int) ([4]string, int) {
type optionItem struct {
text string
isCorrect bool
}
items := []optionItem{
{text: options[0], isCorrect: correctIndex == 0},
{text: options[1], isCorrect: correctIndex == 1},
{text: options[2], isCorrect: correctIndex == 2},
{text: options[3], isCorrect: correctIndex == 3},
}
seedInput := fmt.Sprintf("%s:%d", category, index)
hasher := fnv.New32a()
_, _ = hasher.Write([]byte(seedInput))
rng := rand.New(rand.NewSource(int64(hasher.Sum32())))
rng.Shuffle(len(items), func(i, j int) {
items[i], items[j] = items[j], items[i]
})
var shuffled [4]string
shuffledCorrectIndex := 0
for i, item := range items {
shuffled[i] = item.text
if item.isCorrect {
shuffledCorrectIndex = i
}
}
return shuffled, shuffledCorrectIndex
}
func insertGeneratedQuestions(db *sql.DB, categoryID int, category string, fromIndex int, toIndex int) error {
for i := fromIndex; i <= toIndex; i++ {
difficulty, elo, questionText, explanation, options, correctIndex, graphData := buildGrInfoQuestionContent(category, i)
var qid int
if err := db.QueryRow(`
INSERT INTO grinfo_questions (category_id, difficulty, elo_rating, enunt, explicatie_raspuns, graph_data, is_active)
VALUES ($1, $2, $3, $4, $5, $6::jsonb, TRUE)
RETURNING id
`, categoryID, difficulty, elo, questionText, explanation, graphData).Scan(&qid); err != nil {
return err
}
for idx := 0; idx < 4; idx++ {
if _, err := db.Exec(`
INSERT INTO grinfo_question_options (question_id, option_index, option_text, is_correct)
VALUES ($1, $2, $3, $4)
`, qid, idx, options[idx], idx == correctIndex); err != nil {
return err
}
}
}
return nil
}
func repairGrInfoQuestionOptions(db *sql.DB) error {
rows, err := db.Query(`
SELECT q.id, c.slug
FROM grinfo_questions q
JOIN grinfo_categories c ON c.id = q.category_id
ORDER BY q.id
`)
if err != nil {
return err
}
defer rows.Close()
categoryCounters := map[string]int{}
for rows.Next() {
var questionID int
var categorySlug string
if err := rows.Scan(&questionID, &categorySlug); err != nil {
continue
}
categoryCounters[categorySlug]++
index := categoryCounters[categorySlug]
difficulty, _, questionText, explanation, options, correctIndex, graphData := buildGrInfoQuestionContent(categorySlug, index)
if _, err := db.Exec(`
UPDATE grinfo_questions
SET difficulty = $1,
enunt = $2,
explicatie_raspuns = $3,
graph_data = $4::jsonb
WHERE id = $5
`, difficulty, questionText, explanation, graphData, questionID); err != nil {
return err
}
if _, err := db.Exec(`DELETE FROM grinfo_question_options WHERE question_id = $1`, questionID); err != nil {
return err
}
for idx := 0; idx < 4; idx++ {
if _, err := db.Exec(`
INSERT INTO grinfo_question_options (question_id, option_index, option_text, is_correct)
VALUES ($1, $2, $3, $4)
`, questionID, idx, options[idx], idx == correctIndex); err != nil {
return err
}
}
}
return rows.Err()
}
func cleanupInvalidGrInfoSessions(db *sql.DB) error {
_, err := db.Exec(`
DELETE FROM grinfo_sessions
WHERE final_elo IS NOT NULL
AND final_elo <= 0
`)
return err
}
func apiGrInfoCategoriesHandler(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(`SELECT slug, name FROM grinfo_categories ORDER BY name`)
if err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}
defer rows.Close()
items := make([]map[string]string, 0)
for rows.Next() {
var slug, name string
if err := rows.Scan(&slug, &name); err == nil {
items = append(items, map[string]string{"slug": slug, "name": name})
}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{"categories": items})
}
func apiGrInfoQuestionsHandler(w http.ResponseWriter, r *http.Request) {
category := r.URL.Query().Get("category")
if category == "" {
category = "all"
}
limit := 50
if l := r.URL.Query().Get("limit"); l != "" {
if parsed, err := strconv.Atoi(l); err == nil && parsed > 0 && parsed <= 100 {
limit = parsed
}
}
query := `
SELECT q.id, c.slug, q.difficulty, q.elo_rating, q.enunt, q.explicatie_raspuns, q.graph_data
FROM grinfo_questions q
JOIN grinfo_categories c ON c.id = q.category_id
WHERE q.is_active = TRUE
`
args := []interface{}{}
if category != "all" {
query += ` AND c.slug = $1`
args = append(args, category)
query += ` ORDER BY q.elo_rating ASC, q.id ASC LIMIT $2`
args = append(args, limit)
} else {
query += ` ORDER BY q.elo_rating ASC, q.id ASC LIMIT $1`
args = append(args, limit)
}
rows, err := db.Query(query, args...)
if err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}
defer rows.Close()
questions := make([]GrInfoQuestion, 0)
for rows.Next() {
var q GrInfoQuestion
if err := rows.Scan(&q.ID, &q.Category, &q.Dificultate, &q.EloRating, &q.Enunt, &q.ExplicatieRaspuns, &q.GraphData); err != nil {
continue
}
optionRows, err := db.Query(`
SELECT option_index, option_text, is_correct
FROM grinfo_question_options
WHERE question_id = $1
ORDER BY option_index ASC
`, q.ID)
if err != nil {
continue
}
q.Optiuni = make([]string, 0, 4)
q.RaspunsCorect = 0
for optionRows.Next() {
var idx int
var text string
var isCorrect bool
if err := optionRows.Scan(&idx, &text, &isCorrect); err == nil {
q.Optiuni = append(q.Optiuni, text)
if isCorrect {
q.RaspunsCorect = idx
}
}
}
optionRows.Close()
questions = append(questions, q)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"questions": questions,
"count": len(questions),
})
}
func readGrInfoAdminQuestion(questionID int) (*GrInfoAdminQuestion, error) {
var q GrInfoAdminQuestion
err := db.QueryRow(`
SELECT q.id, c.slug, q.difficulty, q.elo_rating, q.enunt, q.explicatie_raspuns, q.graph_data, q.is_active
FROM grinfo_questions q
JOIN grinfo_categories c ON c.id = q.category_id
WHERE q.id = $1
`, questionID).Scan(&q.ID, &q.Category, &q.Dificultate, &q.EloRating, &q.Enunt, &q.ExplicatieRaspuns, &q.GraphData, &q.IsActive)
if err != nil {
return nil, err
}
optionRows, err := db.Query(`
SELECT option_index, option_text, is_correct
FROM grinfo_question_options
WHERE question_id = $1
ORDER BY option_index ASC
`, questionID)
if err != nil {
return nil, err
}
defer optionRows.Close()
q.Optiuni = []string{"", "", "", ""}
q.RaspunsCorect = 0
for optionRows.Next() {
var idx int
var text string
var isCorrect bool
if err := optionRows.Scan(&idx, &text, &isCorrect); err != nil {
return nil, err
}
if idx >= 0 && idx < 4 {
q.Optiuni[idx] = text
if isCorrect {
q.RaspunsCorect = idx
}
}
}
return &q, optionRows.Err()
}
func parseGrInfoAdminQuestionRequest(r *http.Request) (*GrInfoAdminQuestionRequest, string) {
var req GrInfoAdminQuestionRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, "Body JSON invalid"
}
req.Category = strings.TrimSpace(strings.ToLower(req.Category))
req.Dificultate = strings.TrimSpace(strings.ToLower(req.Dificultate))
req.Enunt = strings.TrimSpace(req.Enunt)
req.ExplicatieRaspuns = strings.TrimSpace(req.ExplicatieRaspuns)
req.GraphData = strings.TrimSpace(req.GraphData)
if req.Category != "orientate" && req.Category != "neorientate" {
return nil, "Categoria trebuie sa fie orientate sau neorientate"
}
if req.Dificultate != "usoara" && req.Dificultate != "medie" && req.Dificultate != "grea" {
return nil, "Dificultatea trebuie sa fie usoara, medie sau grea"
}
if req.EloRating < 900 || req.EloRating > 1900 {
return nil, "ELO trebuie sa fie intre 900 si 1900"
}
if req.Enunt == "" || req.ExplicatieRaspuns == "" {
return nil, "Enuntul si explicatia sunt obligatorii"
}
if len(req.Optiuni) != 4 {
return nil, "Trebuie exact 4 optiuni"
}
for i := range req.Optiuni {
req.Optiuni[i] = strings.TrimSpace(req.Optiuni[i])
if req.Optiuni[i] == "" {
return nil, "Toate optiunile trebuie completate"
}
}
if req.RaspunsCorect < 0 || req.RaspunsCorect > 3 {
return nil, "Raspunsul corect trebuie sa fie intre 0 si 3"
}
if req.GraphData == "" {
req.GraphData = `{}`
}
if !json.Valid([]byte(req.GraphData)) {
return nil, "graphData trebuie sa fie JSON valid"
}
return &req, ""
}
func apiGrInfoAdminQuestionsHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
category := r.URL.Query().Get("category")
if category == "" {
category = "all"
}
includeInactive := r.URL.Query().Get("includeInactive") == "1"
page := 1
if p := r.URL.Query().Get("page"); p != "" {
if parsed, err := strconv.Atoi(p); err == nil && parsed > 0 {
page = parsed
}
}
pageSize := 10
where := ` WHERE 1=1`
args := []interface{}{}
if category != "all" {
args = append(args, category)
where += fmt.Sprintf(" AND c.slug = $%d", len(args))
}
if !includeInactive {
where += ` AND q.is_active = TRUE`
}
countQuery := `
SELECT COUNT(*)
FROM grinfo_questions q
JOIN grinfo_categories c ON c.id = q.category_id
` + where
var totalCount int
if err := db.QueryRow(countQuery, args...).Scan(&totalCount); err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}
totalPages := 1
if totalCount > 0 {
totalPages = (totalCount + pageSize - 1) / pageSize
}
if page > totalPages {
page = totalPages
}
offset := (page - 1) * pageSize
limitPos := len(args) + 1
offsetPos := len(args) + 2
query := `
SELECT q.id
FROM grinfo_questions q
JOIN grinfo_categories c ON c.id = q.category_id
` + where + fmt.Sprintf(`
ORDER BY q.elo_rating ASC, q.id ASC
LIMIT $%d OFFSET $%d
`, limitPos, offsetPos)
args = append(args, pageSize, offset)
rows, err := db.Query(query, args...)
if err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}
defer rows.Close()
questions := make([]GrInfoAdminQuestion, 0)
for rows.Next() {
var qid int
if err := rows.Scan(&qid); err != nil {
continue
}
q, err := readGrInfoAdminQuestion(qid)
if err != nil {
continue
}
questions = append(questions, *q)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"questions": questions,
"count": len(questions),
"totalCount": totalCount,
"page": page,
"pageSize": pageSize,
"totalPages": totalPages,
})
case http.MethodPost:
req, validationErr := parseGrInfoAdminQuestionRequest(r)
if validationErr != "" {
jsonError(w, validationErr, http.StatusBadRequest)
return
}
var categoryID int
if err := db.QueryRow(`SELECT id FROM grinfo_categories WHERE slug = $1`, req.Category).Scan(&categoryID); err != nil {
jsonError(w, "Categorie invalida", http.StatusBadRequest)
return
}
tx, err := db.Begin()
if err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}
defer tx.Rollback()
var newID int
err = tx.QueryRow(`
INSERT INTO grinfo_questions (category_id, difficulty, elo_rating, enunt, explicatie_raspuns, graph_data, is_active)
VALUES ($1, $2, $3, $4, $5, $6::jsonb, $7)
RETURNING id
`, categoryID, req.Dificultate, req.EloRating, req.Enunt, req.ExplicatieRaspuns, req.GraphData, req.IsActive).Scan(&newID)
if err != nil {
jsonError(w, "Nu s-a putut crea intrebarea", http.StatusInternalServerError)
return
}
for idx := 0; idx < 4; idx++ {
if _, err := tx.Exec(`
INSERT INTO grinfo_question_options (question_id, option_index, option_text, is_correct)
VALUES ($1, $2, $3, $4)
`, newID, idx, req.Optiuni[idx], idx == req.RaspunsCorect); err != nil {
jsonError(w, "Nu s-au putut salva optiunile", http.StatusInternalServerError)
return
}
}
if err := tx.Commit(); err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}
created, err := readGrInfoAdminQuestion(newID)
if err != nil {
jsonError(w, "Intrebare creata, dar nu poate fi citita", http.StatusCreated)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(created)
case http.MethodPut:
qid, err := strconv.Atoi(r.URL.Query().Get("id"))
if err != nil || qid <= 0 {
jsonError(w, "Parametrul id este invalid", http.StatusBadRequest)
return
}
req, validationErr := parseGrInfoAdminQuestionRequest(r)
if validationErr != "" {
jsonError(w, validationErr, http.StatusBadRequest)
return
}
var categoryID int
if err := db.QueryRow(`SELECT id FROM grinfo_categories WHERE slug = $1`, req.Category).Scan(&categoryID); err != nil {
jsonError(w, "Categorie invalida", http.StatusBadRequest)
return
}
tx, err := db.Begin()
if err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}
defer tx.Rollback()
res, err := tx.Exec(`
UPDATE grinfo_questions
SET category_id = $1,
difficulty = $2,
elo_rating = $3,
enunt = $4,
explicatie_raspuns = $5,
graph_data = $6::jsonb,
is_active = $7
WHERE id = $8
`, categoryID, req.Dificultate, req.EloRating, req.Enunt, req.ExplicatieRaspuns, req.GraphData, req.IsActive, qid)
if err != nil {
jsonError(w, "Nu s-a putut actualiza intrebarea", http.StatusInternalServerError)
return
}
affected, _ := res.RowsAffected()
if affected == 0 {
jsonError(w, "Intrebarea nu exista", http.StatusNotFound)
return
}
if _, err := tx.Exec(`DELETE FROM grinfo_question_options WHERE question_id = $1`, qid); err != nil {
jsonError(w, "Nu s-au putut actualiza optiunile", http.StatusInternalServerError)
return
}
for idx := 0; idx < 4; idx++ {
if _, err := tx.Exec(`
INSERT INTO grinfo_question_options (question_id, option_index, option_text, is_correct)
VALUES ($1, $2, $3, $4)
`, qid, idx, req.Optiuni[idx], idx == req.RaspunsCorect); err != nil {
jsonError(w, "Nu s-au putut salva optiunile", http.StatusInternalServerError)
return
}
}
if err := tx.Commit(); err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}
updated, err := readGrInfoAdminQuestion(qid)
if err != nil {
jsonError(w, "Intrebarea actualizata, dar nu poate fi citita", http.StatusOK)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(updated)
case http.MethodDelete:
qid, err := strconv.Atoi(r.URL.Query().Get("id"))
if err != nil || qid <= 0 {
jsonError(w, "Parametrul id este invalid", http.StatusBadRequest)
return
}
hardDelete := r.URL.Query().Get("hard") == "1"
if hardDelete {
res, err := db.Exec(`DELETE FROM grinfo_questions WHERE id = $1`, qid)
if err != nil {
jsonError(w, "Nu s-a putut sterge intrebarea", http.StatusInternalServerError)
return
}
affected, _ := res.RowsAffected()
if affected == 0 {
jsonError(w, "Intrebarea nu exista", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "hardDelete": true})
return
}
res, err := db.Exec(`UPDATE grinfo_questions SET is_active = FALSE WHERE id = $1`, qid)
if err != nil {
jsonError(w, "Nu s-a putut dezactiva intrebarea", http.StatusInternalServerError)
return
}
affected, _ := res.RowsAffected()
if affected == 0 {
jsonError(w, "Intrebarea nu exista", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "hardDelete": false})
default:
jsonError(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func apiGrInfoSessionStartHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req GrInfoSessionStartRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
req = GrInfoSessionStartRequest{}
}
if req.InitialElo <= 0 {
req.InitialElo = 1000
}
if req.TotalQuestions <= 0 {
req.TotalQuestions = 10
}
if req.Category == "" {
req.Category = "all"
}
if req.Difficulty == "" {
req.Difficulty = "all"
}
var userID sql.NullInt64
if uidStr := r.Header.Get("X-User-ID"); uidStr != "" {
if uid, err := strconv.Atoi(uidStr); err == nil {
userID = sql.NullInt64{Int64: int64(uid), Valid: true}
}
}
var sessionID int
err := db.QueryRow(`
INSERT INTO grinfo_sessions (user_id, category, difficulty, initial_elo, total_questions)
VALUES ($1, $2, $3, $4, $5)
RETURNING id
`, userID, req.Category, req.Difficulty, req.InitialElo, req.TotalQuestions).Scan(&sessionID)
if err != nil {
jsonError(w, "Database error", http.StatusInternalServerError)
return
}