Compare commits
14 Commits
2f76e6a3ca
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2841413927 | |||
| c6b2bb7800 | |||
| f9311292cc | |||
| b19c811048 | |||
| 76c2f17229 | |||
| 8fd1606424 | |||
| 37e4837e3f | |||
| 0ec12aa0ca | |||
| 1de143740a | |||
| 4088fbc9e7 | |||
| 6cac2f0c9a | |||
| 0de72a629c | |||
| 01bc52502f | |||
| 09aa034f52 |
@@ -1,6 +1,7 @@
|
|||||||
# Server Configuration
|
# Server Configuration
|
||||||
SERVER_PORT=5001
|
SERVER_PORT=5001
|
||||||
REACT_APP_API_BASE_URL=http://localhost:5001
|
REACT_APP_API_BASE_URL=http://localhost:5001
|
||||||
|
BODY_LIMIT=5mb
|
||||||
# Client Configuration
|
# Client Configuration
|
||||||
CLIENT_PORT=3001
|
CLIENT_PORT=3001
|
||||||
REACT_APP_CLIENT_URL=http://localhost:3001
|
REACT_APP_CLIENT_URL=http://localhost:3001
|
||||||
|
|||||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -33,3 +33,4 @@ build/
|
|||||||
# Other
|
# Other
|
||||||
coverage/
|
coverage/
|
||||||
.codebuddy
|
.codebuddy
|
||||||
|
.codex-docwork/
|
||||||
|
|||||||
@@ -84,7 +84,6 @@ _TD.a.push(function (TD) {
|
|||||||
"laser_gun": {
|
"laser_gun": {
|
||||||
damage: 25,
|
damage: 25,
|
||||||
range: 6,
|
range: 6,
|
||||||
max_range: 10,
|
|
||||||
speed: 20,
|
speed: 20,
|
||||||
// bullet_speed: 10, // laser_gun 的 bullet_speed 属性没有用
|
// bullet_speed: 10, // laser_gun 的 bullet_speed 属性没有用
|
||||||
life: 100,
|
life: 100,
|
||||||
|
|||||||
@@ -20,7 +20,20 @@
|
|||||||
for (var i = 0; i < map.buildings.length; i++) {
|
for (var i = 0; i < map.buildings.length; i++) {
|
||||||
var b = map.buildings[i];
|
var b = map.buildings[i];
|
||||||
if (!b || !b.grid) continue;
|
if (!b || !b.grid) continue;
|
||||||
buildings.push({ type: b.type, mx: b.grid.mx, my: b.grid.my, level: b.level, money: b.money });
|
buildings.push({
|
||||||
|
type: b.type,
|
||||||
|
mx: b.grid.mx,
|
||||||
|
my: b.grid.my,
|
||||||
|
level: b.level,
|
||||||
|
money: b.money,
|
||||||
|
killed: b.killed,
|
||||||
|
damage: b.damage,
|
||||||
|
range: b.range,
|
||||||
|
speed: b.speed,
|
||||||
|
life: b.life,
|
||||||
|
shield: b.shield,
|
||||||
|
upgrade_records: b._upgrade_records || null
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,8 +172,36 @@
|
|||||||
if (grid) grid.addBuilding(bi.type);
|
if (grid) grid.addBuilding(bi.type);
|
||||||
var b = grid && grid.building;
|
var b = grid && grid.building;
|
||||||
if (b) {
|
if (b) {
|
||||||
if (typeof bi.level !== 'undefined') b.level = bi.level;
|
var hasSavedBuildingAttrs = (
|
||||||
|
typeof bi.damage !== 'undefined' ||
|
||||||
|
typeof bi.range !== 'undefined' ||
|
||||||
|
typeof bi.speed !== 'undefined' ||
|
||||||
|
typeof bi.life !== 'undefined' ||
|
||||||
|
typeof bi.shield !== 'undefined'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasSavedBuildingAttrs && typeof bi.level !== 'undefined' && bi.level > 0 && typeof b.upgrade === 'function') {
|
||||||
|
for (var ul = 0; ul < bi.level; ul++) b.upgrade();
|
||||||
|
} else if (typeof bi.level !== 'undefined') {
|
||||||
|
b.level = bi.level;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof bi.damage !== 'undefined') b.damage = bi.damage;
|
||||||
|
if (typeof bi.range !== 'undefined') b.range = bi.range;
|
||||||
|
if (typeof bi.speed !== 'undefined') b.speed = bi.speed;
|
||||||
|
if (typeof bi.life !== 'undefined') b.life = bi.life;
|
||||||
|
if (typeof bi.shield !== 'undefined') b.shield = bi.shield;
|
||||||
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
||||||
|
if (typeof bi.killed !== 'undefined') b.killed = bi.killed;
|
||||||
|
if (bi.upgrade_records) {
|
||||||
|
b._upgrade_records = {};
|
||||||
|
for (var rk in bi.upgrade_records) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(bi.upgrade_records, rk)) {
|
||||||
|
b._upgrade_records[rk] = bi.upgrade_records[rk];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.range_px = b.range * TD.grid_size;
|
||||||
b.updateBtnDesc && b.updateBtnDesc();
|
b.updateBtnDesc && b.updateBtnDesc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,20 @@ window.__TD_getState = function () {
|
|||||||
for (var i = 0; i < map.buildings.length; i++) {
|
for (var i = 0; i < map.buildings.length; i++) {
|
||||||
var b = map.buildings[i];
|
var b = map.buildings[i];
|
||||||
if (!b || !b.grid) continue;
|
if (!b || !b.grid) continue;
|
||||||
buildings.push({ type: b.type, mx: b.grid.mx, my: b.grid.my, level: b.level, money: b.money });
|
buildings.push({
|
||||||
|
type: b.type,
|
||||||
|
mx: b.grid.mx,
|
||||||
|
my: b.grid.my,
|
||||||
|
level: b.level,
|
||||||
|
money: b.money,
|
||||||
|
killed: b.killed,
|
||||||
|
damage: b.damage,
|
||||||
|
range: b.range,
|
||||||
|
speed: b.speed,
|
||||||
|
life: b.life,
|
||||||
|
shield: b.shield,
|
||||||
|
upgrade_records: b._upgrade_records || null
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,8 +171,36 @@ window.__TD_loadState = function (s) {
|
|||||||
if (grid) grid.addBuilding(bi.type);
|
if (grid) grid.addBuilding(bi.type);
|
||||||
var b = grid && grid.building;
|
var b = grid && grid.building;
|
||||||
if (b) {
|
if (b) {
|
||||||
if (typeof bi.level !== 'undefined') b.level = bi.level;
|
var hasSavedBuildingAttrs = (
|
||||||
|
typeof bi.damage !== 'undefined' ||
|
||||||
|
typeof bi.range !== 'undefined' ||
|
||||||
|
typeof bi.speed !== 'undefined' ||
|
||||||
|
typeof bi.life !== 'undefined' ||
|
||||||
|
typeof bi.shield !== 'undefined'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasSavedBuildingAttrs && typeof bi.level !== 'undefined' && bi.level > 0 && typeof b.upgrade === 'function') {
|
||||||
|
for (var ul = 0; ul < bi.level; ul++) b.upgrade();
|
||||||
|
} else if (typeof bi.level !== 'undefined') {
|
||||||
|
b.level = bi.level;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof bi.damage !== 'undefined') b.damage = bi.damage;
|
||||||
|
if (typeof bi.range !== 'undefined') b.range = bi.range;
|
||||||
|
if (typeof bi.speed !== 'undefined') b.speed = bi.speed;
|
||||||
|
if (typeof bi.life !== 'undefined') b.life = bi.life;
|
||||||
|
if (typeof bi.shield !== 'undefined') b.shield = bi.shield;
|
||||||
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
||||||
|
if (typeof bi.killed !== 'undefined') b.killed = bi.killed;
|
||||||
|
if (bi.upgrade_records) {
|
||||||
|
b._upgrade_records = {};
|
||||||
|
for (var rk in bi.upgrade_records) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(bi.upgrade_records, rk)) {
|
||||||
|
b._upgrade_records[rk] = bi.upgrade_records[rk];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.range_px = b.range * TD.grid_size;
|
||||||
b.updateBtnDesc && b.updateBtnDesc();
|
b.updateBtnDesc && b.updateBtnDesc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -268,7 +268,20 @@ var _TD = {
|
|||||||
for (var i = 0; i < map.buildings.length; i++) {
|
for (var i = 0; i < map.buildings.length; i++) {
|
||||||
var b = map.buildings[i];
|
var b = map.buildings[i];
|
||||||
if (!b || !b.grid) continue;
|
if (!b || !b.grid) continue;
|
||||||
buildings.push({ type: b.type, mx: b.grid.mx, my: b.grid.my, level: b.level, money: b.money });
|
buildings.push({
|
||||||
|
type: b.type,
|
||||||
|
mx: b.grid.mx,
|
||||||
|
my: b.grid.my,
|
||||||
|
level: b.level,
|
||||||
|
money: b.money,
|
||||||
|
killed: b.killed,
|
||||||
|
damage: b.damage,
|
||||||
|
range: b.range,
|
||||||
|
speed: b.speed,
|
||||||
|
life: b.life,
|
||||||
|
shield: b.shield,
|
||||||
|
upgrade_records: b._upgrade_records || null
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,8 +372,36 @@ var _TD = {
|
|||||||
if (grid) grid.addBuilding(bi.type);
|
if (grid) grid.addBuilding(bi.type);
|
||||||
var b = grid && grid.building;
|
var b = grid && grid.building;
|
||||||
if (b) {
|
if (b) {
|
||||||
if (typeof bi.level !== 'undefined') b.level = bi.level;
|
var hasSavedBuildingAttrs = (
|
||||||
|
typeof bi.damage !== 'undefined' ||
|
||||||
|
typeof bi.range !== 'undefined' ||
|
||||||
|
typeof bi.speed !== 'undefined' ||
|
||||||
|
typeof bi.life !== 'undefined' ||
|
||||||
|
typeof bi.shield !== 'undefined'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasSavedBuildingAttrs && typeof bi.level !== 'undefined' && bi.level > 0 && typeof b.upgrade === 'function') {
|
||||||
|
for (var ul = 0; ul < bi.level; ul++) b.upgrade();
|
||||||
|
} else if (typeof bi.level !== 'undefined') {
|
||||||
|
b.level = bi.level;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof bi.damage !== 'undefined') b.damage = bi.damage;
|
||||||
|
if (typeof bi.range !== 'undefined') b.range = bi.range;
|
||||||
|
if (typeof bi.speed !== 'undefined') b.speed = bi.speed;
|
||||||
|
if (typeof bi.life !== 'undefined') b.life = bi.life;
|
||||||
|
if (typeof bi.shield !== 'undefined') b.shield = bi.shield;
|
||||||
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
||||||
|
if (typeof bi.killed !== 'undefined') b.killed = bi.killed;
|
||||||
|
if (bi.upgrade_records) {
|
||||||
|
b._upgrade_records = {};
|
||||||
|
for (var rk in bi.upgrade_records) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(bi.upgrade_records, rk)) {
|
||||||
|
b._upgrade_records[rk] = bi.upgrade_records[rk];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.range_px = b.range * TD.grid_size;
|
||||||
b.updateBtnDesc && b.updateBtnDesc();
|
b.updateBtnDesc && b.updateBtnDesc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -71,7 +71,20 @@
|
|||||||
for (var i = 0; i < map.buildings.length; i++) {
|
for (var i = 0; i < map.buildings.length; i++) {
|
||||||
var b = map.buildings[i];
|
var b = map.buildings[i];
|
||||||
if (!b || !b.grid) continue;
|
if (!b || !b.grid) continue;
|
||||||
buildings.push({ type: b.type, mx: b.grid.mx, my: b.grid.my, level: b.level, money: b.money });
|
buildings.push({
|
||||||
|
type: b.type,
|
||||||
|
mx: b.grid.mx,
|
||||||
|
my: b.grid.my,
|
||||||
|
level: b.level,
|
||||||
|
money: b.money,
|
||||||
|
killed: b.killed,
|
||||||
|
damage: b.damage,
|
||||||
|
range: b.range,
|
||||||
|
speed: b.speed,
|
||||||
|
life: b.life,
|
||||||
|
shield: b.shield,
|
||||||
|
upgrade_records: b._upgrade_records || null
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -210,8 +223,36 @@
|
|||||||
if (grid) grid.addBuilding(bi.type);
|
if (grid) grid.addBuilding(bi.type);
|
||||||
var b = grid && grid.building;
|
var b = grid && grid.building;
|
||||||
if (b) {
|
if (b) {
|
||||||
if (typeof bi.level !== 'undefined') b.level = bi.level;
|
var hasSavedBuildingAttrs = (
|
||||||
|
typeof bi.damage !== 'undefined' ||
|
||||||
|
typeof bi.range !== 'undefined' ||
|
||||||
|
typeof bi.speed !== 'undefined' ||
|
||||||
|
typeof bi.life !== 'undefined' ||
|
||||||
|
typeof bi.shield !== 'undefined'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasSavedBuildingAttrs && typeof bi.level !== 'undefined' && bi.level > 0 && typeof b.upgrade === 'function') {
|
||||||
|
for (var ul = 0; ul < bi.level; ul++) b.upgrade();
|
||||||
|
} else if (typeof bi.level !== 'undefined') {
|
||||||
|
b.level = bi.level;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof bi.damage !== 'undefined') b.damage = bi.damage;
|
||||||
|
if (typeof bi.range !== 'undefined') b.range = bi.range;
|
||||||
|
if (typeof bi.speed !== 'undefined') b.speed = bi.speed;
|
||||||
|
if (typeof bi.life !== 'undefined') b.life = bi.life;
|
||||||
|
if (typeof bi.shield !== 'undefined') b.shield = bi.shield;
|
||||||
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
||||||
|
if (typeof bi.killed !== 'undefined') b.killed = bi.killed;
|
||||||
|
if (bi.upgrade_records) {
|
||||||
|
b._upgrade_records = {};
|
||||||
|
for (var rk in bi.upgrade_records) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(bi.upgrade_records, rk)) {
|
||||||
|
b._upgrade_records[rk] = bi.upgrade_records[rk];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.range_px = b.range * TD.grid_size;
|
||||||
b.updateBtnDesc && b.updateBtnDesc();
|
b.updateBtnDesc && b.updateBtnDesc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
"debug:server": "cross-env NODE_OPTIONS=\"--loader ts-node/esm --inspect=5858\" ts-node-dev server/server.ts",
|
"debug:server": "cross-env NODE_OPTIONS=\"--loader ts-node/esm --inspect=5858\" ts-node-dev server/server.ts",
|
||||||
"debug:client": "cross-env PORT=3001 react-scripts start",
|
"debug:client": "cross-env PORT=3001 react-scripts start",
|
||||||
"debug": "concurrently \"npm run debug:server\" \"npm run debug:client\"",
|
"debug": "concurrently \"npm run debug:server\" \"npm run debug:client\"",
|
||||||
"build": "react-scripts build",
|
"build": "cross-env GENERATE_SOURCEMAP=false react-scripts build",
|
||||||
"test": "react-scripts test",
|
"test": "react-scripts test",
|
||||||
"eject": "react-scripts eject",
|
"eject": "react-scripts eject",
|
||||||
"migrate-passwords": "ts-node -P tsconfig.json scripts/migratePasswords.ts"
|
"migrate-passwords": "ts-node -P tsconfig.json scripts/migratePasswords.ts"
|
||||||
|
|||||||
48
public/tower-defense/td-pkg-zh-min.js
vendored
48
public/tower-defense/td-pkg-zh-min.js
vendored
@@ -265,7 +265,20 @@ var _TD = {
|
|||||||
for (var i = 0; i < map.buildings.length; i++) {
|
for (var i = 0; i < map.buildings.length; i++) {
|
||||||
var b = map.buildings[i];
|
var b = map.buildings[i];
|
||||||
if (!b || !b.grid) continue;
|
if (!b || !b.grid) continue;
|
||||||
buildings.push({ type: b.type, mx: b.grid.mx, my: b.grid.my, level: b.level, money: b.money });
|
buildings.push({
|
||||||
|
type: b.type,
|
||||||
|
mx: b.grid.mx,
|
||||||
|
my: b.grid.my,
|
||||||
|
level: b.level,
|
||||||
|
money: b.money,
|
||||||
|
killed: b.killed,
|
||||||
|
damage: b.damage,
|
||||||
|
range: b.range,
|
||||||
|
speed: b.speed,
|
||||||
|
life: b.life,
|
||||||
|
shield: b.shield,
|
||||||
|
upgrade_records: b._upgrade_records || null
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { money: TD.money, life: TD.life, score: TD.score, wave: (scene && scene.wave) || 0, buildings: buildings };
|
return { money: TD.money, life: TD.life, score: TD.score, wave: (scene && scene.wave) || 0, buildings: buildings };
|
||||||
@@ -294,8 +307,36 @@ var _TD = {
|
|||||||
if (grid) grid.addBuilding(bi.type);
|
if (grid) grid.addBuilding(bi.type);
|
||||||
var b = grid && grid.building;
|
var b = grid && grid.building;
|
||||||
if (b) {
|
if (b) {
|
||||||
if (typeof bi.level !== 'undefined') b.level = bi.level;
|
var hasSavedBuildingAttrs = (
|
||||||
|
typeof bi.damage !== 'undefined' ||
|
||||||
|
typeof bi.range !== 'undefined' ||
|
||||||
|
typeof bi.speed !== 'undefined' ||
|
||||||
|
typeof bi.life !== 'undefined' ||
|
||||||
|
typeof bi.shield !== 'undefined'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasSavedBuildingAttrs && typeof bi.level !== 'undefined' && bi.level > 0 && typeof b.upgrade === 'function') {
|
||||||
|
for (var ul = 0; ul < bi.level; ul++) b.upgrade();
|
||||||
|
} else if (typeof bi.level !== 'undefined') {
|
||||||
|
b.level = bi.level;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof bi.damage !== 'undefined') b.damage = bi.damage;
|
||||||
|
if (typeof bi.range !== 'undefined') b.range = bi.range;
|
||||||
|
if (typeof bi.speed !== 'undefined') b.speed = bi.speed;
|
||||||
|
if (typeof bi.life !== 'undefined') b.life = bi.life;
|
||||||
|
if (typeof bi.shield !== 'undefined') b.shield = bi.shield;
|
||||||
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
||||||
|
if (typeof bi.killed !== 'undefined') b.killed = bi.killed;
|
||||||
|
if (bi.upgrade_records) {
|
||||||
|
b._upgrade_records = {};
|
||||||
|
for (var rk in bi.upgrade_records) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(bi.upgrade_records, rk)) {
|
||||||
|
b._upgrade_records[rk] = bi.upgrade_records[rk];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.range_px = b.range * TD.grid_size;
|
||||||
b.updateBtnDesc && b.updateBtnDesc();
|
b.updateBtnDesc && b.updateBtnDesc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3845,7 +3886,6 @@ _TD.a.push(function (TD) {
|
|||||||
"laser_gun": {
|
"laser_gun": {
|
||||||
damage: 25,
|
damage: 25,
|
||||||
range: 6,
|
range: 6,
|
||||||
max_range: 10,
|
|
||||||
speed: 20,
|
speed: 20,
|
||||||
// bullet_speed: 10, // laser_gun 的 bullet_speed 属性没有用
|
// bullet_speed: 10, // laser_gun 的 bullet_speed 属性没有用
|
||||||
life: 100,
|
life: 100,
|
||||||
@@ -4584,5 +4624,3 @@ _TD.a.push(function (TD) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
}); // _TD.a.push end
|
}); // _TD.a.push end
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3824,7 +3824,6 @@ _TD.a.push(function (TD) {
|
|||||||
"laser_gun": {
|
"laser_gun": {
|
||||||
damage: 25,
|
damage: 25,
|
||||||
range: 6,
|
range: 6,
|
||||||
max_range: 10,
|
|
||||||
speed: 20,
|
speed: 20,
|
||||||
// bullet_speed: 10, // laser_gun 的 bullet_speed 属性没有用
|
// bullet_speed: 10, // laser_gun 的 bullet_speed 属性没有用
|
||||||
life: 100,
|
life: 100,
|
||||||
|
|||||||
@@ -95,7 +95,20 @@
|
|||||||
for (var i = 0; i < map.buildings.length; i++) {
|
for (var i = 0; i < map.buildings.length; i++) {
|
||||||
var b = map.buildings[i];
|
var b = map.buildings[i];
|
||||||
if (!b || !b.grid) continue;
|
if (!b || !b.grid) continue;
|
||||||
buildings.push({ type: b.type, mx: b.grid.mx, my: b.grid.my, level: b.level, money: b.money });
|
buildings.push({
|
||||||
|
type: b.type,
|
||||||
|
mx: b.grid.mx,
|
||||||
|
my: b.grid.my,
|
||||||
|
level: b.level,
|
||||||
|
money: b.money,
|
||||||
|
killed: b.killed,
|
||||||
|
damage: b.damage,
|
||||||
|
range: b.range,
|
||||||
|
speed: b.speed,
|
||||||
|
life: b.life,
|
||||||
|
shield: b.shield,
|
||||||
|
upgrade_records: b._upgrade_records || null
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,8 +203,36 @@
|
|||||||
grid.addBuilding(bi.type);
|
grid.addBuilding(bi.type);
|
||||||
var b = grid.building;
|
var b = grid.building;
|
||||||
if (b) {
|
if (b) {
|
||||||
if (typeof bi.level !== 'undefined') b.level = bi.level;
|
var hasSavedBuildingAttrs = (
|
||||||
|
typeof bi.damage !== 'undefined' ||
|
||||||
|
typeof bi.range !== 'undefined' ||
|
||||||
|
typeof bi.speed !== 'undefined' ||
|
||||||
|
typeof bi.life !== 'undefined' ||
|
||||||
|
typeof bi.shield !== 'undefined'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!hasSavedBuildingAttrs && typeof bi.level !== 'undefined' && bi.level > 0 && typeof b.upgrade === 'function') {
|
||||||
|
for (var ul = 0; ul < bi.level; ul++) b.upgrade();
|
||||||
|
} else if (typeof bi.level !== 'undefined') {
|
||||||
|
b.level = bi.level;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof bi.damage !== 'undefined') b.damage = bi.damage;
|
||||||
|
if (typeof bi.range !== 'undefined') b.range = bi.range;
|
||||||
|
if (typeof bi.speed !== 'undefined') b.speed = bi.speed;
|
||||||
|
if (typeof bi.life !== 'undefined') b.life = bi.life;
|
||||||
|
if (typeof bi.shield !== 'undefined') b.shield = bi.shield;
|
||||||
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
if (typeof bi.money !== 'undefined') b.money = bi.money;
|
||||||
|
if (typeof bi.killed !== 'undefined') b.killed = bi.killed;
|
||||||
|
if (bi.upgrade_records) {
|
||||||
|
b._upgrade_records = {};
|
||||||
|
for (var rk in bi.upgrade_records) {
|
||||||
|
if (Object.prototype.hasOwnProperty.call(bi.upgrade_records, rk)) {
|
||||||
|
b._upgrade_records[rk] = bi.upgrade_records[rk];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.range_px = b.range * TD.grid_size;
|
||||||
b.updateBtnDesc && b.updateBtnDesc();
|
b.updateBtnDesc && b.updateBtnDesc();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
# 服务器配置
|
# 服务器配置
|
||||||
PORT=5001
|
PORT=5001
|
||||||
NODE_ENV=development
|
NODE_ENV=development
|
||||||
|
BODY_LIMIT=5mb
|
||||||
|
|
||||||
# 数据库配置
|
# 数据库配置
|
||||||
MONGODB_URI=mongodb://localhost:27017/typeskill
|
MONGODB_URI=mongodb://localhost:27017/typeskill
|
||||||
@@ -8,5 +9,8 @@ MONGODB_URI=mongodb://localhost:27017/typeskill
|
|||||||
# JWT配置
|
# JWT配置
|
||||||
JWT_SECRET=your_jwt_secret_key_here
|
JWT_SECRET=your_jwt_secret_key_here
|
||||||
|
|
||||||
|
# 词汇防作弊配置
|
||||||
|
VOCABULARY_FULL_CORRECT_WORD_THRESHOLD=50
|
||||||
|
|
||||||
# CORS配置
|
# CORS配置
|
||||||
CORS_ORIGIN=http://localhost:3000
|
CORS_ORIGIN=http://localhost:3000
|
||||||
@@ -56,6 +56,12 @@ export interface IVocabularyTestRecord extends Document {
|
|||||||
correctAnswer: string;
|
correctAnswer: string;
|
||||||
isCorrect: boolean;
|
isCorrect: boolean;
|
||||||
}>;
|
}>;
|
||||||
|
invalidated?: boolean;
|
||||||
|
riskFlags?: string[];
|
||||||
|
reviewDecision?: 'approved';
|
||||||
|
reviewedBy?: mongoose.Types.ObjectId;
|
||||||
|
reviewedAt?: Date;
|
||||||
|
reviewNote?: string;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,6 +71,35 @@ export interface IVocabularyTestAttempt extends Document {
|
|||||||
testType: 'chinese-to-english' | 'audio-to-english' | 'multiple-choice';
|
testType: 'chinese-to-english' | 'audio-to-english' | 'multiple-choice';
|
||||||
questionWordIds: mongoose.Types.ObjectId[];
|
questionWordIds: mongoose.Types.ObjectId[];
|
||||||
questionTokens: string[];
|
questionTokens: string[];
|
||||||
|
optionTokens?: string[][];
|
||||||
|
optionTexts?: string[][];
|
||||||
|
answeredQuestionTokens?: string[];
|
||||||
|
answerDurations?: number[];
|
||||||
|
answers?: Array<{
|
||||||
|
questionToken: string;
|
||||||
|
word: mongoose.Types.ObjectId;
|
||||||
|
userAnswer: string;
|
||||||
|
correctAnswer: string;
|
||||||
|
isCorrect: boolean;
|
||||||
|
submittedAt: Date;
|
||||||
|
duration: number;
|
||||||
|
riskFlags: string[];
|
||||||
|
interactionSummary?: {
|
||||||
|
keyCount: number;
|
||||||
|
inputCount: number;
|
||||||
|
pasteCount: number;
|
||||||
|
focusCount: number;
|
||||||
|
blurCount: number;
|
||||||
|
pointerCount: number;
|
||||||
|
firstEventOffset: number;
|
||||||
|
lastEventOffset: number;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
riskFlags?: string[];
|
||||||
|
reviewDecision?: 'approved';
|
||||||
|
reviewedBy?: mongoose.Types.ObjectId;
|
||||||
|
reviewedAt?: Date;
|
||||||
|
reviewNote?: string;
|
||||||
issuedAt: Date;
|
issuedAt: Date;
|
||||||
expiresAt: Date;
|
expiresAt: Date;
|
||||||
submittedAt?: Date;
|
submittedAt?: Date;
|
||||||
@@ -149,6 +184,12 @@ const VocabularyTestRecordSchema = new Schema<IVocabularyTestRecord>({
|
|||||||
correctAnswer: { type: String, required: true },
|
correctAnswer: { type: String, required: true },
|
||||||
isCorrect: { type: Boolean, required: true }
|
isCorrect: { type: Boolean, required: true }
|
||||||
}],
|
}],
|
||||||
|
invalidated: { type: Boolean, default: false },
|
||||||
|
riskFlags: [{ type: String }],
|
||||||
|
reviewDecision: { type: String, enum: ['approved'] },
|
||||||
|
reviewedBy: { type: Schema.Types.ObjectId, ref: 'User' },
|
||||||
|
reviewedAt: Date,
|
||||||
|
reviewNote: { type: String, trim: true, maxlength: 500 },
|
||||||
createdAt: { type: Date, default: Date.now }
|
createdAt: { type: Date, default: Date.now }
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -163,6 +204,35 @@ const VocabularyTestAttemptSchema = new Schema<IVocabularyTestAttempt>({
|
|||||||
},
|
},
|
||||||
questionWordIds: [{ type: Schema.Types.ObjectId, ref: 'Word', required: true }],
|
questionWordIds: [{ type: Schema.Types.ObjectId, ref: 'Word', required: true }],
|
||||||
questionTokens: [{ type: String, required: true }],
|
questionTokens: [{ type: String, required: true }],
|
||||||
|
optionTokens: [[{ type: String }]],
|
||||||
|
optionTexts: [[{ type: String }]],
|
||||||
|
answeredQuestionTokens: [{ type: String }],
|
||||||
|
answerDurations: [{ type: Number }],
|
||||||
|
answers: [{
|
||||||
|
questionToken: { type: String, required: true },
|
||||||
|
word: { type: Schema.Types.ObjectId, ref: 'Word', required: true },
|
||||||
|
userAnswer: { type: String, default: '' },
|
||||||
|
correctAnswer: { type: String, required: true },
|
||||||
|
isCorrect: { type: Boolean, required: true },
|
||||||
|
submittedAt: { type: Date, required: true },
|
||||||
|
duration: { type: Number, required: true },
|
||||||
|
riskFlags: [{ type: String }],
|
||||||
|
interactionSummary: {
|
||||||
|
keyCount: { type: Number, default: 0 },
|
||||||
|
inputCount: { type: Number, default: 0 },
|
||||||
|
pasteCount: { type: Number, default: 0 },
|
||||||
|
focusCount: { type: Number, default: 0 },
|
||||||
|
blurCount: { type: Number, default: 0 },
|
||||||
|
pointerCount: { type: Number, default: 0 },
|
||||||
|
firstEventOffset: { type: Number, default: 0 },
|
||||||
|
lastEventOffset: { type: Number, default: 0 }
|
||||||
|
}
|
||||||
|
}],
|
||||||
|
riskFlags: [{ type: String }],
|
||||||
|
reviewDecision: { type: String, enum: ['approved'] },
|
||||||
|
reviewedBy: { type: Schema.Types.ObjectId, ref: 'User' },
|
||||||
|
reviewedAt: Date,
|
||||||
|
reviewNote: { type: String, trim: true, maxlength: 500 },
|
||||||
issuedAt: { type: Date, required: true },
|
issuedAt: { type: Date, required: true },
|
||||||
expiresAt: { type: Date, required: true },
|
expiresAt: { type: Date, required: true },
|
||||||
submittedAt: Date,
|
submittedAt: Date,
|
||||||
|
|||||||
@@ -9,8 +9,13 @@ import multer from 'multer';
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import csv from 'csv-parser';
|
import csv from 'csv-parser';
|
||||||
import { Word, WordSet } from '../models/Vocabulary';
|
import { Word, WordRecord, WordSet, VocabularyTestAttempt, VocabularyTestRecord } from '../models/Vocabulary';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
|
import { INVALIDATING_VOCABULARY_RISK_FLAGS } from '../utils/vocabularyRisk';
|
||||||
|
import {
|
||||||
|
applyVocabularySummaryItemFilters,
|
||||||
|
buildVocabularySummaryFilters
|
||||||
|
} from '../utils/vocabularyAuditFilters';
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
const adminController = new AdminController();
|
const adminController = new AdminController();
|
||||||
@@ -45,6 +50,211 @@ const upload = multer({
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
type VocabularyTestType = 'chinese-to-english' | 'audio-to-english' | 'multiple-choice';
|
||||||
|
type WordRecordModeKey = 'chineseToEnglish' | 'audioToEnglish' | 'multipleChoice';
|
||||||
|
|
||||||
|
const TEST_TYPE_TO_MODE: Record<VocabularyTestType, WordRecordModeKey> = {
|
||||||
|
'chinese-to-english': 'chineseToEnglish',
|
||||||
|
'audio-to-english': 'audioToEnglish',
|
||||||
|
'multiple-choice': 'multipleChoice'
|
||||||
|
};
|
||||||
|
|
||||||
|
const WORD_RECORD_MODES: WordRecordModeKey[] = [
|
||||||
|
'chineseToEnglish',
|
||||||
|
'audioToEnglish',
|
||||||
|
'multipleChoice'
|
||||||
|
];
|
||||||
|
|
||||||
|
const getObjectIdString = (value: any): string => value?._id?.toString?.() || value?.toString?.() || '';
|
||||||
|
|
||||||
|
const parseAdminDateRange = (source: Record<string, any>) => {
|
||||||
|
const start = new Date(String(source.start || source.startTime || ''));
|
||||||
|
const end = new Date(String(source.end || source.endTime || ''));
|
||||||
|
|
||||||
|
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
|
||||||
|
return { error: '请选择有效的开始和结束时间' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (start > end) {
|
||||||
|
return { error: '开始时间不能晚于结束时间' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { start, end };
|
||||||
|
};
|
||||||
|
|
||||||
|
const createEmptyModeStats = () => ({
|
||||||
|
streak: 0,
|
||||||
|
totalCorrect: 0,
|
||||||
|
totalWrong: 0,
|
||||||
|
mastered: false,
|
||||||
|
inWrongBook: false,
|
||||||
|
lastTestedAt: undefined as Date | undefined,
|
||||||
|
lastMasteredAt: undefined as Date | undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
const applyVocabularyAnswer = (modeStats: ReturnType<typeof createEmptyModeStats>, isCorrect: boolean, testedAt: Date) => {
|
||||||
|
if (isCorrect) {
|
||||||
|
modeStats.streak = (modeStats.streak || 0) + 1;
|
||||||
|
modeStats.totalCorrect = (modeStats.totalCorrect || 0) + 1;
|
||||||
|
} else {
|
||||||
|
modeStats.streak = 0;
|
||||||
|
modeStats.totalWrong = (modeStats.totalWrong || 0) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
modeStats.lastTestedAt = testedAt;
|
||||||
|
|
||||||
|
if (modeStats.streak >= 1) {
|
||||||
|
modeStats.mastered = true;
|
||||||
|
modeStats.lastMasteredAt = testedAt;
|
||||||
|
modeStats.inWrongBook = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!modeStats.mastered && modeStats.totalWrong >= 5) {
|
||||||
|
modeStats.inWrongBook = true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getLatestMasteredAt = (state: Record<WordRecordModeKey, ReturnType<typeof createEmptyModeStats>>): Date | undefined => {
|
||||||
|
let latest: Date | undefined;
|
||||||
|
WORD_RECORD_MODES.forEach(mode => {
|
||||||
|
[state[mode].lastMasteredAt, state[mode].lastTestedAt].forEach(value => {
|
||||||
|
if (!value) return;
|
||||||
|
if (!latest || value > latest) latest = value;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return latest;
|
||||||
|
};
|
||||||
|
|
||||||
|
const rebuildVocabularyWordRecordsForUser = async (
|
||||||
|
userId: string,
|
||||||
|
wordIds: string[]
|
||||||
|
) => {
|
||||||
|
const uniqueWordIds = Array.from(new Set(wordIds.filter(id => mongoose.isValidObjectId(id))));
|
||||||
|
if (uniqueWordIds.length === 0) return { affectedWords: 0, rebuiltWords: 0 };
|
||||||
|
|
||||||
|
const userObjectId = new mongoose.Types.ObjectId(userId);
|
||||||
|
const wordObjectIds = uniqueWordIds.map(id => new mongoose.Types.ObjectId(id));
|
||||||
|
const wordIdSet = new Set(uniqueWordIds);
|
||||||
|
const states = new Map<string, Record<WordRecordModeKey, ReturnType<typeof createEmptyModeStats>>>();
|
||||||
|
|
||||||
|
const records = await VocabularyTestRecord.find({
|
||||||
|
user: userObjectId,
|
||||||
|
invalidated: { $ne: true },
|
||||||
|
'results.word': { $in: wordObjectIds }
|
||||||
|
})
|
||||||
|
.select('testType stats.endTime createdAt results attempt')
|
||||||
|
.sort({ 'stats.endTime': 1, createdAt: 1 })
|
||||||
|
.lean();
|
||||||
|
|
||||||
|
const attemptIds = records
|
||||||
|
.map((record: any) => record.attempt?.toString?.() || '')
|
||||||
|
.filter(id => mongoose.isValidObjectId(id));
|
||||||
|
const attempts = attemptIds.length > 0
|
||||||
|
? await VocabularyTestAttempt.find({ _id: { $in: attemptIds } }).select('riskFlags reviewDecision').lean()
|
||||||
|
: [];
|
||||||
|
const invalidatedAttemptIds = new Set(
|
||||||
|
attempts
|
||||||
|
.filter((attempt: any) =>
|
||||||
|
attempt.reviewDecision !== 'approved' &&
|
||||||
|
(attempt.riskFlags || []).some((flag: string) => INVALIDATING_VOCABULARY_RISK_FLAGS.includes(flag))
|
||||||
|
)
|
||||||
|
.map((attempt: any) => attempt._id.toString())
|
||||||
|
);
|
||||||
|
|
||||||
|
records.forEach((record: any) => {
|
||||||
|
const attemptId = record.attempt?.toString?.() || '';
|
||||||
|
if (attemptId && invalidatedAttemptIds.has(attemptId)) return;
|
||||||
|
|
||||||
|
const modeKey = TEST_TYPE_TO_MODE[record.testType as VocabularyTestType];
|
||||||
|
if (!modeKey) return;
|
||||||
|
|
||||||
|
const testedAt = new Date(record.stats?.endTime || record.createdAt || Date.now());
|
||||||
|
(record.results || []).forEach((result: any) => {
|
||||||
|
const wordId = result.word?.toString?.() || String(result.word || '');
|
||||||
|
if (!wordIdSet.has(wordId)) return;
|
||||||
|
|
||||||
|
if (!states.has(wordId)) {
|
||||||
|
states.set(wordId, {
|
||||||
|
chineseToEnglish: createEmptyModeStats(),
|
||||||
|
audioToEnglish: createEmptyModeStats(),
|
||||||
|
multipleChoice: createEmptyModeStats()
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const state = states.get(wordId)!;
|
||||||
|
applyVocabularyAnswer(state[modeKey], Boolean(result.isCorrect), testedAt);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await WordRecord.deleteMany({ user: userObjectId, word: { $in: wordObjectIds } });
|
||||||
|
|
||||||
|
const rebuiltDocs = Array.from(states.entries()).map(([wordId, state]) => {
|
||||||
|
const isFullyMastered = WORD_RECORD_MODES.every(mode => state[mode].mastered);
|
||||||
|
return {
|
||||||
|
user: userObjectId,
|
||||||
|
word: new mongoose.Types.ObjectId(wordId),
|
||||||
|
chineseToEnglish: state.chineseToEnglish,
|
||||||
|
audioToEnglish: state.audioToEnglish,
|
||||||
|
multipleChoice: state.multipleChoice,
|
||||||
|
isFullyMastered,
|
||||||
|
lastFullyMasteredAt: isFullyMastered ? getLatestMasteredAt(state) : undefined,
|
||||||
|
createdAt: new Date()
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
if (rebuiltDocs.length > 0) {
|
||||||
|
await WordRecord.insertMany(rebuiltDocs);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
affectedWords: uniqueWordIds.length,
|
||||||
|
rebuiltWords: rebuiltDocs.length
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const serializeUserRef = (value: any) => {
|
||||||
|
const id = getObjectIdString(value);
|
||||||
|
if (!id) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
_id: id,
|
||||||
|
username: value?.username || '',
|
||||||
|
fullname: value?.fullname || '',
|
||||||
|
email: value?.email || ''
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const serializeWordRef = (value: any) => {
|
||||||
|
const id = getObjectIdString(value);
|
||||||
|
if (!id) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
_id: id,
|
||||||
|
word: value?.word || '',
|
||||||
|
translation: value?.translation || '',
|
||||||
|
pronunciation: value?.pronunciation || '',
|
||||||
|
example: value?.example || ''
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const serializeWordSetRef = (value: any) => {
|
||||||
|
const id = getObjectIdString(value);
|
||||||
|
if (!id) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
_id: id,
|
||||||
|
name: value?.name || '',
|
||||||
|
description: value?.description || ''
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const flattenRiskFlags = (items: any[]): string[] => Array.from(new Set(
|
||||||
|
(items || [])
|
||||||
|
.flatMap(item => Array.isArray(item) ? item : [item])
|
||||||
|
.filter(Boolean)
|
||||||
|
.map(item => String(item))
|
||||||
|
));
|
||||||
|
|
||||||
router.get('/users', adminAuth, async (req, res) => {
|
router.get('/users', adminAuth, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const users = await User.find()
|
const users = await User.find()
|
||||||
@@ -321,4 +531,510 @@ router.get('/vocabulary/word-sets/:id/words', adminAuth, async (req, res) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// 按时间段汇总学生词汇测试通过情况
|
||||||
|
router.get('/vocabulary/test-pass-summary', adminAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const range = parseAdminDateRange(req.query as Record<string, any>);
|
||||||
|
if (range.error) {
|
||||||
|
return res.status(400).json({ message: range.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { start, end } = range as { start: Date; end: Date };
|
||||||
|
const summaryFilters = buildVocabularySummaryFilters(req.query as Record<string, any>);
|
||||||
|
if ('error' in summaryFilters) {
|
||||||
|
return res.status(400).json({ message: summaryFilters.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { userMatchStages, baseMatch, minUniqueWords } = summaryFilters;
|
||||||
|
const validPassItems = await VocabularyTestRecord.aggregate([
|
||||||
|
{
|
||||||
|
$match: {
|
||||||
|
...baseMatch,
|
||||||
|
invalidated: { $ne: true },
|
||||||
|
'stats.endTime': { $gte: start, $lte: end },
|
||||||
|
'stats.correctWords': { $gt: 0 }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ $unwind: '$results' },
|
||||||
|
{ $match: { 'results.isCorrect': true } },
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: '$user',
|
||||||
|
passedWords: { $sum: 1 },
|
||||||
|
uniqueWordIds: { $addToSet: '$results.word' },
|
||||||
|
testRecordIds: { $addToSet: '$_id' },
|
||||||
|
wordSetIds: { $addToSet: '$wordSet' },
|
||||||
|
testTypes: { $addToSet: '$testType' },
|
||||||
|
firstPassedAt: { $min: '$stats.endTime' },
|
||||||
|
lastPassedAt: { $max: '$stats.endTime' }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'users',
|
||||||
|
localField: '_id',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'user'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ $unwind: { path: '$user', preserveNullAndEmptyArrays: true } },
|
||||||
|
...userMatchStages,
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
_id: 0,
|
||||||
|
userId: { $toString: '$_id' },
|
||||||
|
username: '$user.username',
|
||||||
|
fullname: '$user.fullname',
|
||||||
|
email: '$user.email',
|
||||||
|
passedWords: 1,
|
||||||
|
uniqueWords: { $size: '$uniqueWordIds' },
|
||||||
|
testRecords: { $size: '$testRecordIds' },
|
||||||
|
wordSets: { $size: '$wordSetIds' },
|
||||||
|
testTypes: 1,
|
||||||
|
firstPassedAt: 1,
|
||||||
|
lastPassedAt: 1
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ $sort: { passedWords: -1, lastPassedAt: -1 } }
|
||||||
|
]);
|
||||||
|
|
||||||
|
const recordItems = await VocabularyTestRecord.aggregate([
|
||||||
|
{
|
||||||
|
$match: {
|
||||||
|
...baseMatch,
|
||||||
|
'stats.endTime': { $gte: start, $lte: end }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$group: {
|
||||||
|
_id: '$user',
|
||||||
|
totalRecords: { $sum: 1 },
|
||||||
|
validRecords: {
|
||||||
|
$sum: {
|
||||||
|
$cond: [{ $eq: ['$invalidated', true] }, 0, 1]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
invalidatedRecords: {
|
||||||
|
$sum: {
|
||||||
|
$cond: [{ $eq: ['$invalidated', true] }, 1, 0]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
riskFlagSets: { $addToSet: '$riskFlags' },
|
||||||
|
wordSetIds: { $addToSet: '$wordSet' },
|
||||||
|
testTypes: { $addToSet: '$testType' },
|
||||||
|
firstRecordAt: { $min: '$stats.endTime' },
|
||||||
|
lastRecordAt: { $max: '$stats.endTime' }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'users',
|
||||||
|
localField: '_id',
|
||||||
|
foreignField: '_id',
|
||||||
|
as: 'user'
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ $unwind: { path: '$user', preserveNullAndEmptyArrays: true } },
|
||||||
|
...userMatchStages,
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
_id: 0,
|
||||||
|
userId: { $toString: '$_id' },
|
||||||
|
username: '$user.username',
|
||||||
|
fullname: '$user.fullname',
|
||||||
|
email: '$user.email',
|
||||||
|
totalRecords: 1,
|
||||||
|
validRecords: 1,
|
||||||
|
invalidatedRecords: 1,
|
||||||
|
riskFlagSets: 1,
|
||||||
|
wordSets: { $size: '$wordSetIds' },
|
||||||
|
testTypes: 1,
|
||||||
|
firstRecordAt: 1,
|
||||||
|
lastRecordAt: 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
|
||||||
|
const passMap = new Map(validPassItems.map((item: any) => [item.userId, item]));
|
||||||
|
const itemMap = new Map<string, any>();
|
||||||
|
|
||||||
|
recordItems.forEach((recordItem: any) => {
|
||||||
|
const passItem = passMap.get(recordItem.userId) || {};
|
||||||
|
itemMap.set(recordItem.userId, {
|
||||||
|
userId: recordItem.userId,
|
||||||
|
username: recordItem.username || passItem.username || '',
|
||||||
|
fullname: recordItem.fullname || passItem.fullname || '',
|
||||||
|
email: recordItem.email || passItem.email || '',
|
||||||
|
passedWords: passItem.passedWords || 0,
|
||||||
|
uniqueWords: passItem.uniqueWords || 0,
|
||||||
|
testRecords: passItem.testRecords || 0,
|
||||||
|
totalRecords: recordItem.totalRecords || 0,
|
||||||
|
validRecords: recordItem.validRecords || 0,
|
||||||
|
invalidatedRecords: recordItem.invalidatedRecords || 0,
|
||||||
|
wordSets: recordItem.wordSets || passItem.wordSets || 0,
|
||||||
|
testTypes: Array.from(new Set([...(recordItem.testTypes || []), ...(passItem.testTypes || [])])),
|
||||||
|
riskFlags: flattenRiskFlags(recordItem.riskFlagSets || []),
|
||||||
|
firstPassedAt: passItem.firstPassedAt,
|
||||||
|
lastPassedAt: passItem.lastPassedAt,
|
||||||
|
firstRecordAt: recordItem.firstRecordAt,
|
||||||
|
lastRecordAt: recordItem.lastRecordAt
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
validPassItems.forEach((passItem: any) => {
|
||||||
|
if (itemMap.has(passItem.userId)) return;
|
||||||
|
itemMap.set(passItem.userId, {
|
||||||
|
...passItem,
|
||||||
|
totalRecords: passItem.testRecords || 0,
|
||||||
|
validRecords: passItem.testRecords || 0,
|
||||||
|
invalidatedRecords: 0,
|
||||||
|
riskFlags: [],
|
||||||
|
firstRecordAt: passItem.firstPassedAt,
|
||||||
|
lastRecordAt: passItem.lastPassedAt
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = applyVocabularySummaryItemFilters(Array.from(itemMap.values()), minUniqueWords).sort((left, right) => {
|
||||||
|
const passedDelta = (right.passedWords || 0) - (left.passedWords || 0);
|
||||||
|
if (passedDelta !== 0) return passedDelta;
|
||||||
|
|
||||||
|
const riskDelta = (right.invalidatedRecords || 0) - (left.invalidatedRecords || 0);
|
||||||
|
if (riskDelta !== 0) return riskDelta;
|
||||||
|
|
||||||
|
return new Date(right.lastRecordAt || right.lastPassedAt || 0).getTime() -
|
||||||
|
new Date(left.lastRecordAt || left.lastPassedAt || 0).getTime();
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
totalStudents: items.length,
|
||||||
|
totalPassedWords: items.reduce((sum: number, item: any) => sum + (item.passedWords || 0), 0),
|
||||||
|
totalRecords: items.reduce((sum: number, item: any) => sum + (item.totalRecords || 0), 0),
|
||||||
|
invalidatedRecords: items.reduce((sum: number, item: any) => sum + (item.invalidatedRecords || 0), 0),
|
||||||
|
items
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取词汇测试通过统计失败:', error);
|
||||||
|
res.status(500).json({ message: '获取词汇测试通过统计失败' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 查看某个学生在时间段内的词汇测试明细(包含风控 attempt 原始提交)
|
||||||
|
router.get('/vocabulary/test-pass-summary/:userId/details', adminAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const range = parseAdminDateRange(req.query as Record<string, any>);
|
||||||
|
if (range.error) {
|
||||||
|
return res.status(400).json({ message: range.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { start, end } = range as { start: Date; end: Date };
|
||||||
|
const summaryFilters = buildVocabularySummaryFilters(req.query as Record<string, any>);
|
||||||
|
if ('error' in summaryFilters) {
|
||||||
|
return res.status(400).json({ message: summaryFilters.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { baseMatch } = summaryFilters;
|
||||||
|
const { userId } = req.params;
|
||||||
|
if (!mongoose.isValidObjectId(userId)) {
|
||||||
|
return res.status(400).json({ message: '学生ID无效' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await User.findById(userId).select('_id username fullname email').lean();
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({ message: '学生不存在' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const records = await VocabularyTestRecord.find({
|
||||||
|
user: user._id,
|
||||||
|
...baseMatch,
|
||||||
|
'stats.endTime': { $gte: start, $lte: end }
|
||||||
|
})
|
||||||
|
.populate('wordSet', 'name description')
|
||||||
|
.populate('results.word', 'word translation pronunciation example')
|
||||||
|
.populate('reviewedBy', 'username fullname email')
|
||||||
|
.sort({ 'stats.endTime': -1, createdAt: -1 })
|
||||||
|
.lean();
|
||||||
|
|
||||||
|
const attemptIds = records
|
||||||
|
.map((record: any) => getObjectIdString(record.attempt))
|
||||||
|
.filter(id => mongoose.isValidObjectId(id));
|
||||||
|
const attempts = attemptIds.length > 0
|
||||||
|
? await VocabularyTestAttempt.find({ _id: { $in: attemptIds } })
|
||||||
|
.populate('answers.word', 'word translation pronunciation example')
|
||||||
|
.populate('reviewedBy', 'username fullname email')
|
||||||
|
.lean()
|
||||||
|
: [];
|
||||||
|
const attemptMap = new Map(attempts.map((attempt: any) => [attempt._id.toString(), attempt]));
|
||||||
|
|
||||||
|
const recordDetails = records.map((record: any) => {
|
||||||
|
const attemptId = getObjectIdString(record.attempt);
|
||||||
|
const attempt = attemptMap.get(attemptId);
|
||||||
|
|
||||||
|
return {
|
||||||
|
recordId: record._id.toString(),
|
||||||
|
attemptId,
|
||||||
|
wordSet: serializeWordSetRef(record.wordSet),
|
||||||
|
testType: record.testType,
|
||||||
|
stats: record.stats,
|
||||||
|
invalidated: Boolean(record.invalidated),
|
||||||
|
riskFlags: record.riskFlags || [],
|
||||||
|
reviewDecision: record.reviewDecision || attempt?.reviewDecision || '',
|
||||||
|
reviewedAt: record.reviewedAt || attempt?.reviewedAt || null,
|
||||||
|
reviewedBy: serializeUserRef(record.reviewedBy || attempt?.reviewedBy),
|
||||||
|
reviewNote: record.reviewNote || attempt?.reviewNote || '',
|
||||||
|
createdAt: record.createdAt,
|
||||||
|
results: (record.results || []).map((result: any, index: number) => ({
|
||||||
|
index: index + 1,
|
||||||
|
wordId: getObjectIdString(result.word),
|
||||||
|
word: serializeWordRef(result.word),
|
||||||
|
userAnswer: result.userAnswer || '',
|
||||||
|
correctAnswer: result.correctAnswer || '',
|
||||||
|
isCorrect: Boolean(result.isCorrect)
|
||||||
|
})),
|
||||||
|
attempt: attempt ? {
|
||||||
|
attemptId,
|
||||||
|
status: attempt.status,
|
||||||
|
testType: attempt.testType,
|
||||||
|
wordSetId: getObjectIdString(attempt.wordSet),
|
||||||
|
issuedAt: attempt.issuedAt,
|
||||||
|
expiresAt: attempt.expiresAt,
|
||||||
|
submittedAt: attempt.submittedAt,
|
||||||
|
riskFlags: attempt.riskFlags || [],
|
||||||
|
reviewDecision: attempt.reviewDecision || '',
|
||||||
|
reviewedAt: attempt.reviewedAt || null,
|
||||||
|
reviewedBy: serializeUserRef(attempt.reviewedBy),
|
||||||
|
reviewNote: attempt.reviewNote || '',
|
||||||
|
questionWordIds: (attempt.questionWordIds || []).map((wordId: any) => getObjectIdString(wordId)),
|
||||||
|
questionTokens: attempt.questionTokens || [],
|
||||||
|
optionTokens: attempt.optionTokens || [],
|
||||||
|
optionTexts: attempt.optionTexts || [],
|
||||||
|
answeredQuestionTokens: attempt.answeredQuestionTokens || [],
|
||||||
|
answerDurations: attempt.answerDurations || [],
|
||||||
|
answers: (attempt.answers || []).map((answer: any, index: number) => ({
|
||||||
|
index: index + 1,
|
||||||
|
questionToken: answer.questionToken || '',
|
||||||
|
wordId: getObjectIdString(answer.word),
|
||||||
|
word: serializeWordRef(answer.word),
|
||||||
|
userAnswer: answer.userAnswer || '',
|
||||||
|
correctAnswer: answer.correctAnswer || '',
|
||||||
|
isCorrect: Boolean(answer.isCorrect),
|
||||||
|
submittedAt: answer.submittedAt,
|
||||||
|
duration: answer.duration,
|
||||||
|
riskFlags: answer.riskFlags || [],
|
||||||
|
interactionSummary: answer.interactionSummary || null
|
||||||
|
}))
|
||||||
|
} : null
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
start,
|
||||||
|
end,
|
||||||
|
user: {
|
||||||
|
userId: user._id.toString(),
|
||||||
|
username: user.username,
|
||||||
|
fullname: user.fullname,
|
||||||
|
email: user.email
|
||||||
|
},
|
||||||
|
totalRecords: recordDetails.length,
|
||||||
|
totalPassedWords: recordDetails
|
||||||
|
.filter((record: any) => !record.invalidated)
|
||||||
|
.reduce((sum: number, record: any) => sum + Number(record.stats?.correctWords || 0), 0),
|
||||||
|
invalidatedRecords: recordDetails.filter((record: any) => record.invalidated).length,
|
||||||
|
approvedRecords: recordDetails.filter((record: any) => record.reviewDecision === 'approved').length,
|
||||||
|
records: recordDetails
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取词汇测试明细失败:', error);
|
||||||
|
res.status(500).json({ message: '获取词汇测试明细失败' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 人工将风控作废的词汇测试记录转为有效成绩
|
||||||
|
router.post('/vocabulary/test-records/:recordId/approve', adminAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { recordId } = req.params;
|
||||||
|
if (!mongoose.isValidObjectId(recordId)) {
|
||||||
|
return res.status(400).json({ message: '测试记录ID无效' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const record: any = await VocabularyTestRecord.findById(recordId);
|
||||||
|
if (!record) {
|
||||||
|
return res.status(404).json({ message: '测试记录不存在' });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!record.invalidated) {
|
||||||
|
return res.json({
|
||||||
|
message: '该词汇测试记录已经是有效成绩',
|
||||||
|
recordId,
|
||||||
|
alreadyEffective: true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const attemptId = getObjectIdString(record.attempt);
|
||||||
|
if (!mongoose.isValidObjectId(attemptId)) {
|
||||||
|
return res.status(400).json({ message: '该测试记录没有可用于恢复的 attempt 数据' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const attempt: any = await VocabularyTestAttempt.findById(attemptId);
|
||||||
|
if (!attempt) {
|
||||||
|
return res.status(404).json({ message: '原始提交 attempt 不存在,无法转为有效成绩' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const submittedAnswers = Array.isArray(attempt.answers) ? attempt.answers : [];
|
||||||
|
const restoredResults = submittedAnswers
|
||||||
|
.map((answer: any) => {
|
||||||
|
const wordId = getObjectIdString(answer.word);
|
||||||
|
if (!mongoose.isValidObjectId(wordId)) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
word: new mongoose.Types.ObjectId(wordId),
|
||||||
|
userAnswer: String(answer.userAnswer || ''),
|
||||||
|
correctAnswer: String(answer.correctAnswer || ''),
|
||||||
|
isCorrect: Boolean(answer.isCorrect)
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter(Boolean) as Array<{
|
||||||
|
word: mongoose.Types.ObjectId;
|
||||||
|
userAnswer: string;
|
||||||
|
correctAnswer: string;
|
||||||
|
isCorrect: boolean;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
if (restoredResults.length === 0) {
|
||||||
|
return res.status(400).json({ message: '该 attempt 没有可恢复的答题数据' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalWords = restoredResults.length;
|
||||||
|
const correctWords = restoredResults.filter(result => result.isCorrect).length;
|
||||||
|
const reviewedAt = new Date();
|
||||||
|
const reviewNote = String(req.body?.note || '').trim().slice(0, 500);
|
||||||
|
const userId = getObjectIdString(record.user);
|
||||||
|
const affectedWordIds = restoredResults.map(result => result.word.toString());
|
||||||
|
|
||||||
|
await VocabularyTestRecord.updateOne(
|
||||||
|
{ _id: record._id },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
invalidated: false,
|
||||||
|
results: restoredResults,
|
||||||
|
'stats.totalWords': totalWords,
|
||||||
|
'stats.correctWords': correctWords,
|
||||||
|
'stats.accuracy': totalWords > 0 ? (correctWords / totalWords) * 100 : 0,
|
||||||
|
reviewDecision: 'approved',
|
||||||
|
reviewedBy: req.user._id,
|
||||||
|
reviewedAt,
|
||||||
|
reviewNote
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
await VocabularyTestAttempt.updateOne(
|
||||||
|
{ _id: attempt._id },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
reviewDecision: 'approved',
|
||||||
|
reviewedBy: req.user._id,
|
||||||
|
reviewedAt,
|
||||||
|
reviewNote
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const rebuildResult = await rebuildVocabularyWordRecordsForUser(userId, affectedWordIds);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
message: '已将风控记录转为有效成绩',
|
||||||
|
recordId,
|
||||||
|
attemptId,
|
||||||
|
totalWords,
|
||||||
|
correctWords,
|
||||||
|
accuracy: totalWords > 0 ? (correctWords / totalWords) * 100 : 0,
|
||||||
|
riskFlags: Array.from(new Set([...(record.riskFlags || []), ...(attempt.riskFlags || [])])),
|
||||||
|
affectedWords: rebuildResult.affectedWords,
|
||||||
|
rebuiltWords: rebuildResult.rebuiltWords
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('人工放行词汇测试记录失败:', error);
|
||||||
|
res.status(500).json({ message: '人工放行词汇测试记录失败' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 清除某个学生在指定时间段内的词汇测试成绩,并重算掌握状态
|
||||||
|
router.post('/vocabulary/test-pass-summary/clear', adminAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const range = parseAdminDateRange(req.body || {});
|
||||||
|
if (range.error) {
|
||||||
|
return res.status(400).json({ message: range.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { start, end } = range as { start: Date; end: Date };
|
||||||
|
const summaryFilters = buildVocabularySummaryFilters(req.body || {});
|
||||||
|
if ('error' in summaryFilters) {
|
||||||
|
return res.status(400).json({ message: summaryFilters.error });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { baseMatch } = summaryFilters;
|
||||||
|
const { userId } = req.body || {};
|
||||||
|
if (!mongoose.isValidObjectId(userId)) {
|
||||||
|
return res.status(400).json({ message: '学生ID无效' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await User.findById(userId).select('_id username fullname');
|
||||||
|
if (!user) {
|
||||||
|
return res.status(404).json({ message: '学生不存在' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const records = await VocabularyTestRecord.find({
|
||||||
|
user: user._id,
|
||||||
|
invalidated: { $ne: true },
|
||||||
|
...baseMatch,
|
||||||
|
'stats.endTime': { $gte: start, $lte: end },
|
||||||
|
'stats.correctWords': { $gt: 0 }
|
||||||
|
})
|
||||||
|
.select('_id stats.correctWords results.word results.isCorrect')
|
||||||
|
.lean();
|
||||||
|
|
||||||
|
if (records.length === 0) {
|
||||||
|
return res.json({
|
||||||
|
message: '没有找到需要清除的词汇测试成绩',
|
||||||
|
deletedRecords: 0,
|
||||||
|
removedPassedWords: 0,
|
||||||
|
affectedWords: 0,
|
||||||
|
rebuiltWords: 0
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const recordIds = records.map(record => record._id);
|
||||||
|
const affectedWordIds = new Set<string>();
|
||||||
|
let removedPassedWords = 0;
|
||||||
|
|
||||||
|
records.forEach((record: any) => {
|
||||||
|
removedPassedWords += Number(record.stats?.correctWords || 0);
|
||||||
|
(record.results || []).forEach((result: any) => {
|
||||||
|
const wordId = result.word?.toString?.() || String(result.word || '');
|
||||||
|
if (wordId) affectedWordIds.add(wordId);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await VocabularyTestRecord.deleteMany({ _id: { $in: recordIds } });
|
||||||
|
const rebuildResult = await rebuildVocabularyWordRecordsForUser(userId, Array.from(affectedWordIds));
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
message: '词汇测试成绩已清除',
|
||||||
|
userId,
|
||||||
|
username: user.username,
|
||||||
|
fullname: user.fullname,
|
||||||
|
deletedRecords: records.length,
|
||||||
|
removedPassedWords,
|
||||||
|
affectedWords: rebuildResult.affectedWords,
|
||||||
|
rebuiltWords: rebuildResult.rebuiltWords
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('清除词汇测试成绩失败:', error);
|
||||||
|
res.status(500).json({ message: '清除词汇测试成绩失败' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
export default router;
|
export default router;
|
||||||
@@ -8,8 +8,11 @@ import { auth as authMiddleware } from '../middleware/auth';
|
|||||||
import { Word, WordSet, WordRecord, VocabularyTestRecord, VocabularyTestAttempt } from '../models/Vocabulary';
|
import { Word, WordSet, WordRecord, VocabularyTestRecord, VocabularyTestAttempt } from '../models/Vocabulary';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import csv from 'csv-parser';
|
import csv from 'csv-parser';
|
||||||
import { User } from '../models/User';
|
|
||||||
import { config } from '../config';
|
import { config } from '../config';
|
||||||
|
import {
|
||||||
|
INVALIDATING_VOCABULARY_RISK_FLAGS,
|
||||||
|
analyzeVocabularyAttemptResultRisk
|
||||||
|
} from '../utils/vocabularyRisk';
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
@@ -24,13 +27,42 @@ interface EvaluatedVocabularyAnswer {
|
|||||||
isCorrect: boolean;
|
isCorrect: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface VocabularyOptionPayload {
|
||||||
|
token: string;
|
||||||
|
text: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface VocabularyAttemptQuestion {
|
interface VocabularyAttemptQuestion {
|
||||||
questionToken: string;
|
questionToken: string;
|
||||||
wordId: string;
|
wordId: string;
|
||||||
word?: string;
|
word?: string;
|
||||||
translation?: string;
|
translation?: string;
|
||||||
pronunciation?: string;
|
pronunciation?: string;
|
||||||
options?: string[];
|
options?: Array<string | VocabularyOptionPayload>;
|
||||||
|
optionTokenRequest?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InteractionEventPayload {
|
||||||
|
type?: string;
|
||||||
|
key?: string;
|
||||||
|
inputType?: string;
|
||||||
|
value?: string;
|
||||||
|
valueLength?: number;
|
||||||
|
ctrlKey?: boolean;
|
||||||
|
metaKey?: boolean;
|
||||||
|
altKey?: boolean;
|
||||||
|
ts?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface InteractionSummary {
|
||||||
|
keyCount: number;
|
||||||
|
inputCount: number;
|
||||||
|
pasteCount: number;
|
||||||
|
focusCount: number;
|
||||||
|
blurCount: number;
|
||||||
|
pointerCount: number;
|
||||||
|
firstEventOffset: number;
|
||||||
|
lastEventOffset: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const TEST_TYPE_TO_MODE: Record<VocabularyTestType, WordRecordModeKey> = {
|
const TEST_TYPE_TO_MODE: Record<VocabularyTestType, WordRecordModeKey> = {
|
||||||
@@ -45,9 +77,26 @@ const WORD_RECORD_MODES: WordRecordModeKey[] = [
|
|||||||
'multipleChoice'
|
'multipleChoice'
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const getNumericEnv = (names: string[], fallback: number): number => {
|
||||||
|
for (const name of names) {
|
||||||
|
const parsed = Number(process.env[name]);
|
||||||
|
if (Number.isFinite(parsed)) return parsed;
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
};
|
||||||
|
|
||||||
const ATTEMPT_TTL_MS = 30 * 60 * 1000;
|
const ATTEMPT_TTL_MS = 30 * 60 * 1000;
|
||||||
const MIN_SECONDS_PER_QUESTION = Number(process.env.VOCABULARY_MIN_SECONDS_PER_QUESTION || 0.4);
|
const MIN_STUDY_WORD_COUNT = 10;
|
||||||
|
const MAX_STUDY_WORD_COUNT = 100;
|
||||||
|
const MIN_SECONDS_PER_QUESTION = getNumericEnv(['VOCABULARY_MIN_SECONDS_PER_QUESTION', 'MIN_SECONDS_PER_QUESTION'], 2);
|
||||||
|
const MAX_SECONDS_PER_QUESTION = getNumericEnv(['VOCABULARY_MAX_SECONDS_PER_QUESTION', 'MAX_SECONDS_PER_QUESTION'], 10);
|
||||||
|
const VOCABULARY_ALLOWED_ORIGINS = (process.env.VOCABULARY_ALLOWED_ORIGINS || 'https://d1kt.cn,http://localhost:3000,http://localhost:3001')
|
||||||
|
.split(',')
|
||||||
|
.map(item => item.trim())
|
||||||
|
.filter(Boolean);
|
||||||
const ATTEMPT_SECRET = process.env.VOCABULARY_ATTEMPT_SECRET || config.JWT_SECRET;
|
const ATTEMPT_SECRET = process.env.VOCABULARY_ATTEMPT_SECRET || config.JWT_SECRET;
|
||||||
|
const ANSWER_PROOF_SALT = 'd1ktsalt';
|
||||||
|
const INVALID_CREDENTIAL_MESSAGE = '凭证无效,请检查。';
|
||||||
|
|
||||||
const isVocabularyTestType = (value: unknown): value is VocabularyTestType => {
|
const isVocabularyTestType = (value: unknown): value is VocabularyTestType => {
|
||||||
return value === 'chinese-to-english' ||
|
return value === 'chinese-to-english' ||
|
||||||
@@ -66,6 +115,28 @@ const shuffle = <T,>(array: T[]): T[] => {
|
|||||||
|
|
||||||
const getObjectIdString = (value: any): string => value?._id?.toString?.() || value?.toString?.() || '';
|
const getObjectIdString = (value: any): string => value?._id?.toString?.() || value?.toString?.() || '';
|
||||||
|
|
||||||
|
const getRequestOrigin = (req: express.Request): string => {
|
||||||
|
const origin = req.get('origin');
|
||||||
|
if (origin) return origin;
|
||||||
|
|
||||||
|
const referer = req.get('referer');
|
||||||
|
if (!referer) return '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
return new URL(referer).origin;
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const isAllowedVocabularyOrigin = (req: express.Request): boolean => {
|
||||||
|
const origin = getRequestOrigin(req);
|
||||||
|
if (!origin) {
|
||||||
|
return config.NODE_ENV !== 'production';
|
||||||
|
}
|
||||||
|
return VOCABULARY_ALLOWED_ORIGINS.includes(origin);
|
||||||
|
};
|
||||||
|
|
||||||
const signQuestionToken = (
|
const signQuestionToken = (
|
||||||
attemptId: string,
|
attemptId: string,
|
||||||
wordId: string,
|
wordId: string,
|
||||||
@@ -81,6 +152,20 @@ const signQuestionToken = (
|
|||||||
return `${index}.${issuedAtMs}.${signature}`;
|
return `${index}.${issuedAtMs}.${signature}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const signOptionToken = (
|
||||||
|
attemptId: string,
|
||||||
|
questionToken: string,
|
||||||
|
optionText: string,
|
||||||
|
index: number
|
||||||
|
): string => {
|
||||||
|
const payload = `${attemptId}:${questionToken}:${index}:${optionText}`;
|
||||||
|
const signature = crypto
|
||||||
|
.createHmac('sha256', ATTEMPT_SECRET)
|
||||||
|
.update(payload)
|
||||||
|
.digest('hex');
|
||||||
|
return `${index}.${signature}`;
|
||||||
|
};
|
||||||
|
|
||||||
const safeEqualString = (left: string, right: string): boolean => {
|
const safeEqualString = (left: string, right: string): boolean => {
|
||||||
const leftBuffer = Buffer.from(left || '');
|
const leftBuffer = Buffer.from(left || '');
|
||||||
const rightBuffer = Buffer.from(right || '');
|
const rightBuffer = Buffer.from(right || '');
|
||||||
@@ -104,8 +189,8 @@ const buildAnswerProof = (
|
|||||||
userAnswer: string,
|
userAnswer: string,
|
||||||
submittedAt: number
|
submittedAt: number
|
||||||
): string => crypto
|
): string => crypto
|
||||||
.createHash('sha256')
|
.createHash('md5')
|
||||||
.update(`${attemptId}:${questionToken}:${submittedAt}:${String(userAnswer ?? '')}`)
|
.update(`${ANSWER_PROOF_SALT}:${attemptId}:${questionToken}:${submittedAt}:${String(userAnswer ?? '')}:${ANSWER_PROOF_SALT}`)
|
||||||
.digest('hex');
|
.digest('hex');
|
||||||
|
|
||||||
const buildMultipleChoiceOptions = (word: any, pool: any[]): string[] => {
|
const buildMultipleChoiceOptions = (word: any, pool: any[]): string[] => {
|
||||||
@@ -130,7 +215,8 @@ const buildQuestionPayload = (
|
|||||||
word: any,
|
word: any,
|
||||||
testType: VocabularyTestType,
|
testType: VocabularyTestType,
|
||||||
questionToken: string,
|
questionToken: string,
|
||||||
optionsPool: any[]
|
optionsPool: any[],
|
||||||
|
suppliedOptions?: Array<string | VocabularyOptionPayload>
|
||||||
): VocabularyAttemptQuestion => {
|
): VocabularyAttemptQuestion => {
|
||||||
const base = {
|
const base = {
|
||||||
questionToken,
|
questionToken,
|
||||||
@@ -152,10 +238,13 @@ const buildQuestionPayload = (
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const options = suppliedOptions || buildMultipleChoiceOptions(word, optionsPool);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...base,
|
...base,
|
||||||
word: word.word,
|
word: word.word,
|
||||||
options: buildMultipleChoiceOptions(word, optionsPool)
|
options,
|
||||||
|
optionTokenRequest: options.some(option => typeof option === 'string')
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -188,6 +277,121 @@ const evaluateWordAnswer = (word: any, testType: VocabularyTestType, answer: unk
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const summarizeInteractionEvents = (
|
||||||
|
events: InteractionEventPayload[],
|
||||||
|
questionShownAtMs: number
|
||||||
|
): InteractionSummary => {
|
||||||
|
const safeEvents = Array.isArray(events) ? events.slice(0, 300) : [];
|
||||||
|
const timestamps = safeEvents
|
||||||
|
.map(event => Number(event?.ts))
|
||||||
|
.filter(value => Number.isFinite(value));
|
||||||
|
const firstEventTs = timestamps.length > 0 ? Math.min(...timestamps) : questionShownAtMs;
|
||||||
|
const lastEventTs = timestamps.length > 0 ? Math.max(...timestamps) : questionShownAtMs;
|
||||||
|
|
||||||
|
return {
|
||||||
|
keyCount: safeEvents.filter(event => event?.type === 'keydown' || event?.type === 'keyup').length,
|
||||||
|
inputCount: safeEvents.filter(event => event?.type === 'input').length,
|
||||||
|
pasteCount: safeEvents.filter(event => event?.type === 'paste').length,
|
||||||
|
focusCount: safeEvents.filter(event => event?.type === 'focus').length,
|
||||||
|
blurCount: safeEvents.filter(event => event?.type === 'blur').length,
|
||||||
|
pointerCount: safeEvents.filter(event => event?.type === 'pointerdown' || event?.type === 'click' || event?.type === 'change').length,
|
||||||
|
firstEventOffset: Math.max(0, firstEventTs - questionShownAtMs),
|
||||||
|
lastEventOffset: Math.max(0, lastEventTs - questionShownAtMs)
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildKeySequenceText = (events: InteractionEventPayload[]): string => {
|
||||||
|
let text = '';
|
||||||
|
|
||||||
|
events.forEach(event => {
|
||||||
|
if (event?.type !== 'keydown' || event.ctrlKey || event.metaKey || event.altKey) return;
|
||||||
|
|
||||||
|
const key = String(event.key ?? '');
|
||||||
|
if (key === 'Backspace') {
|
||||||
|
text = text.slice(0, -1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (key === 'Spacebar') {
|
||||||
|
text += ' ';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (key.length === 1) {
|
||||||
|
text += key;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return text.slice(0, 500);
|
||||||
|
};
|
||||||
|
|
||||||
|
const analyzeInputTraceRisk = (
|
||||||
|
events: InteractionEventPayload[],
|
||||||
|
userAnswer: string,
|
||||||
|
testType: VocabularyTestType
|
||||||
|
): string[] => {
|
||||||
|
if (testType === 'multiple-choice') return [];
|
||||||
|
|
||||||
|
const flags: string[] = [];
|
||||||
|
const expectedAnswer = normalizeEnglishAnswer(userAnswer);
|
||||||
|
if (!expectedAnswer) return flags;
|
||||||
|
|
||||||
|
const safeEvents = Array.isArray(events) ? events.slice(0, 300) : [];
|
||||||
|
const inputValues = safeEvents
|
||||||
|
.filter(event => event?.type === 'input' && typeof event.value === 'string')
|
||||||
|
.map(event => String(event.value ?? '').slice(0, 500));
|
||||||
|
const lastInputValue = inputValues[inputValues.length - 1];
|
||||||
|
|
||||||
|
if (inputValues.length === 0) {
|
||||||
|
flags.push('missing_input_value_trace');
|
||||||
|
} else if (normalizeEnglishAnswer(lastInputValue) !== expectedAnswer) {
|
||||||
|
flags.push('input_value_mismatch');
|
||||||
|
}
|
||||||
|
|
||||||
|
const keySequence = normalizeEnglishAnswer(buildKeySequenceText(safeEvents));
|
||||||
|
if (keySequence && keySequence !== expectedAnswer) {
|
||||||
|
flags.push('key_sequence_mismatch');
|
||||||
|
}
|
||||||
|
|
||||||
|
return flags;
|
||||||
|
};
|
||||||
|
|
||||||
|
const analyzeAnswerRisk = (
|
||||||
|
durationSeconds: number,
|
||||||
|
summary: InteractionSummary,
|
||||||
|
testType: VocabularyTestType
|
||||||
|
): string[] => {
|
||||||
|
const flags: string[] = [];
|
||||||
|
|
||||||
|
if (durationSeconds > MAX_SECONDS_PER_QUESTION) flags.push('too_slow');
|
||||||
|
|
||||||
|
if (testType === 'multiple-choice') {
|
||||||
|
if (summary.pointerCount === 0) flags.push('missing_choice_interaction');
|
||||||
|
} else {
|
||||||
|
if (durationSeconds < MIN_SECONDS_PER_QUESTION) flags.push('too_fast');
|
||||||
|
if (summary.keyCount === 0) flags.push('missing_key_events');
|
||||||
|
if (summary.inputCount === 0) flags.push('missing_input_events');
|
||||||
|
if (summary.pasteCount > 0) flags.push('paste_used');
|
||||||
|
}
|
||||||
|
|
||||||
|
return flags;
|
||||||
|
};
|
||||||
|
|
||||||
|
const analyzeBatchRisk = (durations: number[]): string[] => {
|
||||||
|
if (durations.length < 3) return [];
|
||||||
|
|
||||||
|
const roundedDurations = durations.map(value => Math.round(value * 10) / 10);
|
||||||
|
const average = roundedDurations.reduce((sum, value) => sum + value, 0) / roundedDurations.length;
|
||||||
|
const variance = roundedDurations.reduce((sum, value) => sum + Math.pow(value - average, 2), 0) / roundedDurations.length;
|
||||||
|
const uniqueWholeSecondCount = new Set(durations.map(value => Math.round(value))).size;
|
||||||
|
const durationRange = Math.max(...durations) - Math.min(...durations);
|
||||||
|
const flags: string[] = [];
|
||||||
|
|
||||||
|
if (durationRange <= 1) flags.push('uniform_answer_intervals');
|
||||||
|
if (variance < 0.05 && roundedDurations.length >= 4) flags.push('uniform_answer_intervals');
|
||||||
|
if (uniqueWholeSecondCount <= 2 && durations.length >= 5) flags.push('repeated_whole_second_intervals');
|
||||||
|
|
||||||
|
return Array.from(new Set(flags));
|
||||||
|
};
|
||||||
|
|
||||||
const buildMasteryStatus = (record: any) => {
|
const buildMasteryStatus = (record: any) => {
|
||||||
const masteryStatus: Record<string, any> = {};
|
const masteryStatus: Record<string, any> = {};
|
||||||
WORD_RECORD_MODES.forEach(mode => {
|
WORD_RECORD_MODES.forEach(mode => {
|
||||||
@@ -457,7 +661,7 @@ router.get('/study-words/:wordSetId', authMiddleware, async (req, res) => {
|
|||||||
if (req.query.count) {
|
if (req.query.count) {
|
||||||
const parsed = parseInt(req.query.count as string, 10);
|
const parsed = parseInt(req.query.count as string, 10);
|
||||||
if (!isNaN(parsed) && parsed > 0) {
|
if (!isNaN(parsed) && parsed > 0) {
|
||||||
targetCount = Math.min(parsed, 100);
|
targetCount = Math.max(MIN_STUDY_WORD_COUNT, Math.min(parsed, MAX_STUDY_WORD_COUNT));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -607,20 +811,24 @@ router.post('/test-attempt', authMiddleware, async (req, res) => {
|
|||||||
const userId = req.user?._id;
|
const userId = req.user?._id;
|
||||||
|
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
return res.status(401).json({ message: '用户信息无效' });
|
return res.status(401).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAllowedVocabularyOrigin(req)) {
|
||||||
|
return res.status(403).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mongoose.isValidObjectId(wordSetId)) {
|
if (!mongoose.isValidObjectId(wordSetId)) {
|
||||||
return res.status(400).json({ message: '单词集ID无效' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isVocabularyTestType(testType)) {
|
if (!isVocabularyTestType(testType)) {
|
||||||
return res.status(400).json({ message: '未知的测试类型' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
const wordSet = await WordSet.findById(wordSetId);
|
const wordSet = await WordSet.findById(wordSetId);
|
||||||
if (!wordSet) {
|
if (!wordSet) {
|
||||||
return res.status(404).json({ message: '未找到单词集' });
|
return res.status(404).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
let selectedWords: any[] = [];
|
let selectedWords: any[] = [];
|
||||||
@@ -628,23 +836,23 @@ router.post('/test-attempt', authMiddleware, async (req, res) => {
|
|||||||
|
|
||||||
if (Array.isArray(wordIds) && wordIds.length > 0) {
|
if (Array.isArray(wordIds) && wordIds.length > 0) {
|
||||||
if (wordIds.length > 100) {
|
if (wordIds.length > 100) {
|
||||||
return res.status(400).json({ message: '单次测试最多100道题' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wordIds.some((id: unknown) => !mongoose.isValidObjectId(id))) {
|
if (wordIds.some((id: unknown) => !mongoose.isValidObjectId(id))) {
|
||||||
return res.status(400).json({ message: '包含无效单词ID' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
const uniqueWordIds = [...new Set(wordIds.map((id: string) => id.toString()))];
|
const uniqueWordIds = [...new Set(wordIds.map((id: string) => id.toString()))];
|
||||||
if (uniqueWordIds.length !== wordIds.length) {
|
if (uniqueWordIds.length !== wordIds.length) {
|
||||||
return res.status(400).json({ message: '测试单词不能重复' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
const wordMap = new Map<string, any>(allWords.map(word => [getObjectIdString(word), word]));
|
const wordMap = new Map<string, any>(allWords.map(word => [getObjectIdString(word), word]));
|
||||||
selectedWords = uniqueWordIds.map(wordId => wordMap.get(wordId));
|
selectedWords = uniqueWordIds.map(wordId => wordMap.get(wordId));
|
||||||
|
|
||||||
if (selectedWords.some(word => !word)) {
|
if (selectedWords.some(word => !word)) {
|
||||||
return res.status(400).json({ message: '测试单词必须属于当前单词集' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
selectedWords = shuffle(selectedWords);
|
selectedWords = shuffle(selectedWords);
|
||||||
@@ -657,7 +865,7 @@ router.post('/test-attempt', authMiddleware, async (req, res) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (selectedWords.length === 0) {
|
if (selectedWords.length === 0) {
|
||||||
return res.status(400).json({ message: '没有可测试的单词' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
const issuedAt = new Date();
|
const issuedAt = new Date();
|
||||||
@@ -679,10 +887,19 @@ router.post('/test-attempt', authMiddleware, async (req, res) => {
|
|||||||
);
|
);
|
||||||
|
|
||||||
attempt.questionTokens = questionTokens;
|
attempt.questionTokens = questionTokens;
|
||||||
|
if (testType === 'multiple-choice') {
|
||||||
|
const optionTexts = selectedWords.map(word => buildMultipleChoiceOptions(word, allWords));
|
||||||
|
attempt.optionTexts = optionTexts;
|
||||||
|
attempt.optionTokens = optionTexts.map((options, index) =>
|
||||||
|
options.map((option, optionIndex) => signOptionToken(attemptId, questionTokens[index], option, optionIndex))
|
||||||
|
);
|
||||||
|
}
|
||||||
await attempt.save();
|
await attempt.save();
|
||||||
|
|
||||||
const questions = selectedWords.map((word, index) =>
|
const questions = selectedWords.map((word, index) =>
|
||||||
buildQuestionPayload(word, testType, questionTokens[index], allWords)
|
buildQuestionPayload(word, testType, questionTokens[index], allWords, testType === 'multiple-choice'
|
||||||
|
? attempt.optionTexts?.[index] || []
|
||||||
|
: undefined)
|
||||||
);
|
);
|
||||||
|
|
||||||
res.status(201).json({
|
res.status(201).json({
|
||||||
@@ -693,7 +910,7 @@ router.post('/test-attempt', authMiddleware, async (req, res) => {
|
|||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('创建测试会话失败:', error);
|
console.error('创建测试会话失败:', error);
|
||||||
res.status(500).json({ message: '创建测试会话失败' });
|
res.status(500).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -703,26 +920,27 @@ router.post('/word-record', (req, res, next) => {
|
|||||||
next();
|
next();
|
||||||
}, authMiddleware, async (req, res) => {
|
}, authMiddleware, async (req, res) => {
|
||||||
return res.status(410).json({
|
return res.status(410).json({
|
||||||
message: '单题记录接口已停用,请通过测试会话提交记录'
|
message: INVALID_CREDENTIAL_MESSAGE
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// 保存测试记录:只能通过服务端签发的 attempt 提交
|
// 单题提交:服务端逐题判分并累计结果
|
||||||
router.post('/test-record', authMiddleware, async (req, res) => {
|
router.post('/test-answer', authMiddleware, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { attemptId, answers } = req.body;
|
const { attemptId, questionToken, userAnswer, submittedAt, answerProof, interactions } = req.body;
|
||||||
const userId = req.user?._id;
|
const userId = req.user?._id;
|
||||||
|
const softRiskFlags: string[] = [];
|
||||||
|
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
return res.status(401).json({ message: '用户信息无效' });
|
return res.status(401).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAllowedVocabularyOrigin(req)) {
|
||||||
|
softRiskFlags.push('invalid_origin');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mongoose.isValidObjectId(attemptId)) {
|
if (!mongoose.isValidObjectId(attemptId)) {
|
||||||
return res.status(400).json({ message: '测试会话ID无效' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
|
||||||
|
|
||||||
if (!Array.isArray(answers) || answers.length === 0) {
|
|
||||||
return res.status(400).json({ message: '测试答案不能为空' });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const attempt = await VocabularyTestAttempt.findOne({
|
const attempt = await VocabularyTestAttempt.findOne({
|
||||||
@@ -731,7 +949,7 @@ router.post('/test-record', authMiddleware, async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!attempt) {
|
if (!attempt) {
|
||||||
return res.status(404).json({ message: '未找到测试会话' });
|
return res.status(404).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
const attemptAny = attempt as any;
|
const attemptAny = attempt as any;
|
||||||
@@ -740,118 +958,300 @@ router.post('/test-record', authMiddleware, async (req, res) => {
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
if (!Number.isFinite(expiresAt.getTime()) || expiresAt.getTime() < now) {
|
if (!Number.isFinite(expiresAt.getTime()) || expiresAt.getTime() < now) {
|
||||||
attemptAny.status = 'expired';
|
softRiskFlags.push('attempt_expired');
|
||||||
await attempt.save();
|
|
||||||
return res.status(410).json({ message: '测试会话已过期,请重新开始测试' });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (attemptAny.status !== 'active') {
|
if (attemptAny.status !== 'active') {
|
||||||
return res.status(409).json({ message: '测试会话已提交或已失效' });
|
return res.status(409).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (answers.length !== attemptAny.questionTokens.length) {
|
const token = String(questionToken ?? '');
|
||||||
return res.status(400).json({ message: '答案数量与测试题目不一致' });
|
const tokenIndex = attemptAny.questionTokens.indexOf(token);
|
||||||
|
if (!token || tokenIndex < 0) {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
const tokenIndexMap = new Map<string, number>();
|
const answeredTokens = Array.isArray(attemptAny.answeredQuestionTokens)
|
||||||
attemptAny.questionTokens.forEach((token: string, index: number) => {
|
? attemptAny.answeredQuestionTokens
|
||||||
tokenIndexMap.set(token, index);
|
: [];
|
||||||
});
|
if (answeredTokens.includes(token)) {
|
||||||
|
return res.status(409).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
const answerSeen = new Set<string>();
|
|
||||||
const evaluatedResults: EvaluatedVocabularyAnswer[] = [];
|
|
||||||
const submittedAnswers: Array<{ token: string; userAnswer: string; submittedAt: number; answerProof: string }> = [];
|
|
||||||
|
|
||||||
for (const item of answers) {
|
|
||||||
const token = String(item?.questionToken ?? '');
|
|
||||||
const userAnswer = String(item?.userAnswer ?? '').trim().slice(0, 500);
|
|
||||||
const answerProof = String(item?.answerProof ?? '');
|
|
||||||
const submittedAtMs = Number.parseInt(String(item?.submittedAt), 10);
|
|
||||||
|
|
||||||
if (!token || !tokenIndexMap.has(token)) {
|
|
||||||
return res.status(400).json({ message: '测试答案的题目标识无效' });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (answerSeen.has(token)) {
|
if (tokenIndex !== answeredTokens.length) {
|
||||||
return res.status(400).json({ message: '测试答案中存在重复题目' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
answerSeen.add(token);
|
|
||||||
|
|
||||||
|
const submittedAtMs = Number.parseInt(String(submittedAt), 10);
|
||||||
if (!Number.isFinite(submittedAtMs)) {
|
if (!Number.isFinite(submittedAtMs)) {
|
||||||
return res.status(400).json({ message: '答案提交时间无效' });
|
softRiskFlags.push('invalid_submitted_at');
|
||||||
|
} else if (Math.abs(now - submittedAtMs) > 5 * 60 * 1000) {
|
||||||
|
softRiskFlags.push('submitted_at_out_of_sync');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Math.abs(now - submittedAtMs) > 5 * 60 * 1000) {
|
const wordId = getObjectIdString(attemptAny.questionWordIds[tokenIndex]);
|
||||||
return res.status(400).json({ message: '答案提交时间异常' });
|
if (!wordId || !verifyQuestionToken(token, attemptId.toString(), wordId, tokenIndex, issuedAt)) {
|
||||||
|
softRiskFlags.push('invalid_question_token');
|
||||||
}
|
}
|
||||||
|
|
||||||
const index = tokenIndexMap.get(token)!;
|
let normalizedUserAnswer = String(userAnswer ?? '').trim().slice(0, 500);
|
||||||
const wordId = getObjectIdString(attemptAny.questionWordIds[index]);
|
if (attemptAny.testType === 'multiple-choice') {
|
||||||
if (!wordId) {
|
const optionTokens = attemptAny.optionTokens?.[tokenIndex] || [];
|
||||||
return res.status(400).json({ message: '测试会话题目数据损坏' });
|
const optionTexts = attemptAny.optionTexts?.[tokenIndex] || [];
|
||||||
|
const selectedOptionIndex = optionTokens.findIndex((optionToken: string) => safeEqualString(optionToken, normalizedUserAnswer));
|
||||||
|
if (selectedOptionIndex < 0) {
|
||||||
|
softRiskFlags.push('invalid_option_token');
|
||||||
|
const fallbackOptionIndex = optionTexts.findIndex((text: string) => text === normalizedUserAnswer);
|
||||||
|
normalizedUserAnswer = fallbackOptionIndex >= 0
|
||||||
|
? optionTexts[fallbackOptionIndex]
|
||||||
|
: String(userAnswer ?? '').trim().slice(0, 500);
|
||||||
|
} else {
|
||||||
|
normalizedUserAnswer = optionTexts[selectedOptionIndex] || '';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!verifyQuestionToken(token, attemptId.toString(), wordId, index, issuedAt)) {
|
const expectedProof = buildAnswerProof(attemptId.toString(), token, String(userAnswer ?? '').trim().slice(0, 500), submittedAtMs);
|
||||||
return res.status(400).json({ message: '测试题目签名无效' });
|
if (!safeEqualString(expectedProof, String(answerProof ?? ''))) {
|
||||||
|
softRiskFlags.push('invalid_answer_proof');
|
||||||
}
|
}
|
||||||
|
|
||||||
const expectedProof = buildAnswerProof(attemptId.toString(), token, userAnswer, submittedAtMs);
|
const questionShownAtMs = tokenIndex === 0
|
||||||
if (!safeEqualString(expectedProof, answerProof)) {
|
? issuedAt.getTime()
|
||||||
return res.status(400).json({ message: '答案校验失败' });
|
: new Date(attemptAny.answers?.[tokenIndex - 1]?.submittedAt || issuedAt).getTime();
|
||||||
}
|
const effectiveSubmittedAtMs = Number.isFinite(submittedAtMs) ? submittedAtMs : now;
|
||||||
|
const duration = Math.max(0, (effectiveSubmittedAtMs - questionShownAtMs) / 1000);
|
||||||
|
const interactionSummary = summarizeInteractionEvents(interactions, questionShownAtMs);
|
||||||
|
const riskFlags = Array.from(new Set([
|
||||||
|
...analyzeAnswerRisk(duration, interactionSummary, attemptAny.testType),
|
||||||
|
...analyzeInputTraceRisk(interactions, normalizedUserAnswer, attemptAny.testType),
|
||||||
|
...softRiskFlags
|
||||||
|
]));
|
||||||
|
|
||||||
submittedAnswers.push({ token, userAnswer, submittedAt: submittedAtMs, answerProof });
|
const word = await Word.findOne({
|
||||||
}
|
_id: wordId,
|
||||||
|
|
||||||
const lastSubmittedAtMs = Math.max(...submittedAnswers.map(item => item.submittedAt));
|
|
||||||
const elapsedSeconds = Math.max(0, (lastSubmittedAtMs - issuedAt.getTime()) / 1000);
|
|
||||||
const minimumSeconds = Math.max(2, answers.length * MIN_SECONDS_PER_QUESTION);
|
|
||||||
if (elapsedSeconds < minimumSeconds) {
|
|
||||||
return res.status(400).json({ message: '答题速度异常,请重新作答' });
|
|
||||||
}
|
|
||||||
|
|
||||||
const questionWordIds = attemptAny.questionWordIds.map((wordId: any) => getObjectIdString(wordId));
|
|
||||||
const wordMap = new Map<string, any>();
|
|
||||||
const words = await Word.find({
|
|
||||||
_id: { $in: questionWordIds },
|
|
||||||
wordSet: attemptAny.wordSet
|
wordSet: attemptAny.wordSet
|
||||||
});
|
});
|
||||||
words.forEach(word => {
|
|
||||||
wordMap.set(getObjectIdString(word), word);
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const item of submittedAnswers) {
|
|
||||||
const index = tokenIndexMap.get(item.token)!;
|
|
||||||
const wordId = questionWordIds[index];
|
|
||||||
const word = wordMap.get(wordId);
|
|
||||||
if (!word) {
|
if (!word) {
|
||||||
return res.status(400).json({ message: '测试会话中的单词已不存在' });
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
const evaluation = evaluateWordAnswer(word, attemptAny.testType, item.userAnswer);
|
const evaluation = evaluateWordAnswer(word, attemptAny.testType, normalizedUserAnswer);
|
||||||
evaluatedResults.push({
|
attemptAny.answeredQuestionTokens = [...answeredTokens, token];
|
||||||
...evaluation,
|
attemptAny.answerDurations = [...(attemptAny.answerDurations || []), duration];
|
||||||
wordId,
|
attemptAny.answers = [
|
||||||
word: evaluation.word
|
...(attemptAny.answers || []),
|
||||||
});
|
{
|
||||||
|
questionToken: token,
|
||||||
|
word: word._id,
|
||||||
|
userAnswer: evaluation.userAnswer,
|
||||||
|
correctAnswer: evaluation.correctAnswer,
|
||||||
|
isCorrect: evaluation.isCorrect,
|
||||||
|
submittedAt: new Date(effectiveSubmittedAtMs),
|
||||||
|
duration,
|
||||||
|
riskFlags,
|
||||||
|
interactionSummary
|
||||||
}
|
}
|
||||||
|
];
|
||||||
|
attemptAny.riskFlags = Array.from(new Set([...(attemptAny.riskFlags || []), ...riskFlags]));
|
||||||
|
await attempt.save();
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
message: '答案已提交',
|
||||||
|
result: {
|
||||||
|
questionToken: token,
|
||||||
|
wordId,
|
||||||
|
word: evaluation.word,
|
||||||
|
userAnswer: evaluation.userAnswer,
|
||||||
|
correctAnswer: evaluation.correctAnswer,
|
||||||
|
isCorrect: evaluation.isCorrect
|
||||||
|
},
|
||||||
|
progress: {
|
||||||
|
answered: attemptAny.answeredQuestionTokens.length,
|
||||||
|
total: attemptAny.questionTokens.length,
|
||||||
|
finished: attemptAny.answeredQuestionTokens.length === attemptAny.questionTokens.length
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('提交单题答案失败:', error);
|
||||||
|
res.status(500).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 选择题点击选项后换取该选项的一次性凭证
|
||||||
|
router.post('/test-option-token', authMiddleware, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { attemptId, questionToken, optionText } = req.body;
|
||||||
|
const userId = req.user?._id;
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return res.status(401).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAllowedVocabularyOrigin(req)) {
|
||||||
|
return res.status(403).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mongoose.isValidObjectId(attemptId)) {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const attempt = await VocabularyTestAttempt.findOne({
|
||||||
|
_id: attemptId,
|
||||||
|
user: userId
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!attempt) {
|
||||||
|
return res.status(404).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const attemptAny = attempt as any;
|
||||||
|
if (attemptAny.status !== 'active') {
|
||||||
|
return res.status(409).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attemptAny.testType !== 'multiple-choice') {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = String(questionToken ?? '');
|
||||||
|
const tokenIndex = attemptAny.questionTokens.indexOf(token);
|
||||||
|
if (!token || tokenIndex < 0) {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const optionTexts = attemptAny.optionTexts?.[tokenIndex] || [];
|
||||||
|
const selectedIndex = optionTexts.findIndex((text: string) => text === String(optionText ?? ''));
|
||||||
|
if (selectedIndex < 0) {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const answeredTokens = Array.isArray(attemptAny.answeredQuestionTokens)
|
||||||
|
? attemptAny.answeredQuestionTokens
|
||||||
|
: [];
|
||||||
|
if (tokenIndex !== answeredTokens.length) {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const optionToken = attemptAny.optionTokens?.[tokenIndex]?.[selectedIndex];
|
||||||
|
if (!optionToken) {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
questionToken: token,
|
||||||
|
optionToken
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取选择项凭证失败:', error);
|
||||||
|
res.status(500).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 保存测试记录:只能通过服务端签发的 attempt 提交
|
||||||
|
router.post('/test-record', authMiddleware, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { attemptId } = req.body;
|
||||||
|
const userId = req.user?._id;
|
||||||
|
const finalRiskFlags: string[] = [];
|
||||||
|
|
||||||
|
if (!userId) {
|
||||||
|
return res.status(401).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAllowedVocabularyOrigin(req)) {
|
||||||
|
finalRiskFlags.push('invalid_origin');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!mongoose.isValidObjectId(attemptId)) {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const attempt = await VocabularyTestAttempt.findOne({
|
||||||
|
_id: attemptId,
|
||||||
|
user: userId
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!attempt) {
|
||||||
|
return res.status(404).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const attemptAny = attempt as any;
|
||||||
|
const issuedAt = new Date(attemptAny.issuedAt || attemptAny.createdAt);
|
||||||
|
const expiresAt = new Date(attemptAny.expiresAt);
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
if (!Number.isFinite(expiresAt.getTime()) || expiresAt.getTime() < now) {
|
||||||
|
finalRiskFlags.push('attempt_expired');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attemptAny.status !== 'active') {
|
||||||
|
return res.status(409).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const submittedAnswers = Array.isArray(attemptAny.answers) ? attemptAny.answers : [];
|
||||||
|
if (submittedAnswers.length !== attemptAny.questionTokens.length) {
|
||||||
|
return res.status(400).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
|
}
|
||||||
|
|
||||||
|
const lastSubmittedAtMs = Math.max(...submittedAnswers.map((item: any) => new Date(item.submittedAt).getTime()));
|
||||||
|
const isMultipleChoiceAttempt = attemptAny.testType === 'multiple-choice';
|
||||||
|
if (!isMultipleChoiceAttempt) {
|
||||||
|
const elapsedSeconds = Math.max(0, (lastSubmittedAtMs - issuedAt.getTime()) / 1000);
|
||||||
|
const minimumSeconds = Math.max(2, attemptAny.questionTokens.length * MIN_SECONDS_PER_QUESTION);
|
||||||
|
if (elapsedSeconds < minimumSeconds) {
|
||||||
|
finalRiskFlags.push('too_fast');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const submittedWordIds = submittedAnswers.map((item: any) => getObjectIdString(item.word));
|
||||||
|
const submittedWords = await Word.find({ _id: { $in: submittedWordIds } }).select('_id word');
|
||||||
|
const submittedWordMap = new Map<string, string>();
|
||||||
|
submittedWords.forEach(word => {
|
||||||
|
submittedWordMap.set(getObjectIdString(word), word.word);
|
||||||
|
});
|
||||||
|
|
||||||
|
const evaluatedResults: EvaluatedVocabularyAnswer[] = submittedAnswers.map((item: any) => {
|
||||||
|
const wordId = getObjectIdString(item.word);
|
||||||
|
return {
|
||||||
|
wordId,
|
||||||
|
word: submittedWordMap.get(wordId) || '',
|
||||||
|
userAnswer: item.userAnswer,
|
||||||
|
correctAnswer: item.correctAnswer,
|
||||||
|
isCorrect: Boolean(item.isCorrect)
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const totalWords = evaluatedResults.length;
|
||||||
|
const originallyCorrectWords = evaluatedResults.filter(result => result.isCorrect).length;
|
||||||
|
const batchRiskFlags = [
|
||||||
|
...finalRiskFlags,
|
||||||
|
...(isMultipleChoiceAttempt ? [] : analyzeBatchRisk(attemptAny.answerDurations || [])),
|
||||||
|
...analyzeVocabularyAttemptResultRisk({
|
||||||
|
testType: attemptAny.testType,
|
||||||
|
totalWords,
|
||||||
|
correctWords: originallyCorrectWords
|
||||||
|
})
|
||||||
|
];
|
||||||
|
attemptAny.riskFlags = Array.from(new Set([...(attemptAny.riskFlags || []), ...batchRiskFlags]));
|
||||||
|
const shouldInvalidateBatch = INVALIDATING_VOCABULARY_RISK_FLAGS.some(flag => (attemptAny.riskFlags || []).includes(flag));
|
||||||
|
|
||||||
const claimedAttempt = await VocabularyTestAttempt.findOneAndUpdate(
|
const claimedAttempt = await VocabularyTestAttempt.findOneAndUpdate(
|
||||||
{ _id: attempt._id, user: userId, status: 'active' },
|
{ _id: attempt._id, user: userId, status: 'active' },
|
||||||
{ $set: { status: 'submitted', submittedAt: new Date(lastSubmittedAtMs) } },
|
{ $set: { status: 'submitted', submittedAt: new Date(lastSubmittedAtMs), riskFlags: attemptAny.riskFlags } },
|
||||||
{ new: true }
|
{ new: true }
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!claimedAttempt) {
|
if (!claimedAttempt) {
|
||||||
return res.status(409).json({ message: '测试会话已提交或已失效' });
|
return res.status(409).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!shouldInvalidateBatch) {
|
||||||
for (const result of evaluatedResults) {
|
for (const result of evaluatedResults) {
|
||||||
await updateWordRecordForAnswer(userId, result.wordId, attemptAny.testType, result.isCorrect);
|
await updateWordRecordForAnswer(userId, result.wordId, attemptAny.testType, result.isCorrect);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const totalWords = evaluatedResults.length;
|
const correctWords = shouldInvalidateBatch ? 0 : originallyCorrectWords;
|
||||||
const correctWords = evaluatedResults.filter(result => result.isCorrect).length;
|
|
||||||
const verifiedStats = {
|
const verifiedStats = {
|
||||||
totalWords,
|
totalWords,
|
||||||
correctWords,
|
correctWords,
|
||||||
@@ -867,23 +1267,33 @@ router.post('/test-record', authMiddleware, async (req, res) => {
|
|||||||
attempt: attempt._id,
|
attempt: attempt._id,
|
||||||
testType: attemptAny.testType,
|
testType: attemptAny.testType,
|
||||||
stats: verifiedStats,
|
stats: verifiedStats,
|
||||||
results: evaluatedResults.map(result => ({
|
results: submittedAnswers.map((result: any) => ({
|
||||||
word: result.wordId,
|
word: result.word,
|
||||||
userAnswer: result.userAnswer,
|
userAnswer: result.userAnswer,
|
||||||
correctAnswer: result.correctAnswer,
|
correctAnswer: result.correctAnswer,
|
||||||
isCorrect: result.isCorrect
|
isCorrect: shouldInvalidateBatch ? false : result.isCorrect
|
||||||
}))
|
})),
|
||||||
|
invalidated: shouldInvalidateBatch,
|
||||||
|
riskFlags: attemptAny.riskFlags || []
|
||||||
});
|
});
|
||||||
|
|
||||||
res.status(201).json({
|
res.status(201).json({
|
||||||
message: '测试记录已保存',
|
message: shouldInvalidateBatch ? INVALID_CREDENTIAL_MESSAGE : '测试记录已保存',
|
||||||
attemptId: attempt._id.toString(),
|
attemptId: attempt._id.toString(),
|
||||||
stats: verifiedStats,
|
stats: verifiedStats,
|
||||||
submittedAt: new Date(lastSubmittedAtMs)
|
results: submittedAnswers.map((result: any) => ({
|
||||||
|
wordId: getObjectIdString(result.word),
|
||||||
|
word: submittedWordMap.get(getObjectIdString(result.word)) || '',
|
||||||
|
userAnswer: result.userAnswer,
|
||||||
|
correctAnswer: result.correctAnswer,
|
||||||
|
isCorrect: shouldInvalidateBatch ? false : result.isCorrect
|
||||||
|
})),
|
||||||
|
submittedAt: new Date(lastSubmittedAtMs),
|
||||||
|
invalidated: shouldInvalidateBatch
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('保存测试记录失败:', error);
|
console.error('保存测试记录失败:', error);
|
||||||
res.status(500).json({ message: '保存测试记录失败' });
|
res.status(500).json({ message: INVALID_CREDENTIAL_MESSAGE });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -25,11 +25,13 @@ import sudokuRouter from './routes/sudoku';
|
|||||||
// 加载环境变量
|
// 加载环境变量
|
||||||
dotenv.config();
|
dotenv.config();
|
||||||
|
|
||||||
|
const BODY_LIMIT = process.env.BODY_LIMIT || '5mb';
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
// 中间件配置
|
// 中间件配置
|
||||||
app.use(express.json());
|
app.use(express.json({ limit: BODY_LIMIT }));
|
||||||
app.use(express.urlencoded({ extended: true }));
|
app.use(express.urlencoded({ extended: true, limit: BODY_LIMIT }));
|
||||||
app.use(cors());
|
app.use(cors());
|
||||||
|
|
||||||
// 静态文件服务 - 优先处理 public 目录下的静态文件
|
// 静态文件服务 - 优先处理 public 目录下的静态文件
|
||||||
@@ -202,7 +204,40 @@ app.use((req, res, next) => {
|
|||||||
|
|
||||||
// 错误处理中间件
|
// 错误处理中间件
|
||||||
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
|
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||||
console.error(err.stack);
|
if (res.headersSent) {
|
||||||
|
return next(err);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
err?.type === 'entity.too.large' ||
|
||||||
|
err?.name === 'PayloadTooLargeError' ||
|
||||||
|
err?.status === 413 ||
|
||||||
|
err?.statusCode === 413
|
||||||
|
) {
|
||||||
|
console.warn('Request body too large:', {
|
||||||
|
method: req.method,
|
||||||
|
path: req.path,
|
||||||
|
limit: BODY_LIMIT
|
||||||
|
});
|
||||||
|
return res.status(413).json({
|
||||||
|
error: '请求体过大,请缩小单次提交内容',
|
||||||
|
code: 'PAYLOAD_TOO_LARGE'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err?.type === 'entity.parse.failed') {
|
||||||
|
console.error('Invalid JSON payload:', {
|
||||||
|
method: req.method,
|
||||||
|
path: req.path,
|
||||||
|
message: err?.message
|
||||||
|
});
|
||||||
|
return res.status(400).json({
|
||||||
|
error: '请求体格式无效',
|
||||||
|
code: 'INVALID_JSON'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error(err?.stack || err);
|
||||||
res.status(500).send('Something broke!');
|
res.status(500).send('Something broke!');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
48
server/utils/vocabularyAuditFilters.test.ts
Normal file
48
server/utils/vocabularyAuditFilters.test.ts
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {
|
||||||
|
applyVocabularySummaryItemFilters,
|
||||||
|
buildVocabularySummaryFilters
|
||||||
|
} from './vocabularyAuditFilters';
|
||||||
|
|
||||||
|
const uniqueWordFilter = buildVocabularySummaryFilters({ minUniqueWords: '40' });
|
||||||
|
assert.deepEqual(uniqueWordFilter, {
|
||||||
|
minUniqueWords: 40,
|
||||||
|
userMatchStages: [],
|
||||||
|
baseMatch: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const legacyFilter = buildVocabularySummaryFilters({ minCorrectWords: '35' });
|
||||||
|
assert.deepEqual(legacyFilter, {
|
||||||
|
minUniqueWords: 35,
|
||||||
|
userMatchStages: [],
|
||||||
|
baseMatch: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const emptyFilter = buildVocabularySummaryFilters({});
|
||||||
|
assert.deepEqual(emptyFilter, {
|
||||||
|
minUniqueWords: undefined,
|
||||||
|
userMatchStages: [],
|
||||||
|
baseMatch: {}
|
||||||
|
});
|
||||||
|
|
||||||
|
const studentFilter = buildVocabularySummaryFilters({ studentNo: 'A.12' });
|
||||||
|
assert.deepEqual(studentFilter.userMatchStages, [{
|
||||||
|
$match: {
|
||||||
|
'user.username': {
|
||||||
|
$regex: 'A\\.12',
|
||||||
|
$options: 'i'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}]);
|
||||||
|
|
||||||
|
const invalidFilter = buildVocabularySummaryFilters({ minUniqueWords: '4.5' });
|
||||||
|
assert.deepEqual(invalidFilter, { error: '去重单词数量必须是正整数' });
|
||||||
|
|
||||||
|
const filteredItems = applyVocabularySummaryItemFilters([
|
||||||
|
{ userId: 'below', uniqueWords: 39 },
|
||||||
|
{ userId: 'equal', uniqueWords: 40 },
|
||||||
|
{ userId: 'above', uniqueWords: 41 }
|
||||||
|
], 40);
|
||||||
|
assert.deepEqual(filteredItems.map(item => item.userId), ['equal', 'above']);
|
||||||
|
|
||||||
|
console.log('vocabularyAuditFilters tests passed');
|
||||||
52
server/utils/vocabularyAuditFilters.ts
Normal file
52
server/utils/vocabularyAuditFilters.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
const escapeRegex = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
|
||||||
|
const parseOptionalPositiveInt = (value: unknown, fieldName: string) => {
|
||||||
|
const raw = String(value ?? '').trim();
|
||||||
|
if (!raw) return { value: undefined as number | undefined };
|
||||||
|
|
||||||
|
if (!/^\d+$/.test(raw)) {
|
||||||
|
return { error: `${fieldName}必须是正整数` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = Number(raw);
|
||||||
|
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||||
|
return { error: `${fieldName}必须大于0` };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { value: parsed };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const buildVocabularySummaryFilters = (query: Record<string, any>) => {
|
||||||
|
const studentNo = String(query.studentNo || '').trim();
|
||||||
|
const rawMinUniqueWords = query.minUniqueWords ?? query.minCorrectWords ?? query.minWords;
|
||||||
|
const wordCountResult = parseOptionalPositiveInt(rawMinUniqueWords, '去重单词数量');
|
||||||
|
if ('error' in wordCountResult) return { error: wordCountResult.error };
|
||||||
|
|
||||||
|
const minUniqueWords = wordCountResult.value;
|
||||||
|
const userMatchStages = studentNo
|
||||||
|
? [{
|
||||||
|
$match: {
|
||||||
|
'user.username': {
|
||||||
|
$regex: escapeRegex(studentNo),
|
||||||
|
$options: 'i'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
: [];
|
||||||
|
|
||||||
|
const baseMatch: Record<string, any> = {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
minUniqueWords,
|
||||||
|
userMatchStages,
|
||||||
|
baseMatch
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
export const applyVocabularySummaryItemFilters = <T extends { uniqueWords?: number }>(
|
||||||
|
items: T[],
|
||||||
|
minUniqueWords?: number
|
||||||
|
): T[] => {
|
||||||
|
if (typeof minUniqueWords !== 'number') return items;
|
||||||
|
return items.filter(item => Number(item.uniqueWords || 0) >= minUniqueWords);
|
||||||
|
};
|
||||||
58
server/utils/vocabularyRisk.test.ts
Normal file
58
server/utils/vocabularyRisk.test.ts
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import {
|
||||||
|
DEFAULT_VOCABULARY_FULL_CORRECT_WORD_THRESHOLD,
|
||||||
|
VOCABULARY_FULL_CORRECT_RISK_FLAG,
|
||||||
|
analyzeVocabularyAttemptResultRisk
|
||||||
|
} from './vocabularyRisk';
|
||||||
|
|
||||||
|
const defaultThreshold = DEFAULT_VOCABULARY_FULL_CORRECT_WORD_THRESHOLD;
|
||||||
|
|
||||||
|
assert.equal(defaultThreshold, 50);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
analyzeVocabularyAttemptResultRisk({
|
||||||
|
testType: 'chinese-to-english',
|
||||||
|
totalWords: defaultThreshold + 1,
|
||||||
|
correctWords: defaultThreshold + 1
|
||||||
|
}),
|
||||||
|
[VOCABULARY_FULL_CORRECT_RISK_FLAG]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
analyzeVocabularyAttemptResultRisk({
|
||||||
|
testType: 'audio-to-english',
|
||||||
|
totalWords: defaultThreshold,
|
||||||
|
correctWords: defaultThreshold
|
||||||
|
}),
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
analyzeVocabularyAttemptResultRisk({
|
||||||
|
testType: 'chinese-to-english',
|
||||||
|
totalWords: defaultThreshold + 1,
|
||||||
|
correctWords: defaultThreshold
|
||||||
|
}),
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
analyzeVocabularyAttemptResultRisk({
|
||||||
|
testType: 'multiple-choice',
|
||||||
|
totalWords: defaultThreshold + 1,
|
||||||
|
correctWords: defaultThreshold + 1
|
||||||
|
}),
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
analyzeVocabularyAttemptResultRisk({
|
||||||
|
testType: 'audio-to-english',
|
||||||
|
totalWords: 41,
|
||||||
|
correctWords: 41,
|
||||||
|
threshold: 40
|
||||||
|
}),
|
||||||
|
[VOCABULARY_FULL_CORRECT_RISK_FLAG]
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log('vocabularyRisk tests passed');
|
||||||
59
server/utils/vocabularyRisk.ts
Normal file
59
server/utils/vocabularyRisk.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
export type VocabularyRiskTestType = 'chinese-to-english' | 'audio-to-english' | 'multiple-choice';
|
||||||
|
|
||||||
|
export const DEFAULT_VOCABULARY_FULL_CORRECT_WORD_THRESHOLD = 50;
|
||||||
|
export const VOCABULARY_FULL_CORRECT_RISK_FLAG = 'large_batch_all_correct';
|
||||||
|
|
||||||
|
export const INVALIDATING_VOCABULARY_RISK_FLAGS: string[] = [
|
||||||
|
'invalid_origin',
|
||||||
|
'invalid_answer_proof',
|
||||||
|
'invalid_question_token',
|
||||||
|
'invalid_option_token',
|
||||||
|
'invalid_submitted_at',
|
||||||
|
'submitted_at_out_of_sync',
|
||||||
|
'attempt_expired',
|
||||||
|
'too_fast',
|
||||||
|
'too_slow',
|
||||||
|
'missing_choice_interaction',
|
||||||
|
'missing_input_value_trace',
|
||||||
|
'input_value_mismatch',
|
||||||
|
'uniform_answer_intervals',
|
||||||
|
'repeated_whole_second_intervals',
|
||||||
|
VOCABULARY_FULL_CORRECT_RISK_FLAG
|
||||||
|
];
|
||||||
|
|
||||||
|
const parsePositiveThreshold = (value: unknown): number | undefined => {
|
||||||
|
const parsed = Number(value);
|
||||||
|
return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getVocabularyFullCorrectWordThreshold = (): number => {
|
||||||
|
return parsePositiveThreshold(process.env.VOCABULARY_FULL_CORRECT_WORD_THRESHOLD) ??
|
||||||
|
DEFAULT_VOCABULARY_FULL_CORRECT_WORD_THRESHOLD;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const analyzeVocabularyAttemptResultRisk = ({
|
||||||
|
testType,
|
||||||
|
totalWords,
|
||||||
|
correctWords,
|
||||||
|
threshold = getVocabularyFullCorrectWordThreshold()
|
||||||
|
}: {
|
||||||
|
testType: VocabularyRiskTestType | string;
|
||||||
|
totalWords: number;
|
||||||
|
correctWords: number;
|
||||||
|
threshold?: number;
|
||||||
|
}): string[] => {
|
||||||
|
const effectiveThreshold = parsePositiveThreshold(threshold) ??
|
||||||
|
DEFAULT_VOCABULARY_FULL_CORRECT_WORD_THRESHOLD;
|
||||||
|
const safeTotalWords = Number.isFinite(totalWords) ? totalWords : 0;
|
||||||
|
const safeCorrectWords = Number.isFinite(correctWords) ? correctWords : 0;
|
||||||
|
|
||||||
|
if (
|
||||||
|
testType !== 'multiple-choice' &&
|
||||||
|
safeTotalWords > effectiveThreshold &&
|
||||||
|
safeTotalWords === safeCorrectWords
|
||||||
|
) {
|
||||||
|
return [VOCABULARY_FULL_CORRECT_RISK_FLAG];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
};
|
||||||
184
src/api/admin.ts
184
src/api/admin.ts
@@ -94,6 +94,172 @@ export interface Word {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface VocabularyPassSummaryItem {
|
||||||
|
userId: string;
|
||||||
|
username: string;
|
||||||
|
fullname: string;
|
||||||
|
email?: string;
|
||||||
|
passedWords: number;
|
||||||
|
uniqueWords: number;
|
||||||
|
testRecords: number;
|
||||||
|
totalRecords?: number;
|
||||||
|
validRecords?: number;
|
||||||
|
invalidatedRecords?: number;
|
||||||
|
wordSets: number;
|
||||||
|
testTypes: string[];
|
||||||
|
riskFlags?: string[];
|
||||||
|
firstPassedAt: string;
|
||||||
|
lastPassedAt: string;
|
||||||
|
firstRecordAt?: string;
|
||||||
|
lastRecordAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyPassSummaryResponse {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
totalStudents: number;
|
||||||
|
totalPassedWords: number;
|
||||||
|
totalRecords?: number;
|
||||||
|
invalidatedRecords?: number;
|
||||||
|
items: VocabularyPassSummaryItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyAuditQueryParams {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
studentNo?: string;
|
||||||
|
minUniqueWords?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ClearVocabularyPassSummaryResponse {
|
||||||
|
message: string;
|
||||||
|
userId?: string;
|
||||||
|
username?: string;
|
||||||
|
fullname?: string;
|
||||||
|
deletedRecords: number;
|
||||||
|
removedPassedWords: number;
|
||||||
|
affectedWords: number;
|
||||||
|
rebuiltWords: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyAuditWordBrief {
|
||||||
|
_id: string;
|
||||||
|
word?: string;
|
||||||
|
translation?: string;
|
||||||
|
pronunciation?: string;
|
||||||
|
example?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyAuditUserBrief {
|
||||||
|
_id?: string;
|
||||||
|
userId?: string;
|
||||||
|
username?: string;
|
||||||
|
fullname?: string;
|
||||||
|
email?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyAuditInteractionSummary {
|
||||||
|
keyCount: number;
|
||||||
|
inputCount: number;
|
||||||
|
pasteCount: number;
|
||||||
|
focusCount: number;
|
||||||
|
blurCount: number;
|
||||||
|
pointerCount: number;
|
||||||
|
firstEventOffset: number;
|
||||||
|
lastEventOffset: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyAuditResultDetail {
|
||||||
|
index: number;
|
||||||
|
wordId: string;
|
||||||
|
word: VocabularyAuditWordBrief | null;
|
||||||
|
userAnswer: string;
|
||||||
|
correctAnswer: string;
|
||||||
|
isCorrect: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyAuditAnswerDetail extends VocabularyAuditResultDetail {
|
||||||
|
questionToken: string;
|
||||||
|
submittedAt?: string;
|
||||||
|
duration?: number;
|
||||||
|
riskFlags: string[];
|
||||||
|
interactionSummary?: VocabularyAuditInteractionSummary | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyAuditAttemptDetail {
|
||||||
|
attemptId: string;
|
||||||
|
status: string;
|
||||||
|
testType: string;
|
||||||
|
wordSetId: string;
|
||||||
|
issuedAt?: string;
|
||||||
|
expiresAt?: string;
|
||||||
|
submittedAt?: string;
|
||||||
|
riskFlags: string[];
|
||||||
|
reviewDecision?: string;
|
||||||
|
reviewedAt?: string;
|
||||||
|
reviewedBy?: VocabularyAuditUserBrief | null;
|
||||||
|
reviewNote?: string;
|
||||||
|
questionWordIds: string[];
|
||||||
|
questionTokens: string[];
|
||||||
|
optionTokens: string[][];
|
||||||
|
optionTexts: string[][];
|
||||||
|
answeredQuestionTokens: string[];
|
||||||
|
answerDurations: number[];
|
||||||
|
answers: VocabularyAuditAnswerDetail[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyAuditRecordDetail {
|
||||||
|
recordId: string;
|
||||||
|
attemptId: string;
|
||||||
|
wordSet: {
|
||||||
|
_id: string;
|
||||||
|
name?: string;
|
||||||
|
description?: string;
|
||||||
|
} | null;
|
||||||
|
testType: string;
|
||||||
|
stats: {
|
||||||
|
totalWords: number;
|
||||||
|
correctWords: number;
|
||||||
|
accuracy: number;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
duration: number;
|
||||||
|
};
|
||||||
|
invalidated: boolean;
|
||||||
|
riskFlags: string[];
|
||||||
|
reviewDecision?: string;
|
||||||
|
reviewedAt?: string;
|
||||||
|
reviewedBy?: VocabularyAuditUserBrief | null;
|
||||||
|
reviewNote?: string;
|
||||||
|
createdAt: string;
|
||||||
|
results: VocabularyAuditResultDetail[];
|
||||||
|
attempt: VocabularyAuditAttemptDetail | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface VocabularyPassSummaryDetailsResponse {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
user: VocabularyAuditUserBrief;
|
||||||
|
totalRecords: number;
|
||||||
|
totalPassedWords: number;
|
||||||
|
invalidatedRecords: number;
|
||||||
|
approvedRecords: number;
|
||||||
|
records: VocabularyAuditRecordDetail[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApproveVocabularyTestRecordResponse {
|
||||||
|
message: string;
|
||||||
|
recordId: string;
|
||||||
|
attemptId?: string;
|
||||||
|
totalWords?: number;
|
||||||
|
correctWords?: number;
|
||||||
|
accuracy?: number;
|
||||||
|
riskFlags?: string[];
|
||||||
|
affectedWords?: number;
|
||||||
|
rebuiltWords?: number;
|
||||||
|
alreadyEffective?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export const adminApi = {
|
export const adminApi = {
|
||||||
getUsers: async (): Promise<User[]> => {
|
getUsers: async (): Promise<User[]> => {
|
||||||
return api.get<User[]>('/admin/users');
|
return api.get<User[]>('/admin/users');
|
||||||
@@ -176,5 +342,21 @@ export const adminApi = {
|
|||||||
updateWords: async (words: any[]) => {
|
updateWords: async (words: any[]) => {
|
||||||
return api.put('/api/vocabulary/words', { words });
|
return api.put('/api/vocabulary/words', { words });
|
||||||
},
|
},
|
||||||
};
|
|
||||||
|
|
||||||
|
getVocabularyPassSummary: async (params: VocabularyAuditQueryParams): Promise<VocabularyPassSummaryResponse> => {
|
||||||
|
return api.get<VocabularyPassSummaryResponse>('/admin/vocabulary/test-pass-summary', { params });
|
||||||
|
},
|
||||||
|
|
||||||
|
clearVocabularyPassSummary: async (data: { userId: string; start: string; end: string; studentNo?: string; minUniqueWords?: string }): Promise<ClearVocabularyPassSummaryResponse> => {
|
||||||
|
return api.post<ClearVocabularyPassSummaryResponse>('/admin/vocabulary/test-pass-summary/clear', data);
|
||||||
|
},
|
||||||
|
|
||||||
|
getVocabularyPassSummaryDetails: async (params: { userId: string } & VocabularyAuditQueryParams): Promise<VocabularyPassSummaryDetailsResponse> => {
|
||||||
|
const { userId, ...query } = params;
|
||||||
|
return api.get<VocabularyPassSummaryDetailsResponse>(`/admin/vocabulary/test-pass-summary/${userId}/details`, { params: query });
|
||||||
|
},
|
||||||
|
|
||||||
|
approveVocabularyTestRecord: async (recordId: string, data: { note?: string } = {}): Promise<ApproveVocabularyTestRecordResponse> => {
|
||||||
|
return api.post<ApproveVocabularyTestRecordResponse>(`/admin/vocabulary/test-records/${recordId}/approve`, data);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import AdminCodeManager from './AdminCodeManager';
|
|||||||
import AdminPracticeRecords from './AdminPracticeRecords';
|
import AdminPracticeRecords from './AdminPracticeRecords';
|
||||||
import AdminOAuth2Manager from './AdminOAuth2Manager';
|
import AdminOAuth2Manager from './AdminOAuth2Manager';
|
||||||
import AdminVocabularyManager from './AdminVocabularyManager';
|
import AdminVocabularyManager from './AdminVocabularyManager';
|
||||||
|
import AdminVocabularyScoreAudit from './AdminVocabularyScoreAudit';
|
||||||
|
|
||||||
interface TabPanelProps {
|
interface TabPanelProps {
|
||||||
children?: React.ReactNode;
|
children?: React.ReactNode;
|
||||||
@@ -62,6 +63,7 @@ const AdminDashboard: React.FC = () => {
|
|||||||
<Tab label="代码管理" />
|
<Tab label="代码管理" />
|
||||||
<Tab label="练习记录" />
|
<Tab label="练习记录" />
|
||||||
<Tab label="单词库管理" />
|
<Tab label="单词库管理" />
|
||||||
|
<Tab label="词汇成绩核查" />
|
||||||
{user.username === 'bobcoc' && <Tab label="OAuth2管理" />}
|
{user.username === 'bobcoc' && <Tab label="OAuth2管理" />}
|
||||||
</Tabs>
|
</Tabs>
|
||||||
|
|
||||||
@@ -77,8 +79,11 @@ const AdminDashboard: React.FC = () => {
|
|||||||
<TabPanel value={tabValue} index={3}>
|
<TabPanel value={tabValue} index={3}>
|
||||||
<AdminVocabularyManager />
|
<AdminVocabularyManager />
|
||||||
</TabPanel>
|
</TabPanel>
|
||||||
{user.username === 'bobcoc' && (
|
|
||||||
<TabPanel value={tabValue} index={4}>
|
<TabPanel value={tabValue} index={4}>
|
||||||
|
<AdminVocabularyScoreAudit />
|
||||||
|
</TabPanel>
|
||||||
|
{user.username === 'bobcoc' && (
|
||||||
|
<TabPanel value={tabValue} index={5}>
|
||||||
<AdminOAuth2Manager />
|
<AdminOAuth2Manager />
|
||||||
</TabPanel>
|
</TabPanel>
|
||||||
)}
|
)}
|
||||||
|
|||||||
658
src/components/AdminVocabularyScoreAudit.tsx
Normal file
658
src/components/AdminVocabularyScoreAudit.tsx
Normal file
@@ -0,0 +1,658 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Button, Card, Collapse, DatePicker, Descriptions, Input, message, Modal, Popconfirm, Space, Statistic, Table, Tag, Typography } from 'antd';
|
||||||
|
import type { ColumnsType } from 'antd/es/table';
|
||||||
|
import { CheckCircleOutlined, DeleteOutlined, EyeOutlined, SearchOutlined } from '@ant-design/icons';
|
||||||
|
import {
|
||||||
|
adminApi,
|
||||||
|
VocabularyAuditAnswerDetail,
|
||||||
|
VocabularyAuditRecordDetail,
|
||||||
|
VocabularyPassSummaryDetailsResponse,
|
||||||
|
VocabularyPassSummaryItem,
|
||||||
|
VocabularyPassSummaryResponse
|
||||||
|
} from '../api/admin';
|
||||||
|
|
||||||
|
const { RangePicker } = DatePicker;
|
||||||
|
|
||||||
|
const TEST_TYPE_LABELS: Record<string, string> = {
|
||||||
|
'chinese-to-english': '看中文写英文',
|
||||||
|
'audio-to-english': '听发音写单词',
|
||||||
|
'multiple-choice': '选择正确翻译'
|
||||||
|
};
|
||||||
|
|
||||||
|
const toIsoString = (value: any): string => {
|
||||||
|
if (!value) return '';
|
||||||
|
if (typeof value.toDate === 'function') return value.toDate().toISOString();
|
||||||
|
if (typeof value.toISOString === 'function') return value.toISOString();
|
||||||
|
return new Date(value).toISOString();
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDateTime = (value?: string) => {
|
||||||
|
if (!value) return '-';
|
||||||
|
return new Date(value).toLocaleString('zh-CN');
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDuration = (value?: number) => {
|
||||||
|
if (typeof value !== 'number' || Number.isNaN(value)) return '-';
|
||||||
|
return `${Math.round(value * 10) / 10} 秒`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderCopyableId = (value?: string) => {
|
||||||
|
if (!value) return '-';
|
||||||
|
return (
|
||||||
|
<Typography.Text copyable ellipsis style={{ display: 'inline-block', maxWidth: 180 }}>
|
||||||
|
{value}
|
||||||
|
</Typography.Text>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderRiskTags = (flags?: string[]) => {
|
||||||
|
const uniqueFlags = Array.from(new Set((flags || []).filter(Boolean)));
|
||||||
|
if (uniqueFlags.length === 0) return <Typography.Text type="secondary">-</Typography.Text>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Space wrap size={[4, 4]}>
|
||||||
|
{uniqueFlags.map(flag => (
|
||||||
|
<Tag key={flag} color="orange">{flag}</Tag>
|
||||||
|
))}
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderJsonBlock = (value: any) => (
|
||||||
|
<pre
|
||||||
|
style={{
|
||||||
|
margin: 0,
|
||||||
|
maxHeight: 320,
|
||||||
|
overflow: 'auto',
|
||||||
|
padding: 12,
|
||||||
|
background: '#f5f5f5',
|
||||||
|
borderRadius: 6,
|
||||||
|
whiteSpace: 'pre-wrap',
|
||||||
|
wordBreak: 'break-word'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{JSON.stringify(value ?? null, null, 2)}
|
||||||
|
</pre>
|
||||||
|
);
|
||||||
|
|
||||||
|
const getRecordRiskFlags = (record: VocabularyAuditRecordDetail) => Array.from(new Set([
|
||||||
|
...(record.riskFlags || []),
|
||||||
|
...(record.attempt?.riskFlags || [])
|
||||||
|
]));
|
||||||
|
|
||||||
|
const getAnswerRows = (record: VocabularyAuditRecordDetail): VocabularyAuditAnswerDetail[] => {
|
||||||
|
if (record.attempt?.answers?.length) return record.attempt.answers;
|
||||||
|
|
||||||
|
return record.results.map(result => ({
|
||||||
|
...result,
|
||||||
|
questionToken: '',
|
||||||
|
riskFlags: [],
|
||||||
|
interactionSummary: null
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const AdminVocabularyScoreAudit: React.FC = () => {
|
||||||
|
const [range, setRange] = useState<[string, string] | null>(null);
|
||||||
|
const [studentNo, setStudentNo] = useState('');
|
||||||
|
const [minUniqueWords, setMinUniqueWords] = useState('');
|
||||||
|
const [summary, setSummary] = useState<VocabularyPassSummaryResponse | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [clearingUserId, setClearingUserId] = useState<string | null>(null);
|
||||||
|
const [detailOpen, setDetailOpen] = useState(false);
|
||||||
|
const [detailLoading, setDetailLoading] = useState(false);
|
||||||
|
const [selectedStudent, setSelectedStudent] = useState<VocabularyPassSummaryItem | null>(null);
|
||||||
|
const [details, setDetails] = useState<VocabularyPassSummaryDetailsResponse | null>(null);
|
||||||
|
const [approvingRecordId, setApprovingRecordId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const getFilterParams = () => ({
|
||||||
|
studentNo: studentNo.trim() || undefined,
|
||||||
|
minUniqueWords: minUniqueWords.trim() || undefined
|
||||||
|
});
|
||||||
|
|
||||||
|
const fetchSummary = async () => {
|
||||||
|
if (!range) {
|
||||||
|
message.warning('请先选择开始和结束时间');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const response = await adminApi.getVocabularyPassSummary({
|
||||||
|
start: range[0],
|
||||||
|
end: range[1],
|
||||||
|
...getFilterParams()
|
||||||
|
});
|
||||||
|
setSummary(response);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取词汇测试通过统计失败:', error);
|
||||||
|
message.error('获取词汇测试通过统计失败');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchStudentDetails = async (row: VocabularyPassSummaryItem) => {
|
||||||
|
if (!range) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setDetailLoading(true);
|
||||||
|
const response = await adminApi.getVocabularyPassSummaryDetails({
|
||||||
|
userId: row.userId,
|
||||||
|
start: range[0],
|
||||||
|
end: range[1],
|
||||||
|
...getFilterParams()
|
||||||
|
});
|
||||||
|
setDetails(response);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取词汇测试明细失败:', error);
|
||||||
|
message.error('获取词汇测试明细失败');
|
||||||
|
} finally {
|
||||||
|
setDetailLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openStudentDetails = async (row: VocabularyPassSummaryItem) => {
|
||||||
|
setSelectedStudent(row);
|
||||||
|
setDetails(null);
|
||||||
|
setDetailOpen(true);
|
||||||
|
await fetchStudentDetails(row);
|
||||||
|
};
|
||||||
|
|
||||||
|
const approveRecord = async (record: VocabularyAuditRecordDetail) => {
|
||||||
|
try {
|
||||||
|
setApprovingRecordId(record.recordId);
|
||||||
|
const response = await adminApi.approveVocabularyTestRecord(record.recordId);
|
||||||
|
if (response.alreadyEffective) {
|
||||||
|
message.info(response.message);
|
||||||
|
} else {
|
||||||
|
message.success(`已恢复为有效成绩:${response.correctWords || 0}/${response.totalWords || 0}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (selectedStudent) {
|
||||||
|
await fetchStudentDetails(selectedStudent);
|
||||||
|
}
|
||||||
|
await fetchSummary();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('人工放行词汇测试记录失败:', error);
|
||||||
|
message.error('人工放行词汇测试记录失败');
|
||||||
|
} finally {
|
||||||
|
setApprovingRecordId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const clearStudentScores = async (row: VocabularyPassSummaryItem) => {
|
||||||
|
if (!range) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setClearingUserId(row.userId);
|
||||||
|
const response = await adminApi.clearVocabularyPassSummary({
|
||||||
|
userId: row.userId,
|
||||||
|
start: range[0],
|
||||||
|
end: range[1],
|
||||||
|
...getFilterParams()
|
||||||
|
});
|
||||||
|
message.success(`已清除 ${response.removedPassedWords} 个通过单词,删除 ${response.deletedRecords} 条测试记录`);
|
||||||
|
await fetchSummary();
|
||||||
|
if (selectedStudent?.userId === row.userId) {
|
||||||
|
await fetchStudentDetails(row);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('清除词汇测试成绩失败:', error);
|
||||||
|
message.error('清除词汇测试成绩失败');
|
||||||
|
} finally {
|
||||||
|
setClearingUserId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const answerColumns: ColumnsType<VocabularyAuditAnswerDetail> = [
|
||||||
|
{
|
||||||
|
title: '#',
|
||||||
|
dataIndex: 'index',
|
||||||
|
key: 'index',
|
||||||
|
width: 56
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '单词',
|
||||||
|
key: 'word',
|
||||||
|
width: 180,
|
||||||
|
render: (_, row) => (
|
||||||
|
<div>
|
||||||
|
<div style={{ fontWeight: 600 }}>{row.word?.word || row.wordId || '-'}</div>
|
||||||
|
<Typography.Text type="secondary">{row.word?.translation || '-'}</Typography.Text>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '提交答案',
|
||||||
|
dataIndex: 'userAnswer',
|
||||||
|
key: 'userAnswer',
|
||||||
|
width: 180
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '正确答案',
|
||||||
|
dataIndex: 'correctAnswer',
|
||||||
|
key: 'correctAnswer',
|
||||||
|
width: 180
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '结果',
|
||||||
|
dataIndex: 'isCorrect',
|
||||||
|
key: 'isCorrect',
|
||||||
|
width: 96,
|
||||||
|
render: (isCorrect: boolean) => (
|
||||||
|
<Tag color={isCorrect ? 'green' : 'red'}>{isCorrect ? '正确' : '错误'}</Tag>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '用时',
|
||||||
|
dataIndex: 'duration',
|
||||||
|
key: 'duration',
|
||||||
|
width: 96,
|
||||||
|
render: formatDuration
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '提交时间',
|
||||||
|
dataIndex: 'submittedAt',
|
||||||
|
key: 'submittedAt',
|
||||||
|
width: 180,
|
||||||
|
render: formatDateTime
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '题目 Token',
|
||||||
|
dataIndex: 'questionToken',
|
||||||
|
key: 'questionToken',
|
||||||
|
width: 200,
|
||||||
|
render: renderCopyableId
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'RiskFlags',
|
||||||
|
dataIndex: 'riskFlags',
|
||||||
|
key: 'riskFlags',
|
||||||
|
width: 220,
|
||||||
|
render: renderRiskTags
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '交互摘要',
|
||||||
|
dataIndex: 'interactionSummary',
|
||||||
|
key: 'interactionSummary',
|
||||||
|
width: 260,
|
||||||
|
render: summary => {
|
||||||
|
if (!summary) return <Typography.Text type="secondary">-</Typography.Text>;
|
||||||
|
return (
|
||||||
|
<Space wrap size={[4, 4]}>
|
||||||
|
<Tag>key {summary.keyCount}</Tag>
|
||||||
|
<Tag>input {summary.inputCount}</Tag>
|
||||||
|
<Tag>paste {summary.pasteCount}</Tag>
|
||||||
|
<Tag>pointer {summary.pointerCount}</Tag>
|
||||||
|
<Tag>focus {summary.focusCount}</Tag>
|
||||||
|
<Tag>blur {summary.blurCount}</Tag>
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const renderRecordExpanded = (record: VocabularyAuditRecordDetail) => {
|
||||||
|
const recordJson = {
|
||||||
|
recordId: record.recordId,
|
||||||
|
attemptId: record.attemptId,
|
||||||
|
wordSet: record.wordSet,
|
||||||
|
testType: record.testType,
|
||||||
|
stats: record.stats,
|
||||||
|
invalidated: record.invalidated,
|
||||||
|
riskFlags: record.riskFlags,
|
||||||
|
reviewDecision: record.reviewDecision,
|
||||||
|
reviewedAt: record.reviewedAt,
|
||||||
|
reviewedBy: record.reviewedBy,
|
||||||
|
reviewNote: record.reviewNote,
|
||||||
|
createdAt: record.createdAt,
|
||||||
|
results: record.results
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||||
|
<Descriptions size="small" bordered column={{ xs: 1, sm: 2, md: 3 }}>
|
||||||
|
<Descriptions.Item label="记录ID">{renderCopyableId(record.recordId)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="Attempt ID">{renderCopyableId(record.attemptId)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="单词集">{record.wordSet?.name || record.wordSet?._id || '-'}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="开始时间">{formatDateTime(record.stats?.startTime)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="结束时间">{formatDateTime(record.stats?.endTime)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="时长">{formatDuration(record.stats?.duration)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="成绩">{`${record.stats?.correctWords || 0}/${record.stats?.totalWords || 0}`}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="正确率">{`${Math.round((record.stats?.accuracy || 0) * 10) / 10}%`}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="人工审核">
|
||||||
|
{record.reviewDecision === 'approved' ? (
|
||||||
|
<Space wrap>
|
||||||
|
<Tag color="green">已放行</Tag>
|
||||||
|
<Typography.Text type="secondary">
|
||||||
|
{record.reviewedBy?.fullname || record.reviewedBy?.username || ''}
|
||||||
|
</Typography.Text>
|
||||||
|
<Typography.Text type="secondary">{formatDateTime(record.reviewedAt)}</Typography.Text>
|
||||||
|
</Space>
|
||||||
|
) : (
|
||||||
|
<Typography.Text type="secondary">-</Typography.Text>
|
||||||
|
)}
|
||||||
|
</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="记录 RiskFlags" span={3}>{renderRiskTags(record.riskFlags)}</Descriptions.Item>
|
||||||
|
<Descriptions.Item label="Attempt RiskFlags" span={3}>{renderRiskTags(record.attempt?.riskFlags)}</Descriptions.Item>
|
||||||
|
</Descriptions>
|
||||||
|
|
||||||
|
<Table
|
||||||
|
size="small"
|
||||||
|
columns={answerColumns}
|
||||||
|
dataSource={getAnswerRows(record)}
|
||||||
|
rowKey={row => `${record.recordId}-${row.index}-${row.questionToken || row.wordId}`}
|
||||||
|
pagination={false}
|
||||||
|
scroll={{ x: 1600 }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Collapse
|
||||||
|
size="small"
|
||||||
|
items={[
|
||||||
|
{
|
||||||
|
key: 'record-json',
|
||||||
|
label: '成绩记录 JSON',
|
||||||
|
children: renderJsonBlock(recordJson)
|
||||||
|
},
|
||||||
|
...(record.attempt ? [{
|
||||||
|
key: 'attempt-json',
|
||||||
|
label: 'Attempt JSON',
|
||||||
|
children: renderJsonBlock(record.attempt)
|
||||||
|
}] : [])
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const detailColumns: ColumnsType<VocabularyAuditRecordDetail> = [
|
||||||
|
{
|
||||||
|
title: '时间',
|
||||||
|
dataIndex: ['stats', 'endTime'],
|
||||||
|
key: 'endTime',
|
||||||
|
width: 180,
|
||||||
|
render: formatDateTime,
|
||||||
|
sorter: (a, b) => new Date(a.stats?.endTime || 0).getTime() - new Date(b.stats?.endTime || 0).getTime(),
|
||||||
|
defaultSortOrder: 'descend'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '状态',
|
||||||
|
key: 'status',
|
||||||
|
width: 120,
|
||||||
|
render: (_, record) => {
|
||||||
|
if (record.invalidated) return <Tag color="red">风控作废</Tag>;
|
||||||
|
if (record.reviewDecision === 'approved') return <Tag color="green">人工有效</Tag>;
|
||||||
|
return <Tag color="blue">有效</Tag>;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '题型',
|
||||||
|
dataIndex: 'testType',
|
||||||
|
key: 'testType',
|
||||||
|
width: 150,
|
||||||
|
render: (type: string) => <Tag color="blue">{TEST_TYPE_LABELS[type] || type}</Tag>
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '单词集',
|
||||||
|
key: 'wordSet',
|
||||||
|
width: 160,
|
||||||
|
render: (_, record) => record.wordSet?.name || record.wordSet?._id || '-'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '成绩',
|
||||||
|
key: 'score',
|
||||||
|
width: 110,
|
||||||
|
sorter: (a, b) => (a.stats?.correctWords || 0) - (b.stats?.correctWords || 0),
|
||||||
|
render: (_, record) => <Tag color="green">{record.stats?.correctWords || 0}/{record.stats?.totalWords || 0}</Tag>
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Attempt ID',
|
||||||
|
dataIndex: 'attemptId',
|
||||||
|
key: 'attemptId',
|
||||||
|
width: 200,
|
||||||
|
render: renderCopyableId
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'RiskFlags',
|
||||||
|
key: 'riskFlags',
|
||||||
|
width: 260,
|
||||||
|
render: (_, record) => renderRiskTags(getRecordRiskFlags(record))
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'actions',
|
||||||
|
fixed: 'right',
|
||||||
|
width: 150,
|
||||||
|
render: (_, record) => record.invalidated ? (
|
||||||
|
<Popconfirm
|
||||||
|
title="确认将该风控记录转为有效成绩?"
|
||||||
|
description="会按原始 attempt 答案恢复正确率,并重算这些单词的掌握状态。"
|
||||||
|
okText="确认放行"
|
||||||
|
cancelText="取消"
|
||||||
|
onConfirm={() => approveRecord(record)}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
type="primary"
|
||||||
|
icon={<CheckCircleOutlined />}
|
||||||
|
loading={approvingRecordId === record.recordId}
|
||||||
|
>
|
||||||
|
转有效
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
) : (
|
||||||
|
<Typography.Text type="secondary">-</Typography.Text>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
const columns: ColumnsType<VocabularyPassSummaryItem> = [
|
||||||
|
{
|
||||||
|
title: '学生',
|
||||||
|
key: 'student',
|
||||||
|
render: (_, row) => (
|
||||||
|
<div>
|
||||||
|
<div style={{ fontWeight: 600 }}>{row.fullname || row.username || '未知学生'}</div>
|
||||||
|
<Typography.Text type="secondary">{row.username || row.email || row.userId}</Typography.Text>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '有效通过',
|
||||||
|
dataIndex: 'passedWords',
|
||||||
|
key: 'passedWords',
|
||||||
|
sorter: (a, b) => a.passedWords - b.passedWords,
|
||||||
|
defaultSortOrder: 'descend',
|
||||||
|
render: (value: number) => <Tag color="green">{value}</Tag>
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '去重单词',
|
||||||
|
dataIndex: 'uniqueWords',
|
||||||
|
key: 'uniqueWords',
|
||||||
|
sorter: (a, b) => a.uniqueWords - b.uniqueWords
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '测试记录',
|
||||||
|
key: 'records',
|
||||||
|
sorter: (a, b) => (a.totalRecords || a.testRecords || 0) - (b.totalRecords || b.testRecords || 0),
|
||||||
|
render: (_, row) => (
|
||||||
|
<Space wrap size={[4, 4]}>
|
||||||
|
<Tag color="blue">有效 {row.validRecords ?? row.testRecords ?? 0}</Tag>
|
||||||
|
<Tag>全部 {row.totalRecords || row.testRecords || 0}</Tag>
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '风控',
|
||||||
|
key: 'risk',
|
||||||
|
sorter: (a, b) => (a.invalidatedRecords || 0) - (b.invalidatedRecords || 0),
|
||||||
|
render: (_, row) => (
|
||||||
|
<Space direction="vertical" size={4}>
|
||||||
|
<Tag color={(row.invalidatedRecords || 0) > 0 ? 'red' : 'green'}>
|
||||||
|
作废 {row.invalidatedRecords || 0}
|
||||||
|
</Tag>
|
||||||
|
{renderRiskTags(row.riskFlags)}
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '题型',
|
||||||
|
dataIndex: 'testTypes',
|
||||||
|
key: 'testTypes',
|
||||||
|
render: (types: string[]) => (
|
||||||
|
<Space wrap>
|
||||||
|
{(types || []).map(type => (
|
||||||
|
<Tag key={type} color="blue">{TEST_TYPE_LABELS[type] || type}</Tag>
|
||||||
|
))}
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '首次记录',
|
||||||
|
key: 'firstRecordAt',
|
||||||
|
render: (_, row) => formatDateTime(row.firstRecordAt || row.firstPassedAt)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '最后记录',
|
||||||
|
key: 'lastRecordAt',
|
||||||
|
render: (_, row) => formatDateTime(row.lastRecordAt || row.lastPassedAt)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'actions',
|
||||||
|
render: (_, row) => (
|
||||||
|
<Space wrap>
|
||||||
|
<Button icon={<EyeOutlined />} onClick={() => openStudentDetails(row)}>
|
||||||
|
详情
|
||||||
|
</Button>
|
||||||
|
<Popconfirm
|
||||||
|
title="确认清除该学生在所选时间段内的词汇测试成绩?"
|
||||||
|
description="会删除对应测试记录,并重算这些单词的掌握状态。"
|
||||||
|
okText="确认清除"
|
||||||
|
cancelText="取消"
|
||||||
|
okButtonProps={{ danger: true }}
|
||||||
|
onConfirm={() => clearStudentScores(row)}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
danger
|
||||||
|
icon={<DeleteOutlined />}
|
||||||
|
loading={clearingUserId === row.userId}
|
||||||
|
>
|
||||||
|
清除成绩
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</Space>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card title="词汇测试成绩核查">
|
||||||
|
<Space direction="vertical" size="large" style={{ width: '100%' }}>
|
||||||
|
<Space wrap>
|
||||||
|
<RangePicker
|
||||||
|
showTime
|
||||||
|
onChange={(dates: any) => {
|
||||||
|
if (!dates || !dates[0] || !dates[1]) {
|
||||||
|
setRange(null);
|
||||||
|
setSummary(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setRange([toIsoString(dates[0]), toIsoString(dates[1])]);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
allowClear
|
||||||
|
placeholder="输入学生学号"
|
||||||
|
value={studentNo}
|
||||||
|
onChange={event => setStudentNo(event.target.value)}
|
||||||
|
onPressEnter={fetchSummary}
|
||||||
|
style={{ width: 220 }}
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
allowClear
|
||||||
|
type="number"
|
||||||
|
placeholder="最少去重单词数"
|
||||||
|
value={minUniqueWords}
|
||||||
|
onChange={event => setMinUniqueWords(event.target.value)}
|
||||||
|
onPressEnter={fetchSummary}
|
||||||
|
style={{ width: 180 }}
|
||||||
|
/>
|
||||||
|
<Button type="primary" icon={<SearchOutlined />} loading={loading} onClick={fetchSummary}>
|
||||||
|
查询
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
|
|
||||||
|
{summary && (
|
||||||
|
<Space wrap>
|
||||||
|
<Statistic title="学生数" value={summary.totalStudents} />
|
||||||
|
<Statistic title="通过单词总数" value={summary.totalPassedWords} />
|
||||||
|
<Statistic title="测试记录" value={summary.totalRecords || 0} />
|
||||||
|
<Statistic title="风控作废" value={summary.invalidatedRecords || 0} />
|
||||||
|
<Statistic title="开始时间" value={formatDateTime(summary.start)} />
|
||||||
|
<Statistic title="结束时间" value={formatDateTime(summary.end)} />
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Table
|
||||||
|
columns={columns}
|
||||||
|
dataSource={summary?.items || []}
|
||||||
|
rowKey="userId"
|
||||||
|
loading={loading}
|
||||||
|
scroll={{ x: 1280 }}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 10,
|
||||||
|
showSizeChanger: true,
|
||||||
|
showQuickJumper: true,
|
||||||
|
showTotal: total => `共 ${total} 名学生`
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
|
||||||
|
<Modal
|
||||||
|
title={`词汇提交明细 - ${details?.user.fullname || details?.user.username || selectedStudent?.fullname || selectedStudent?.username || ''}`}
|
||||||
|
open={detailOpen}
|
||||||
|
width={1280}
|
||||||
|
footer={null}
|
||||||
|
destroyOnClose
|
||||||
|
onCancel={() => {
|
||||||
|
setDetailOpen(false);
|
||||||
|
setDetails(null);
|
||||||
|
setSelectedStudent(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Space direction="vertical" size="large" style={{ width: '100%', maxHeight: '72vh', overflow: 'auto' }}>
|
||||||
|
{details && (
|
||||||
|
<Space wrap>
|
||||||
|
<Statistic title="测试记录" value={details.totalRecords} />
|
||||||
|
<Statistic title="有效通过单词" value={details.totalPassedWords} />
|
||||||
|
<Statistic title="风控作废" value={details.invalidatedRecords} />
|
||||||
|
<Statistic title="人工放行" value={details.approvedRecords} />
|
||||||
|
<Statistic title="开始时间" value={formatDateTime(details.start)} />
|
||||||
|
<Statistic title="结束时间" value={formatDateTime(details.end)} />
|
||||||
|
</Space>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<Table
|
||||||
|
size="small"
|
||||||
|
columns={detailColumns}
|
||||||
|
dataSource={details?.records || []}
|
||||||
|
rowKey="recordId"
|
||||||
|
loading={detailLoading}
|
||||||
|
expandable={{
|
||||||
|
expandedRowRender: renderRecordExpanded,
|
||||||
|
rowExpandable: record => Boolean(record.attempt || record.results.length > 0)
|
||||||
|
}}
|
||||||
|
scroll={{ x: 1300 }}
|
||||||
|
pagination={{
|
||||||
|
defaultPageSize: 5,
|
||||||
|
showSizeChanger: true,
|
||||||
|
showTotal: total => `共 ${total} 条记录`
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Space>
|
||||||
|
</Modal>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AdminVocabularyScoreAudit;
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
import React, { useState, useEffect, useRef } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Card, Button, Input, Progress, Modal, message, Tabs, Radio, Spin, Select, Table, Tag, InputNumber, Space } from 'antd';
|
import { Card, Button, Input, Progress, Modal, message, Tabs, Radio, Spin, Table, Tag, InputNumber, Space } from 'antd';
|
||||||
import { SoundOutlined, CaretLeftOutlined, CaretRightOutlined, TrophyOutlined, HistoryOutlined, ReloadOutlined, SettingOutlined, LinkOutlined } from '@ant-design/icons';
|
import { SoundOutlined, CaretLeftOutlined, CaretRightOutlined, TrophyOutlined, HistoryOutlined, ReloadOutlined, SettingOutlined, LinkOutlined } from '@ant-design/icons';
|
||||||
import CryptoJS from 'crypto-js';
|
import CryptoJS from 'crypto-js';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { api, ApiError, authEvents } from '../api/apiClient';
|
import { api, ApiError, authEvents } from '../api/apiClient';
|
||||||
import { API_PATHS } from '../config';
|
import { API_PATHS } from '../config';
|
||||||
import type { TabsProps } from 'antd';
|
import type { TabsProps } from 'antd';
|
||||||
import type { RadioChangeEvent } from 'antd/lib/radio';
|
|
||||||
|
|
||||||
interface Word {
|
interface Word {
|
||||||
_id?: string;
|
_id?: string;
|
||||||
@@ -74,13 +73,34 @@ interface PendingAnswer {
|
|||||||
answerProof: string;
|
answerProof: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface InteractionEventPayload {
|
||||||
|
type: string;
|
||||||
|
ts: number;
|
||||||
|
key?: string;
|
||||||
|
inputType?: string;
|
||||||
|
value?: string;
|
||||||
|
valueLength?: number;
|
||||||
|
ctrlKey?: boolean;
|
||||||
|
metaKey?: boolean;
|
||||||
|
altKey?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NativeInputLikeEvent extends Event {
|
||||||
|
inputType?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TestOption {
|
||||||
|
text: string;
|
||||||
|
token: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface TestQuestion {
|
interface TestQuestion {
|
||||||
questionToken: string;
|
questionToken: string;
|
||||||
wordId: string;
|
wordId: string;
|
||||||
word?: string;
|
word?: string;
|
||||||
translation?: string;
|
translation?: string;
|
||||||
pronunciation?: string;
|
pronunciation?: string;
|
||||||
options?: string[];
|
options?: Array<string | TestOption>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface SavedVocabularyTestRecordResponse {
|
interface SavedVocabularyTestRecordResponse {
|
||||||
@@ -93,6 +113,8 @@ interface SavedVocabularyTestRecordResponse {
|
|||||||
endTime: string | Date;
|
endTime: string | Date;
|
||||||
duration: number;
|
duration: number;
|
||||||
};
|
};
|
||||||
|
results: TestResult[];
|
||||||
|
invalidated?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TestAttemptResponse {
|
interface TestAttemptResponse {
|
||||||
@@ -102,6 +124,26 @@ interface TestAttemptResponse {
|
|||||||
questions: TestQuestion[];
|
questions: TestQuestion[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface SubmitAnswerResponse {
|
||||||
|
message: string;
|
||||||
|
result: TestResult;
|
||||||
|
progress: {
|
||||||
|
answered: number;
|
||||||
|
total: number;
|
||||||
|
finished: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OptionTokenResponse {
|
||||||
|
questionToken: string;
|
||||||
|
optionToken: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ANSWER_PROOF_SALT = 'd1ktsalt';
|
||||||
|
const INVALID_CREDENTIAL_MESSAGE = '凭证无效,请检查。';
|
||||||
|
const MIN_STUDY_WORD_COUNT = 10;
|
||||||
|
const MAX_STUDY_WORD_COUNT = 100;
|
||||||
|
|
||||||
const VocabularyStudy: React.FC = () => {
|
const VocabularyStudy: React.FC = () => {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
@@ -124,11 +166,10 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
const [testStarted, setTestStarted] = useState(false);
|
const [testStarted, setTestStarted] = useState(false);
|
||||||
const [testFinished, setTestFinished] = useState(false);
|
const [testFinished, setTestFinished] = useState(false);
|
||||||
const [testResults, setTestResults] = useState<TestResult[]>([]);
|
const [testResults, setTestResults] = useState<TestResult[]>([]);
|
||||||
const [answerFeedback, setAnswerFeedback] = useState<TestResult | null>(null);
|
|
||||||
const [testAttemptId, setTestAttemptId] = useState<string>('');
|
const [testAttemptId, setTestAttemptId] = useState<string>('');
|
||||||
const [pendingAnswers, setPendingAnswers] = useState<PendingAnswer[]>([]);
|
const [pendingAnswers, setPendingAnswers] = useState<PendingAnswer[]>([]);
|
||||||
const [testAttemptLoading, setTestAttemptLoading] = useState(false);
|
const [testAttemptLoading, setTestAttemptLoading] = useState(false);
|
||||||
const [options, setOptions] = useState<string[]>([]);
|
const [options, setOptions] = useState<TestOption[]>([]);
|
||||||
const [isModalVisible, setIsModalVisible] = useState(false);
|
const [isModalVisible, setIsModalVisible] = useState(false);
|
||||||
const timeOffsetRef = useRef<number>(0);
|
const timeOffsetRef = useRef<number>(0);
|
||||||
const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);
|
const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);
|
||||||
@@ -143,6 +184,8 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
// 使用ref存储当前选中ID,这样可以立即访问
|
// 使用ref存储当前选中ID,这样可以立即访问
|
||||||
const currentWordSetIdRef = useRef<string>('');
|
const currentWordSetIdRef = useRef<string>('');
|
||||||
const answerSubmittingRef = useRef(false);
|
const answerSubmittingRef = useRef(false);
|
||||||
|
const interactionsRef = useRef<InteractionEventPayload[]>([]);
|
||||||
|
const questionShownAtRef = useRef<number>(0);
|
||||||
|
|
||||||
// 测试输入框ref
|
// 测试输入框ref
|
||||||
const inputRef = useRef<any>(null);
|
const inputRef = useRef<any>(null);
|
||||||
@@ -293,7 +336,7 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
// 处理单词数量变更
|
// 处理单词数量变更
|
||||||
const handleWordCountChange = (value: number | null) => {
|
const handleWordCountChange = (value: number | null) => {
|
||||||
if (value !== null) {
|
if (value !== null) {
|
||||||
setWordCount(value);
|
setWordCount(Math.max(MIN_STUDY_WORD_COUNT, Math.min(value, MAX_STUDY_WORD_COUNT)));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -429,7 +472,6 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
setTestAttemptId('');
|
setTestAttemptId('');
|
||||||
setPendingAnswers([]);
|
setPendingAnswers([]);
|
||||||
setTestResults([]);
|
setTestResults([]);
|
||||||
setAnswerFeedback(null);
|
|
||||||
const wordIds = studyWords.map(getWordId).filter(Boolean);
|
const wordIds = studyWords.map(getWordId).filter(Boolean);
|
||||||
if (wordIds.length === 0) {
|
if (wordIds.length === 0) {
|
||||||
message.error('单词数据不完整,请重新加载后再试');
|
message.error('单词数据不完整,请重新加载后再试');
|
||||||
@@ -456,7 +498,9 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
setShowAnswer(false);
|
setShowAnswer(false);
|
||||||
setTestResults([]);
|
setTestResults([]);
|
||||||
setPendingAnswers([]);
|
setPendingAnswers([]);
|
||||||
setOptions(questions[0]?.options || []);
|
setOptions(normalizeOptions(questions[0]));
|
||||||
|
resetInteractionTrace();
|
||||||
|
setIsModalVisible(false);
|
||||||
setStudyStats({
|
setStudyStats({
|
||||||
totalWords: 0,
|
totalWords: 0,
|
||||||
correctWords: 0,
|
correctWords: 0,
|
||||||
@@ -465,11 +509,7 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
duration: 0
|
duration: 0
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ApiError) {
|
message.error(INVALID_CREDENTIAL_MESSAGE);
|
||||||
message.error(`创建测试会话失败: ${error.message}`);
|
|
||||||
} else {
|
|
||||||
message.error('创建测试会话失败');
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setTestAttemptLoading(false);
|
setTestAttemptLoading(false);
|
||||||
}
|
}
|
||||||
@@ -487,48 +527,109 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
|
|
||||||
const getWordId = (word: Word): string => word._id || word.id;
|
const getWordId = (word: Word): string => word._id || word.id;
|
||||||
|
|
||||||
|
const normalizeOptions = (question?: TestQuestion): TestOption[] => {
|
||||||
|
if (!question?.options) return [];
|
||||||
|
return question.options.map(option => {
|
||||||
|
if (typeof option === 'string') {
|
||||||
|
return { text: option, token: '' };
|
||||||
|
}
|
||||||
|
return option;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetInteractionTrace = () => {
|
||||||
|
const now = Date.now();
|
||||||
|
interactionsRef.current = [{
|
||||||
|
type: 'question-shown',
|
||||||
|
ts: now
|
||||||
|
}];
|
||||||
|
questionShownAtRef.current = now;
|
||||||
|
};
|
||||||
|
|
||||||
|
const recordInteraction = (event: InteractionEventPayload) => {
|
||||||
|
if (!testStarted || testFinished || showAnswer) return;
|
||||||
|
interactionsRef.current = [
|
||||||
|
...interactionsRef.current,
|
||||||
|
{
|
||||||
|
...event,
|
||||||
|
ts: Date.now()
|
||||||
|
}
|
||||||
|
].slice(-300);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTestInputElement = (): HTMLInputElement | null => {
|
||||||
|
return inputRef.current?.input || null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const moveTestInputCaretToEnd = () => {
|
||||||
|
window.setTimeout(() => {
|
||||||
|
const input = getTestInputElement();
|
||||||
|
if (!input) return;
|
||||||
|
const end = input.value.length;
|
||||||
|
input.setSelectionRange(end, end);
|
||||||
|
}, 0);
|
||||||
|
};
|
||||||
|
|
||||||
|
const focusTestInputAtEnd = () => {
|
||||||
|
inputRef.current?.focus?.();
|
||||||
|
moveTestInputCaretToEnd();
|
||||||
|
};
|
||||||
|
|
||||||
|
const shouldBlockInputKey = (event: React.KeyboardEvent<HTMLInputElement>): boolean => {
|
||||||
|
const input = event.currentTarget;
|
||||||
|
const selectionStart = input.selectionStart ?? input.value.length;
|
||||||
|
const selectionEnd = input.selectionEnd ?? input.value.length;
|
||||||
|
const hasSelection = selectionStart !== selectionEnd;
|
||||||
|
const caretAtEnd = selectionStart === input.value.length && selectionEnd === input.value.length;
|
||||||
|
const navigationKeys = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End'];
|
||||||
|
const shortcutKey = event.key.toLowerCase();
|
||||||
|
|
||||||
|
if (navigationKeys.includes(event.key) || event.key === 'Delete') return true;
|
||||||
|
if ((event.ctrlKey || event.metaKey) && ['a', 'x', 'v', 'z', 'y'].includes(shortcutKey)) return true;
|
||||||
|
if (event.key === 'Backspace') return hasSelection || !caretAtEnd;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMultipleChoiceChange = async (option: TestOption) => {
|
||||||
|
const currentQuestion = testWords[testIndex];
|
||||||
|
if (!currentQuestion || !testAttemptId || showAnswer) return;
|
||||||
|
|
||||||
|
recordInteraction({
|
||||||
|
type: 'change',
|
||||||
|
valueLength: option.text.length
|
||||||
|
});
|
||||||
|
|
||||||
|
if (option.token) {
|
||||||
|
setUserAnswer(option.token);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await api.post<OptionTokenResponse>(API_PATHS.VOCABULARY.TEST_OPTION_TOKEN, {
|
||||||
|
attemptId: testAttemptId,
|
||||||
|
questionToken: currentQuestion.questionToken,
|
||||||
|
optionText: option.text
|
||||||
|
});
|
||||||
|
|
||||||
|
setOptions(prev => prev.map(item =>
|
||||||
|
item.text === option.text
|
||||||
|
? { ...item, token: response.optionToken }
|
||||||
|
: item
|
||||||
|
));
|
||||||
|
setUserAnswer(response.optionToken);
|
||||||
|
} catch (error) {
|
||||||
|
setUserAnswer(option.text);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const buildAnswerProof = (
|
const buildAnswerProof = (
|
||||||
attemptId: string,
|
attemptId: string,
|
||||||
questionToken: string,
|
questionToken: string,
|
||||||
userAnswer: string,
|
userAnswer: string,
|
||||||
submittedAt: number
|
submittedAt: number
|
||||||
): string => {
|
): string => {
|
||||||
return CryptoJS.SHA256(`${attemptId}:${questionToken}:${submittedAt}:${userAnswer}`).toString();
|
return CryptoJS.MD5(`${ANSWER_PROOF_SALT}:${attemptId}:${questionToken}:${submittedAt}:${userAnswer}:${ANSWER_PROOF_SALT}`).toString();
|
||||||
};
|
|
||||||
|
|
||||||
function normalizeAnswer(str: string): string {
|
|
||||||
return str
|
|
||||||
.replace(/(/g, '(')
|
|
||||||
.replace(/)/g, ')')
|
|
||||||
.replace(/,/g, ',') // 全角逗号转半角
|
|
||||||
.replace(/\s+/g, '') // 去除所有空格
|
|
||||||
.replace(/,/g, '') // 去除所有逗号
|
|
||||||
.replace(/[^\w()]/g, '') // 只保留字母、数字、括号
|
|
||||||
.toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
const getQuestionWord = (question: TestQuestion): Word | undefined => {
|
|
||||||
return studyWords.find(word => getWordId(word) === question.wordId);
|
|
||||||
};
|
|
||||||
|
|
||||||
const buildLocalTestResult = (question: TestQuestion, rawUserAnswer: string): TestResult => {
|
|
||||||
const matchedWord = getQuestionWord(question);
|
|
||||||
const userAnswer = rawUserAnswer.trim();
|
|
||||||
const correctAnswer = testType === 'multiple-choice'
|
|
||||||
? String(matchedWord?.translation ?? question.translation ?? '').trim()
|
|
||||||
: String(matchedWord?.word ?? question.word ?? '').trim();
|
|
||||||
const isCorrect = testType === 'multiple-choice'
|
|
||||||
? userAnswer === correctAnswer
|
|
||||||
: normalizeAnswer(userAnswer) === normalizeAnswer(correctAnswer);
|
|
||||||
|
|
||||||
return {
|
|
||||||
questionToken: question.questionToken,
|
|
||||||
wordId: question.wordId,
|
|
||||||
word: String(matchedWord?.word ?? question.word ?? question.translation ?? '').trim(),
|
|
||||||
userAnswer,
|
|
||||||
correctAnswer,
|
|
||||||
isCorrect
|
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// 提交答案
|
// 提交答案
|
||||||
@@ -541,9 +642,20 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
answerSubmittingRef.current = false;
|
answerSubmittingRef.current = false;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const submittedAt = Date.now();
|
|
||||||
const normalizedUserAnswer = userAnswer.trim();
|
const normalizedUserAnswer = userAnswer.trim();
|
||||||
const localResult = buildLocalTestResult(currentQuestion, normalizedUserAnswer);
|
if (!normalizedUserAnswer) {
|
||||||
|
answerSubmittingRef.current = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const isKnownMultipleChoiceAnswer = options.some(option =>
|
||||||
|
option.token === normalizedUserAnswer || option.text === normalizedUserAnswer
|
||||||
|
);
|
||||||
|
if (testType === 'multiple-choice' && options.length > 0 && !isKnownMultipleChoiceAnswer) {
|
||||||
|
answerSubmittingRef.current = false;
|
||||||
|
message.warning('请选择一个选项后再提交');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const submittedAt = Date.now();
|
||||||
const answerProof = buildAnswerProof(
|
const answerProof = buildAnswerProof(
|
||||||
testAttemptId,
|
testAttemptId,
|
||||||
currentQuestion.questionToken,
|
currentQuestion.questionToken,
|
||||||
@@ -551,6 +663,20 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
submittedAt
|
submittedAt
|
||||||
);
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const submittedAnswer = {
|
||||||
|
questionToken: currentQuestion.questionToken,
|
||||||
|
userAnswer: normalizedUserAnswer,
|
||||||
|
submittedAt,
|
||||||
|
answerProof,
|
||||||
|
interactions: interactionsRef.current
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await api.post<SubmitAnswerResponse>(API_PATHS.VOCABULARY.TEST_ANSWER, {
|
||||||
|
attemptId: testAttemptId,
|
||||||
|
...submittedAnswer
|
||||||
|
});
|
||||||
|
|
||||||
const updatedPendingAnswers = [
|
const updatedPendingAnswers = [
|
||||||
...pendingAnswers,
|
...pendingAnswers,
|
||||||
{
|
{
|
||||||
@@ -560,14 +686,9 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
answerProof
|
answerProof
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
const updatedTestResults = [
|
|
||||||
...testResults,
|
|
||||||
localResult
|
|
||||||
];
|
|
||||||
|
|
||||||
setPendingAnswers(updatedPendingAnswers);
|
setPendingAnswers(updatedPendingAnswers);
|
||||||
setTestResults(updatedTestResults);
|
setTestResults(prev => [...prev, response.result]);
|
||||||
setAnswerFeedback(localResult);
|
|
||||||
setShowAnswer(true);
|
setShowAnswer(true);
|
||||||
setUserAnswer('');
|
setUserAnswer('');
|
||||||
|
|
||||||
@@ -576,7 +697,7 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
const nextIndex = testIndex + 1;
|
const nextIndex = testIndex + 1;
|
||||||
setTestIndex(nextIndex);
|
setTestIndex(nextIndex);
|
||||||
setShowAnswer(false);
|
setShowAnswer(false);
|
||||||
setAnswerFeedback(null);
|
resetInteractionTrace();
|
||||||
answerSubmittingRef.current = false;
|
answerSubmittingRef.current = false;
|
||||||
if (testType === 'audio-to-english') {
|
if (testType === 'audio-to-english') {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
@@ -584,35 +705,22 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
}, 500);
|
}, 500);
|
||||||
}
|
}
|
||||||
if (testType === 'multiple-choice') {
|
if (testType === 'multiple-choice') {
|
||||||
setOptions(testWords[nextIndex]?.options || []);
|
setOptions(normalizeOptions(testWords[nextIndex]));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
answerSubmittingRef.current = false;
|
answerSubmittingRef.current = false;
|
||||||
finishTestWithResults(updatedPendingAnswers, updatedTestResults);
|
finishTestWithResults(updatedPendingAnswers);
|
||||||
}
|
}
|
||||||
}, 1500);
|
}, 1500);
|
||||||
|
} catch (error) {
|
||||||
|
answerSubmittingRef.current = false;
|
||||||
|
message.error(INVALID_CREDENTIAL_MESSAGE);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 使用指定结果完成测试
|
// 使用指定结果完成测试
|
||||||
const finishTestWithResults = async (finalAnswers: PendingAnswer[], finalResults: TestResult[]) => {
|
const finishTestWithResults = async (finalAnswers: PendingAnswer[]) => {
|
||||||
try {
|
try {
|
||||||
const lastSubmittedAtMs = finalAnswers.length > 0
|
|
||||||
? Math.max(...finalAnswers.map(item => item.submittedAt))
|
|
||||||
: Date.now();
|
|
||||||
const localCorrectWords = finalResults.filter(result => result.isCorrect).length;
|
|
||||||
const localStats = {
|
|
||||||
totalWords: finalResults.length,
|
|
||||||
correctWords: localCorrectWords,
|
|
||||||
accuracy: finalResults.length > 0 ? (localCorrectWords / finalResults.length) * 100 : 0,
|
|
||||||
startTime: studyStats.startTime,
|
|
||||||
endTime: new Date(lastSubmittedAtMs),
|
|
||||||
duration: Math.max(0, (lastSubmittedAtMs - studyStats.startTime.getTime()) / 1000)
|
|
||||||
};
|
|
||||||
|
|
||||||
setTestResults(finalResults);
|
|
||||||
setStudyStats(localStats);
|
|
||||||
setTestFinished(true);
|
|
||||||
|
|
||||||
// 添加调试信息
|
// 添加调试信息
|
||||||
console.log('测试完成状态(带结果):', {
|
console.log('测试完成状态(带结果):', {
|
||||||
finalResultsLength: finalAnswers.length,
|
finalResultsLength: finalAnswers.length,
|
||||||
@@ -621,15 +729,9 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
currentStudyStats: studyStats
|
currentStudyStats: studyStats
|
||||||
});
|
});
|
||||||
|
|
||||||
// 提交测试记录,后端会用数据库答案重新判分
|
// 提交测试记录,后端会用服务端累计的逐题答案重新判分
|
||||||
const savedRecord = await api.post<SavedVocabularyTestRecordResponse>(API_PATHS.VOCABULARY.TEST_RECORD, {
|
const savedRecord = await api.post<SavedVocabularyTestRecordResponse>(API_PATHS.VOCABULARY.TEST_RECORD, {
|
||||||
attemptId: testAttemptId,
|
attemptId: testAttemptId
|
||||||
answers: finalAnswers.map(answer => ({
|
|
||||||
questionToken: answer.questionToken,
|
|
||||||
userAnswer: answer.userAnswer,
|
|
||||||
submittedAt: answer.submittedAt,
|
|
||||||
answerProof: answer.answerProof
|
|
||||||
}))
|
|
||||||
});
|
});
|
||||||
|
|
||||||
setStudyStats({
|
setStudyStats({
|
||||||
@@ -640,24 +742,27 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
endTime: new Date(savedRecord.stats.endTime),
|
endTime: new Date(savedRecord.stats.endTime),
|
||||||
duration: savedRecord.stats.duration
|
duration: savedRecord.stats.duration
|
||||||
});
|
});
|
||||||
|
setTestResults(savedRecord.results);
|
||||||
setPendingAnswers([]);
|
setPendingAnswers([]);
|
||||||
setTestAttemptId('');
|
setTestAttemptId('');
|
||||||
|
setShowAnswer(false);
|
||||||
|
setTestFinished(true);
|
||||||
|
|
||||||
|
if (savedRecord.invalidated) {
|
||||||
|
message.error(INVALID_CREDENTIAL_MESSAGE);
|
||||||
|
} else {
|
||||||
message.success('测试完成,记录已保存');
|
message.success('测试完成,记录已保存');
|
||||||
|
}
|
||||||
setIsModalVisible(true);
|
setIsModalVisible(true);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof ApiError) {
|
message.error(INVALID_CREDENTIAL_MESSAGE);
|
||||||
message.error(`保存测试记录失败: ${error.message}`);
|
|
||||||
} else {
|
|
||||||
message.error('保存测试记录失败');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 完成测试 - 兼容原来的调用方式
|
// 完成测试 - 兼容原来的调用方式
|
||||||
const finishTest = async () => {
|
const finishTest = async () => {
|
||||||
// 使用当前的测试结果完成测试
|
// 使用当前的测试结果完成测试
|
||||||
await finishTestWithResults([...pendingAnswers], [...testResults]);
|
await finishTestWithResults([...pendingAnswers]);
|
||||||
};
|
};
|
||||||
|
|
||||||
// 重新开始测试
|
// 重新开始测试
|
||||||
@@ -670,9 +775,10 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
setUserAnswer('');
|
setUserAnswer('');
|
||||||
setShowAnswer(false);
|
setShowAnswer(false);
|
||||||
setTestResults([]);
|
setTestResults([]);
|
||||||
setAnswerFeedback(null);
|
|
||||||
setPendingAnswers([]);
|
setPendingAnswers([]);
|
||||||
setOptions([]);
|
setOptions([]);
|
||||||
|
interactionsRef.current = [];
|
||||||
|
questionShownAtRef.current = 0;
|
||||||
answerSubmittingRef.current = false;
|
answerSubmittingRef.current = false;
|
||||||
// 重置统计信息
|
// 重置统计信息
|
||||||
setStudyStats({
|
setStudyStats({
|
||||||
@@ -796,10 +902,16 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
testType === 'multiple-choice' &&
|
testType === 'multiple-choice' &&
|
||||||
testWords.length > 0
|
testWords.length > 0
|
||||||
) {
|
) {
|
||||||
setOptions(testWords[testIndex]?.options || []);
|
setOptions(normalizeOptions(testWords[testIndex]));
|
||||||
}
|
}
|
||||||
}, [testIndex, testType, testStarted, testFinished, testWords]);
|
}, [testIndex, testType, testStarted, testFinished, testWords]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (testStarted && !testFinished && testWords.length > 0) {
|
||||||
|
resetInteractionTrace();
|
||||||
|
}
|
||||||
|
}, [testIndex, testStarted, testFinished, testWords.length]);
|
||||||
|
|
||||||
// 自动播放第一个听力单词
|
// 自动播放第一个听力单词
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (
|
if (
|
||||||
@@ -886,14 +998,14 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
|
|
||||||
<h4>学习单词数量:</h4>
|
<h4>学习单词数量:</h4>
|
||||||
<InputNumber
|
<InputNumber
|
||||||
min={5}
|
min={MIN_STUDY_WORD_COUNT}
|
||||||
max={100}
|
max={MAX_STUDY_WORD_COUNT}
|
||||||
value={wordCount}
|
value={wordCount}
|
||||||
onChange={handleWordCountChange}
|
onChange={handleWordCountChange}
|
||||||
style={{ width: 120 }}
|
style={{ width: 120 }}
|
||||||
/>
|
/>
|
||||||
<span style={{ marginLeft: 10, color: '#888' }}>
|
<span style={{ marginLeft: 10, color: '#888' }}>
|
||||||
(范围: 5-100个单词)
|
(范围: {MIN_STUDY_WORD_COUNT}-{MAX_STUDY_WORD_COUNT}个单词)
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1241,12 +1353,19 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
<Radio.Group
|
<Radio.Group
|
||||||
value={userAnswer}
|
value={userAnswer}
|
||||||
disabled={showAnswer}
|
disabled={showAnswer}
|
||||||
onChange={e => setUserAnswer(e.target.value)}
|
|
||||||
style={{ width: '100%', display: 'flex', flexDirection: 'column' }}
|
style={{ width: '100%', display: 'flex', flexDirection: 'column' }}
|
||||||
>
|
>
|
||||||
{options.map(option => (
|
{options.map(option => (
|
||||||
<Radio key={option} value={option} style={{ marginBottom: 10, height: 'auto', padding: '8px 5px' }}>
|
<Radio
|
||||||
{option}
|
key={option.text}
|
||||||
|
value={option.token || option.text}
|
||||||
|
onClick={() => {
|
||||||
|
recordInteraction({ type: 'click', valueLength: option.text.length });
|
||||||
|
handleMultipleChoiceChange(option);
|
||||||
|
}}
|
||||||
|
style={{ marginBottom: 10, height: 'auto', padding: '8px 5px' }}
|
||||||
|
>
|
||||||
|
{option.text}
|
||||||
</Radio>
|
</Radio>
|
||||||
))}
|
))}
|
||||||
</Radio.Group>
|
</Radio.Group>
|
||||||
@@ -1255,40 +1374,77 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
placeholder="请输入英文单词"
|
placeholder="请输入英文单词"
|
||||||
value={userAnswer}
|
value={userAnswer}
|
||||||
onChange={e => setUserAnswer(e.target.value)}
|
onChange={e => {
|
||||||
|
recordInteraction({
|
||||||
|
type: 'input',
|
||||||
|
inputType: (e.nativeEvent as NativeInputLikeEvent)?.inputType,
|
||||||
|
value: e.target.value,
|
||||||
|
valueLength: e.target.value.length
|
||||||
|
});
|
||||||
|
setUserAnswer(e.target.value);
|
||||||
|
moveTestInputCaretToEnd();
|
||||||
|
}}
|
||||||
|
onKeyDown={e => {
|
||||||
|
recordInteraction({
|
||||||
|
type: 'keydown',
|
||||||
|
key: e.key,
|
||||||
|
value: userAnswer,
|
||||||
|
valueLength: userAnswer.length,
|
||||||
|
ctrlKey: e.ctrlKey,
|
||||||
|
metaKey: e.metaKey,
|
||||||
|
altKey: e.altKey
|
||||||
|
});
|
||||||
|
if (shouldBlockInputKey(e)) {
|
||||||
|
e.preventDefault();
|
||||||
|
moveTestInputCaretToEnd();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onFocus={() => {
|
||||||
|
recordInteraction({ type: 'focus', valueLength: userAnswer.length });
|
||||||
|
moveTestInputCaretToEnd();
|
||||||
|
}}
|
||||||
|
onBlur={() => recordInteraction({ type: 'blur', valueLength: userAnswer.length })}
|
||||||
|
onMouseDown={e => {
|
||||||
|
e.preventDefault();
|
||||||
|
focusTestInputAtEnd();
|
||||||
|
}}
|
||||||
|
onMouseUp={moveTestInputCaretToEnd}
|
||||||
|
onSelect={moveTestInputCaretToEnd}
|
||||||
|
onKeyUp={moveTestInputCaretToEnd}
|
||||||
|
onContextMenu={e => e.preventDefault()}
|
||||||
|
onCut={e => e.preventDefault()}
|
||||||
|
onDrop={e => e.preventDefault()}
|
||||||
disabled={showAnswer}
|
disabled={showAnswer}
|
||||||
style={{ marginBottom: 15 }}
|
style={{ marginBottom: 15, userSelect: 'none', WebkitUserSelect: 'none' }}
|
||||||
onPressEnter={e => {
|
onPressEnter={e => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
|
if (!userAnswer.trim() || showAnswer) return;
|
||||||
submitAnswer();
|
submitAnswer();
|
||||||
}}
|
}}
|
||||||
autoFocus
|
autoFocus
|
||||||
size="large"
|
size="large"
|
||||||
onPaste={e => e.preventDefault()}
|
onPaste={e => {
|
||||||
|
recordInteraction({ type: 'paste', value: userAnswer, valueLength: userAnswer.length });
|
||||||
|
e.preventDefault();
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{showAnswer && (
|
{showAnswer && (
|
||||||
<div style={{
|
<div style={{
|
||||||
padding: 15,
|
padding: 15,
|
||||||
backgroundColor: answerFeedback?.isCorrect ? '#f6ffed' : '#fff2f0',
|
backgroundColor: '#f6f8fa',
|
||||||
borderRadius: 4,
|
borderRadius: 4,
|
||||||
marginBottom: 15,
|
marginBottom: 15,
|
||||||
border: `1px solid ${answerFeedback?.isCorrect ? '#b7eb8f' : '#ffccc7'}`
|
border: '1px solid #d9d9d9'
|
||||||
}}>
|
}}>
|
||||||
<div style={{
|
<div style={{
|
||||||
fontWeight: 'bold',
|
fontWeight: 'bold',
|
||||||
color: answerFeedback?.isCorrect ? '#389e0d' : '#cf1322',
|
color: '#1677ff',
|
||||||
marginBottom: 5
|
marginBottom: 5
|
||||||
}}>
|
}}>
|
||||||
{answerFeedback?.isCorrect ? '回答正确' : '回答错误'}
|
本题已提交
|
||||||
</div>
|
</div>
|
||||||
{answerFeedback && (
|
|
||||||
<>
|
|
||||||
<div>正确答案: {answerFeedback.correctAnswer}</div>
|
|
||||||
<div>你的答案: {answerFeedback.userAnswer || '(空)'}</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<div>正在进入下一题...</div>
|
<div>正在进入下一题...</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -1296,7 +1452,7 @@ const VocabularyStudy: React.FC = () => {
|
|||||||
<Button
|
<Button
|
||||||
type="primary"
|
type="primary"
|
||||||
onClick={submitAnswer}
|
onClick={submitAnswer}
|
||||||
disabled={!userAnswer || showAnswer}
|
disabled={!userAnswer.trim() || showAnswer}
|
||||||
style={{ width: '100%' }}
|
style={{ width: '100%' }}
|
||||||
>
|
>
|
||||||
提交答案
|
提交答案
|
||||||
|
|||||||
@@ -49,6 +49,8 @@ export const API_PATHS = {
|
|||||||
STUDY_WORDS: '/vocabulary/study-words',
|
STUDY_WORDS: '/vocabulary/study-words',
|
||||||
UPLOAD: '/vocabulary/upload',
|
UPLOAD: '/vocabulary/upload',
|
||||||
TEST_ATTEMPT: '/vocabulary/test-attempt',
|
TEST_ATTEMPT: '/vocabulary/test-attempt',
|
||||||
|
TEST_ANSWER: '/vocabulary/test-answer',
|
||||||
|
TEST_OPTION_TOKEN: '/vocabulary/test-option-token',
|
||||||
WORD_RECORD: '/vocabulary/word-record',
|
WORD_RECORD: '/vocabulary/word-record',
|
||||||
TEST_RECORD: '/vocabulary/test-record',
|
TEST_RECORD: '/vocabulary/test-record',
|
||||||
STUDY_RECORDS: '/vocabulary/test-records',
|
STUDY_RECORDS: '/vocabulary/test-records',
|
||||||
|
|||||||
Reference in New Issue
Block a user