You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1055 lines
35 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package BaseStudentDao
import (
"dsBaseRpc/Const"
"dsBaseRpc/RpcService/BaseClass/BaseClassDao"
"dsBaseRpc/RpcService/BaseOrganization/BaseOrganizationDao"
"dsBaseRpc/RpcService/BaseParent/BaseParentDao"
"dsBaseRpc/RpcService/BaseStudent/BaseStudentProto"
"dsBaseRpc/RpcService/SysDict/SysDictKit"
"dsBaseRpc/RpcService/SysLoginperson/SysLoginpersonDao"
"dsBaseRpc/RpcService/SysLoginperson/SysLoginpersonService"
"dsBaseRpc/Utils/CommonUtil"
"dsBaseRpc/Utils/DateUtil"
"dsBaseRpc/Utils/DbUtil"
"dsBaseRpc/Utils/ExcelUtil"
"dsBaseRpc/Utils/FileUtil"
"dsBaseRpc/Utils/IdCardUtil"
"dsBaseRpc/Utils/LogUtil"
"dsBaseRpc/Utils/PinYinUtil"
"dsBaseRpc/Utils/RedisUtil"
"dsBaseRpc/Utils/SqlKit"
"dsBaseRpc/models"
"errors"
"fmt"
"github.com/xormplus/builder"
"github.com/xuri/excelize/v2"
"regexp"
"strconv"
"strings"
"time"
)
var db = DbUtil.Engine
//记录操作日志
func ActionLog(ms []models.TBaseStudent, actionCode string, actionPersonId string, actionIp string) {
msLog := make([]models.TBaseStudentLog, len(ms))
for i := range ms {
_ = CommonUtil.CopyFields(ms[i], &msLog[i])
msLog[i].LogId = CommonUtil.GetUUID()
msLog[i].ActionCode = actionCode
msLog[i].ActionIpAddress = actionIp
msLog[i].ActionPersonId = actionPersonId
}
//批量保存
_, _ = db.Insert(msLog)
}
//通过主键集合查找对应的实体bean集合
func GetByIds(ids []string) ([]models.TBaseStudent, error) {
ms := make([]models.TBaseStudent, 0)
err := db.In("person_id", ids).Find(&ms)
if err != nil {
return nil, err
}
return ms, nil
}
//增加
func AddBaseStudent(model models.TBaseStudent) (int64, error) {
return db.Insert(model)
}
//修改
func UpdateBaseStudent(model models.TBaseStudent, ForceUpdateFields []string) (int64, error) {
//1、清除Redis缓存
var ids = []string{model.PersonId}
var selector = SqlKit.GetBean("t_base_student")
SqlKit.DeleteCacheByIds(ids, selector)
//更改登录表中的学生姓名
_, _ = SysLoginpersonDao.UpdatePersonName(model.PersonId, model.Xm)
//2、计算本次操作有哪些字段需要更新
NeedUpdateFields := CommonUtil.GetNeedUpdateFields(model)
//3、合并强制更新的字段
ForceUpdateFields = append(ForceUpdateFields, NeedUpdateFields...)
//4、去重
ForceUpdateFields = CommonUtil.RemoveDuplicatesAndEmpty(ForceUpdateFields)
//更改排序号
//1权限排序号的范围是parent_id
var myBuilder = builder.Dialect(builder.MYSQL).Select("person_id").From("t_base_student")
_, _ = myBuilder.ToBoundSQL()
//(2)查询获取到parent_id
var m1 models.TBaseStudent
_, _ = db.ID(model.PersonId).Get(&m1)
//5、更新操作,强制更新这些列
affected, err := db.ID(model.PersonId).Cols(ForceUpdateFields...).Update(model)
return affected, err
}
//分页查询
func PageBaseStudent(in *BaseStudentProto.QueryArg) ([]map[string]interface{}, int32, error) {
//接收传入参数
var limit = int(in.Limit)
var offset = int((in.Page - 1) * in.Limit)
var myBuilder = builder.Dialect(builder.MYSQL).Select("t1.*,t2.login_name,t2.b_use as login_b_use,t2.pwd,t2.original_pwd").From("t_base_student as t1").
InnerJoin("t_sys_loginperson as t2", "t1.person_id=t2.person_id")
myBuilder.Where(builder.Eq{"t1.class_id": in.ClassId}).And(builder.Eq{"t1.b_use": 1}).And(builder.Like{"t1.xm", in.Xm})
//分页
myBuilder.Limit(limit, offset)
//获取拼接完成的SQL语句
sql, err := myBuilder.OrderBy("t1.id_int asc").ToBoundSQL()
if err != nil {
return nil, 0, err
}
list, count, err := SqlKit.Query(sql)
//对于教师是不是修改过账号进行判断
SysLoginpersonService.FillPwdIsChange(&list)
//返回结果
return list, count, err
}
//批量学生调整班级
func ReviseTeacherOrg(Ids []string, ClassId string) error {
//声明事务
session := db.NewSession()
defer func() {
err := session.Close()
if err != nil {
fmt.Println(err.Error())
}
}()
_ = session.Begin()
for i := range Ids {
var person models.TBaseStudent
person.ClassId = ClassId
_, err := db.ID(Ids[i]).Cols("class_id").Update(person)
if err != nil {
_ = session.Rollback()
return err
}
}
//提交事务
err := session.Commit()
return err
}
//导出学生账号信息到EXCEL
func ExportStudentAccountInfoExcel(in *BaseStudentProto.ModelArg) ([]map[string]interface{}, int32, error) {
var myBuilder = builder.Dialect(builder.MYSQL).Select(
`t1.*,t4.stage_name,t3.class_name,
(select login_name from t_sys_loginperson where person_id=t5.person_id) as parent_login_name,
(select original_pwd from t_sys_loginperson where person_id=t5.person_id) as parent_original_pwd`).
From("t_sys_loginperson as t1").
InnerJoin("t_base_student as t2", "t1.person_id=t2.person_id").
InnerJoin("t_base_class as t3", "t2.class_id=t3.class_id").
InnerJoin("t_dm_stage as t4", "t3.stage_id=t4.stage_id").
InnerJoin("t_base_parent as t5", "t2.person_id=t5.student_id")
myBuilder.Where(builder.Eq{"t1.b_use": 1}).
And(builder.Eq{"t2.b_use": 1}).
And(builder.Eq{"t3.b_use": 1}).
And(builder.Eq{"t4.b_use": 1}).And(builder.Eq{"t2.bureau_id": in.BureauId})
//如果指定了班级
if len(in.ClassId) > 0 {
classIds := make([]string, 0)
classIds = append(classIds, in.ClassId)
myBuilder.And(builder.In("t3.class_id", classIds))
}
myBuilder.OrderBy("t3.stage_id").OrderBy("t3.id_int").OrderBy("t2.id_int")
sql, err := myBuilder.ToBoundSQL()
if err != nil {
return nil, 0, err
}
list, count, err := SqlKit.Query(sql)
return list, count, err
}
/**
功能生成导入学生的EXCEL模板
作者:黄海
时间2020-06-05
*/
func ExportStudentInfoExcel(targetPath string, bureauId string, ExportExcelStatus int32, ClassIds []string) {
//1、配置文件
jsonTemplate := "student.json"
f, _, _, SheetName := ExcelUtil.TemplateAddDict("student.xlsx", jsonTemplate)
//2、添加批注
_ = f.AddComment(SheetName, "B201", `{"author":"示例: ","text":"填写年份全称,如2019 或 2020。"}`)
_ = f.AddComment(SheetName, "C201", `{"author":"示例: ","text":"填写本年级内班级的编号,如1或2,代表本年级内的1班或2班。"}`)
_ = f.AddComment(SheetName, "F201", `{"author":"示例: ","text":"1980-01-01"}`)
//整数类型
var stylePathPrefix = "./Config/ExcelStyle/"
tableStyleIntPath := stylePathPrefix + "tableStyleInt.json"
if !FileUtil.PathExists(tableStyleIntPath) {
tableStyleIntPath = "." + tableStyleIntPath
}
tableStyleIntStyle, _ := f.NewStyle(FileUtil.ReadFileContent(tableStyleIntPath))
//3、入学年份+班号的有效性
for k := 2 + ExcelUtil.HiddenRows; k <= 5000+ExcelUtil.HiddenRows; k++ {
//设置单元格格式
cName := "B" + CommonUtil.ConvertIntToString(k)
f.SetCellStyle(SheetName, cName, cName, tableStyleIntStyle)
//入学年份
dvRange := excelize.NewDataValidation(true)
dvRange.Sqref = "B" + CommonUtil.ConvertIntToString(k) + ":B" + CommonUtil.ConvertIntToString(k)
_ = dvRange.SetRange(2014, 2030, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorBetween)
dvRange.SetError(excelize.DataValidationErrorStyleStop, "入学年份校验错误", "系统只支持2014-2030年度的班级")
_ = f.AddDataValidation(SheetName, dvRange)
//设置单元格格式
cName = "C" + CommonUtil.ConvertIntToString(k)
f.SetCellStyle(SheetName, cName, cName, tableStyleIntStyle)
//班号
dvRange = excelize.NewDataValidation(true)
dvRange.Sqref = "C" + CommonUtil.ConvertIntToString(k) + ":C" + CommonUtil.ConvertIntToString(k)
_ = dvRange.SetRange(1, 99, excelize.DataValidationTypeWhole, excelize.DataValidationOperatorBetween)
dvRange.SetError(excelize.DataValidationErrorStyleStop, "班号录入错误", "系统只支持1-99的班号")
_ = f.AddDataValidation(SheetName, dvRange)
}
//4、添加是否的下拉框K--->P
for i := 11; i <= 16; i++ {
//要设置下拉框的列
cName, _ := excelize.ColumnNumberToName(i)
dvRange := excelize.NewDataValidation(true)
dvRange.Sqref = cName + CommonUtil.ConvertIntToString(2+ExcelUtil.HiddenRows) + ":" + cName + CommonUtil.ConvertIntToString(ExcelUtil.RowsCount+ExcelUtil.HiddenRows)
_ = dvRange.SetDropList([]string{"是", "否"})
_ = f.AddDataValidation(SheetName, dvRange)
}
//5、当前学校应该有哪些学段
stageList, _, _ := BaseClassDao.GetStage(bureauId)
stageArray := CommonUtil.ConvertSqlListToArray(stageList, "stage_name")
//学段没有那么多,不必使用名称管理器,采用数组即可
if len(stageList) > 0 {
for k := 2 + ExcelUtil.HiddenRows; k <= 5000+ExcelUtil.HiddenRows; k++ {
dvRange := excelize.NewDataValidation(true)
dvRange.Sqref = "A" + CommonUtil.ConvertIntToString(k) + ":A" + CommonUtil.ConvertIntToString(k)
_ = dvRange.SetDropList(stageArray)
_ = f.AddDataValidation(SheetName, dvRange)
}
}
if ExportExcelStatus > 0 {
//将现有数据填充到下载的模板中
var myBuilder = builder.Dialect(builder.MYSQL).Select(`t1.person_id,t2.stage_id,t2.rxnf,t2.bh,t1.xm,t1.xbm,t1.csrq,
(case t1.sfzjh when '-1' then '' else t1.sfzjh end ) as sfzjh,
t1.mzm,t1.zzmmm,t1.sfzjlxm,t1.dszybz,t1.sqznbz,t1.jcwgrysqznbz,
t1.gebz,t1.lsetbz,t1.cjbz`).
From("t_base_student as t1").InnerJoin("t_base_class as t2", "t1.class_id=t2.class_id").
InnerJoin("t_dm_stage as t3", " t2.stage_id=t3.stage_id").Where(builder.Eq{"t1.b_use": 1}).
And(builder.Eq{"t2.b_use": 1}).And(builder.Eq{"t1.bureau_id": bureauId})
//如果指定要哪个班级的导出
if len(ClassIds) > 0 {
myBuilder.And(builder.In("t2.class_id", ClassIds))
}
myBuilder.OrderBy("t2.stage_id,t2.rxnf,t2.bh,t1.id_int asc")
sql, _ := myBuilder.ToBoundSQL()
list, err := db.SQL(sql).Query().List()
if err != nil {
LogUtil.Error(Const.DataBaseActionError, "查询现有学生数据时出错!")
return
}
for i := range list {
record := list[i]
//扩展性别
if record["xbm"].(string) == "1" {
record["xbm"] = "男"
} else {
record["xbm"] = "女"
}
//扩展学段
record["stage_name"] = SysDictKit.MapStageIdToName[record["stage_id"].(string)]
//扩展民族
record["mzm"] = SysDictKit.MapDictKindCodeToChinese["mzm"+"_"+record["mzm"].(string)]
//扩展政治面貌
record["zzmmm"] = SysDictKit.MapDictKindCodeToChinese["zzmmm"+"_"+record["zzmmm"].(string)]
//扩展身份证件类型
record["sfzjlxm"] = SysDictKit.MapDictKindCodeToChinese["sfzjlxm"+"_"+record["sfzjlxm"].(string)]
//独生子女
record["dszybz"] = SysDictKit.MapTrueOrFalseValueToName[CommonUtil.ConvertInt64ToString(record["dszybz"].(int64))]
//随迁子女
record["sqznbz"] = SysDictKit.MapTrueOrFalseValueToName[CommonUtil.ConvertInt64ToString(record["sqznbz"].(int64))]
//务工子女
record["jcwgrysqznbz"] = SysDictKit.MapTrueOrFalseValueToName[CommonUtil.ConvertInt64ToString(record["jcwgrysqznbz"].(int64))]
//孤儿
record["gebz"] = SysDictKit.MapTrueOrFalseValueToName[CommonUtil.ConvertInt64ToString(record["gebz"].(int64))]
//留守儿童
record["lsetbz"] = SysDictKit.MapTrueOrFalseValueToName[CommonUtil.ConvertInt64ToString(record["lsetbz"].(int64))]
//残疾儿童
record["cjbz"] = SysDictKit.MapTrueOrFalseValueToName[CommonUtil.ConvertInt64ToString(record["cjbz"].(int64))]
}
//填充
var colNames = []string{"stage_name", "rxnf", "bh", "xm", "xbm", "csrq", "mzm", "zzmmm", "sfzjlxm", "sfzjh", "dszybz", "sqznbz", "jcwgrysqznbz", "gebz", "lsetbz", "cjbz"}
for i := range list {
for j := range colNames {
cName, _ := excelize.ColumnNumberToName(j + 1)
cName = cName + strconv.Itoa(i+2+ExcelUtil.HiddenRows)
_ = f.SetCellValue(SheetName, cName, list[i][colNames[j]])
}
//单独填充上person_id,为了能在没有身份号的唯一标识的情况下,确定是新增还是修改
cName := "Q"
cName = cName + strconv.Itoa(i+2+ExcelUtil.HiddenRows)
_ = f.SetCellValue(SheetName, cName, list[i]["person_id"])
}
}
// 6、根据指定路径保存文件
if err := f.SaveAs(targetPath); err != nil {
println(err.Error())
}
}
//导入本校学生信息
func ImportStudentInfoExcel(excelPath string, bureauId string, actionPersonId string, actionIp string) (bool, string, error) {
//判断文件是不是存在
if !FileUtil.PathExists(excelPath) {
return false, "03", nil //03:文件没有找到
}
//模板是不是系统提供的
var templateSuccess = true
//excel级别检查
var excelSuccess = true
//临时表级别检查
var mysqlSuccess = true
//新增记录个数
var insertCount = 0
//修改记录个数
var updateCount = 0
//批次号
var batchId = CommonUtil.GetUUID()
//配置文件,用于校验读入的表格是不是系统规定好的格式
jsonTemplate := "student.json"
var s1 = ExcelUtil.ReadJson(jsonTemplate, ExcelUtil.ImportFlag)
//此单位下的哪些班级,按学部+入学年份+班号--->对应的class_id
MapClass, _ := getClassMap(bureauId)
//此学校下有哪些学部
MapStage := BaseClassDao.GetStageMap(bureauId)
//1、对模板的合法性进行检查
templateSuccess = ExcelUtil.IsValidTemplate(excelPath, s1)
if !templateSuccess {
return false, "01", nil //01:不是系统提供的模板,无法完成导入!
}
//2、对excel的合法性进行检查
excelSuccess = checkExcel(excelPath, s1, MapClass, MapStage)
//两个有一个不成功,则提示
if !excelSuccess {
return false, "02", nil //02:在excel检测中发现问题请检查后重新上传
}
//将excel文件读取到mysql的临时数据表中
err := readToTable(excelPath, s1, MapClass, bureauId, batchId, MapStage)
if err != nil {
return false, Const.DataBaseActionError, err
}
//3、对数据库中的人员身份证号进行检查
mysqlSuccess = checkTempTable(excelPath, s1, batchId, bureauId)
//两个有一个不成功,则提示
if !mysqlSuccess {
return false, "02", nil //02:在excel检测中发现问题请检查后重新上传
}
//4、获取所有单位的一些属性用于一会维护人员信息时使用
var bureauModel models.TBaseOrganization
_, _ = db.Where("org_id=?", bureauId).Get(&bureauModel)
//6、新增
insertCount, _, _ = insertStudent(batchId, bureauModel, actionPersonId, actionIp)
//7、修改
updateCount, _, _ = updateStudentImport(batchId, bureauModel, actionPersonId, actionIp)
return true, "插入" + CommonUtil.ConvertIntToString(insertCount) + "条记录,更新" + CommonUtil.ConvertIntToString(updateCount) + "条记录!", nil
}
/**********************************以下为辅助函数*************************************************************************/
/**
功能:指定学校下有哪些班级
作者:黄海
时间2020-06-19
*/
func getClassMap(bureauId string) (map[string]string, error) {
//1、此单位下的哪些部门名称
sql := `select t1.class_id,t1.stage_id,t2.stage_name,t1.rxnf,t1.bh from t_base_class as t1 inner join t_dm_stage as t2 on t1.stage_id=t2.stage_id where t1.bureau_id=? and t1.b_use=1`
listClass, err := db.SQL(sql, bureauId).Query().List()
if err != nil {
return nil, err
}
//转为map一会方便用于填充班级号
var MapClass = make(map[string]string)
for i := range listClass {
MapClass[listClass[i]["stage_name"].(string)+"_"+CommonUtil.ConvertInt64ToString(listClass[i]["rxnf"].(int64))+"_"+CommonUtil.ConvertInt64ToString(listClass[i]["bh"].(int64))] = listClass[i]["class_id"].(string)
}
return MapClass, nil
}
/**
功能检查excel,1是检查是不是系统提供的模板2是检查是不是存在EXCEL级别的错误
作者:黄海
时间2020-06-18
*/
func checkExcel(excelPath string, s1 ExcelUtil.TemplateStruct, MapClass map[string]string, MapStage map[string]string) bool {
//打开指定的文件
f, err := excelize.OpenFile(excelPath)
if err != nil {
LogUtil.Error(Const.IoActionError, "文件丢失:"+excelPath)
return false
}
// excel级别检查的结果
var firstSuccess = true
//身份证的map
var _idCardMap = make(map[string][]int)
//遍历所有数据
rows, _ := f.GetRows(s1.Title)
//当前年份
CurrentYear := time.Now().Year()
RedStyle, _ := f.GetCellStyle(s1.Title, Const.RedCell)
WhiteStyle, _ := f.GetCellStyle(s1.Title, Const.WhiteCell)
for i, row := range rows {
//放过表头
if i < ExcelUtil.HiddenRows+1 {
continue
}
//如果连续三个格为空,则不记入预导入行
if row[0] == "" && row[1] == "" && row[2] == "" {
continue
}
//真实显示的字段,不要把名称管理器的内容遍历出来
for j := 0; j < len(s1.Cols); j++ {
//必填写项目+值域检查
var pass = true
//(0)学部
if j == 0 {
//符合学部的Map
if _, ok := MapStage[row[j]]; !ok {
pass = false
}
}
//(1)入学年份
if j == 1 {
if row[j] == "" {
pass = false
} else {
//入学年份是不是数字
pattern := "\\d+" //反斜杠要转义
result, _ := regexp.MatchString(pattern, row[j])
if result {
//是不是与现在的所在年份在下6上1范围内
if CommonUtil.ConvertStringToInt(row[j]) < (CurrentYear-6) || CommonUtil.ConvertStringToInt(row[j]) > CurrentYear+1 {
pass = false
}
}
}
}
//(2)班号
if j == 2 {
if row[j] == "" {
pass = false
} else {
pattern := "\\d+" //反斜杠要转义
result, _ := regexp.MatchString(pattern, row[j])
if result {
if CommonUtil.ConvertStringToInt(row[j]) <= 0 || CommonUtil.ConvertStringToInt(row[j]) > 99 {
pass = false
} else {
if _, ok := MapClass[row[j-2]+"_"+row[j-1]+"_"+row[j]]; !ok {
pass = false
}
}
} else {
pass = false
}
}
}
//(3) 姓名
if j == 3 {
if row[j] == "" {
pass = false
}
}
//(4)性别
if j == 4 {
if row[j] != "男" && row[j] != "女" {
pass = false
}
}
//(5)出生日期
if j == 5 {
//是不是合法出生日期
if !DateUtil.CheckDateStr(row[j]) {
pass = false
}
//是合法日期
//尝试转一下整数
s := row[j]
_, err := strconv.Atoi(s)
if err == nil { //如果可以转为整数那么可能是距离1900-01-01的天数
row[j] = DateUtil.ConvertToFormatDay(row[j]) //转为合法日期格式
}
}
//(6)民族
if j == 6 {
if _, ok := SysDictKit.MapDictKindChineseToCode["mzm_"+row[j]]; !ok {
pass = false
}
}
//(7)政治面貌
if j == 7 {
if _, ok := SysDictKit.MapDictKindChineseToCode["zzmmm_"+row[j]]; !ok {
pass = false
}
}
//(8)身份证件类型
if j == 8 {
if _, ok := SysDictKit.MapDictKindChineseToCode["sfzjlxm_"+row[j]]; !ok {
pass = false
}
if row[j] == "" {
pass = true
}
}
//(9)身份证号
if j == 9 {
if row[j-1] == "居民身份证" && row[j] != "" && !CommonUtil.IsIdCard(CommonUtil.CompressStr(row[j])) {
pass = false
}
if len(row[j]) > 0 {
_idCardMap[CommonUtil.CompressStr(row[j])] = append(_idCardMap[CommonUtil.CompressStr(row[j])], i+1)
}
}
//(10)独生子女
if j == 10 {
row[j] = strings.Replace(row[j], " ", "", -1)
if _, ok := SysDictKit.MapTrueOrFalseNameToValue[row[j]]; !ok {
pass = false
}
}
//(11)随迁子女
if j == 11 {
row[j] = strings.Replace(row[j], " ", "", -1)
if _, ok := SysDictKit.MapTrueOrFalseNameToValue[row[j]]; !ok {
pass = false
}
}
//(12)务工子女
if j == 12 {
row[j] = strings.Replace(row[j], " ", "", -1)
if _, ok := SysDictKit.MapTrueOrFalseNameToValue[row[j]]; !ok {
pass = false
}
}
//(13)孤儿
if j == 13 {
row[j] = strings.Replace(row[j], " ", "", -1)
if _, ok := SysDictKit.MapTrueOrFalseNameToValue[row[j]]; !ok {
pass = false
}
}
//(14)留守儿童
if j == 14 {
row[j] = strings.Replace(row[j], " ", "", -1)
if _, ok := SysDictKit.MapTrueOrFalseNameToValue[row[j]]; !ok {
pass = false
}
}
//(15)残疾儿童
if j == 15 {
row[j] = strings.Replace(row[j], " ", "", -1)
if _, ok := SysDictKit.MapTrueOrFalseNameToValue[row[j]]; !ok {
pass = false
}
}
//标红
cName, _ := excelize.ColumnNumberToName(j + 1)
cell := cName + CommonUtil.ConvertIntToString(i+1)
nowStyle, _ := f.GetCellStyle(s1.Title, cell)
if !pass {
//红色
if nowStyle != RedStyle {
_ = f.SetCellStyle(s1.Title, cell, cell, RedStyle)
}
firstSuccess = false
} else {
if nowStyle != WhiteStyle {
_ = f.SetCellStyle(s1.Title, cell, cell, WhiteStyle)
}
}
}
}
//判断身份证号是不是在本EXCEL中存在重复如果存在需要进行标识
for _, rowArray := range _idCardMap {
//重复
if len(rowArray) > 1 {
for i := range rowArray {
cell := "J" + CommonUtil.ConvertIntToString(rowArray[i])
//重复
style, _ := f.GetCellStyle(s1.Title, Const.BlueCell)
_ = f.SetCellStyle(s1.Title, cell, cell, style)
}
firstSuccess = false
}
}
// 根据指定路径保存文件(不管是不是通过,都保存一次)
if err := f.SaveAs(excelPath); err != nil {
println(err.Error())
}
return firstSuccess
}
/**
功能将excel的内容读入到数据库的临时表中
作者:黄海
时间2020-06-18
*/
func readToTable(excelPath string, s1 ExcelUtil.TemplateStruct, MapClass map[string]string, bureauId string, batchId string, MapStage map[string]string) error {
var ms = make([]models.TBaseStudentImportExcel, 0)
f, _ := excelize.OpenFile(excelPath)
rows, _ := f.GetRows(s1.Title)
for i, row := range rows {
//放过第一行
if i < ExcelUtil.HiddenRows+1 {
continue
}
//如果连续三个格为空,则不记入预导入行
if row[0] == "" && row[1] == "" && row[2] == "" {
continue
}
//导入到临时表中
var m models.TBaseStudentImportExcel
//主键
m.Id = CommonUtil.GetUUID()
//学部
m.StageId = MapStage[row[0]]
//入学年份
m.Rxnf = int32(CommonUtil.ConvertStringToInt(row[1]))
//班号
m.Bh = int32(CommonUtil.ConvertStringToInt(row[2]))
//单位ID
m.BureauId = bureauId
//如果班级已存在那么保存上班级ID否则存入默认值
if _, ok := MapClass[row[0]+"_"+row[1]+"_"+row[2]]; ok {
m.ClassId = MapClass[row[0]+"_"+row[1]+"_"+row[2]]
} else {
m.ClassId = Const.ZeroGuid
}
//姓名
m.Xm = row[3]
//性别
if row[4] == "男" {
m.Xbm = "1"
} else {
m.Xbm = "2"
}
//出生日期
m.Csrq = DateUtil.ConvertDate(row[5])
//民族
m.Mzm = SysDictKit.MapDictKindChineseToCode["mzm_"+row[6]]
//政治面貌
m.Zzmmm = SysDictKit.MapDictKindChineseToCode["zzmmm_"+row[7]]
//身份证件类型
m.Sfzjlxm = SysDictKit.MapDictKindChineseToCode["sfzjlxm_"+row[8]]
//身份证件号
m.Sfzjh = CommonUtil.CompressStr(row[9])
//独生子女
m.Dszybz = int32(CommonUtil.ConvertStringToInt(SysDictKit.MapTrueOrFalseNameToValue[row[10]]))
//随迁子女
m.Sqznbz = int32(CommonUtil.ConvertStringToInt(SysDictKit.MapTrueOrFalseNameToValue[row[11]]))
//务工子女
m.Jcwgrysqznbz = int32(CommonUtil.ConvertStringToInt(SysDictKit.MapTrueOrFalseNameToValue[row[12]]))
//孤儿
m.Gebz = int32(CommonUtil.ConvertStringToInt(SysDictKit.MapTrueOrFalseNameToValue[row[13]]))
//留守儿童
m.Lsetbz = int32(CommonUtil.ConvertStringToInt(SysDictKit.MapTrueOrFalseNameToValue[row[14]]))
//残疾儿童
m.Cjbz = int32(CommonUtil.ConvertStringToInt(SysDictKit.MapTrueOrFalseNameToValue[row[15]]))
//批次号
m.BatchId = batchId
//人员ID
if len(row) == 17 {
m.PersonId = row[16]
} else {
m.PersonId = ""
}
//第几行的数据
m.RowNumber = int32(i + 1)
//添加到数组中
ms = append(ms, m)
}
_, err := db.Insert(ms)
return err
}
/**
功能:在临时表中检查身份证号的合法性,本次上传的身份证号,不能存在于系统中的其它单位
作者:黄海
时间2020-06-18
*/
func checkTempTable(excelPath string, s1 ExcelUtil.TemplateStruct, batchId string, bureauId string) bool {
//打开excel文件
f, _ := excelize.OpenFile(excelPath)
var success = true
/****************************************************************************/
//是否存在本次导入的身份证号与其它单位的已有身份证号相同,这样的不让导入,用蓝色标识出来
sql := `select t1.sfzjh,t2.row_number from t_base_teacher as t1
inner join t_base_student_import_excel as t2
on t1.sfzjh=t2.sfzjh
inner join t_base_teacher_org as t3
on t1.person_id=t3.person_id and t3.b_use=1 and t3.is_main=1
where t2.batch_id=? and t3.bureau_id<>? and t1.sfzjh<>''`
listIdCardTeacher, err := db.SQL(sql, batchId, bureauId).Query().List()
if err != nil {
LogUtil.Error(Const.DataBaseActionError, "在查询学生的身份证号重复时发生严重错误!")
return false
}
//存在教师身份证号检查重复
for i := range listIdCardTeacher {
rowNumber := listIdCardTeacher[i]["row_number"].(int64)
cell := "F" + CommonUtil.ConvertInt64ToString(rowNumber)
style, _ := f.GetCellStyle(s1.Title, Const.YellowCell)
_ = f.SetCellStyle(s1.Title, cell, cell, style)
//设计二级检查失败
success = false
}
/****************************************************************************/
//检查学生的身份证号重复
sql = `select t1.sfzjh,t2.row_number from t_base_student as t1 inner join t_base_student_import_excel as t2
on t1.sfzjh=t2.sfzjh where t2.batch_id=? and t1.bureau_id<>? and t1.sfzjh<>''`
listIdCardStudent, err := db.SQL(sql, batchId, bureauId).Query().List()
if err != nil {
LogUtil.Error(Const.DataBaseActionError, "在查询学生的身份证号重复时发生严重错误!")
return false
}
//存在学生身份证号检查重复
for i := range listIdCardStudent {
rowNumber := listIdCardStudent[i]["row_number"].(int64)
cell := "J" + CommonUtil.ConvertInt64ToString(rowNumber)
style, _ := f.GetCellStyle(s1.Title, Const.YellowCell)
_ = f.SetCellStyle(s1.Title, cell, cell, style)
//设计二级检查失败
success = false
}
/****************************************************************************/
// 根据指定路径保存文件(不管是不是通过,都保存一次)
if err := f.SaveAs(excelPath); err != nil {
println(err.Error())
}
return success
}
/**
功能:插入学生
*/
func insertStudent(batchId string, bureauModel models.TBaseOrganization, actionPersonId string, actionIp string) (int, string, error) {
//新增学生
studentImportExcelArray := make([]models.TBaseStudentImportExcel, 0)
studentArray := make([]models.TBaseStudent, 0)
_ = db.Where("batch_id=? and length(person_id)=0", batchId).Find(&studentImportExcelArray)
for i := range studentImportExcelArray {
r1 := studentImportExcelArray[i]
var model models.TBaseStudent
//所在班级
model.ClassId = r1.ClassId
//人员编号
model.PersonId = CommonUtil.GetUUID()
//单位
model.BureauId = bureauModel.BureauId
//导入即可用
model.BUse = 1
//身份证号
model.Sfzjh = r1.Sfzjh
//身份证件类型
model.Sfzjlxm = r1.Sfzjlxm
//所属省份
model.ProvinceCode = bureauModel.ProvinceCode
//所属城市
model.CityCode = bureauModel.CityCode
//县区
model.DistrictCode = bureauModel.DistrictCode
//主校
model.MainSchoolId = bureauModel.MainSchoolId
//出生日期与性别
if model.Sfzjlxm == "1" {
//根据身份证号,提取男女,出生日期
isValid, birthday, xbm := IdCardUtil.GetIdCardNoInfo(r1.Sfzjh)
if isValid {
model.Csrq = DateUtil.ConvertDate(birthday)
model.Xbm = xbm
} else {
model.Csrq = r1.Csrq
model.Xbm = r1.Xbm
}
} else {
model.Csrq = r1.Csrq
model.Xbm = r1.Xbm
}
//民族
model.Mzm = r1.Mzm
//姓名
model.Xm = r1.Xm
//曾用名
model.Cym = model.Xm
//姓名拼音
model.Xmpy = PinYinUtil.PinYin(model.Xm)
//政治面貌
model.Zzmmm = r1.Zzmmm
//状态
model.StateId = 1
//独生子女
model.Dszybz = r1.Dszybz
//随迁子女
model.Sqznbz = r1.Sqznbz
//务工子女
model.Jcwgrysqznbz = r1.Jcwgrysqznbz
//孤儿
model.Gebz = r1.Gebz
//留守儿童
model.Lsetbz = r1.Lsetbz
//残疾儿童
model.Cjbz = r1.Cjbz
//添加到数组中
studentArray = append(studentArray, model)
}
//批量插入
if len(studentArray) > 0 {
_, err := db.Insert(&studentArray)
if err != nil {
return 0, Const.DataBaseActionError, err
}
//生成日志
ActionLog(studentArray, Const.ActionInsert, actionPersonId, actionIp)
//产生登录名
accountArray := SysLoginpersonService.GenerateLoginAccount(3, int64(len(studentImportExcelArray)))
var loginpersonModels = make([]models.TSysLoginperson, 0)
for i := range studentArray {
//调用dao
model := new(models.TSysLoginperson)
model.Id = CommonUtil.GetUUID()
model.LoginName = accountArray[i].LoginName
model.Pwd = accountArray[i].Pwd
model.OriginalPwd = accountArray[i].OriginalPwd
model.IdentityId = 3
model.PersonId = studentArray[i].PersonId
model.PersonName = studentArray[i].Xm
model.BUse = 1
loginpersonModels = append(loginpersonModels, *model)
}
//批量插入
if len(loginpersonModels) > 0 {
_, err = db.Insert(&loginpersonModels)
if err != nil {
return 0, Const.DataBaseActionError, err
}
}
/*生成家长及账号*/
for i := range studentArray {
model := studentArray[i]
//为学生创建对应的家长
modelParent := new(models.TBaseParent)
modelParent.PersonId = CommonUtil.GetUUID()
modelParent.Xm = model.Xm + "家长"
modelParent.Lxdh = "-1"
modelParent.StudentId = model.PersonId
modelParent.ClassId = model.ClassId
modelParent.BureauId = model.BureauId
modelParent.ProvinceCode = model.ProvinceCode
modelParent.CityCode = model.CityCode
modelParent.DistrictCode = model.DistrictCode
modelParent.MainSchoolId = model.MainSchoolId
modelParent.BUse = 1
_, err = BaseParentDao.AddBaseParent(*modelParent)
if err != nil {
return 0, Const.DataBaseActionError, err
}
//为家长创建账号
_, err = SysLoginpersonService.AddLoginperson(4, modelParent.PersonId, modelParent.Xm)
if err != nil {
return 0, Const.DataBaseActionError, err
}
}
return len(studentArray), "保存成功", nil
}
return 0, "没有记录需要进行保存", nil
}
/**
功能:更新导入的学生
*/
func updateStudentImport(batchId string, bureauModel models.TBaseOrganization, actionPersonId string, actionIp string) (int, string, error) {
//准备身份证号与人员id的映射map
sql := `select t1.person_id,t1.sfzjh from t_base_student as t1 inner join t_base_student_import_excel as t2
on t1.sfzjh=t2.sfzjh where t2.batch_id=?`
list, _ := db.SQL(sql, batchId).Query().List()
var MapSfzjh = make(map[string]string)
for i := range list {
MapSfzjh[list[i]["sfzjh"].(string)] = list[i]["person_id"].(string)
}
//开始
studentImportExcelArray := make([]models.TBaseStudentImportExcel, 0)
studentArray := make([]models.TBaseStudent, 0)
_ = db.Where("batch_id=? and length(person_id)=36", batchId).Find(&studentImportExcelArray)
//准备更新的数据
for i := range studentImportExcelArray {
r1 := studentImportExcelArray[i]
var model models.TBaseStudent
//人员编号
model.PersonId = MapSfzjh[r1.Sfzjh] //通过身份证件号反向获取到人员的id
//班级ID
model.ClassId = r1.ClassId
//单位
model.BureauId = bureauModel.BureauId
//导入即可用
model.BUse = 1
//身份证号
model.Sfzjh = r1.Sfzjh
//身份证件类型
model.Sfzjlxm = r1.Sfzjlxm
//所属省份
model.ProvinceCode = bureauModel.ProvinceCode
//所属城市
model.CityCode = bureauModel.CityCode
//县区
model.DistrictCode = bureauModel.DistrictCode
//主校
model.MainSchoolId = bureauModel.MainSchoolId
//出生日期与性别
if model.Sfzjlxm == "1" {
//根据身份证号,提取男女,出生日期
_, birthday, xbm := IdCardUtil.GetIdCardNoInfo(r1.Sfzjh)
model.Csrq = DateUtil.ConvertDate(birthday)
model.Xbm = xbm
} else {
//如果不是身份证号,那就用个默认值吧
model.Csrq = DateUtil.ConvertDate("1977-10-11")
model.Xbm = "1"
}
//排序号
//model.SortId = 1 //排序号就不修改了,防止人为修改对了,这样导入再修改回去
//姓名
model.Xm = r1.Xm
//曾用名
model.Cym = model.Xm
//姓名拼音
model.Xmpy = PinYinUtil.PinYin(model.Xm)
//民族
model.Mzm = r1.Mzm
//政治面貌
model.Zzmmm = r1.Zzmmm
//状态
model.StateId = 1
//独生子女
model.Dszybz = r1.Dszybz
//随迁子女
model.Sqznbz = r1.Sqznbz
//务工子女
model.Jcwgrysqznbz = r1.Jcwgrysqznbz
//孤儿
model.Gebz = r1.Gebz
//留守儿童
model.Lsetbz = r1.Lsetbz
//残疾儿童
model.Cjbz = r1.Cjbz
//添加到数组中
studentArray = append(studentArray, model)
}
//批量更新
if len(studentArray) > 0 {
//声明事务
session := db.NewSession()
defer func() {
err := session.Close()
if err != nil {
fmt.Println(err.Error())
}
}()
_ = session.Begin()
for k := range studentArray {
_, err := session.Where("person_id=?", studentArray[k].PersonId).Update(studentArray[k])
if err != nil {
_ = session.Rollback()
return 0, Const.DataBaseActionError, err
}
}
//事务提交
err := session.Commit()
if err != nil {
return 0, Const.DataBaseActionError, err
}
//生成日志
var studentIds = make([]string, 0)
for i := range studentArray {
studentIds = append(studentIds, studentArray[i].PersonId)
}
ms, err := GetByIds(studentIds)
ActionLog(ms, Const.ActionUpdate, actionPersonId, actionIp)
//删除缓存
for i := range studentArray {
key := SqlKit.GetBean("t_base_student").RedisPrefix + studentArray[i].PersonId
RedisUtil.DEL(key)
}
return len(studentArray), "保存成功", nil
}
return 0, "没有记录需要保存", nil
}
//通过学生的IDS获取到对应家长的IDS
func GetParentIds(studentIds []string) ([]string, error) {
var myBuilder = builder.Dialect(builder.MYSQL).Select("person_id").From("t_base_parent")
myBuilder.Where(builder.In("student_id", studentIds)).And(builder.Eq{"b_use": 1})
sql, err := myBuilder.ToBoundSQL()
if err != nil {
return nil, err
}
list, err := db.SQL(sql).Query().List()
if err != nil {
return nil, err
}
var parentIds = make([]string, 0)
for i := range list {
parentIds = append(parentIds, list[i]["person_id"].(string))
}
return parentIds, nil
}
//学生的调转
func StudentTransfer(personId string, classId string) (bool, string, error) {
//1、获取班级信息
list := SqlKit.QueryByIds([]string{classId}, "t_base_class")
if list == nil || len(list) == 0 {
return false, "没有找到指定的班级信息", errors.New("没有找到指定的班级信息")
}
//单位ID
bureauId := list[0]["bureau_id"].(string)
_, provinceCode, cityCode, districtCode, mainSchoolId, _ := BaseOrganizationDao.GetBureauAdministrativeDivision(bureauId)
//2、修改学生信息
sql := `update t_base_student set bureau_id=?,class_id=?,province_code=?,city_code=?,district_code=?,main_school_id=? where person_id=? and b_use=1`
_, err := db.SQL(sql, bureauId, classId, provinceCode, cityCode, districtCode, mainSchoolId, personId).Execute()
fmt.Println(err)
//3、修改家长信息
sql = `update t_base_parent set bureau_id=?,class_id=?,province_code=?,city_code=?,district_code=?,main_school_id=? where student_id=? and b_use=1`
_, _ = db.SQL(sql, bureauId, classId, provinceCode, cityCode, districtCode, mainSchoolId, personId).Execute()
return true, "保存成功", nil
}