dao-user.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. package dao
  2. import (
  3. "database/sql"
  4. "exam_system/config"
  5. "exam_system/entity"
  6. "exam_system/result"
  7. "exam_system/utils"
  8. "exam_system/vo"
  9. "fmt"
  10. "log"
  11. "mime/multipart"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/jmoiron/sqlx"
  16. "github.com/xuri/excelize/v2"
  17. "golang.org/x/crypto/bcrypt"
  18. )
  19. // FindUserbySid 是否存在
  20. func FindUserbySid(sid string) *result.Result {
  21. sqlStr := `SELECT
  22. u.id,
  23. u.username,
  24. u.sid,
  25. u.create_at,
  26. u.update_at,
  27. u.password,
  28. u.status,
  29. group_concat( DISTINCT(r.name) ) role_name,
  30. t.name term_name,
  31. c.name class_name
  32. FROM
  33. user u
  34. LEFT JOIN class c ON u.class_id = c.id
  35. LEFT JOIN term t ON c.term_id = t.id
  36. LEFT JOIN user_role ur ON u.id = ur.user_id
  37. LEFT JOIN role r ON ur.role_id = r.id
  38. WHERE
  39. u.sid =? and u.delete_at is null
  40. GROUP BY u.id`
  41. var u vo.UserVo
  42. err := config.DB.Get(&u, sqlStr, sid)
  43. if err != nil {
  44. if err == sql.ErrNoRows {
  45. return result.DATA_NOT_FOUND
  46. }
  47. return result.UNKNOW_ERROR.SetMsg(err.Error())
  48. }
  49. return result.SuccessResult(u)
  50. }
  51. // FindUserbyId 通过Id 查询
  52. func FindUserbyId(id int) *result.Result {
  53. sqlStr := `SELECT
  54. u.id,
  55. u.username,
  56. u.sid,
  57. u.create_at,
  58. u.update_at,
  59. group_concat( DISTINCT(r.NAME) ) role_name,
  60. t.name term_name,
  61. c.name class_name
  62. FROM
  63. user u
  64. LEFT JOIN class c ON u.class_id = c.id
  65. LEFT JOIN term t ON c.term_id = t.id
  66. LEFT JOIN user_role ur ON u.id = ur.user_id
  67. LEFT JOIN role r ON ur.role_id = r.id
  68. WHERE
  69. u.id =? and u.delete_at is null
  70. GROUP BY u.id`
  71. var user vo.UserVo
  72. err := config.DB.Get(&user, sqlStr, id)
  73. if err != nil {
  74. return result.UNKNOW_ERROR.SetMsg(err.Error())
  75. }
  76. return result.SUCCESS.SetData(user)
  77. }
  78. // InsertUser 插入
  79. func InsertUser(user *entity.User, userType string) *result.Result {
  80. tx, err := config.DB.Beginx() // 开启事务
  81. if err != nil {
  82. log.Printf("begin trans failed, err:%v\n", err)
  83. return result.UNKNOW_ERROR
  84. }
  85. return utils.Transation(tx, err, func(tx *sqlx.Tx) *result.Result {
  86. // 1.先查询用户是否存在
  87. sqlStr := "select id,username,password,sid,class_id from user where sid=? and delete_at is null"
  88. var u entity.User
  89. err = tx.Get(&u, sqlStr, user.Sid)
  90. if err != nil && err.Error() != "sql: no rows in result set" {
  91. return result.UNKNOW_ERROR.SetMsg(err.Error())
  92. }
  93. if u.ID != 0 {
  94. return result.USER_IS_EXISTED
  95. }
  96. // 2、插入用户表
  97. sqlStr = "insert into user(username, password,sid,create_at,update_at,status,class_id) values (?,?,?,?,?,?,?)"
  98. var ret sql.Result
  99. ret, err = tx.Exec(sqlStr, user.Username, user.Password, user.Sid, time.Now(), time.Now(), user.Status, user.ClassId)
  100. if err != nil {
  101. tx.Rollback()
  102. return result.UNKNOW_ERROR.SetMsg(err.Error())
  103. }
  104. id, _ := ret.LastInsertId()
  105. // 3、通过名字获取角色
  106. sqlStr = "select id from role where name=? limit 1"
  107. var r entity.Role
  108. err = tx.Get(&r, sqlStr, userType)
  109. if err != nil {
  110. return result.UNKNOW_ERROR.SetMsg(err.Error())
  111. }
  112. // 4、插入用户角色表
  113. sqlStr = "insert into user_role(user_id, role_id,create_at,update_at) values (?,?,?,?)"
  114. _, err = tx.Exec(sqlStr, id, r.Id, time.Now(), time.Now())
  115. if err != nil {
  116. return result.UNKNOW_ERROR.SetMsg(err.Error())
  117. }
  118. // 5、查询班级还未开始的考试
  119. sqlStr = "select e.id from exam_class ec left join exam e on e.id = ec.exam_id where ec.class_id=? and e.end_at>=?"
  120. var count []int64
  121. err = tx.Select(&count, sqlStr, user.ClassId, time.Now())
  122. if err != nil && err != sql.ErrNoRows {
  123. return result.UNKNOW_ERROR.SetMsg(err.Error())
  124. }
  125. // 6、添加考试记录
  126. sqlStr = "insert into exam_record(create_at, update_at, user_id, exam_id,status) values (?,?,?,?,?)"
  127. prepare, _ := tx.Prepare(sqlStr)
  128. for _, examId := range count {
  129. _, err = prepare.Exec(time.Now(), time.Now(), id, examId, entity.NOT_TESTED)
  130. if err != nil && err != sql.ErrNoRows {
  131. return result.UNKNOW_ERROR.SetMsg(err.Error())
  132. }
  133. }
  134. // 7、更新考试人数
  135. sqlStr = "update exam set user_count = user_count+1 where id in (?)"
  136. var updateExamStr string
  137. var param []interface{}
  138. updateExamStr, param, err = sqlx.In(sqlStr, count)
  139. _, err = tx.Exec(updateExamStr, param...)
  140. if err != nil {
  141. return result.UNKNOW_ERROR.SetMsg(err.Error())
  142. }
  143. return result.SUCCESS.SetData(id)
  144. })
  145. }
  146. // UpdateUser 根据id
  147. func UpdateUser(user *entity.User, userType string) *result.Result {
  148. tx, err := config.DB.Beginx() // 开启事务
  149. if err != nil {
  150. log.Printf("begin trans failed, err:%v\n", err)
  151. return result.UNKNOW_ERROR
  152. }
  153. return utils.Transation(tx, err, func(tx *sqlx.Tx) *result.Result {
  154. // 1.先查询用户
  155. sqlStr := "select id,username,password,sid,class_id from user where id=?"
  156. var u entity.User
  157. err = tx.Get(&u, sqlStr, user.ID)
  158. if err != nil && err.Error() != "sql: no rows in result set" {
  159. return result.UNKNOW_ERROR.SetMsg(err.Error())
  160. }
  161. // 2、更新用户表(管理员插入默认为正常)
  162. parms := make([]interface{}, 0)
  163. sqlStr = `update user set username = ?, `
  164. parms = append(parms, user.Username)
  165. if user.Password != "" {
  166. hash, _ := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
  167. user.Password = string(hash)
  168. parms = append(parms, user.Password)
  169. sqlStr += `password = ?, `
  170. }
  171. if user.Sid != "" && user.Sid != u.Sid {
  172. parms = append(parms, user.Sid)
  173. sqlStr += `sid = ?, `
  174. }
  175. sqlStr += "class_id = ?,update_at=?,status=? where id = ?"
  176. parms = append(parms, user.ClassId)
  177. parms = append(parms, time.Now())
  178. parms = append(parms, user.Status)
  179. parms = append(parms, user.ID)
  180. var ret sql.Result
  181. ret, err = tx.Exec(sqlStr, parms...)
  182. if err != nil {
  183. return result.UNKNOW_ERROR.SetMsg(err.Error())
  184. }
  185. affected, _ := ret.RowsAffected()
  186. // 3、获取角色
  187. var r entity.Role
  188. sqlStr = "select id from role where name=? limit 1"
  189. err = tx.Get(&r, sqlStr, userType)
  190. if err != nil {
  191. return result.UNKNOW_ERROR.SetMsg(err.Error())
  192. }
  193. // 4、更新用户角色表
  194. sqlStr = "select id from user_role where user_id=?"
  195. var id int
  196. var ret2 sql.Result
  197. _ = tx.Get(&id, sqlStr, u.ID)
  198. if id == 0 {
  199. sqlStr = "insert into user_role(user_id, role_id,create_at,update_at) values (?,?,?,?)"
  200. ret2, err = tx.Exec(sqlStr, u.ID, r.Id, time.Now(), time.Now())
  201. if err != nil {
  202. return result.UNKNOW_ERROR.SetMsg(err.Error())
  203. }
  204. } else {
  205. sqlStr = "update user_role set role_id=? ,update_at=? where user_id=?"
  206. ret2, err = tx.Exec(sqlStr, r.Id, time.Now(), user.ID)
  207. if err != nil {
  208. return result.UNKNOW_ERROR.SetMsg(err.Error())
  209. }
  210. }
  211. affected2, _ := ret2.RowsAffected()
  212. return result.SUCCESS.SetData(result.NewResultChange(affected + affected2))
  213. })
  214. }
  215. // DeleteUsers 删除
  216. func DeleteUsers(ids []string) *result.Result {
  217. parm := []interface{}{time.Now()}
  218. parmStr := ""
  219. for k, id := range ids {
  220. parm = append(parm, id)
  221. if k == (len(ids) - 1) {
  222. parmStr += "?"
  223. } else {
  224. parmStr += "?,"
  225. }
  226. }
  227. sqlStr := fmt.Sprintf("update user set delete_at=? where id in (%s)", parmStr)
  228. res, err := config.DB.Exec(sqlStr, parm...)
  229. if err != nil {
  230. return result.UNKNOW_ERROR.SetMsg(err.Error())
  231. }
  232. return result.SUCCESS.SetData(res)
  233. }
  234. func FindUserList(page, size int, sort string, query map[string]interface{}) *result.Result {
  235. tx, err := config.DB.Beginx() // 开启事务
  236. if err != nil {
  237. log.Printf("begin trans failed, err:%v\n", err)
  238. return result.UNKNOW_ERROR
  239. }
  240. return utils.Transation(tx, err, func(tx *sqlx.Tx) *result.Result {
  241. sqlStr := `
  242. SELECT
  243. u.id,
  244. u.username,
  245. u.sid,
  246. group_concat(DISTINCT ( r.name )) role_name,
  247. u.create_at,
  248. u.update_at,
  249. t.name term_name,
  250. c.name class_name
  251. FROM
  252. user u
  253. LEFT JOIN class c ON u.class_id = c.id
  254. LEFT JOIN term t ON c.term_id = t.id
  255. LEFT JOIN user_role ur ON u.id = ur.user_id
  256. LEFT JOIN role r ON ur.role_id = r.id
  257. WHERE
  258. u.delete_at IS NULL `
  259. params := make([]interface{}, 0)
  260. if query["username"] != nil {
  261. sqlStr += "and u.username like ? "
  262. params = append(params, "%"+query["username"].(string)+"%")
  263. }
  264. if query["sid"] != nil {
  265. sqlStr += "and u.sid = ? "
  266. params = append(params, query["sid"])
  267. }
  268. if query["class_id"] != nil {
  269. sqlStr += "and u.class_id=? "
  270. params = append(params, query["class_id"])
  271. }
  272. if query["role"] != nil {
  273. sqlStr += "and r.name = ? "
  274. params = append(params, query["role"])
  275. }
  276. sqlStr += `GROUP BY u.id `
  277. if sort == "asc" {
  278. sqlStr += `Order By u.create_at asc
  279. `
  280. } else {
  281. sqlStr += `Order By u.create_at desc
  282. `
  283. }
  284. sqlStr += `LIMIT ?,?`
  285. params = append(params, utils.PostionSize(page, size), size)
  286. var users []vo.UserVo
  287. err = tx.Select(&users, sqlStr, params...)
  288. if err != nil {
  289. return result.UNKNOW_ERROR.SetMsg(err.Error())
  290. }
  291. sqlStr = `SELECT
  292. count(u.id)
  293. FROM
  294. user u
  295. LEFT JOIN class c ON u.class_id = c.id
  296. LEFT JOIN term t ON c.term_id = t.id
  297. LEFT JOIN user_role ur ON u.id = ur.user_id
  298. LEFT JOIN role r ON ur.role_id = r.id
  299. WHERE
  300. u.delete_at IS NULL `
  301. params = make([]interface{}, 0)
  302. if query["username"] != nil {
  303. sqlStr += "and u.username like ? "
  304. params = append(params, "%"+query["username"].(string)+"%")
  305. }
  306. if query["sid"] != nil {
  307. sqlStr += "and u.sid = ? "
  308. params = append(params, query["sid"].(string))
  309. }
  310. if query["class_id"] != nil {
  311. sqlStr += "and u.class_id=? "
  312. params = append(params, query["class_id"])
  313. }
  314. if query["role"] != nil {
  315. sqlStr += "and r.name = ? "
  316. params = append(params, query["role"])
  317. }
  318. total := 0
  319. err = tx.Get(&total, sqlStr, params...)
  320. if err != nil {
  321. return result.UNKNOW_ERROR.SetMsg(err.Error())
  322. }
  323. return result.SuccessResult(result.NewPage(page, len(users), total, users))
  324. })
  325. }
  326. // InsertBatchUserByClassId 导入xlsx
  327. func InsertBatchUserByClassId(file multipart.File, classId int) *result.Result {
  328. xlsFile, err := excelize.OpenReader(file)
  329. if err != nil {
  330. return result.UNKNOW_ERROR.SetMsg(err.Error())
  331. }
  332. tx, err := config.DB.Beginx() // 开启事务
  333. if err != nil {
  334. log.Printf("begin trans failed, err:%v\n", err)
  335. return result.UNKNOW_ERROR
  336. }
  337. return utils.Transation(tx, err, func(tx *sqlx.Tx) *result.Result {
  338. var total int64 = 0
  339. // 1.查询用户是否已存在
  340. userStr := "select id,sid from user where sid = ? and delete_at is null limit 1"
  341. // 2.插入用户
  342. userAddStr := "insert into user(username, password,sid,create_at,update_at,status,class_id) values (?,?,?,?,?,?,?)"
  343. var userAddStmt *sql.Stmt
  344. userAddStmt, err = tx.Prepare(userAddStr)
  345. if err != nil {
  346. return result.UNKNOW_ERROR.SetMsg(err.Error())
  347. }
  348. // 3.获取角色列表
  349. rolesStr := "select id,name from role"
  350. var roles []*entity.Role
  351. err = tx.Select(&roles, rolesStr)
  352. if err != nil {
  353. return result.UNKNOW_ERROR.SetMsg(err.Error())
  354. }
  355. // 4、插入用户角色表
  356. roleAddStr := "insert into user_role(user_id, role_id,create_at,update_at) values (?,?,?,?)"
  357. var roleAddStmt *sql.Stmt
  358. roleAddStmt, err = tx.Prepare(roleAddStr)
  359. if err != nil {
  360. return result.UNKNOW_ERROR.SetMsg(err.Error())
  361. }
  362. // 5、更新用户
  363. userUpdateStr := "update user set username=?,password=?,sid=?,update_at=?,status=?,class_id=? where id = ?"
  364. var userUpdateStmt *sql.Stmt
  365. userUpdateStmt, err = tx.Prepare(userUpdateStr)
  366. if err != nil {
  367. return result.UNKNOW_ERROR.SetMsg(err.Error())
  368. }
  369. // 6、更新用户角色
  370. roleUpdateStr := "update user_role set role_id=? ,update_at=? where user_id=?"
  371. var roleUpdateStmt *sql.Stmt
  372. roleUpdateStmt, err = tx.Prepare(roleUpdateStr)
  373. if err != nil {
  374. return result.UNKNOW_ERROR.SetMsg(err.Error())
  375. }
  376. i := 2
  377. for {
  378. sid, _ := xlsFile.GetCellValue("Sheet1", "A"+strconv.Itoa(i))
  379. username, _ := xlsFile.GetCellValue("Sheet1", "B"+strconv.Itoa(i))
  380. roleName, _ := xlsFile.GetCellValue("Sheet1", "D"+strconv.Itoa(i))
  381. password, _ := xlsFile.GetCellValue("Sheet1", "E"+strconv.Itoa(i))
  382. if sid == "" {
  383. break
  384. }
  385. i++
  386. hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  387. password = string(hash)
  388. // 1、查询用户是否存在
  389. var user entity.User
  390. err = tx.Get(&user, userStr, sid)
  391. // 存在插入,不存在更新
  392. var ret sql.Result
  393. if err != nil {
  394. if err == sql.ErrNoRows {
  395. // 2、插入用户
  396. ret, err = userAddStmt.Exec(username, password, sid, time.Now(), time.Now(), entity.NORMAL, classId)
  397. if err != nil {
  398. return result.UNKNOW_ERROR.SetMsg(err.Error())
  399. }
  400. id, _ := ret.LastInsertId()
  401. affected, _ := ret.RowsAffected()
  402. total += affected
  403. // 3、通过名字获取角色
  404. var role entity.Role
  405. for _, r := range roles {
  406. if r.Name == roleName {
  407. role = *r
  408. break
  409. }
  410. }
  411. // 4、插入角色
  412. _, err = roleAddStmt.Exec(id, role.Id, time.Now(), time.Now())
  413. if err != nil {
  414. return result.UNKNOW_ERROR.SetMsg(err.Error())
  415. }
  416. } else {
  417. return result.UNKNOW_ERROR.SetMsg(err.Error())
  418. }
  419. } else {
  420. // 1、更新用户
  421. ret, err = userUpdateStmt.Exec(username, password, sid, time.Now(), entity.NORMAL, classId, user.ID)
  422. if err != nil {
  423. return result.UNKNOW_ERROR.SetMsg(err.Error())
  424. }
  425. affected, _ := ret.RowsAffected()
  426. total += affected
  427. // 2、获取角色
  428. var role entity.Role
  429. for _, r := range roles {
  430. if r.Name == roleName {
  431. role = *r
  432. break
  433. }
  434. }
  435. // 3、更新角色
  436. _, err = roleUpdateStmt.Exec(role.Id, time.Now(), user.ID)
  437. if err != nil {
  438. return result.UNKNOW_ERROR.SetMsg(err.Error())
  439. }
  440. }
  441. }
  442. res := result.NewResultChange(total)
  443. res.RowsFailed = int64(i-2) - total
  444. return result.SuccessResult(res)
  445. })
  446. }
  447. // InsertBatchUserByTermId 导入xlsx
  448. func InsertBatchUserByTermId(file multipart.File, termId, classId int) *result.Result {
  449. xlsFile, err := excelize.OpenReader(file)
  450. if err != nil {
  451. return result.UNKNOW_ERROR.SetMsg(err.Error())
  452. }
  453. tx, err := config.DB.Beginx() // 开启事务
  454. if err != nil {
  455. log.Printf("begin trans failed, err:%v\n", err)
  456. return result.UNKNOW_ERROR
  457. }
  458. return utils.Transation(tx, err, func(tx *sqlx.Tx) *result.Result {
  459. var total int64 = 0
  460. // 1.查询班级
  461. classStr := "SELECT c.id,c.term_id FROM class c,term t WHERE t.name=? and c.name = ? and c.term_id = t.id AND c.delete_at IS NULL limit 1"
  462. // 1.查询用户是否已存在
  463. userStr := "select id,sid from user where sid = ? and delete_at is null limit 1"
  464. // 2.插入用户
  465. userAddStr := "insert into user(username, password,sid,create_at,update_at,status,class_id) values (?,?,?,?,?,?,?)"
  466. var userAddStmt *sql.Stmt
  467. userAddStmt, err = tx.Prepare(userAddStr)
  468. if err != nil {
  469. return result.UNKNOW_ERROR.SetMsg(err.Error())
  470. }
  471. // 3.获取角色列表
  472. rolesStr := "select id,name from role"
  473. var roles []*entity.Role
  474. err = tx.Select(&roles, rolesStr)
  475. if err != nil {
  476. return result.UNKNOW_ERROR.SetMsg(err.Error())
  477. }
  478. // 4、插入用户角色表
  479. roleAddStr := "insert into user_role(user_id, role_id,create_at,update_at) values (?,?,?,?)"
  480. var roleAddStmt *sql.Stmt
  481. roleAddStmt, err = tx.Prepare(roleAddStr)
  482. if err != nil {
  483. return result.UNKNOW_ERROR.SetMsg(err.Error())
  484. }
  485. // 5、更新用户
  486. userUpdateStr := "update user set username=?,password=?,sid=?,update_at=?,status=?,class_id=? where id = ?"
  487. var userUpdateStmt *sql.Stmt
  488. userUpdateStmt, err = tx.Prepare(userUpdateStr)
  489. if err != nil {
  490. return result.UNKNOW_ERROR.SetMsg(err.Error())
  491. }
  492. // 6、更新用户角色
  493. roleUpdateStr := "update user_role set role_id=? ,update_at=? where user_id=?"
  494. var roleUpdateStmt *sql.Stmt
  495. roleUpdateStmt, err = tx.Prepare(roleUpdateStr)
  496. if err != nil {
  497. return result.UNKNOW_ERROR.SetMsg(err.Error())
  498. }
  499. i := 2
  500. for {
  501. sid, _ := xlsFile.GetCellValue("Sheet1", "A"+strconv.Itoa(i))
  502. username, _ := xlsFile.GetCellValue("Sheet1", "B"+strconv.Itoa(i))
  503. termClassName, _ := xlsFile.GetCellValue("Sheet1", "C"+strconv.Itoa(i))
  504. roleName, _ := xlsFile.GetCellValue("Sheet1", "D"+strconv.Itoa(i))
  505. password, _ := xlsFile.GetCellValue("Sheet1", "E"+strconv.Itoa(i))
  506. if sid == "" {
  507. break
  508. }
  509. i++
  510. hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  511. password = string(hash)
  512. // 1.查询班级
  513. var class entity.Class
  514. termClass := strings.Split(termClassName, ">")
  515. if len(termClass) == 2 {
  516. fmt.Println(classStr)
  517. err = tx.Get(&class, classStr, termClass[0], termClass[1])
  518. if err != nil {
  519. if err == sql.ErrNoRows {
  520. err = nil
  521. continue
  522. }
  523. return result.UNKNOW_ERROR.SetMsg(err.Error())
  524. }
  525. }
  526. fmt.Println()
  527. if roleName == "student" && class.TermId != termId || (classId != 0 && class.Id != nil && *class.Id == classId) {
  528. continue
  529. }
  530. // 2、查询用户是否存在
  531. var user entity.User
  532. err = tx.Get(&user, userStr, sid)
  533. // 存在插入,不存在更新
  534. var ret sql.Result
  535. if err != nil {
  536. if err == sql.ErrNoRows {
  537. // 2、插入用户
  538. ret, err = userAddStmt.Exec(username, password, sid, time.Now(), time.Now(), entity.NORMAL, class.Id)
  539. if err != nil {
  540. return result.UNKNOW_ERROR.SetMsg(err.Error())
  541. }
  542. id, _ := ret.LastInsertId()
  543. user.ID = int(id)
  544. affected, _ := ret.RowsAffected()
  545. total += affected
  546. // 3、通过名字获取角色
  547. var role entity.Role
  548. for _, r := range roles {
  549. if r.Name == roleName {
  550. role = *r
  551. break
  552. }
  553. }
  554. // 4、插入角色
  555. _, err = roleAddStmt.Exec(id, role.Id, time.Now(), time.Now())
  556. if err != nil {
  557. return result.UNKNOW_ERROR.SetMsg(err.Error())
  558. }
  559. } else {
  560. return result.UNKNOW_ERROR.SetMsg(err.Error())
  561. }
  562. } else {
  563. // 1、更新用户
  564. ret, err = userUpdateStmt.Exec(username, password, sid, time.Now(), entity.NORMAL, class.Id, user.ID)
  565. if err != nil {
  566. return result.UNKNOW_ERROR.SetMsg(err.Error())
  567. }
  568. affected, _ := ret.RowsAffected()
  569. total += affected
  570. // 2、获取角色
  571. var role entity.Role
  572. for _, r := range roles {
  573. if r.Name == roleName {
  574. role = *r
  575. break
  576. }
  577. }
  578. // 3、更新角色
  579. _, err = roleUpdateStmt.Exec(role.Id, time.Now(), user.ID)
  580. if err != nil {
  581. return result.UNKNOW_ERROR.SetMsg(err.Error())
  582. }
  583. }
  584. // 更新考试
  585. // 5、查询班级还未开始的考试
  586. sqlStr := "select e.id from exam_class ec left join exam e on e.id = ec.exam_id where ec.class_id=? and e.end_at>=?"
  587. var count []int64
  588. err = tx.Select(&count, sqlStr, user.ClassId, time.Now())
  589. if err != nil && err != sql.ErrNoRows {
  590. return result.UNKNOW_ERROR.SetMsg(err.Error())
  591. }
  592. // 6、添加考试记录
  593. sqlStr = "insert into exam_record(create_at, update_at, user_id, exam_id,status) values (?,?,?,?,?)"
  594. prepare, _ := tx.Prepare(sqlStr)
  595. for _, examId := range count {
  596. _, err = prepare.Exec(time.Now(), time.Now(), user.ID, examId, entity.NOT_TESTED)
  597. if err != nil && err != sql.ErrNoRows {
  598. return result.UNKNOW_ERROR.SetMsg(err.Error())
  599. }
  600. }
  601. // 7、更新考试人数
  602. sqlStr = "update exam set user_count = user_count+1 where id in (?)"
  603. var updateExamStr string
  604. var param []interface{}
  605. updateExamStr, param, err = sqlx.In(sqlStr, count)
  606. _, err = tx.Exec(updateExamStr, param...)
  607. if err != nil {
  608. return result.UNKNOW_ERROR.SetMsg(err.Error())
  609. }
  610. }
  611. res := result.NewResultChange(total)
  612. res.RowsFailed = int64(i-2) - total
  613. return result.SuccessResult(res)
  614. })
  615. }
  616. // InsertBatchUser 导入xlsx(excel读内存)
  617. func InsertBatchUser(file multipart.File) *result.Result {
  618. xlsFile, err := excelize.OpenReader(file)
  619. if err != nil {
  620. return result.UNKNOW_ERROR.SetMsg(err.Error())
  621. }
  622. tx, err := config.DB.Beginx() // 开启事务
  623. if err != nil {
  624. log.Printf("begin trans failed, err:%v\n", err)
  625. return result.UNKNOW_ERROR
  626. }
  627. return utils.Transation(tx, err, func(tx *sqlx.Tx) *result.Result {
  628. i := 2
  629. var total int64 = 0
  630. // 1.查询班级
  631. classStr := "SELECT c.id FROM class c,term t WHERE t.name=? and c.name = ? and c.term_id = t.id AND c.delete_at IS NULL limit 1"
  632. // 2.查询用户是否已存在
  633. userStr := "select id,sid from user where sid = ? and delete_at is null limit 1"
  634. // 3.插入用户
  635. userAddStr := "insert into user(username, password,sid,create_at,update_at,status,class_id) values (?,?,?,?,?,?,?)"
  636. var userAddStmt *sql.Stmt
  637. userAddStmt, err = tx.Prepare(userAddStr)
  638. if err != nil {
  639. return result.UNKNOW_ERROR.SetMsg(err.Error())
  640. }
  641. // 3.获取角色列表
  642. rolesStr := "select id,name from role"
  643. var roles []*entity.Role
  644. err = tx.Select(&roles, rolesStr)
  645. if err != nil {
  646. return result.UNKNOW_ERROR.SetMsg(err.Error())
  647. }
  648. // 4、插入用户角色表
  649. roleAddStr := "insert into user_role(user_id, role_id,create_at,update_at) values (?,?,?,?)"
  650. var roleAddStmt *sql.Stmt
  651. roleAddStmt, err = tx.Prepare(roleAddStr)
  652. if err != nil {
  653. return result.UNKNOW_ERROR.SetMsg(err.Error())
  654. }
  655. // 5、更新用户
  656. userUpdateStr := "update user set username=?,password=?,sid=?,update_at=?,status=?,class_id=? where id = ?"
  657. var userUpdateStmt *sql.Stmt
  658. userUpdateStmt, err = tx.Prepare(userUpdateStr)
  659. if err != nil {
  660. return result.UNKNOW_ERROR.SetMsg(err.Error())
  661. }
  662. // 6、更新用户角色
  663. roleUpdateStr := "update user_role set role_id=? ,update_at=? where user_id=?"
  664. var roleUpdateStmt *sql.Stmt
  665. roleUpdateStmt, err = tx.Prepare(roleUpdateStr)
  666. if err != nil {
  667. return result.UNKNOW_ERROR.SetMsg(err.Error())
  668. }
  669. var users []*vo.UserVo
  670. for {
  671. sid, _ := xlsFile.GetCellValue("Sheet1", "A"+strconv.Itoa(i))
  672. username, _ := xlsFile.GetCellValue("Sheet1", "B"+strconv.Itoa(i))
  673. className, _ := xlsFile.GetCellValue("Sheet1", "C"+strconv.Itoa(i))
  674. roleName, _ := xlsFile.GetCellValue("Sheet1", "D"+strconv.Itoa(i))
  675. password, _ := xlsFile.GetCellValue("Sheet1", "E"+strconv.Itoa(i))
  676. if sid == "" {
  677. break
  678. }
  679. user := entity.User{Sid: sid, Username: username, Password: password}
  680. users = append(users, &vo.UserVo{User: user, RoleName: &roleName, ClassName: &className})
  681. i++
  682. }
  683. for _, v := range users {
  684. // 1、查询学期班级
  685. termClass := strings.Split(*v.ClassName, ">")
  686. var class entity.Class
  687. if len(termClass) == 2 {
  688. err = tx.Get(&class, classStr, termClass[0], termClass[1])
  689. if err != nil {
  690. if err == sql.ErrNoRows {
  691. err = nil
  692. continue
  693. }
  694. return result.UNKNOW_ERROR.SetMsg(err.Error())
  695. }
  696. }
  697. hash, _ := bcrypt.GenerateFromPassword([]byte(v.Password), bcrypt.DefaultCost)
  698. v.Password = string(hash)
  699. // 2、查询用户是否存在
  700. var user entity.User
  701. err = tx.Get(&user, userStr, v.Sid)
  702. // 存在插入,不存在更新
  703. var ret sql.Result
  704. if err != nil {
  705. if err == sql.ErrNoRows {
  706. // 2、插入用户
  707. ret, err = userAddStmt.Exec(v.Username, v.Password, v.Sid, time.Now(), time.Now(), entity.NORMAL, class.Id)
  708. if err != nil {
  709. return result.UNKNOW_ERROR.SetMsg(err.Error())
  710. }
  711. id, _ := ret.LastInsertId()
  712. affected, _ := ret.RowsAffected()
  713. total += affected
  714. // 3、通过名字获取角色
  715. var role entity.Role
  716. for _, r := range roles {
  717. if r.Name == *v.RoleName {
  718. role = *r
  719. break
  720. }
  721. }
  722. // 4、插入角色
  723. _, err = roleAddStmt.Exec(id, role.Id, time.Now(), time.Now())
  724. if err != nil {
  725. return result.UNKNOW_ERROR.SetMsg(err.Error())
  726. }
  727. } else {
  728. return result.UNKNOW_ERROR.SetMsg(err.Error())
  729. }
  730. } else {
  731. // 2、更新用户
  732. ret, err = userUpdateStmt.Exec(v.Username, v.Password, v.Sid, time.Now(), entity.NORMAL, class.Id, user.ID)
  733. if err != nil {
  734. return result.UNKNOW_ERROR.SetMsg(err.Error())
  735. }
  736. affected, _ := ret.RowsAffected()
  737. total += affected
  738. // 获取角色
  739. var role entity.Role
  740. for _, r := range roles {
  741. if r.Name == *v.RoleName {
  742. role = *r
  743. break
  744. }
  745. }
  746. // 3、更新角色
  747. _, err = roleUpdateStmt.Exec(role.Id, time.Now(), user.ID)
  748. if err != nil {
  749. return result.UNKNOW_ERROR.SetMsg(err.Error())
  750. }
  751. }
  752. }
  753. res := result.NewResultChange(total)
  754. res.RowsFailed = int64(i-2) - total
  755. return result.SuccessResult(res)
  756. })
  757. }
  758. // ImportUserInfo 导入学生信息
  759. func DownloadUserInfo(file *excelize.File) *result.Result {
  760. sqlStr := ` select
  761. u.id,
  762. u.username,
  763. u.password,
  764. u.sid,
  765. u.create_at,
  766. u.update_at,
  767. group_concat( DISTINCT(r.NAME) ) role_name,
  768. t.name term_name,
  769. c.name class_name
  770. FROM
  771. user u
  772. LEFT JOIN class c ON u.class_id = c.id
  773. LEFT JOIN term t ON c.term_id = t.id
  774. LEFT JOIN user_role ur ON u.id = ur.user_id
  775. LEFT JOIN role r ON ur.role_id = r.id
  776. WHERE
  777. u.delete_at is null
  778. GROUP BY u.id`
  779. var users []*vo.UserVo
  780. err := config.DB.Select(&users, sqlStr)
  781. if err != nil {
  782. return result.UNKNOW_ERROR.SetMsg(err.Error())
  783. }
  784. i := 2
  785. for _, user := range users {
  786. file.SetCellValue("Sheet1", "A"+strconv.Itoa(i), user.Sid)
  787. file.SetCellValue("Sheet1", "B"+strconv.Itoa(i), user.Username)
  788. if user.ClassName != nil && user.TermName != nil {
  789. file.SetCellValue("Sheet1", "C"+strconv.Itoa(i), (*user.TermName + ">" + *user.ClassName))
  790. }
  791. if user.RoleName != nil {
  792. file.SetCellValue("Sheet1", "D"+strconv.Itoa(i), *user.RoleName)
  793. }
  794. file.SetCellValue("Sheet1", "E"+strconv.Itoa(i), user.Password)
  795. i++
  796. }
  797. return result.SUCCESS
  798. }