dao-user.go 25 KB

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