北斗导航定位通信综合实践赛服务系统

This commit is contained in:
2026-03-27 17:50:54 +08:00
commit f1d7b4895c
44 changed files with 1810 additions and 0 deletions

63
app/controller/Bind.js Normal file
View File

@@ -0,0 +1,63 @@
const Controller = require('../core/base_controller');
const fileName = "Bind";
class BindController extends Controller {
// 绑定北斗卡
async bindCard() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const { card_id, card_imsi } = ctx.request.body;
const result = await ctx.service.bind.bindCard(uid, card_id, card_imsi);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
this.setResponse(ctx, 200, '操作成功', "deconstruction", result);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "bindCard";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
// 解绑北斗卡
async unBindCard() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const { card_id, card_imsi } = ctx.request.body;
const result = await ctx.service.bind.unBindCard(uid, card_id, card_imsi);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
this.setResponse(ctx, 200, '操作成功', "deconstruction", result);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "unBindCard";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
}
module.exports = BindController;

64
app/controller/Check.js Normal file
View File

@@ -0,0 +1,64 @@
const Controller = require('../core/base_controller');
const fileName = "Check";
class CheckController extends Controller {
// 检查竞赛账号是否已经绑定北斗卡
async checkUser() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const result = await ctx.service.check.checkUser(uid);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
const data = {
card_id: result.dataValues.card_id,
};
this.setResponse(ctx, 200, '操作成功', "deconstruction", data);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "checkUser";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
// 检查北斗卡是否已经被绑定
async checkBind() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const { card_id } = ctx.request.body;
const result = await ctx.service.check.checkBind(card_id);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
this.setResponse(ctx, 200, '操作成功', "none");
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "checkBind";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
}
module.exports = CheckController;

67
app/controller/Contest.js Normal file
View File

@@ -0,0 +1,67 @@
const Controller = require('../core/base_controller');
const fileName = "Contest";
class ContestController extends Controller {
// 系统获取竞赛基本信息
async contestMsg() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const result = await ctx.service.contest.contestMsg(uid);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
const data = {
contestMsg: result.dataValues
}
this.setResponse(ctx, 200, '操作成功', "deconstruction", data);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "contestMsg";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
// 系统获取排名信息
async ranking() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const result = await ctx.service.contest.ranking(uid);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
const data = {
rankList: result
}
this.setResponse(ctx, 200, '操作成功', "deconstruction", data);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "ranking";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
}
module.exports = ContestController;

133
app/controller/Exam.js Normal file
View File

@@ -0,0 +1,133 @@
const Controller = require('../core/base_controller');
const fileName = "Exam";
class ExamController extends Controller {
// 学生获取历史消息
async getHistoryMsg() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const body = ctx.request.body;
const result = await ctx.service.exam.getHistoryMsg(uid, body);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
let historyMsg = [];
result.rows.forEach(element => {
historyMsg.push(element.dataValues);
});
const data = {
historyMsg: historyMsg,
count: result.count
};
this.setResponse(ctx, 200, '操作成功', "deconstruction", data);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "getHistoryMsg";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
// 学生删除历史消息
async delHistoryMsg() {
const ctx = this.ctx;
try {
let rdmcode = await checkUid(ctx);
if (!rdmcode) {
setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const body = ctx.request.body;
const model = decryptRequest(body.model);
const password = decryptRequest(body.password);
const requestMsg = body.userMsg;
const resetList = await ctx.service.exam.delHistoryMsg(uid, model, password, requestMsg);
if (resetList == "error") {
setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (resetList) {
setResponse(ctx, 200, '删除历史消息成功', "none");
} else {
setResponse(ctx, 404, '删除历史消息失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "delHistoryMsg";
ctx.app.middleware.utils.log('../../../controllerLog', blockName + ">>>>" + error);
setResponse(ctx, 500, '服务器错误', "none");
}
}
// 学生完成答题
async answer() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const body = ctx.request.body;
const result = await ctx.service.exam.answer(uid, body);
// await ctx.service.bind.unBindCard(uid);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
this.setResponse(ctx, 200, '操作成功', "none");
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "answer";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
// 学生查看成绩信息
async grades() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const result = await ctx.service.exam.grades(uid);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
const data = {
grades: result.dataValues
};
this.setResponse(ctx, 200, '操作成功', "deconstruction", data);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "grades";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
}
module.exports = ExamController;

74
app/controller/Topic.js Normal file
View File

@@ -0,0 +1,74 @@
const Controller = require('../core/base_controller');
const fileName = "Topic";
class TopicController extends Controller {
// 学生抽取/读取题目
async topic() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const uid = JSON.parse(rdmcode).uid;
const bind = await ctx.service.check.checkUser(uid);
if (!bind) {
this.setResponse(ctx, 333, '未绑定北斗卡', "none");
return;
}
const { answerId } = ctx.request.body;
const result = await ctx.service.topic.topic(uid, answerId);
if (bind == "error" || result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result.code == 200) {
const data = {
examination: result.examination,
shortMsg: result.shortMsg,
};
this.setResponse(ctx, 200, '操作成功', "deconstruction", data);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "topic";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
// 系统读取单选题
async radio() {
const { ctx } = this;
try {
let rdmcode = await this.checkUid(ctx);
if (!rdmcode) {
this.setResponse(ctx, 401, 'token过期或错误', "none");
return;
}
const { radioArr } = ctx.request.body;
const result = await ctx.service.topic.radio(radioArr);
if (result == "error") {
this.setResponse(ctx, 500, '服务器错误', "none");
return;
}
if (result) {
const data = {
radioTopic: result,
}
this.setResponse(ctx, 200, '操作成功', "deconstruction", data);
} else {
this.setResponse(ctx, 404, '操作失败', "none");
}
} catch (error) {
const blockName = fileName + "--" + "radio";
ctx.app.middleware.log('../../controllerLog', blockName + ">>>>" + error);
this.setResponse(ctx, 500, '服务器错误', "none");
}
}
}
module.exports = TopicController;

133
app/core/base_controller.js Normal file
View File

@@ -0,0 +1,133 @@
const { Controller } = require('egg');
const sha256 = require("crypto-js/sha256");
const CryptoJS = require("crypto-js");
const KEY = CryptoJS.enc.Utf8.parse('BDQH');
class BaseController extends Controller {
shaForm = (body, salt) => {
return sha256(sha256(body).toString() + salt).toString();
}
encryptRequest = (body) => {
return CryptoJS.AES.encrypt(body, KEY, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
}
decryptRequest = (body) => {
return CryptoJS.AES.decrypt(body, KEY, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8);
}
// 用户uid生成函数
generateNumberString = (side) => {
// 获取当前日期(年月日)
const now = new Date();
const year = String(now.getFullYear()).padStart(4, '0');
const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以加1
const date = String(now.getDate()).padStart(2, '0');
const dateString = year + month + date;
// 获取当前时间戳的后三位
const timestamp = String(Date.now()).slice(-3);
// 生成三位随机数字
const randomDigits = Math.floor(Math.random() * 100).toString().padStart(3, '0');
// 组合成最终的15位字符串
const fullNumberString = dateString + timestamp + randomDigits + side;
return fullNumberString;
}
// 随机盐生成函数
generateRandomString = () => {
const lowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz';
const upperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numbers = '0123456789';
let result = '';
// 生成5位随机小写字母
for (let i = 0; i < 5; i++) {
const randomIndex = Math.floor(Math.random() * lowerCaseLetters.length);
result += lowerCaseLetters[randomIndex];
}
// 生成5位随机大写字母
for (let i = 0; i < 5; i++) {
const randomIndex = Math.floor(Math.random() * upperCaseLetters.length);
result += upperCaseLetters[randomIndex];
}
// 生成2位随机数字
for (let i = 0; i < 2; i++) {
const randomIndex = Math.floor(Math.random() * numbers.length);
result += numbers[randomIndex];
}
// 打乱整个字符串
const characters = result.split('');
for (let i = characters.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[characters[i], characters[j]] = [characters[j], characters[i]];
}
return characters.join('');
}
// 随机生成12位客户端id
generateClientId = () => {
const numbers = '0123456789';
let result = '';
// 生成4位随机数字
for (let i = 0; i < 4; i++) {
const randomIndex = Math.floor(Math.random() * numbers.length);
result += numbers[randomIndex];
}
// 打乱整个字符串
const characters = result.split('');
for (let i = characters.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[characters[i], characters[j]] = [characters[j], characters[i]];
}
// 获取当前日期(年月日)
const now = new Date();
const year = String(now.getFullYear()).padStart(4, '0');
const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以加1
const date = String(now.getDate()).padStart(2, '0');
const dateString = year + month + date;
const fullNumberString = dateString + characters.join('');
return fullNumberString;
}
checkUid = async (ctx) => {
const token = ctx.request.header.authorization;
const redis = ctx.app.redis;
const contest = await redis.get('db5').get(token);
return contest ? contest : false;
};
setResponse = (ctx, code, msg, model, data = {}) => {
const modelType = {
"none": { code, msg },
"deconstruction": { code, msg, ...data },
"polymerization": { code, msg, data }
}
ctx.body = modelType[model];
}
}
module.exports = BaseController;

112
app/core/base_service.js Normal file
View File

@@ -0,0 +1,112 @@
const { Service } = require('egg');
const { Op } = require('sequelize');
const sha256 = require("crypto-js/sha256");
const CryptoJS = require("crypto-js");
const KEY = CryptoJS.enc.Utf8.parse('BDQH');
class BaseService extends Service {
shaForm = (body, salt) => {
return sha256(sha256(body).toString() + salt).toString();
}
encryptRequest = (body) => {
return CryptoJS.AES.encrypt(body, KEY, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
}
decryptRequest = (body) => {
return CryptoJS.AES.decrypt(body, KEY, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8);
}
// uid生成函数
generateNumberString = () => {
// 获取当前日期(年月日)
const now = new Date();
const year = String(now.getFullYear()).padStart(4, '0');
const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,所以加1
const date = String(now.getDate()).padStart(2, '0');
const dateString = year + month + date;
// 获取当前时间戳的后四位
const timestamp = String(Date.now()).slice(-4);
// 生成四位随机数字
const randomDigits = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
// 组合成最终的16位数字字符串
const fullNumberString = dateString + timestamp + randomDigits;
return fullNumberString;
}
// 随机盐生成函数
generateRandomString = () => {
const lowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz';
const upperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numbers = '0123456789';
let result = '';
// 生成5位随机小写字母
for (let i = 0; i < 5; i++) {
const randomIndex = Math.floor(Math.random() * lowerCaseLetters.length);
result += lowerCaseLetters[randomIndex];
}
// 生成5位随机大写字母
for (let i = 0; i < 5; i++) {
const randomIndex = Math.floor(Math.random() * upperCaseLetters.length);
result += upperCaseLetters[randomIndex];
}
// 生成2位随机数字
for (let i = 0; i < 2; i++) {
const randomIndex = Math.floor(Math.random() * numbers.length);
result += numbers[randomIndex];
}
// 打乱整个字符串
const characters = result.split('');
for (let i = characters.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[characters[i], characters[j]] = [characters[j], characters[i]];
}
return characters.join('');
}
// 全角字符转半角字符
toHalfWidth = (str) => {
// 全角字符到半角字符的映射表
const fullWidthToHalfWidthMap = {
'!': '!', '"': '"', '#': '#', '$': '$', '%': '%', '&': '&', ''': "'",
'(': '(', ')': ')', '*': '*', '+': '+', ',': ',', '-': '-', '.': '.',
'/': '/', ':': ':', ';': ';', '<': '<', '=': '=', '>': '>', '?': '?',
'@': '@', 'A': 'A', 'B': 'B', 'C': 'C', 'D': 'D', 'E': 'E', 'F': 'F',
'G': 'G', 'H': 'H', 'I': 'I', 'J': 'J', 'K': 'K', 'L': 'L', 'M': 'M',
'N': 'N', 'O': 'O', 'P': 'P', 'Q': 'Q', 'R': 'R', 'S': 'S', 'T': 'T',
'U': 'U', 'V': 'V', 'W': 'W', 'X': 'X', 'Y': 'Y', 'Z': 'Z', '[': '[',
'\': '\\', ']': ']', '^': '^', '_': '_', '`': '`', 'a': 'a', 'b': 'b',
'c': 'c', 'd': 'd', 'e': 'e', 'f': 'f', 'g': 'g', 'h': 'h', 'i': 'i',
'j': 'j', 'k': 'k', 'l': 'l', 'm': 'm', 'n': 'n', 'o': 'o', 'p': 'p',
'q': 'q', 'r': 'r', 's': 's', 't': 't', 'u': 'u', 'v': 'v', 'w': 'w',
'x': 'x', 'y': 'y', 'z': 'z', '{': '{', '|': '|', '}': '}', '~': '~',
'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6',
'7': '7', '8': '8', '9': '9', ' ': ' ' // 全角空格到半角空格的映射
};
// 遍历输入字符串,将全角字符替换为半角字符
return str.split('').map(char => fullWidthToHalfWidthMap[char] || char).join('');
}
}
module.exports = BaseService;

72
app/middleware/log.js Normal file
View File

@@ -0,0 +1,72 @@
// 错误日志
const fs = require('fs');
const os = require('os');
const path = require('path');
const dirCheck = (dirPath) => {
// 检查文件夹是否存在
fs.access(dirPath, fs.constants.F_OK, (err) => {
if (err) {
// 文件夹不存在
console.log('文件夹不存在,正在创建...');
fs.mkdir(dirPath, { recursive: true }, (err) => {
if (err) throw err;
console.log('文件夹已创建');
});
} else {
// 文件夹存在
console.log('文件夹已存在');
}
});
}
module.exports = (filePath, msg) => {
// 获取时间
let now = new Date(),
times = {
year: now.getFullYear(),
month: now.getMonth() + 1,
day: now.getDate(),
hour: now.getHours(),
minute: now.getMinutes(),
second: now.getSeconds()
};
// 获取操作系统类型
const type = os.type();
console.log(`操作系统类型: ${type}`);
filePath = path.join(__dirname, filePath);
dirCheck(filePath);
const yearPath = filePath + '/' + times.year;
dirCheck(yearPath);
const monthPath = yearPath + '/' + times.month;
dirCheck(monthPath);
const dayPath = monthPath + '/' + times.day + '.txt';
const logTime = '[' + times.year + '-' + times.month + '-' + times.day + '>>>' + times.hour + ':' + times.minute + ':' + times.second + ']' + '>>>';
let crlf;
// 判断操作系统类型,设置换行符
if (type === 'Windows_NT') {
crlf = '\n';
} else {
crlf = '\r\n';
}
// 读取文件内容
fs.readFile(dayPath, 'utf8', (err, data) => {
if (err) {
if (err.code === 'ENOENT') {
// 文件不存在,直接写入新内容(这里实际上还是使用了覆盖的方式)
fs.writeFile(dayPath, logTime + msg + crlf, (err) => {
if (err) throw err;
console.log('文件已创建并写入新内容');
});
} else {
throw err;
}
} else {
// 文件存在,追加新内容
fs.appendFile(dayPath, logTime + msg + crlf, (err) => {
if (err) throw err;
console.log('新内容已追加到文件');
});
}
});
};

22
app/model3/BDCard.js Normal file
View File

@@ -0,0 +1,22 @@
'use strict';
module.exports = (app) => {
const { INTEGER, CHAR, DATE } = app.Sequelize;
const BDCard = app.model3.define('bd-card', {
id: { type: INTEGER(8), primaryKey: true, autoIncrement: true },
card_id: CHAR(8),
card_imsi: CHAR(18),
type: INTEGER(3),
status: INTEGER(3),
created_at: DATE,
updated_at: DATE,
},{
freezeTableName: true,
timestamp: true,
createdAt: true,
updatedAt: true,
});
return BDCard;
};

24
app/model4/Account.js Normal file
View File

@@ -0,0 +1,24 @@
'use strict';
module.exports = (app) => {
const { INTEGER, CHAR, STRING, DATE } = app.Sequelize;
const Account = app.model4.define('account', {
id: { type: INTEGER(8), primaryKey: true, autoIncrement: true },
uid: CHAR(15),
salt: CHAR(24),
contest_uid: CHAR(15),
account_name: STRING(20),
password: CHAR(64),
status: INTEGER(3),
created_at: DATE,
login_status: INTEGER(3),
},{
freezeTableName: true,
timestamp: true,
createdAt: true,
updatedAt: false,
});
return Account;
};

22
app/model4/ChoiceTopic.js Normal file
View File

@@ -0,0 +1,22 @@
'use strict';
module.exports = (app) => {
const { INTEGER, CHAR, STRING } = app.Sequelize;
const ChoiceTopic = app.model4.define('choice-topic', {
id: { type: INTEGER(5), primaryKey: true, autoIncrement: true },
topic: STRING(300),
options_a: STRING(300),
options_b: STRING(300),
options_c: STRING(300),
options_d: STRING(300),
answer: CHAR(1),
},{
freezeTableName: true,
timestamp: false,
createdAt: false,
updatedAt: false,
});
return ChoiceTopic;
};

29
app/model4/Contest.js Normal file
View File

@@ -0,0 +1,29 @@
'use strict';
module.exports = (app) => {
const { INTEGER, CHAR, STRING, DATE } = app.Sequelize;
const Contest = app.model4.define('contest', {
id: { type: INTEGER(8), primaryKey: true, autoIncrement: true },
uid: CHAR(15),
contest_name: STRING(50),
contest_organizers: STRING(50),
contest_term: STRING(5),
type: INTEGER(3),
status: INTEGER(3),
online_start: DATE,
online_end: DATE,
offline_start: DATE,
offline_end: DATE,
contest_start: DATE,
contest_end: DATE,
created_at: DATE,
},{
freezeTableName: true,
timestamp: true,
createdAt: true,
updatedAt: false,
});
return Contest;
};

34
app/model4/Examination.js Normal file
View File

@@ -0,0 +1,34 @@
'use strict';
module.exports = (app) => {
const { INTEGER, CHAR, STRING, DATE } = app.Sequelize;
const Examination = app.model4.define('examination', {
id: { type: INTEGER(8), primaryKey: true, autoIncrement: true },
user_uid: CHAR(15),
contest_uid: CHAR(15),
exam_type: INTEGER(3),
topic_type: INTEGER(3),
topic1: STRING(2),
topic2: STRING(2),
topic3: STRING(50),
topic5: STRING(10),
answer: STRING(20),
answer1: STRING(2),
answer2: STRING(2),
answer3: STRING(10),
answer4: STRING(20),
answer5: STRING(10),
score: INTEGER(3),
score_collection: CHAR(9),
created_at: DATE,
updated_at: DATE,
},{
freezeTableName: true,
timestamp: true,
createdAt: true,
updatedAt: true,
});
return Examination;
};

24
app/model4/TShortMsg.js Normal file
View File

@@ -0,0 +1,24 @@
'use strict';
module.exports = (app) => {
const { INTEGER, CHAR, TEXT, DATE } = app.Sequelize;
const TShortMsg = app.model4.define('tshort-msg', {
id: { type: INTEGER(8), primaryKey: true, autoIncrement: true },
user_uid: CHAR(15),
card_id: CHAR(8),
receiver_address: CHAR(8),
original_msg: TEXT,
send_type: INTEGER(1),
encode_type: INTEGER(1),
msg_data: TEXT,
created_at: DATE,
},{
freezeTableName: true,
timestamp: true,
createdAt: true,
updatedAt: false,
});
return TShortMsg;
};

18
app/model4/TuserBind.js Normal file
View File

@@ -0,0 +1,18 @@
'use strict';
module.exports = (app) => {
const { INTEGER, CHAR } = app.Sequelize;
const TuserBind = app.model4.define('tuser-bind', {
id: { type: INTEGER(8), primaryKey: true, autoIncrement: true },
card_id: CHAR(8),
user_uid: CHAR(15),
},{
freezeTableName: true,
timestamp: false,
createdAt: false,
updatedAt: false,
});
return TuserBind;
};

31
app/router.js Normal file
View File

@@ -0,0 +1,31 @@
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
// 系统获取竞赛基本信息
router.post("/contestMsg", controller.contest.contestMsg);
// 系统获取排名信息
router.post("/ranking", controller.contest.ranking);
// 检查竞赛账号是否已经绑定北斗卡
router.post("/checkUser", controller.check.checkUser);
// 检查北斗卡是否已经被绑定
router.post("/checkBind", controller.check.checkBind);
// 绑定北斗卡
router.post("/bindCard", controller.bind.bindCard);
// 解绑北斗卡
router.post("/unBindCard", controller.bind.unBindCard);
// 学生抽取/读取题目
router.post("/topic", controller.topic.topic);
// 系统读取单选题
router.post("/radio", controller.topic.radio);
// 学生获取历史消息
router.post("/getHistoryMsg", controller.exam.getHistoryMsg);
// 学生删除历史消息
router.post('/delHistoryMsg', controller.exam.delHistoryMsg);
// 学生完成答题
router.post("/answer", controller.exam.answer);
// 学生查看成绩信息
router.post("/grades", controller.exam.grades);
};

41
app/service/Bind.js Normal file
View File

@@ -0,0 +1,41 @@
'use strict';
const Service = require('../core/base_service');
const { Op } = require('sequelize');
const fileName = "Bind";
class BindService extends Service {
// 竞赛账号绑定北斗卡
async bindCard(uid, card_id, card_imsi) {
const { ctx } = this;
try {
const card = await ctx.model3.BDCard.update({ status: 3 }, { where: { card_id, card_imsi, status: 0 } });
if (card[0] == 0) return false;
const result = await ctx.model4.TuserBind.create({ user_uid: uid, card_id });
return result ? true : false;
} catch (error) {
const blockName = fileName + "--" + "bindCard";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
// 竞赛账号解绑北斗卡
async unBindCard(uid, card_id, card_imsi) {
const { ctx } = this;
try {
const card = await ctx.model3.BDCard.update({ status: 0 }, { where: { card_id, card_imsi, status: 3 } });
if (card[0] == 0) return false;
const result = await ctx.model4.TuserBind.destroy({ where: { user_uid: uid } });
return result.length == 0 ? false : true;
} catch (error) {
const blockName = fileName + "--" + "unBindCard";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
}
module.exports = BindService;

37
app/service/Check.js Normal file
View File

@@ -0,0 +1,37 @@
'use strict';
const Service = require('../core/base_service');
const { Op } = require('sequelize');
const fileName = "Check";
class CheckService extends Service {
// 检查竞赛账号是否已经绑定北斗卡
async checkUser(uid) {
const { ctx } = this;
try {
const result = await ctx.model4.TuserBind.findOne({ where: { user_uid: uid } });
return result || false;
} catch (error) {
const blockName = fileName + "--" + "checkUser";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
// 检查北斗卡是否已经被绑定
async checkBind(card_id) {
const { ctx } = this;
try {
const result = await ctx.model3.BDCard.findOne({ where: { card_id, status: 0 } });
return result || false;
} catch (error) {
const blockName = fileName + "--" + "checkBind";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
}
module.exports = CheckService;

75
app/service/Contest.js Normal file
View File

@@ -0,0 +1,75 @@
'use strict';
const Service = require('../core/base_service');
const { Op } = require('sequelize');
const fileName = "Contest";
class ContestService extends Service {
// 系统获取竞赛基本信息
async contestMsg(uid) {
const { ctx } = this;
try {
const user = await ctx.model4.Account.findOne({ attributes: ['contest_uid'], where: { uid } });
if (!user) return false;
const result = await ctx.model4.Contest.findOne({ where: { uid: user.dataValues.contest_uid }, order: [['created_at', 'DESC']] });
console.log(result)
return result || false;
} catch (error) {
const blockName = fileName + "--" + "contestMsg";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
// 系统获取排名信息
async ranking(uid) {
const { ctx } = this;
try {
// 按得分降序排序,得分相同时按创建时间降序排序
let include = [
{
model: ctx.model4.Account,
attributes: ['account_name'],
}
];
ctx.model4.Examination.belongsTo(ctx.model4.Account, { foreignKey: 'user_uid', targetKey: 'uid' });
const result = await ctx.model4.Examination.findAll({
attributes: ['score', 'created_at', 'updated_at'],
where: { updated_at: { [Op.ne]: null } },
// 先按得分降序排序
order: [['score', 'DESC'],],
limit: 100,
include,
});
if (result.length == 0) return false;
// 使用 Set 获取不同得分值
const uniqueScore = new Set(result.map(item => item.dataValues.score));
// 将 Set 转换为数组
const uniqueScoreArr = Array.from(uniqueScore);
// 对数组进行降序排序
uniqueScoreArr.sort((a, b) => b - a);
let allScoreArr = [];
uniqueScoreArr.forEach(score => {
let sameScoreArr = [];
result.forEach(item => {
if (item.dataValues.score == score) {
sameScoreArr.push(item);
item.timeDifference = item.dataValues.updated_at - item.dataValues.created_at;
}
});
// 按创建时间降序排序
sameScoreArr.sort((a, b) => b.timeDifference - a.timeDifference);
allScoreArr.push(...sameScoreArr);
});
return allScoreArr;
} catch (error) {
const blockName = fileName + "--" + "ranking";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
}
module.exports = ContestService;

243
app/service/Exam.js Normal file
View File

@@ -0,0 +1,243 @@
'use strict';
const Service = require('../core/base_service');
const { Op } = require('sequelize');
const fileName = "Exam";
class ExamService extends Service {
// 学生获取历史消息
async getHistoryMsg(uid, body) {
const { ctx } = this;
try {
let { offset, limit, searchOptions, sortOptions } = body;
offset = (offset - 1) * limit;
let attributes = ['id', 'card_id', 'encode_type', 'msg_data', 'created_at'],
where = { user_uid: uid }, order = [], dbOptions, joinSubstring = [],
substring = ['card_id', 'msg_data'], key = ['encode_type'], between = ['created_at'];
attributes.forEach(element => {
if (searchOptions[element]) {
if (searchOptions[element] == '*空') {
if (joinSubstring.includes(element)) {
where[element] = null;
} else {
where[element] = [null, ''];
}
} else if (substring.includes(element)) {
where[element] = { [Op.substring]: searchOptions[element] };
} else if (key.includes(element)) {
where[element] = searchOptions[element] == "1" ? true : false;
} else if (between.includes(element)) {
where[element] = { [Op.between]: [searchOptions[element][0], searchOptions[element][1]] };
}
}
if (sortOptions[element] == true) {
order.push([element, 'ASC']);
} else if (sortOptions[element] == false) {
order.push([element, 'DESC']);
}
});
dbOptions = { attributes, offset, limit, where, order };
const result = await ctx.model4.TShortMsg.findAndCountAll(dbOptions);
return result.rows.length == 0 ? false : result;
} catch (error) {
const blockName = fileName + "--" + "getHistoryMsg";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
// 学生删除历史消息
async delHistoryMsg(uid, modelType, password, requestMsg) {
const { ctx } = this;
try {
const result = await ctx.model4.Account.findOne({ where: { uid } });
if (!result || result.dataValues.password !== this.shaForm(password, this.decryptRequest(result.dataValues.salt))) return false;
let where = {};
if (modelType == "single") {
const { card_id, encode_type, msg_data, origin_time } = requestMsg;
where = { user_uid: uid, card_id, encode_type, msg_data, created_at: origin_time };
} else if (modelType == "multiple") {
let card_id = [], encode_type = [], msg_data = [], created_at = [];
for (const key in requestMsg) {
requestMsg[key].forEach(element => {
card_id.push(element.card_id),
encode_type.push(element.encode_type),
msg_data.push(element.msg_data),
created_at.push(element.origin_time)
});
}
where = { user_uid: uid, card_id, encode_type, msg_data, created_at };
} else if (modelType == "all") {
where = { user_uid: uid };
}
const resetList = await ctx.model4.TShortMsg.destroy({ where });
return resetList.length == 0 ? false : resetList;
} catch (error) {
const blockName = fileName + "--" + "delHistoryMsg";
ctx.app.middleware.utils.log('../../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
// 学生完成答题
async answer(uid, body) {
const { ctx } = this;
try {
// 根据 updated_at 来判断是否已经完成过答题,确保只能提交一次答题,如果已经完成答题则不允许再次提交答案
const userExam = await ctx.model4.Examination.findOne({ attributes: ['topic1', 'topic2', 'topic3', 'topic5'], where: { user_uid: uid, updated_at: null } });
if (!userExam) return false;
// 根据答案进行评分
const shortMsg = await ctx.model4.TShortMsg.findAll({ attributes: ['id', 'msg_data'], where: { user_uid: uid } });
if (shortMsg.length == 0) return false;
const { answer1, answer2, answer3, answer4, answer5 } = body;
const answerObj = {};
const answerArr = [answer1, answer2, answer3, answer4, answer5];
shortMsg.forEach(element => {
if (element.dataValues.id == answer1) {
if (element.dataValues.msg_data.length > 2) {
answerObj.answer1 = element.dataValues.msg_data.slice(0, 2);
} else {
answerObj.answer1 = element.dataValues.msg_data;
}
}
if (element.dataValues.id == answer2) {
if (element.dataValues.msg_data.length > 2) {
answerObj.answer2 = element.dataValues.msg_data.slice(0, 2);
} else {
answerObj.answer2 = element.dataValues.msg_data;
}
}
if (element.dataValues.id == answer3) {
if (element.dataValues.msg_data.length > 10) {
answerObj.answer3 = element.dataValues.msg_data.slice(0, 10);
} else {
answerObj.answer3 = element.dataValues.msg_data;
}
}
if (element.dataValues.id == answer4) {
if (element.dataValues.msg_data.length > 20) {
answerObj.answer4 = element.dataValues.msg_data.slice(0, 20);
} else {
answerObj.answer4 = element.dataValues.msg_data;
}
}
if (element.dataValues.id == answer5) {
if (element.dataValues.msg_data.length > 10) {
answerObj.answer5 = element.dataValues.msg_data.slice(0, 10);
} else {
answerObj.answer5 = element.dataValues.msg_data;
}
}
});
let score = 0;
let scoreCollection = [];
if (this.toHalfWidth(answerObj.answer1) == userExam.dataValues.topic1) {
score = score + 1;
scoreCollection.push(1);
} else {
scoreCollection.push(0);
}
if (this.toHalfWidth(answerObj.answer2) == userExam.dataValues.topic2) {
score = score + 1;
scoreCollection.push(1);
} else{
scoreCollection.push(0);
}
let topic3Arr = userExam.dataValues.topic3.split(",");
const radioAnswer = await ctx.model4.ChoiceTopic.findAll({ attributes: ['id', 'answer'], where: { id: topic3Arr } });
if (radioAnswer.length == 0) return false;
let answer3Str = "";
const radioAnswerObj = {};
radioAnswer.forEach(item => {
radioAnswerObj[item.dataValues.id] = item.dataValues.answer;
});
topic3Arr.forEach(element => {
answer3Str = answer3Str + radioAnswerObj[element];
});
if (this.toHalfWidth(answerObj.answer3) == answer3Str) {
score = score + 3;
scoreCollection.push(1);
} else {
scoreCollection.push(0);
}
if (this.toHalfWidth(answerObj.answer4).length == 17) {
const longitude = parseFloat(this.toHalfWidth(answerObj.answer4).slice(0, 3) + "." + this.toHalfWidth(answerObj.answer4).slice(3, 9));
const latitude = parseFloat(this.toHalfWidth(answerObj.answer4).slice(9, 11) + "." + this.toHalfWidth(answerObj.answer4).slice(11));
if (-180 <= longitude && longitude <= 180 && -90 <= latitude && latitude <= 90) {
score = score + 3;
scoreCollection.push(1);
} else {
scoreCollection.push(0);
}
}
if (this.toHalfWidth(answerObj.answer5) == userExam.dataValues.topic5) {
score = score + 2;
scoreCollection.push(1);
} else {
scoreCollection.push(0);
}
const updateMsg = {
answer: answerArr.join(","),
answer1: answerObj.answer1,
answer2: answerObj.answer2,
answer3: answerObj.answer3,
answer4: answerObj.answer4,
answer5: answerObj.answer5,
score,
score_collection: scoreCollection.join(","),
updated_at: new Date(),
};
const result = await ctx.model4.Examination.update(updateMsg, { where: { user_uid: uid, updated_at: null } });
return !result[0] == 0;
} catch (error) {
const blockName = fileName + "--" + "answer";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
// 学生查看成绩信息
async grades(uid) {
const { ctx } = this;
try {
let include = [{
model: ctx.model4.Account,
attributes: ['account_name'],
}];
ctx.model4.Examination.belongsTo(ctx.model4.Account, { foreignKey: 'user_uid', targetKey: 'uid' });
const userExam = await ctx.model4.Examination.findOne({
attributes: ['score', 'score_collection', 'created_at', 'updated_at'],
where: { user_uid: uid, updated_at: { [Op.ne]: null } },
include
});
if (!userExam) return false;
// 查找得分比当前得分高的数据数目
const higherScoresCount = await ctx.model4.Examination.findAndCountAll({
where: {
score: { [Op.gt]: userExam.dataValues.score },
updated_at: { [Op.ne]: null }
}
});
// 查找相同得分的所有数据
const sameScores = await ctx.model4.Examination.findAndCountAll({
where: {
score: userExam.dataValues.score,
created_at: { [Op.lt]: userExam.dataValues.created_at },
updated_at: { [Op.ne]: null }
}
});
// 计算总排名(比当前得分高的数目 + 相同得分的数目 + 1(当前用户自己))
const totalRank = higherScoresCount.count + sameScores.count + 1;
userExam.dataValues.totalRank = totalRank;
return userExam;
} catch (error) {
const blockName = fileName + "--" + "grades";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
}
module.exports = ExamService;

113
app/service/Topic.js Normal file
View File

@@ -0,0 +1,113 @@
'use strict';
const Service = require('../core/base_service');
const { Op } = require('sequelize');
const fileName = "Topic";
class TopicService extends Service {
// 学生抽取/读取题目
async topic(uid, answerId) {
const { ctx } = this;
try {
let contestTopic = await ctx.model4.Examination.findOne({ where: { user_uid: uid } });
if (!contestTopic) {
const result = await ctx.model4.ChoiceTopic.findAndCountAll();
// 选择题一共10道,首先获取数据数目
let bdCardMsg = [];
// 若不满10道题,则直接将题目 id 放入数组中
if (result.rows.length < 10 || result.rows.length == 10) {
bdCardMsg = result.rows.map(item => item.id);
} else {
// 创建一个空数组来存储随机数
let randomNumbers = [];
// 循环,直到数组中的元素数量达到十个
while (randomNumbers.length < 10) {
let arrNum;
do {
// 获取一个随机数
arrNum = Math.floor(Math.random() * result.count);
} while (randomNumbers.includes(arrNum)); // 检查随机数是否已存在,如果存在则重新抽取
// 将随机数添加到数组中
randomNumbers.push(arrNum);
// 将随机数作为下标,向 bdCardMsg 数组中添加对应题目数据
bdCardMsg.push(result.rows[arrNum].id);
}
}
const hanzi = "北斗航天科学教育科普导航定位通信";
const randomCharIndex = Math.floor(Math.random() * hanzi.length);
const randomChar = hanzi.charAt(randomCharIndex);
const number = "0123456789";
const randomNumIndex = Math.floor(Math.random() * number.length);
const randomNum = number.charAt(randomNumIndex);
const sensor = ["温度", "湿度", "超声波传感器", "光线"];
const randomArrCharIndex = Math.floor(Math.random() * sensor.length);
const randomArrChar = sensor[randomArrCharIndex];
let sensorData, num;
if (randomArrChar == "温度") {
num = Math.floor(Math.random() * 899) + 100;
num = num.toString().slice(0, -1) + "." + num.toString().slice(-1);
sensorData = "温度" + num + "度";
} else if (randomArrChar == "湿度") {
num = Math.floor(Math.random() * 899) + 100;
num = num.toString().slice(0, -1) + "." + num.toString().slice(-1);
sensorData = "湿度" + num + "%";
} else if (randomArrChar == "超声波传感器") {
num = Math.floor(Math.random() * 89) + 10;
sensorData = "距离" + num + "厘米";
} else if (randomArrChar == "光线") {
num = Math.floor(Math.random() * 3095) + 1000;
sensorData = "光线强度" + num;
}
const user = await ctx.model4.Account.findOne({ attributes: ['contest_uid'], where: { uid } });
if (!user) return { code: 404 };
const contest = await ctx.model4.Contest.findOne({ attributes: ['type'], where: { uid: user.dataValues.contest_uid, status: 0 } });
if (!contest) return { code: 404 };
const form = {
user_uid: uid,
contest_uid: user.dataValues.contest_uid,
exam_type: contest.dataValues.type,
topic1: randomChar,
topic2: randomNum,
topic3: bdCardMsg.join(","),
topic5: sensorData,
created_at: new Date(),
};
contestTopic = await ctx.model4.Examination.create(form, { silent: true });
if (!contestTopic) return { code: 404 };
}
contestTopic.dataValues.topic3.match(/[^a-zA-Z]/g).join('');
let idArr;
if (contestTopic.dataValues.updated_at != null) {
idArr = contestTopic.dataValues.answer.split(",");
} else {
idArr = answerId;
}
let attributes = ['id', 'card_id', 'encode_type', 'msg_data', 'created_at'],
where = { id: idArr, user_uid: uid },
dbOptions = { attributes, where };
const result = await ctx.model4.TShortMsg.findAndCountAll(dbOptions);
return { code: 200, examination: contestTopic.dataValues, shortMsg: result.rows };
} catch (error) {
const blockName = fileName + "--" + "topic";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
// 系统读取单选题
async radio(radioArr) {
const { ctx } = this;
try {
const Radio = await ctx.model4.ChoiceTopic.findAll({ attributes: ['id', 'topic', 'options_a', 'options_b', 'options_c', 'options_d'], where: { id: radioArr } });
return Radio.length == 0 ? false : Radio;
} catch (error) {
const blockName = fileName + "--" + "radio";
ctx.app.middleware.log('../../serviceLog', blockName + ">>>>" + error);
return 'error';
}
}
}
module.exports = TopicService;