private void UploadWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List <JHSemesterScoreRecord> list = e.Argument as List <JHSemesterScoreRecord>;
            int total = list.Count;

            if (total == 0)
            {
                return;
            }
            int count = 0;

            foreach (JHSemesterScoreRecord record in list)
            {
                count++;
                //editor.Save();
                if (string.IsNullOrEmpty(record.ID))
                {
                    JHSemesterScore.Insert(record);
                }
                else
                {
                    JHSemesterScore.Update(record);
                }

                _upload_worker.ReportProgress((int)((double)count * 100 / (double)total), "上傳學期成績…");
            }
        }
Ejemplo n.º 2
0
        public static void Main()
        {
            Global.Params = ModuleLoader.GetDeployParametsers(typeof(Program), "Mode=KaoHsiung");

            //學生學期成績
            string key = "JHSchool.Student.Detail0050";

            if (FISCA.Permission.UserAcl.Current[key].Editable || FISCA.Permission.UserAcl.Current[key].Viewable)
            {
                K12.Presentation.NLDPanels.Student.AddDetailBulider(new DetailBulider <SemesterScoreItem>());
            }

            JHSchool.SF.Evaluation.SemesterScoreEditor.RegisterHandler(delegate(string studentId)
            {
                SemesterScoreEditor form;
                form = new SemesterScoreEditor(JHStudent.SelectByID(studentId));
                return(form.ShowDialog());
            });
            JHSchool.SF.Evaluation.SemesterScoreEditor.RegisterHandler(delegate(string studentId, int schoolYear, int semester)
            {
                SemesterScoreEditor form;
                form = new SemesterScoreEditor(JHStudent.SelectByID(studentId), JHSemesterScore.SelectBySchoolYearAndSemester(studentId, schoolYear, semester));
                return(form.ShowDialog());
            });
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 載入多筆學生學期成績(依學年度學期篩選)(一般生)
        /// </summary>
        /// <param name="SchoolYear"></param>
        /// <param name="Semester"></param>
        /// <param name="StudentIDList"></param>
        public static void LoadSemesterScoreRecord(int SchoolYear, int Semester, List <string> ClassIDList, List <string> notRankStudentIDList)
        {
            _ClassStudCount.Clear();
            List <JHClassRecord> ClassRecList  = JHClass.SelectByIDs(ClassIDList);
            List <string>        StudentIDList = new List <string>();

            foreach (JHClassRecord ClassRec in ClassRecList)
            {
                foreach (JHStudentRecord studRec in ClassRec.Students)
                {
                    if (studRec.Status == K12.Data.StudentRecord.StudentStatus.一般 && !notRankStudentIDList.Contains(studRec.ID))//剔除不排名學生
                    {
                        StudentIDList.Add(studRec.ID);

                        if (_ClassStudCount.ContainsKey(studRec.Class.ID))
                        {
                            _ClassStudCount[studRec.Class.ID]++;
                        }
                        else
                        {
                            _ClassStudCount.Add(studRec.Class.ID, 1);
                        }
                    }
                }
            }

            // 取得多筆學生學年度學期成績
            _SemesterScoreRecordList = JHSemesterScore.SelectBySchoolYearAndSemester(StudentIDList, SchoolYear, Semester);
        }
Ejemplo n.º 4
0
        private void updateSemesterSubjectScore(object item)
        {
            List <List <JHSemesterScoreRecord> > updatePackages = (List <List <JHSemesterScoreRecord> >)item;

            foreach (List <JHSemesterScoreRecord> package in updatePackages)
            {
                JHSemesterScore.Update(package);
            }
        }
Ejemplo n.º 5
0
        private void insertSemesterSubjectScore(object item)
        {
            List <List <JHSemesterScoreRecord> > insertPackages = (List <List <JHSemesterScoreRecord> >)item;

            foreach (List <JHSemesterScoreRecord> package in insertPackages)
            {
                JHSemesterScore.Insert(package);
            }
        }
Ejemplo n.º 6
0
        public QuickInputSemesterScoreForm(JHStudentRecord student)
            : this()
        {
            _student = student;
            JHScoreCalcRuleRecord record = student.ScoreCalcRule;

            _calculator = new ScoreCalculator(record);
            _util       = new SemesterHistoryUtility(JHSemesterHistory.SelectByStudentID(student.ID));
            _semesterScoreRecordList = JHSemesterScore.SelectByStudentID(_student.ID);

            errorProvider.SetError(cboSchoolYear, "無效的學年度");
            errorProvider.SetError(cboSemester, "無效的學期");
        }
Ejemplo n.º 7
0
        public Form1()
        {
            InitializeComponent();

            FISCA.Authentication.DSAServices.SetLicense("SmartSchoolLicense.key");
            FISCA.Authentication.DSAServices.Login("adrnin", "1234");

            Student = JHStudent.SelectByID("147285");
            listBox1.DisplayMember = "SchoolYear";
            foreach (var record in JHSemesterScore.SelectByStudentID(Student.ID))
            {
                listBox1.Items.Add(record);
            }
        }
        private List <JHSemesterScoreRecord> ReadSemesterScore()
        {
            List <string> studIds = Students.Values.ToKeys();
            FunctionSpliter <string, JHSemesterScoreRecord> spliter = new FunctionSpliter <string, JHSemesterScoreRecord>(100, Util.MaxThread);

            spliter.Function = delegate(List <string> studIdPart)
            {
                return(JHSemesterScore.SelectBySchoolYearAndSemester(studIdPart, null, null));
            };
            spliter.ProgressChange = delegate(int progress)
            {
                Reporter.Feedback("讀取學期成績資料...", Util.CalculatePercentage(studIds.Count, progress));
            };
            return(spliter.Execute(studIds));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 取得學生學期成績
        /// </summary>
        /// <param name="utilCache"></param>
        /// <returns></returns>
        private Dictionary <string, StudentScores> GetStudentScores(Dictionary <string, HistoryUtil> utilCache)
        {
            Dictionary <string, StudentScores> scores = new Dictionary <string, StudentScores>();

            foreach (JHSemesterScoreRecord scoreRecord in JHSemesterScore.SelectByStudentIDs(AllStudentID))
            {
                if (!scores.ContainsKey(scoreRecord.RefStudentID))
                {
                    StudentScores studentScores = new StudentScores(utilCache[scoreRecord.RefStudentID]);
                    scores.Add(scoreRecord.RefStudentID, studentScores);
                }
                scores[scoreRecord.RefStudentID].Add(scoreRecord);
            }
            return(scores);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// (Network Access)將目前學期的資料填入到 Courses、SCAttends 變數中。
        /// </summary>
        private void FillCurrentSemesterData()
        {
            SemesterScores = new Dictionary <string, JHSemesterScoreRecord>();
            List <JHSemesterScoreRecord> records = JHSemesterScore.SelectBySchoolYearAndSemester(Students.ToKeys(), Sems.SelectedSchoolYear, Sems.SelectedSemester);

            foreach (JHSemesterScoreRecord each in records)
            {
                if (SemesterScores.ContainsKey(each.RefStudentID))
                {
                    throw new ArgumentException(string.Format("學生編號{0},同一學期有兩筆成績?", each.RefStudentID));
                }

                SemesterScores.Add(each.RefStudentID, each);
            }
        }
Ejemplo n.º 11
0
        public SemesterScoreItem()
        {
            InitializeComponent();
            InitializeQuickAddButton();

            _domainList = new List <string>();
            InitializeColumnHeader();

            UserPermission = Framework.User.Acl[FCode.GetCode(GetType())];

            btnAdd.Visible    = UserPermission.Editable;
            btnModify.Visible = UserPermission.Editable;
            btnDelete.Visible = UserPermission.Editable;
            btnView.Visible   = UserPermission.Viewable & !UserPermission.Editable;

            _worker         = new BackgroundWorker();
            _worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                if (_student == null)
                {
                    _student = JHStudent.SelectByID("" + e.Argument);
                }
                else if (_student.ID != "" + e.Argument)
                {
                    _student = JHStudent.SelectByID("" + e.Argument);
                }

                e.Result = JHSemesterScore.SelectByStudentID("" + e.Argument);
            };
            _worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                if (_RunningID != PrimaryKey)
                {
                    _RunningID = PrimaryKey;
                    _worker.RunWorkerAsync(_RunningID);
                    return;
                }

                _recordList = e.Result as List <JHSemesterScoreRecord>;
                FillListView();
            };

            FISCA.InteractionService.SubscribeEvent("CalculationHelper.SaveSemesterScore", (sender, args) => {
                AfterSaveSemesterScore();
            });
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 取得領域成績並判斷是否及格
        /// </summary>
        /// <param name="studDataList"></param>
        /// <param name="SchoolYear"></param>
        /// <param name="Semester"></param>
        /// <param name="passScore"></param>
        /// <returns></returns>
        public static List <StudentData> CalcStudDomainScorePass(List <StudentData> studDataList, int SchoolYear, int Semester, decimal passScore)
        {
            // 取得學期成績
            Dictionary <string, JHSemesterScoreRecord> studSemsScoreDict = new Dictionary <string, JHSemesterScoreRecord>();
            List <string> studIDList = (from data in studDataList select data.StudentID).ToList();
            List <JHSemesterScoreRecord> semsScoreList = JHSemesterScore.SelectByStudentIDs(studIDList);

            foreach (JHSemesterScoreRecord rec in semsScoreList)
            {
                if (rec.SchoolYear == SchoolYear && rec.Semester == Semester)
                {
                    if (!studSemsScoreDict.ContainsKey(rec.RefStudentID))
                    {
                        studSemsScoreDict.Add(rec.RefStudentID, rec);
                    }
                }
            }

            // 判斷學生領域成績是否及格
            foreach (StudentData sd in studDataList)
            {
                if (studSemsScoreDict.ContainsKey(sd.StudentID))
                {
                    sd.StudSemesterScoreRecord = studSemsScoreDict[sd.StudentID];
                    foreach (DomainScore ds in studSemsScoreDict[sd.StudentID].Domains.Values)
                    {
                        if (!sd.DomainScorePassDict.ContainsKey(ds.Domain))
                        {
                            sd.DomainScorePassDict.Add(ds.Domain, false);
                            sd.DomainScoreDict.Add(ds.Domain, 0);
                        }


                        if (ds.Score.HasValue)
                        {
                            sd.DomainScoreDict[ds.Domain] = ds.Score.Value;
                            if (ds.Score.Value >= passScore)
                            {
                                sd.DomainScorePassDict[ds.Domain] = true;
                            }
                        }
                    }
                }
            }
            return(studDataList);
        }
        public void ExecuteAutoCorrect(IEnumerable <string> EntityIDs)
        {
            try
            {
                if (!K12.Data.Utility.Utility.IsNullOrEmpty(EntityIDs))
                {
                    if (MsgBox.Show("自動修正將依照檢查結果建議值進行修正總共" + EntityIDs.Count() + "筆,強烈建議您務必將檢查結果匯出備份,是否進行自動修正?", "您是否要進行自動修正?", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        StringBuilder strBuilder = new StringBuilder(1024 * 1024);
                        List <string> LogValues  = new List <string>();

                        strBuilder.AppendLine("學號,狀態,學年度,學期" + Environment.NewLine);

                        foreach (JHSemesterScoreRecord sems in CorrectableRecs)
                        {
                            if (EntityIDs.Contains(sems.ID))
                            {
                                LogValues.Add(sems.Student.StudentNumber);
                                LogValues.Add(sems.Student.StatusStr);
                                LogValues.Add("" + sems.SchoolYear);
                                LogValues.Add("" + sems.Semester);
                                strBuilder.AppendLine(string.Join(",", LogValues.ToArray()));
                                LogValues.Clear();
                            }
                        }

                        FISCA.LogAgent.ApplicationLog.Log("資料合理性檢查.學生學期科目與領域成績有空值", "刪除學生學期科目與領域成績有空值", strBuilder.ToString());
                        JHSemesterScore.Delete(EntityIDs);
                        MsgBox.Show("已自動修正完成!");
                    }
                }
            }
            catch (Exception e)
            {
                SmartSchool.ErrorReporting.ReportingService.ReportException(e);

                MsgBox.Show(e.Message);
            }
        }
Ejemplo n.º 14
0
        //刪除
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count <= 0)
            {
                return;
            }
            ListViewItem item = listView.SelectedItems[0];

            string info = string.Format("{0}學年度 第{1}學期", item.SubItems[0].Text, item.SubItems[1].Text);

            if (Framework.MsgBox.Show("您確定要刪除「" + item.SubItems[0].Text + "學年度 第" + item.SubItems[1].Text + "學期」的學期成績嗎?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                JHSemesterScoreRecord record = item.Tag as JHSemesterScoreRecord;
                JHSemesterScore.Delete(record);
                FISCA.LogAgent.ApplicationLog.Log("成績系統.學期成績", "刪除學期成績", "student", PrimaryKey, string.Format("{0},刪除「{1}」的學期成績", StudentInfoConvertor.GetInfoWithClass(_student), info));

                listView.Items.Remove(listView.SelectedItems[0]);
                listView.Refresh();
            }

            listView.Focus();
        }
Ejemplo n.º 15
0
        public override void InitializeImport(SmartSchool.API.PlugIn.Import.ImportWizard wizard)
        {
            Dictionary <string, int>             _ID_SchoolYear_Semester_GradeYear = new Dictionary <string, int>();
            Dictionary <string, List <string> >  _ID_SchoolYear_Semester_Subject   = new Dictionary <string, List <string> >();
            Dictionary <string, JHStudentRecord> _StudentCollection = new Dictionary <string, JHStudentRecord>();
            Dictionary <JHStudentRecord, Dictionary <int, decimal> > _StudentPassScore = new Dictionary <JHStudentRecord, Dictionary <int, decimal> >();
            Dictionary <string, List <JHSemesterScoreRecord> >       semsDict          = new Dictionary <string, List <JHSemesterScoreRecord> >();

            wizard.PackageLimit = 3000;
            //wizard.ImportableFields.AddRange("領域", "科目", "學年度", "學期", "權數", "節數", "分數評量", "努力程度", "文字描述", "註記");
            //wizard.ImportableFields.AddRange("領域", "科目", "學年度", "學期", "權數", "節數", "分數評量", "文字描述", "註記");

            //2015.1.27 Cloud新增
            wizard.ImportableFields.AddRange("領域", "科目", "學年度", "學期", "權數", "節數", "成績", "原始成績", "補考成績", "努力程度", "文字描述", "註記");

            wizard.RequiredFields.AddRange("領域", "科目", "學年度", "學期");

            wizard.ValidateStart += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateStartEventArgs e)
            {
                #region ValidateStart
                _ID_SchoolYear_Semester_GradeYear.Clear();
                _ID_SchoolYear_Semester_Subject.Clear();
                _StudentCollection.Clear();

                List <JHStudentRecord> list = JHStudent.SelectByIDs(e.List);

                MultiThreadWorker <JHStudentRecord> loader = new MultiThreadWorker <JHStudentRecord>();
                loader.MaxThreads     = 3;
                loader.PackageSize    = 250;
                loader.PackageWorker += delegate(object sender1, PackageWorkEventArgs <JHStudentRecord> e1)
                {
                    foreach (var item in JHSemesterScore.SelectByStudents(e1.List))
                    {
                        if (!semsDict.ContainsKey(item.RefStudentID))
                        {
                            semsDict.Add(item.RefStudentID, new List <JHSchool.Data.JHSemesterScoreRecord>());
                        }
                        semsDict[item.RefStudentID].Add(item);
                    }
                };
                loader.Run(list);

                foreach (JHStudentRecord stu in list)
                {
                    if (!_StudentCollection.ContainsKey(stu.ID))
                    {
                        _StudentCollection.Add(stu.ID, stu);
                    }
                }
                #endregion
            };
            wizard.ValidateRow += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateRowEventArgs e)
            {
                #region ValidateRow
                int             t;
                decimal         d;
                JHStudentRecord student;
                if (_StudentCollection.ContainsKey(e.Data.ID))
                {
                    student = _StudentCollection[e.Data.ID];
                }
                else
                {
                    e.ErrorMessage = "壓根就沒有這個學生" + e.Data.ID;
                    return;
                }
                bool inputFormatPass = true;
                #region 驗各欄位填寫格式
                foreach (string field in e.SelectFields)
                {
                    string value = e.Data[field];
                    switch (field)
                    {
                    default:
                        break;

                    case "領域":
                        //if (value == "")
                        //{
                        //    inputFormatPass &= false;
                        //    e.ErrorFields.Add(field, "必須填寫");
                        //}
                        //else if (!Domains.Contains(value))
                        //{
                        //    inputFormatPass &= false;
                        //    e.ErrorFields.Add(field, "必須為七大領域");
                        //}
                        break;

                    case "科目":
                        if (value == "")
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填寫");
                        }
                        break;

                    case "學年度":
                        if (value == "" || !int.TryParse(value, out t))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入學年度");
                        }
                        break;

                    case "權數":
                    case "節數":
                        if (value == "" || !decimal.TryParse(value, out d))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入數值");
                        }
                        break;

                    //case "成績年級":
                    //    if (value == "" || !int.TryParse(value, out t))
                    //    {
                    //        inputFormatPass &= false;
                    //        e.ErrorFields.Add(field, "必須填入整數");
                    //    }
                    //    break;
                    case "學期":
                        if (value == "" || !int.TryParse(value, out t) || t > 2 || t < 1)
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入1或2");
                        }
                        break;

                    //case "分數評量":
                    //    if (value != "" && !decimal.TryParse(value, out d))
                    //    {
                    //        inputFormatPass &= false;
                    //        e.ErrorFields.Add(field, "必須填入空白或數值");
                    //    }
                    //    break;
                    case "成績":
                        if (value != "" && !decimal.TryParse(value, out d))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入空白或數值");
                        }
                        break;

                    case "原始成績":
                        if (value != "" && !decimal.TryParse(value, out d))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入空白或數值");
                        }
                        break;

                    case "補考成績":
                        if (value != "" && !decimal.TryParse(value, out d))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入空白或數值");
                        }
                        break;
                        //case "努力程度":
                        //    if (value != "" && !int.TryParse(value, out t))
                        //    {
                        //        inputFormatPass &= false;
                        //        e.ErrorFields.Add(field, "必須填入空白或數值");
                        //    }
                        //    break;
                    }
                }
                #endregion
                //輸入格式正確才會針對情節做檢驗
                if (inputFormatPass)
                {
                    string errorMessage = "";

                    string subject    = e.Data["科目"];
                    string schoolYear = e.Data["學年度"];
                    string semester   = e.Data["學期"];
                    int?   sy         = null;
                    int?   se         = null;
                    if (int.TryParse(schoolYear, out t))
                    {
                        sy = t;
                    }
                    if (int.TryParse(semester, out t))
                    {
                        se = t;
                    }
                    if (sy != null && se != null)
                    {
                        string key = e.Data.ID + "_" + sy + "_" + se;
                        #region 驗證新增科目成績
                        List <JHSemesterScoreRecord> semsList;
                        if (semsDict.ContainsKey(student.ID))
                        {
                            semsList = semsDict[student.ID];
                        }
                        else
                        {
                            semsList = new List <JHSemesterScoreRecord>();
                        }
                        foreach (JHSemesterScoreRecord record in semsList)
                        {
                            if (record.SchoolYear != sy)
                            {
                                continue;
                            }
                            if (record.Semester != se)
                            {
                                continue;
                            }

                            bool   isNewSubjectInfo = true;
                            string message          = "";
                            foreach (K12.Data.SubjectScore s in record.Subjects.Values)
                            {
                                if (s.Subject == subject)
                                {
                                    isNewSubjectInfo = false;
                                }
                            }
                            if (isNewSubjectInfo)
                            {
                                if (!e.WarningFields.ContainsKey("查無此科目"))
                                {
                                    e.WarningFields.Add("查無此科目", "學生在此學期並無此筆科目成績資訊,將會新增此科目成績");
                                }
                                foreach (string field in new string[] { "領域", "科目", "學年度", "學期", "權數", "節數" })
                                {
                                    if (!e.SelectFields.Contains(field))
                                    {
                                        message += (message == "" ? "發現此學期無此科目,\n將會新增成績\n缺少成績必要欄位" : "、") + field;
                                    }
                                }
                                if (message != "")
                                {
                                    errorMessage += (errorMessage == "" ? "" : "\n") + message;
                                }
                            }
                        }
                        #endregion
                        #region 驗證重複科目資料
                        //string skey = subject + "_" + le;
                        string skey = subject;
                        if (!_ID_SchoolYear_Semester_Subject.ContainsKey(key))
                        {
                            _ID_SchoolYear_Semester_Subject.Add(key, new List <string>());
                        }
                        if (_ID_SchoolYear_Semester_Subject[key].Contains(skey))
                        {
                            errorMessage += (errorMessage == "" ? "" : "\n") + "同一學期不允許多筆相同科目的資料";
                        }
                        else
                        {
                            _ID_SchoolYear_Semester_Subject[key].Add(skey);
                        }
                        #endregion
                    }
                    e.ErrorMessage = errorMessage;
                }
                #endregion
            };

            wizard.ImportPackage += delegate(object sender, SmartSchool.API.PlugIn.Import.ImportPackageEventArgs e)
            {
                #region ImportPackage
                Dictionary <string, List <RowData> > id_Rows = new Dictionary <string, List <RowData> >();
                #region 分包裝
                foreach (RowData data in e.Items)
                {
                    if (!id_Rows.ContainsKey(data.ID))
                    {
                        id_Rows.Add(data.ID, new List <RowData>());
                    }
                    id_Rows[data.ID].Add(data);
                }
                #endregion
                //List<SmartSchool.Feature.Score.AddScore.InsertInfo> insertList = new List<SmartSchool.Feature.Score.AddScore.InsertInfo>();
                //List<SmartSchool.Feature.Score.EditScore.UpdateInfo> updateList = new List<SmartSchool.Feature.Score.EditScore.UpdateInfo>();
                List <JHSemesterScoreRecord> insertList = new List <JHSemesterScoreRecord>();
                List <JHSemesterScoreRecord> updateList = new List <JHSemesterScoreRecord>();
                //交叉比對各學生資料
                #region 交叉比對各學生資料
                foreach (string id in id_Rows.Keys)
                {
                    XmlDocument     doc        = new XmlDocument();
                    JHStudentRecord studentRec = _StudentCollection[id];
                    //該學生的學期科目成績
                    Dictionary <SemesterInfo, JHSemesterScoreRecord> semesterScoreDictionary = new Dictionary <SemesterInfo, JHSemesterScoreRecord>();
                    #region 整理現有的成績資料
                    List <JHSchool.Data.JHSemesterScoreRecord> semsList;
                    if (semsDict.ContainsKey(studentRec.ID))
                    {
                        semsList = semsDict[studentRec.ID];
                    }
                    else
                    {
                        semsList = new List <JHSchool.Data.JHSemesterScoreRecord>();
                    }
                    foreach (JHSemesterScoreRecord var in semsList)
                    {
                        SemesterInfo info = new SemesterInfo();
                        info.SchoolYear = var.SchoolYear;
                        info.Semester   = var.Semester;

                        if (!semesterScoreDictionary.ContainsKey(info))
                        {
                            semesterScoreDictionary.Add(info, var);
                        }

                        //string key = var.Subject + "_" + var.Level;
                        //if (!semesterScoreDictionary.ContainsKey(var.SchoolYear))
                        //    semesterScoreDictionary.Add(var.SchoolYear, new Dictionary<int, Dictionary<string, SemesterSubjectScoreInfo>>());
                        //if (!semesterScoreDictionary[var.SchoolYear].ContainsKey(var.Semester))
                        //    semesterScoreDictionary[var.SchoolYear].Add(var.Semester, new Dictionary<string, SemesterSubjectScoreInfo>());
                        //if (!semesterScoreDictionary[var.SchoolYear][var.Semester].ContainsKey(key))
                        //    semesterScoreDictionary[var.SchoolYear][var.Semester].Add(key, var);
                    }
                    #endregion

                    //要匯入的學期科目成績
                    Dictionary <SemesterInfo, Dictionary <string, RowData> > semesterImportScoreDictionary = new Dictionary <SemesterInfo, Dictionary <string, RowData> >();

                    #region 整理要匯入的資料
                    foreach (RowData row in id_Rows[id])
                    {
                        int    t;
                        string subject    = row["科目"];
                        string schoolYear = row["學年度"];
                        string semester   = row["學期"];
                        int    sy         = int.Parse(schoolYear);
                        int    se         = int.Parse(semester);

                        SemesterInfo info = new SemesterInfo();
                        info.SchoolYear = sy;
                        info.Semester   = se;

                        if (!semesterImportScoreDictionary.ContainsKey(info))
                        {
                            semesterImportScoreDictionary.Add(info, new Dictionary <string, RowData>());
                        }
                        if (!semesterImportScoreDictionary[info].ContainsKey(subject))
                        {
                            semesterImportScoreDictionary[info].Add(subject, row);
                        }
                    }
                    #endregion

                    //學期年級重整
                    //Dictionary<SemesterInfo, int> semesterGradeYear = new Dictionary<SemesterInfo, int>();
                    //要變更成績的學期
                    List <SemesterInfo> updatedSemester = new List <SemesterInfo>();
                    //在變更學期中新增加的成績資料
                    Dictionary <SemesterInfo, List <RowData> > updatedNewSemesterScore = new Dictionary <SemesterInfo, List <RowData> >();
                    //要增加成績的學期
                    Dictionary <SemesterInfo, List <RowData> > insertNewSemesterScore = new Dictionary <SemesterInfo, List <RowData> >();
                    //開始處理ImportScore
                    #region 開始處理ImportScore
                    foreach (SemesterInfo info in semesterImportScoreDictionary.Keys)
                    {
                        foreach (string subject in semesterImportScoreDictionary[info].Keys)
                        {
                            RowData data = semesterImportScoreDictionary[info][subject];
                            //如果是本來沒有這筆學期的成績就加到insertNewSemesterScore
                            if (!semesterScoreDictionary.ContainsKey(info))
                            {
                                if (!insertNewSemesterScore.ContainsKey(info))
                                {
                                    insertNewSemesterScore.Add(info, new List <RowData>());
                                }
                                insertNewSemesterScore[info].Add(data);
                            }
                            else
                            {
                                bool hasChanged = false;
                                //修改已存在的資料
                                if (semesterScoreDictionary[info].Subjects.ContainsKey(subject))
                                {
                                    JHSemesterScoreRecord record = semesterScoreDictionary[info];

                                    #region 直接修改已存在的成績資料的Detail
                                    foreach (string field in e.ImportFields)
                                    {
                                        K12.Data.SubjectScore score = record.Subjects[subject];
                                        string value = data[field];
                                        //"分數評量", "努力程度", "文字描述", "註記"
                                        switch (field)
                                        {
                                        default:
                                            break;

                                        case "領域":
                                            if (score.Domain != value)
                                            {
                                                score.Domain = value;
                                                hasChanged   = true;
                                            }
                                            break;

                                        case "權數":
                                            if ("" + score.Credit != value)
                                            {
                                                score.Credit = decimal.Parse(value);
                                                hasChanged   = true;
                                            }
                                            break;

                                        case "節數":
                                            if ("" + score.Period != value)
                                            {
                                                score.Period = decimal.Parse(value);
                                                hasChanged   = true;
                                            }
                                            break;

                                        //case "成績年級":
                                        //    int gy = int.Parse(data["成績年級"]);
                                        //    if (record.GradeYear != gy)
                                        //    {
                                        //        semesterGradeYear[info] = gy;
                                        //        hasChanged = true;
                                        //    }
                                        //    break;
                                        //case "分數評量":
                                        //    if ("" + score.Score != value)
                                        //    {
                                        //        decimal d;
                                        //        if (decimal.TryParse(value, out d))
                                        //            score.Score = d;
                                        //        else
                                        //            score.Score = null;
                                        //        hasChanged = true;
                                        //    }
                                        //    break;
                                        case "成績":
                                            if ("" + score.Score != value)
                                            {
                                                decimal d;
                                                if (decimal.TryParse(value, out d))
                                                {
                                                    score.Score = d;
                                                }
                                                else
                                                {
                                                    score.Score = null;
                                                }
                                                hasChanged = true;
                                            }
                                            break;

                                        case "原始成績":
                                            if ("" + score.ScoreOrigin != value)
                                            {
                                                decimal d;
                                                if (decimal.TryParse(value, out d))
                                                {
                                                    score.ScoreOrigin = d;
                                                }
                                                else
                                                {
                                                    score.ScoreOrigin = null;
                                                }
                                                hasChanged = true;
                                            }
                                            break;

                                        case "補考成績":
                                            if ("" + score.ScoreMakeup != value)
                                            {
                                                decimal d;
                                                if (decimal.TryParse(value, out d))
                                                {
                                                    score.ScoreMakeup = d;
                                                }
                                                else
                                                {
                                                    score.ScoreMakeup = null;
                                                }
                                                hasChanged = true;
                                            }
                                            break;

                                        //case "努力程度":
                                        //    if ("" + score.Effort != value)
                                        //    {
                                        //        int i;
                                        //        if (int.TryParse(value, out i))
                                        //            score.Effort = i;
                                        //        else
                                        //            score.Effort = null;
                                        //        hasChanged = true;
                                        //    }
                                        //    break;
                                        case "文字描述":
                                            if ("" + score.Text != value)
                                            {
                                                score.Text = value;
                                                hasChanged = true;
                                            }
                                            break;

                                        case "註記":
                                            if (score.Comment != value)
                                            {
                                                score.Comment = value;
                                                hasChanged    = true;
                                            }
                                            break;
                                        }
                                    }
                                    #endregion
                                }
                                else//加入新成績至已存在的學期
                                {
                                    if (!updatedNewSemesterScore.ContainsKey(info))
                                    {
                                        updatedNewSemesterScore.Add(info, new List <RowData>());
                                    }
                                    updatedNewSemesterScore[info].Add(data);
                                    hasChanged = true;
                                }
                                //真的有變更
                                if (hasChanged)
                                {
                                    #region 登錄有變更的學期
                                    if (!updatedSemester.Contains(info))
                                    {
                                        updatedSemester.Add(info);
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                    #endregion
                    //處理已登錄要更新的學期成績
                    #region 處理已登錄要更新的學期成績
                    foreach (SemesterInfo info in updatedSemester)
                    {
                        //Dictionary<int, Dictionary<int, string>> semeScoreID = (Dictionary<int, Dictionary<int, string>>)studentRec.Fields["SemesterSubjectScoreID"];
                        //string semesterScoreID = semeScoreID[sy][se];//從學期抓ID
                        //int gradeyear = semesterGradeYear[info];//抓年級
                        //XmlElement subjectScoreInfo = doc.CreateElement("SemesterSubjectScoreInfo");
                        #region 產生該學期科目成績的XML
                        //foreach (SemesterSubjectScoreInfo scoreInfo in semesterScoreDictionary[sy][se].Values)
                        //{
                        //    subjectScoreInfo.AppendChild(doc.ImportNode(scoreInfo.Detail, true));
                        //}

                        updateList.Add(semesterScoreDictionary[info]);

                        //if (updatedNewSemesterScore.ContainsKey(sy) && updatedNewSemesterScore[sy].ContainsKey(se))
                        if (updatedNewSemesterScore.ContainsKey(info))
                        {
                            foreach (RowData row in updatedNewSemesterScore[info])
                            {
                                //XmlElement newScore = doc.CreateElement("Subject");
                                K12.Data.SubjectScore subjectScore = new K12.Data.SubjectScore();
                                #region 建立newScore
                                //foreach (string field in new string[] { "領域", "科目", "權數", "節數", "分數評量", "努力程度", "文字描述", "註記" })
                                //foreach (string field in new string[] { "領域", "科目", "權數", "節數", "分數評量", "文字描述", "註記" })
                                foreach (string field in new string[] { "領域", "科目", "權數", "節數", "成績", "原始成績", "補考成績", "文字描述", "註記" })
                                {
                                    if (e.ImportFields.Contains(field))
                                    {
                                        decimal d;

                                        #region 填入科目資訊
                                        string value = row[field];
                                        switch (field)
                                        {
                                        default:
                                            break;

                                        case "領域":
                                            subjectScore.Domain = value;
                                            break;

                                        case "科目":
                                            subjectScore.Subject = value;
                                            break;

                                        case "權數":
                                            subjectScore.Credit = decimal.Parse(value);
                                            break;

                                        case "節數":
                                            subjectScore.Period = decimal.Parse(value);
                                            break;

                                        //case "分數評量":
                                        //    decimal d;
                                        //    if (decimal.TryParse(value, out d))
                                        //        subjectScore.Score = d;
                                        //    else
                                        //        subjectScore.Score = null;
                                        //    break;
                                        case "成績":
                                            if (decimal.TryParse(value, out d))
                                            {
                                                subjectScore.Score = d;
                                            }
                                            else
                                            {
                                                subjectScore.Score = null;
                                            }
                                            break;

                                        case "原始成績":
                                            if (decimal.TryParse(value, out d))
                                            {
                                                subjectScore.ScoreOrigin = d;
                                            }
                                            else
                                            {
                                                subjectScore.ScoreOrigin = null;
                                            }
                                            break;

                                        case "補考成績":
                                            if (decimal.TryParse(value, out d))
                                            {
                                                subjectScore.ScoreMakeup = d;
                                            }
                                            else
                                            {
                                                subjectScore.ScoreMakeup = null;
                                            }
                                            break;

                                        //case "努力程度":
                                        //    int i;
                                        //    if (int.TryParse(value, out i))
                                        //        subjectScore.Effort = i;
                                        //    else
                                        //        subjectScore.Effort = null;
                                        //    break;
                                        case "文字描述":
                                            subjectScore.Text = value;
                                            break;

                                        case "註記":
                                            subjectScore.Comment = value;
                                            break;
                                        }
                                        #endregion
                                    }
                                }
                                #endregion
                                //subjectScoreInfo.AppendChild(newScore);
                                JHSemesterScoreRecord record = semesterScoreDictionary[info];
                                if (!record.Subjects.ContainsKey(subjectScore.Subject))
                                {
                                    record.Subjects.Add(subjectScore.Subject, subjectScore);
                                }
                                else
                                {
                                    record.Subjects[subjectScore.Subject] = subjectScore;
                                }

                                updateList.Add(record);
                            }
                        }
                        #endregion
                        //updateList.Add(new SmartSchool.Feature.Score.EditScore.UpdateInfo(semesterScoreID, gradeyear, subjectScoreInfo));
                    }
                    #endregion
                    //處理新增成績學期
                    #region 處理新增成績學期
                    foreach (SemesterInfo info in insertNewSemesterScore.Keys)
                    {
                        //int gradeyear = semesterGradeYear[info];//抓年級
                        foreach (RowData row in insertNewSemesterScore[info])
                        {
                            K12.Data.SubjectScore subjectScore = new K12.Data.SubjectScore();
                            //foreach (string field in new string[] { "領域", "科目", "權數", "節數", "分數評量", "努力程度", "文字描述", "註記" })
                            //foreach (string field in new string[] { "領域", "科目", "權數", "節數", "分數評量", "文字描述", "註記" })
                            foreach (string field in new string[] { "領域", "科目", "權數", "節數", "成績", "原始成績", "補考成績", "文字描述", "註記" })
                            {
                                if (e.ImportFields.Contains(field))
                                {
                                    decimal d;

                                    string value = row[field];
                                    switch (field)
                                    {
                                    default: break;

                                    case "領域":
                                        subjectScore.Domain = value;
                                        break;

                                    case "科目":
                                        subjectScore.Subject = value;
                                        break;

                                    case "權數":
                                        subjectScore.Credit = decimal.Parse(value);
                                        break;

                                    case "節數":
                                        subjectScore.Period = decimal.Parse(value);
                                        break;

                                    //case "分數評量":
                                    //    decimal d;
                                    //    if (decimal.TryParse(value, out d))
                                    //        subjectScore.Score = d;
                                    //    else
                                    //        subjectScore.Score = null;
                                    //    break;
                                    case "成績":
                                        if (decimal.TryParse(value, out d))
                                        {
                                            subjectScore.Score = d;
                                        }
                                        else
                                        {
                                            subjectScore.Score = null;
                                        }
                                        break;

                                    case "原始成績":
                                        if (decimal.TryParse(value, out d))
                                        {
                                            subjectScore.ScoreOrigin = d;
                                        }
                                        else
                                        {
                                            subjectScore.ScoreOrigin = null;
                                        }
                                        break;

                                    case "補考成績":
                                        if (decimal.TryParse(value, out d))
                                        {
                                            subjectScore.ScoreMakeup = d;
                                        }
                                        else
                                        {
                                            subjectScore.ScoreMakeup = null;
                                        }
                                        break;

                                    //case "努力程度":
                                    //    int i;
                                    //    if (int.TryParse(value, out i))
                                    //        subjectScore.Effort = i;
                                    //    else
                                    //        subjectScore.Effort = null;
                                    //    break;
                                    case "文字描述":
                                        subjectScore.Text = value;
                                        break;

                                    case "註記":
                                        subjectScore.Comment = value;
                                        break;
                                    }
                                }
                            }
                            //subjectScoreInfo.AppendChild(newScore);
                            JHSemesterScoreRecord record = new JHSemesterScoreRecord();
                            record.SchoolYear   = info.SchoolYear;
                            record.Semester     = info.Semester;
                            record.RefStudentID = studentRec.ID;
                            //record.GradeYear = gradeyear;

                            if (!record.Subjects.ContainsKey(subjectScore.Subject))
                            {
                                record.Subjects.Add(subjectScore.Subject, subjectScore);
                            }
                            else
                            {
                                record.Subjects[subjectScore.Subject] = subjectScore;
                            }

                            insertList.Add(record);
                        }
                        //insertList.Add(new SmartSchool.Feature.Score.AddScore.InsertInfo(studentRec.StudentID, "" + sy, "" + se, gradeyear, "", subjectScoreInfo));
                    }
                    #endregion
                }
                #endregion


                Dictionary <string, JHSemesterScoreRecord> iList = new Dictionary <string, JHSemesterScoreRecord>();
                Dictionary <string, JHSemesterScoreRecord> uList = new Dictionary <string, JHSemesterScoreRecord>();

                foreach (var record in insertList)
                {
                    string key = record.RefStudentID + "_" + record.SchoolYear + "_" + record.Semester;
                    if (!iList.ContainsKey(key))
                    {
                        iList.Add(key, new JHSemesterScoreRecord());
                    }
                    JHSemesterScoreRecord newRecord = iList[key];
                    newRecord.RefStudentID = record.RefStudentID;
                    newRecord.SchoolYear   = record.SchoolYear;
                    newRecord.Semester     = record.Semester;

                    foreach (var subject in record.Subjects.Keys)
                    {
                        if (!newRecord.Subjects.ContainsKey(subject))
                        {
                            newRecord.Subjects.Add(subject, record.Subjects[subject]);
                        }
                    }
                }

                foreach (var record in updateList)
                {
                    string key = record.RefStudentID + "_" + record.SchoolYear + "_" + record.Semester;
                    if (!uList.ContainsKey(key))
                    {
                        uList.Add(key, record);
                    }
                    JHSemesterScoreRecord newRecord = uList[key];
                    newRecord.RefStudentID = record.RefStudentID;
                    newRecord.SchoolYear   = record.SchoolYear;
                    newRecord.Semester     = record.Semester;
                    newRecord.ID           = record.ID;

                    foreach (var subject in record.Subjects.Keys)
                    {
                        if (!newRecord.Subjects.ContainsKey(subject))
                        {
                            newRecord.Subjects.Add(subject, record.Subjects[subject]);
                        }
                    }
                }

                List <string> ids = new List <string>(id_Rows.Keys);
                Dictionary <string, JHSemesterScoreRecord> origs = new Dictionary <string, JHSemesterScoreRecord>();
                foreach (var record in JHSemesterScore.SelectByStudentIDs(ids))
                {
                    if (!origs.ContainsKey(record.ID))
                    {
                        origs.Add(record.ID, record);
                    }
                }
                foreach (var record in uList.Values)
                {
                    if (origs.ContainsKey(record.ID))
                    {
                        foreach (var domain in origs[record.ID].Domains.Keys)
                        {
                            if (!record.Domains.ContainsKey(domain))
                            {
                                record.Domains.Add(domain, origs[record.ID].Domains[domain]);
                            }
                        }
                    }
                }

                JHSemesterScore.Insert(new List <JHSemesterScoreRecord>(iList.Values));

                JHSemesterScore.Update(new List <JHSemesterScoreRecord>(uList.Values));

                FISCA.LogAgent.ApplicationLog.Log("成績系統.匯入匯出", "匯入學期科目成績", "總共匯入" + (insertList.Count + updateList.Count) + "筆學期科目成績。");
                #endregion
            };
            wizard.ImportComplete += delegate
            {
                MsgBox.Show("匯入完成");
            };
        }
        private void BgWorkerExport_DoWork(object sender, DoWorkEventArgs e)
        {
            bgWorkerExport.ReportProgress(1);
            try
            {
                // 取得預設樣板
                Workbook  wb  = new Workbook(new MemoryStream(Properties.Resources.Template));
                Worksheet wst = wb.Worksheets[0];


                // 取得學生基本資料
                List <StudentInfo> StudentInfoList = QueryData.GetStudentInfoList3();

                List <string> StudentIDList = new List <string>();
                foreach (StudentInfo si in StudentInfoList)
                {
                    StudentIDList.Add(si.StudentID);
                }

                // 取得地址資訊
                Dictionary <string, JHAddressRecord> AddressDict = new Dictionary <string, JHAddressRecord>();
                List <JHAddressRecord> tmpAddress = JHAddress.SelectByStudentIDs(StudentIDList);
                foreach (JHAddressRecord rec in tmpAddress)
                {
                    if (!AddressDict.ContainsKey(rec.RefStudentID))
                    {
                        AddressDict.Add(rec.RefStudentID, rec);
                    }
                }

                // 取得電話資料
                Dictionary <string, JHPhoneRecord> PhoneDict = new Dictionary <string, JHPhoneRecord>();
                List <JHPhoneRecord> tmpPhone = JHPhone.SelectByStudentIDs(StudentIDList);
                foreach (JHPhoneRecord rec in tmpPhone)
                {
                    if (!PhoneDict.ContainsKey(rec.RefStudentID))
                    {
                        PhoneDict.Add(rec.RefStudentID, rec);
                    }
                }

                bgWorkerExport.ReportProgress(20);

                // 取得監護人父母資訊
                Dictionary <string, JHParentRecord> ParentDict = new Dictionary <string, JHParentRecord>();
                List <JHParentRecord> tmpParent = JHParent.SelectByStudentIDs(StudentIDList);
                foreach (JHParentRecord rec in tmpParent)
                {
                    if (!ParentDict.ContainsKey(rec.RefStudentID))
                    {
                        ParentDict.Add(rec.RefStudentID, rec);
                    }
                }

                // 轉換各項類別對照值
                Dictionary <string, string> MappingTag1 = new Dictionary <string, string>();
                Dictionary <string, string> MappingTag2 = new Dictionary <string, string>();
                Dictionary <string, string> MappingTag3 = new Dictionary <string, string>();
                Dictionary <string, string> MappingTag4 = new Dictionary <string, string>();

                // 取得學生類別
                Dictionary <string, List <string> > StudentTagDict = QueryData.GetStudentTagName(StudentIDList);

                // 解析對照設定
                XElement elmRoot = XElement.Parse(_Configure.MappingContent);
                if (elmRoot != null)
                {
                    foreach (XElement elm in elmRoot.Elements("Group"))
                    {
                        string gpName = elm.Attribute("Name").Value;
                        if (gpName == "學生身分")
                        {
                            foreach (XElement elm1 in elm.Elements("Item"))
                            {
                                string tagName = elm1.Attribute("TagName").Value;
                                if (!MappingTag1.ContainsKey(tagName) && tagName.Length > 0)
                                {
                                    MappingTag1.Add(tagName, elm1.Attribute("Code").Value);
                                }
                            }
                        }

                        if (gpName == "身心障礙")
                        {
                            foreach (XElement elm1 in elm.Elements("Item"))
                            {
                                string tagName = elm1.Attribute("TagName").Value;
                                if (!MappingTag2.ContainsKey(tagName) && tagName.Length > 0)
                                {
                                    MappingTag2.Add(tagName, elm1.Attribute("Code").Value);
                                }
                            }
                        }

                        if (gpName == "學生報名身分設定")
                        {
                            foreach (XElement elm1 in elm.Elements("Item"))
                            {
                                string tagName = elm1.Attribute("TagName").Value;
                                if (!MappingTag3.ContainsKey(tagName) && tagName.Length > 0)
                                {
                                    MappingTag3.Add(tagName, elm1.Attribute("Code").Value);
                                }
                            }
                        }

                        if (gpName == "失業勞工子女")
                        {
                            foreach (XElement elm1 in elm.Elements("Item"))
                            {
                                string tagName = elm1.Attribute("TagName").Value;
                                if (!MappingTag4.ContainsKey(tagName) && tagName.Length > 0)
                                {
                                    MappingTag4.Add(tagName, elm1.Attribute("Code").Value);
                                }
                            }
                        }
                    }
                }


                // 取得語言認證學生id
                List <string> hasLanguageCertificateIDList = QueryData.GetLanguageCertificate(StudentIDList);

                bgWorkerExport.ReportProgress(40);

                // 取得成績相關資料
                Dictionary <string, List <JHSemesterScoreRecord> > SemesterScoreRecordDict = new Dictionary <string, List <JHSemesterScoreRecord> >();
                List <JHSemesterScoreRecord> tmpSemsScore = JHSemesterScore.SelectByStudentIDs(StudentIDList);
                foreach (JHSemesterScoreRecord rec in tmpSemsScore)
                {
                    if (!SemesterScoreRecordDict.ContainsKey(rec.RefStudentID))
                    {
                        SemesterScoreRecordDict.Add(rec.RefStudentID, new List <JHSemesterScoreRecord>());
                    }

                    SemesterScoreRecordDict[rec.RefStudentID].Add(rec);
                }

                // 取得功過紀錄
                // 功過對照表
                JHMeritDemeritReduceRecord DemeritReduceRecord = JHMeritDemeritReduce.Select();
                // 懲
                Dictionary <string, List <JHDemeritRecord> > DemeritRecordDict = new Dictionary <string, List <JHDemeritRecord> >();
                List <JHDemeritRecord> tmpDemeritRecord = JHDemerit.SelectByStudentIDs(StudentIDList);
                foreach (JHDemeritRecord rec in tmpDemeritRecord)
                {
                    if (rec.Cleared == "是")
                    {
                        continue;
                    }

                    if (rec.OccurDate > _Configure.EndDate)
                    {
                        continue;
                    }
                    else
                    {
                        if (!DemeritRecordDict.ContainsKey(rec.RefStudentID))
                        {
                            DemeritRecordDict.Add(rec.RefStudentID, new List <JHDemeritRecord>());
                        }

                        DemeritRecordDict[rec.RefStudentID].Add(rec);
                    }
                }
                // 獎
                Dictionary <string, List <JHMeritRecord> > MeritRecordDict = new Dictionary <string, List <JHMeritRecord> >();
                List <JHMeritRecord> tmpMeritRecord = JHMerit.SelectByStudentIDs(StudentIDList);
                foreach (JHMeritRecord rec in tmpMeritRecord)
                {
                    if (rec.OccurDate > _Configure.EndDate)
                    {
                        continue;
                    }
                    else
                    {
                        if (!MeritRecordDict.ContainsKey(rec.RefStudentID))
                        {
                            MeritRecordDict.Add(rec.RefStudentID, new List <JHMeritRecord>());
                        }

                        MeritRecordDict[rec.RefStudentID].Add(rec);
                    }
                }

                // 填入幹部資料
                StudentInfoList = QueryData.FillCad(StudentIDList, StudentInfoList);

                // 填入中低收入戶
                StudentInfoList = QueryData.FillIncomeType(StudentIDList, StudentInfoList);

                // 填入競賽成績
                StudentInfoList = QueryData.FillStudentCompetitionScore(StudentIDList, StudentInfoList, _Configure.EndDate);

                // 取得學生體適能資料並填入
                StudentInfoList = QueryData.FillStudentFitness(StudentIDList, StudentInfoList, _Configure.EndDate);

                // 填入 Excel 資料
                int wstRIdx = 1;


                bgWorkerExport.ReportProgress(70);

                // 幹部限制
                List <string> CadreName1 = _Configure.LoadCareNames();

                foreach (StudentInfo si in StudentInfoList)
                {
                    // 考區代碼 0, 12/屏東考區
                    wst.Cells[wstRIdx, 0].PutValue(12);
                    // 集報單位代碼 1,學校代碼
                    wst.Cells[wstRIdx, 1].PutValue(K12.Data.School.Code);
                    // 序號 2
                    wst.Cells[wstRIdx, 2].PutValue(wstRIdx);
                    // 學號 3
                    wst.Cells[wstRIdx, 3].PutValue(si.StudentNumber);
                    // 班級 4
                    wst.Cells[wstRIdx, 4].PutValue(si.ClassName);
                    // 座號 5
                    wst.Cells[wstRIdx, 5].PutValue(si.SeatNo);
                    // 學生姓名 6
                    wst.Cells[wstRIdx, 6].PutValue(si.StudentName);
                    // 身分證統一編號 7
                    wst.Cells[wstRIdx, 7].PutValue(si.IDNumber);

                    // 性別 8
                    wst.Cells[wstRIdx, 8].PutValue(si.GenderCode);

                    // 出生年(民國年) 9
                    wst.Cells[wstRIdx, 9].PutValue(si.BirthYear);
                    // 出生月 10
                    wst.Cells[wstRIdx, 10].PutValue(si.BirthMonth);
                    // 出生日 11
                    wst.Cells[wstRIdx, 11].PutValue(si.BirthDay);
                    // 畢業學校代碼 12
                    wst.Cells[wstRIdx, 12].PutValue(K12.Data.School.Code);

                    // 畢業年(民國年) 13
                    int gyear;
                    if (int.TryParse(K12.Data.School.DefaultSchoolYear, out gyear))
                    {
                        wst.Cells[wstRIdx, 13].PutValue(gyear + 1);
                    }

                    // 畢肄業 14
                    wst.Cells[wstRIdx, 14].PutValue(1);


                    // 就學區 17

                    // 低收入戶 18
                    if (si.incomeType1)
                    {
                        wst.Cells[wstRIdx, 18].PutValue(1);
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 18].PutValue(0);
                    }

                    // 中低收入戶 19
                    if (si.incomeType2)
                    {
                        wst.Cells[wstRIdx, 19].PutValue(1);
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 19].PutValue(0);
                    }

                    wst.Cells[wstRIdx, 15].PutValue("0");
                    wst.Cells[wstRIdx, 16].PutValue("0");
                    wst.Cells[wstRIdx, 20].PutValue("0");
                    wst.Cells[wstRIdx, 28].PutValue("0");

                    if (StudentTagDict.ContainsKey(si.StudentID))
                    {
                        foreach (string tagName in StudentTagDict[si.StudentID])
                        {
                            if (MappingTag1.ContainsKey(tagName))
                            {
                                // 學生身分 15
                                wst.Cells[wstRIdx, 15].PutValue(MappingTag1[tagName]);
                            }

                            if (MappingTag2.ContainsKey(tagName))
                            {
                                si.isSpecial = true;
                                // 身心障礙 16
                                wst.Cells[wstRIdx, 16].PutValue(MappingTag2[tagName]);
                            }

                            if (MappingTag3.ContainsKey(tagName))
                            {
                                // 學生報名身分 28
                                wst.Cells[wstRIdx, 28].PutValue(MappingTag3[tagName]);
                            }
                            if (MappingTag4.ContainsKey(tagName))
                            {
                                // 失業勞工子女 20
                                wst.Cells[wstRIdx, 20].PutValue(MappingTag4[tagName]);
                            }
                        }
                    }



                    // 資料授權 21
                    wst.Cells[wstRIdx, 21].PutValue(0);

                    string parentName = "";


                    // 家長姓名 22
                    if (ParentDict.ContainsKey(si.StudentID))
                    {
                        if (!string.IsNullOrWhiteSpace(ParentDict[si.StudentID].CustodianName))
                        {
                            parentName = ParentDict[si.StudentID].CustodianName;
                        }
                        else if (!string.IsNullOrWhiteSpace(ParentDict[si.StudentID].FatherName))
                        {
                            parentName = ParentDict[si.StudentID].FatherName;
                        }
                        else if (!string.IsNullOrWhiteSpace(ParentDict[si.StudentID].MotherName))
                        {
                            parentName = ParentDict[si.StudentID].MotherName;
                        }
                        else
                        {
                        }
                        wst.Cells[wstRIdx, 22].PutValue(parentName);
                    }


                    // 市內電話 23
                    // 行動電話 24
                    if (PhoneDict.ContainsKey(si.StudentID))
                    {
                        wst.Cells[wstRIdx, 23].PutValue(PhoneDict[si.StudentID].Contact.Replace("-", "").Replace(")", "").Replace("(", ""));
                        wst.Cells[wstRIdx, 24].PutValue(PhoneDict[si.StudentID].Cell.Replace("-", "").Replace(")", "").Replace("(", ""));
                    }


                    // 郵遞區號 25
                    if (AddressDict.ContainsKey(si.StudentID))
                    {
                        string zipCode = "";

                        if (AddressDict[si.StudentID].MailingZipCode != null)
                        {
                            zipCode = AddressDict[si.StudentID].MailingZipCode;
                        }

                        if (zipCode.Length >= 3)
                        {
                            zipCode = zipCode.Substring(0, 3);
                        }

                        wst.Cells[wstRIdx, 25].PutValue(zipCode);

                        // 通訊地址 26
                        wst.Cells[wstRIdx, 26].PutValue(AddressDict[si.StudentID].MailingCounty + AddressDict[si.StudentID].MailingTown + AddressDict[si.StudentID].MailingDistrict + AddressDict[si.StudentID].MailingArea + AddressDict[si.StudentID].MailingDetail);
                    }
                    // 非中華民國身分證號 27
                    if (si.isTaiwanID)
                    {
                        wst.Cells[wstRIdx, 27].PutValue("");
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 27].PutValue("V");
                    }


                    // 市內電話分機 29

                    // 均衡學習 30
                    // 計算分數
                    if (SemesterScoreRecordDict.ContainsKey(si.StudentID))
                    {
                        si.CalcSemsScore5(SemesterScoreRecordDict[si.StudentID]);
                        // 成績滿5學期才顯示
                        if (si.hasSemester5Score)
                        {
                            wst.Cells[wstRIdx, 30].PutValue(si.Semester5Score);
                        }
                    }

                    // 服務表現 31
                    si.CalcCadreScore(CadreName1);
                    wst.Cells[wstRIdx, 31].PutValue(si.ServiceScore);

                    // 品德表現 32
                    if (DemeritRecordDict.ContainsKey(si.StudentID))
                    {
                        if (MeritRecordDict.ContainsKey(si.StudentID))
                        {
                            si.CalcDemeritMemeritScore(DemeritRecordDict[si.StudentID], MeritRecordDict[si.StudentID], DemeritReduceRecord);
                        }
                        else
                        {
                            si.CalcDemeritMemeritScore(DemeritRecordDict[si.StudentID], new List <JHMeritRecord>(), DemeritReduceRecord);
                        }
                        wst.Cells[wstRIdx, 32].PutValue(si.MeritDemeritScore);
                    }
                    else
                    {
                        // 沒有懲戒
                        wst.Cells[wstRIdx, 32].PutValue(10);
                    }


                    // 競賽表現 33
                    si.CalcCompetitionScore();
                    wst.Cells[wstRIdx, 33].PutValue(si.CompetitionScore);

                    // 體適能 34
                    // 計算並填入
                    si.CalcFitnessScore();
                    wst.Cells[wstRIdx, 34].PutValue(si.FitnessScore);

                    // 本土語言認證 35
                    if (hasLanguageCertificateIDList.Contains(si.StudentID))
                    {
                        wst.Cells[wstRIdx, 35].PutValue(2);
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 35].PutValue(0);
                    }



                    // 36~39 系統無法提供先空
                    // 適性發展_高中 36
                    // 適性發展_高職 37
                    // 適性發展_綜合高中 38
                    // 適性發展_五專 39

                    wstRIdx++;
                }

                bgWorkerExport.ReportProgress(100);

                e.Result = wb;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 17
0
        public DataCache(Options options)
        {
            var student_ids = from student in options.Students select student.ID;

            #region 取得 AutoSummary
            _autoSummaryCache = new Dictionary <string, AutoSummaryRecord>();
            foreach (AutoSummaryRecord record in AutoSummary.Select(student_ids.ToList <string>(), null))
            {
                if (record.SchoolYear == options.SchoolYear &&
                    record.Semester == options.Semester)
                {
                    if (!_autoSummaryCache.ContainsKey(record.RefStudentID))
                    {
                        _autoSummaryCache.Add(record.RefStudentID, record);
                    }
                }
            }
            #endregion

            #region 取得 SemesterScore
            _semesterScoreCache = new Dictionary <string, JHSemesterScoreRecord>();
            foreach (var record in JHSemesterScore.SelectByStudentIDs(student_ids.ToList <string>()))
            {
                if (record.SchoolYear == options.SchoolYear &&
                    record.Semester == options.Semester)
                {
                    if (!_semesterScoreCache.ContainsKey(record.RefStudentID))
                    {
                        _semesterScoreCache.Add(record.RefStudentID, record);
                    }
                }
            }
            #endregion
            #region 取得 SemesterHistoryItem
            _historyItemCache = new Dictionary <string, K12.Data.SemesterHistoryItem>();
            foreach (var record in JHSemesterHistory.SelectByStudentIDs(student_ids))
            {
                foreach (var item in record.SemesterHistoryItems)
                {
                    if (item.SchoolYear == options.SchoolYear &&
                        item.Semester == options.Semester)
                    {
                        if (!_historyItemCache.ContainsKey(item.RefStudentID))
                        {
                            _historyItemCache.Add(item.RefStudentID, item);
                        }
                    }
                }
            }
            #endregion

            if (Global.Params["Mode"] == "KaoHsiung")
            {
                #region 取得社團成績
                _assnScoreCache = new Dictionary <string, AssnScore>();

                FISCA.UDT.AccessHelper ah = new FISCA.UDT.AccessHelper();
                string          condition = string.Format("SchoolYear='{0}' and Semester='{1}'", options.SchoolYear, options.Semester);
                List <AssnCode> list      = ah.Select <AssnCode>(condition);
                foreach (AssnCode record in list)
                {
                    if (!_assnScoreCache.ContainsKey(record.StudentID))
                    {
                        XmlElement scores      = K12.Data.XmlHelper.LoadXml(record.Scores);
                        XmlElement itemElement = (XmlElement)scores.SelectSingleNode("Item");
                        if (itemElement != null)
                        {
                            AssnScore assnScore = new AssnScore()
                            {
                                Score  = itemElement.GetAttribute("Score"),
                                Effort = itemElement.GetAttribute("Effort"),
                                Text   = itemElement.GetAttribute("Text")
                            };
                            _assnScoreCache.Add(record.StudentID, assnScore);
                        }
                    }
                }

                //<Content>
                //<Item AssociationName="籃球社" Score="" Effort="" Text=""></Item>
                //</Content>
                #endregion
            }
        }
Ejemplo n.º 18
0
        public override void InitializeExport(SmartSchool.API.PlugIn.Export.ExportWizard wizard)
        {
            SmartSchool.API.PlugIn.VirtualCheckBox filterRepeat = new SmartSchool.API.PlugIn.VirtualCheckBox("自動略過重讀成績", true);
            wizard.Options.Add(filterRepeat);

            //2017/6/16 穎驊新增,因應[02-02][06] 計算學期科目成績新增清空原成績模式 項目, 新增 "刪除"欄位,使使用者能匯入 刪除成績資料
            wizard.ExportableFields.AddRange("領域", "學年度", "學期", "權數", "節數", "成績", "原始成績", "補考成績", "努力程度", "文字描述", "註記", "刪除");
            wizard.ExportPackage += delegate(object sender, SmartSchool.API.PlugIn.Export.ExportPackageEventArgs e)
            {
                #region ExportPackage
                List <JHStudentRecord> students = JHStudent.SelectByIDs(e.List);

                Dictionary <string, List <JHSemesterScoreRecord> > semsDict = new Dictionary <string, List <JHSemesterScoreRecord> >();
                foreach (JHSemesterScoreRecord record in JHSemesterScore.SelectByStudentIDs(e.List))
                {
                    if (!semsDict.ContainsKey(record.RefStudentID))
                    {
                        semsDict.Add(record.RefStudentID, new List <JHSemesterScoreRecord>());
                    }
                    semsDict[record.RefStudentID].Add(record);
                }

                foreach (JHStudentRecord stu in students)
                {
                    if (!semsDict.ContainsKey(stu.ID))
                    {
                        continue;
                    }

                    foreach (JHSemesterScoreRecord record in semsDict[stu.ID])
                    {
                        foreach (K12.Data.DomainScore domain in record.Domains.Values)
                        {
                            RowData row = new RowData();
                            row.ID = stu.ID;
                            foreach (string field in e.ExportFields)
                            {
                                if (wizard.ExportableFields.Contains(field))
                                {
                                    switch (field)
                                    {
                                    case "領域": row.Add(field, "" + domain.Domain); break;

                                    case "學年度": row.Add(field, "" + record.SchoolYear); break;

                                    case "學期": row.Add(field, "" + record.Semester); break;

                                    case "權數": row.Add(field, "" + domain.Credit); break;

                                    case "節數": row.Add(field, "" + domain.Period); break;

                                    case "成績": row.Add(field, "" + domain.Score); break;

                                    case "原始成績": row.Add(field, "" + domain.ScoreOrigin); break;

                                    case "補考成績": row.Add(field, "" + domain.ScoreMakeup); break;

                                    case "努力程度": row.Add(field, "" + domain.Effort); break;

                                    case "文字描述": row.Add(field, domain.Text); break;

                                    case "註記": row.Add(field, domain.Comment); break;

                                    case "刪除": row.Add(field, ""); break;
                                    }
                                }
                            }
                            e.Items.Add(row);
                        }
                    }
                }
                #endregion

                FISCA.LogAgent.ApplicationLog.Log("成績系統.匯入匯出", "匯出學期領域成績", "總共匯出" + e.Items.Count + "筆學期領域成績。");
            };
        }
Ejemplo n.º 19
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!inputed)
            {
                MsgBox.Show("尚未輸入成績");
                return;
            }

            if (!IsValid())
            {
                return;
            }

            try
            {
                int schoolYear = int.Parse(cboSchoolYear.Text);
                int semester   = int.Parse(cboSemester.Text);
                //int gradeYear = 0;

                //SemesterScoreRecordEditor editor = new SemesterScoreRecordEditor(_student, schoolYear, semester, gradeYear);
                JHSemesterScoreRecord newRecord = new JHSemesterScoreRecord();
                newRecord.RefStudentID = _student.ID;
                newRecord.SchoolYear   = schoolYear;
                newRecord.Semester     = semester;

                K12.Data.DomainScore liter    = new K12.Data.DomainScore();
                PeriodCredit         literpc1 = new PeriodCredit();
                PeriodCredit         literpc2 = new PeriodCredit();
                literpc1.Parse(textBoxX25.Text);
                literpc2.Parse(textBoxX26.Text);
                //if (!int.TryParse(textBoxX25.Text, out literpc1))
                //    literpc1 = 0;
                //if (!int.TryParse(textBoxX26.Text, out literpc2))
                //    literpc2 = 0;
                int effort1, effort2;
                if (!int.TryParse(textBoxX17.Text, out effort1))
                {
                    effort1 = 0;
                }
                if (!int.TryParse(textBoxX18.Text, out effort2))
                {
                    effort2 = 0;
                }

                liter.Period = literpc1.Period + literpc2.Period;
                liter.Credit = literpc1.Credit + literpc2.Credit;
                liter.Domain = "語文";
                //liter.Effort = (int)((effort1 + effort2) / 2);
                liter.Effort = 1;
                decimal d;
                liter.Score = decimal.TryParse(labelX14.Text, out d) ? (decimal?)d : null;
                liter.Text  = textBoxX9.Text + " " + textBoxX10.Text;

                newRecord.Domains.Add("語文", liter);

                if (CheckDomainValid(textBoxX27, textBoxX3, textBoxX19))
                {
                    newRecord.Domains.Add("數學", GetDomainScore("語文", textBoxX27, textBoxX3, textBoxX19, textBoxX11));
                }
                if (CheckDomainValid(textBoxX28, textBoxX4, textBoxX20))
                {
                    newRecord.Domains.Add("社會", GetDomainScore("社會", textBoxX28, textBoxX4, textBoxX20, textBoxX12));
                }
                if (CheckDomainValid(textBoxX29, textBoxX5, textBoxX21))
                {
                    newRecord.Domains.Add("藝術與人文", GetDomainScore("藝術與人文", textBoxX29, textBoxX5, textBoxX21, textBoxX13));
                }
                if (CheckDomainValid(textBoxX30, textBoxX6, textBoxX22))
                {
                    newRecord.Domains.Add("自然與生活科技", GetDomainScore("自然與生活科技", textBoxX30, textBoxX6, textBoxX22, textBoxX14));
                }
                if (CheckDomainValid(textBoxX31, textBoxX7, textBoxX23))
                {
                    newRecord.Domains.Add("健康與體育", GetDomainScore("健康與體育", textBoxX31, textBoxX7, textBoxX23, textBoxX15));
                }
                if (CheckDomainValid(textBoxX32, textBoxX8, textBoxX24))
                {
                    newRecord.Domains.Add("綜合活動", GetDomainScore("綜合活動", textBoxX32, textBoxX8, textBoxX24, textBoxX16));
                }

                if (textBoxX25.Enabled)
                {
                    K12.Data.SubjectScore subject1 = new K12.Data.SubjectScore();
                    subject1.Domain  = "語文";
                    subject1.Subject = textBoxX36.Text;
                    subject1.Score   = decimal.Parse(textBoxX1.Text);
                    //subject1.Effort = int.Parse(textBoxX17.Text);
                    subject1.Effort = 1;
                    subject1.Text   = textBoxX9.Text;
                    //subject1.Period = subject1.Credit = int.Parse(textBoxX25.Text);
                    subject1.Period = literpc1.Period;
                    subject1.Credit = literpc1.Credit;
                    newRecord.Subjects.Add(subject1.Subject, subject1);
                }

                if (textBoxX26.Enabled)
                {
                    K12.Data.SubjectScore subject2 = new K12.Data.SubjectScore();
                    subject2.Domain  = "語文";
                    subject2.Subject = textBoxX37.Text;
                    subject2.Score   = decimal.Parse(textBoxX2.Text);
                    subject2.Effort  = int.Parse(textBoxX18.Text);
                    subject2.Text    = textBoxX10.Text;
                    //subject2.Period = subject2.Credit = int.Parse(textBoxX26.Text);
                    subject2.Period = literpc2.Period;
                    subject2.Credit = literpc2.Credit;
                    newRecord.Subjects.Add(subject2.Subject, subject2);
                }

                foreach (DataGridViewRow row in dgv.Rows)
                {
                    if (row.IsNewRow)
                    {
                        continue;
                    }
                    PeriodCredit pc = new PeriodCredit();
                    pc.Parse("" + row.Cells[chsPeriodCredit.Index].Value);
                    K12.Data.SubjectScore subject = new K12.Data.SubjectScore();
                    subject.Domain  = "" + row.Cells[chsDomain.Index].Value;
                    subject.Subject = "" + row.Cells[chsSubject.Index].Value;
                    subject.Period  = pc.Period;
                    subject.Credit  = pc.Credit;
                    subject.Score   = decimal.Parse("" + row.Cells[chsScore.Index].Value);
                    //subject.Effort = int.Parse("" + row.Cells[chsEffort.Index].Value);
                    subject.Effort = 1;
                    subject.Text   = "" + row.Cells[chsText.Index].Value;

                    newRecord.Subjects.Add(subject.Subject, subject);
                }

                if (!string.IsNullOrEmpty(textBoxX33.Text))
                {
                    newRecord.Domains.Add("彈性課程", GetElasticDomain());
                }
                if (!string.IsNullOrEmpty(textBoxX34.Text))
                {
                    newRecord.LearnDomainScore = decimal.Parse(textBoxX34.Text);
                }
                if (!string.IsNullOrEmpty(textBoxX35.Text))
                {
                    newRecord.CourseLearnScore = decimal.Parse(textBoxX35.Text);
                }

                JHSemesterScore.Insert(newRecord);
                SaveLog(newRecord);
            }
            catch (Exception ex)
            {
                MsgBox.Show("儲存失敗");
                this.DialogResult = DialogResult.Cancel;
                this.Close();
                return;
            }

            this.DialogResult = DialogResult.OK;
        }
Ejemplo n.º 20
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(K12.Data.School.ChineseName);

            globalFieldName.Add("列印日期");
            globalFieldValue.Add(DateConvert.CDate(DateTime.Now.ToString("yyyy/MM/dd")));

            globalFieldName.Add("列印時間");
            globalFieldValue.Add(DateTime.Now.ToString("HH:mm:ss"));

            ReportConfiguration _Dylanconfig = new ReportConfiguration(Global.OneFileSave);

            OneFileSave = _Dylanconfig.GetBoolean("單檔儲存", false);
            StudentDoc  = new Dictionary <string, Document>();

            double total = _students.Count;
            double count = 0;

            List <string> student_ids = new List <string>();

            foreach (JHStudentRecord item in _students)
            {
                student_ids.Add(item.ID);
            }

            #region 快取資料
            //取得異動資料
            Dictionary <string, List <JHUpdateRecordRecord> > updateRecordCache = new Dictionary <string, List <JHUpdateRecordRecord> >();
            foreach (var record in JHUpdateRecord.SelectByStudentIDs(student_ids))
            {
                if (!updateRecordCache.ContainsKey(record.StudentID))
                {
                    updateRecordCache.Add(record.StudentID, new List <JHUpdateRecordRecord>());
                }
                updateRecordCache[record.StudentID].Add(record);
            }

            //取得缺曠獎懲資料
            Dictionary <string, List <AutoSummaryRecord> > autoSummaryCache = new Dictionary <string, List <AutoSummaryRecord> >();
            foreach (AutoSummaryRecord record in AutoSummary.Select(student_ids, null))
            {
                if (!autoSummaryCache.ContainsKey(record.RefStudentID))
                {
                    autoSummaryCache.Add(record.RefStudentID, new List <AutoSummaryRecord>());
                }
                autoSummaryCache[record.RefStudentID].Add(record);
            }

            //取得學期歷程
            Dictionary <string, JHSemesterHistoryRecord> semesterHistoryCache = new Dictionary <string, JHSemesterHistoryRecord>();
            foreach (var record in JHSemesterHistory.SelectByStudentIDs(student_ids))
            {
                if (!semesterHistoryCache.ContainsKey(record.RefStudentID))
                {
                    semesterHistoryCache.Add(record.RefStudentID, record);
                }
            }

            //取得學期成績
            Dictionary <string, List <JHSemesterScoreRecord> > semesterScoreCache = new Dictionary <string, List <JHSemesterScoreRecord> >();
            foreach (var record in JHSemesterScore.SelectByStudentIDs(student_ids))
            {
                if (!semesterScoreCache.ContainsKey(record.RefStudentID))
                {
                    semesterScoreCache.Add(record.RefStudentID, new List <JHSemesterScoreRecord>());
                }
                semesterScoreCache[record.RefStudentID].Add(record);
            }

            // 取得畢業成績
            Dictionary <string, K12.Data.GradScoreRecord> StudGradScoreDic = new Dictionary <string, GradScoreRecord>();
            foreach (GradScoreRecord score in GradScore.SelectByIDs <GradScoreRecord>(student_ids))
            {
                StudGradScoreDic.Add(score.RefStudentID, score);
            }

            ////課程
            //JHCourse.RemoveAll();
            //Dictionary<string, JHCourseRecord> courseCache = new Dictionary<string, JHCourseRecord>();
            //foreach (JHCourseRecord record in JHCourse.SelectAll())
            //{
            //    if (!courseCache.ContainsKey(record.ID))
            //        courseCache.Add(record.ID, record);
            //}
            #endregion

            #region 判斷要列印的領域科目
            Dictionary <string, bool> domains = new Dictionary <string, bool>();
            //Dictionary<string, List<string>> subjects = new Dictionary<string, List<string>>();

            //List<JHCourseRecord> courseList = new List<JHCourseRecord>(courseCache.Values);

            //courseList.Sort(delegate(JHCourseRecord x, JHCourseRecord y)
            //{
            //    return JHSchool.Evaluation.Subject.CompareSubjectOrdinal(x.Subject, y.Subject);
            //});

            string domainSubjectSetup = Config.GetString("領域科目設定", "Domain");
            if (domainSubjectSetup == "Domain")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }

                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
            }
            else if (domainSubjectSetup == "Subject")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
            }
            else
            {
                throw new Exception("請重新儲存一次列印設定");
            }

            //foreach (var domain in JHSchool.Evaluation.Subject.Domains)
            //    subjects.Add(domain, new List<string>());
            //if (!subjects.ContainsKey("")) subjects.Add("", new List<string>());

            //foreach (var course in courseList)
            //{
            //    if (!subjects.ContainsKey(course.Domain))
            //        subjects.Add(course.Domain, new List<string>());
            //    if (!subjects[course.Domain].Contains(course.Subject) &&
            //        domains.ContainsKey(course.Domain) &&
            //        domains[course.Domain] == false)
            //    {
            //        subjects[course.Domain].Add(course.Subject);
            //    }
            //}
            #endregion

            DocumentBuilder templateBuilder = new DocumentBuilder(_template);

            #region 節權數顯示
            string pcDisplay   = string.Empty;
            bool   printPeriod = Config.GetBoolean("列印節數", true);
            bool   printCredit = Config.GetBoolean("列印權數", false);
            if (printPeriod && printCredit)
            {
                pcDisplay = "節" + Environment.NewLine + "權" + Environment.NewLine + "數";
            }
            else if (printPeriod)
            {
                pcDisplay = "節" + Environment.NewLine + "數";
            }
            else if (printCredit)
            {
                pcDisplay = "權" + Environment.NewLine + "數";
            }


            while (templateBuilder.MoveToMergeField("節權數"))
            {
                templateBuilder.Write(pcDisplay);
            }
            #endregion

            #region 文字評語是否列印
            bool printText = Config.GetBoolean("列印文字評語", true);
            if (printText == false)
            {
                templateBuilder.MoveToMergeField("學習領域評量");
                (templateBuilder.CurrentParagraph.ParentNode as Cell).ParentRow.ParentTable.Remove();
            }
            #endregion

            #region  務學習時數
            Global._SLRDict.Clear();
            Global._SLRDict = Utility.GetServiceLearningDetail(student_ids);
            #endregion

            #region 產生
            foreach (JHStudentRecord student in _students)
            {
                count++;

                Document        each    = (Document)_template.Clone(true);
                DocumentBuilder builder = new DocumentBuilder(each);

                #region 建立學期歷程對照
                List <SemesterHistoryItem> semesterHistoryList = null;
                if (semesterHistoryCache.ContainsKey(student.ID))
                {
                    semesterHistoryList = semesterHistoryCache[student.ID].SemesterHistoryItems;
                }
                else
                {
                    semesterHistoryList = new List <SemesterHistoryItem>();
                }

                SemesterMap map = new SemesterMap();
                map.SetData(semesterHistoryList);
                #endregion

                #region 學生基本資料
                StudentBasicInfo basicInfo = new StudentBasicInfo(builder);
                basicInfo.SetStudent(student, semesterHistoryList);
                #endregion

                #region 異動資料
                List <JHUpdateRecordRecord> updateRecordList = null;
                if (updateRecordCache.ContainsKey(student.ID))
                {
                    updateRecordList = updateRecordCache[student.ID];
                }
                else
                {
                    updateRecordList = new List <JHUpdateRecordRecord>();
                }

                StudentUpdateRecordProcessor updateRecordProcessor = new StudentUpdateRecordProcessor(builder);
                updateRecordProcessor.SetData(updateRecordList);
                #endregion

                #region 日常表現
                List <AutoSummaryRecord> autoSummaryList = null;
                if (autoSummaryCache.ContainsKey(student.ID))
                {
                    autoSummaryList = autoSummaryCache[student.ID];
                }
                else
                {
                    autoSummaryList = new List <AutoSummaryRecord>();
                }

                StudentMoralProcessor moralProcessor = new StudentMoralProcessor(builder, map);
                moralProcessor.SetData(autoSummaryList);
                #endregion

                #region 學期歷程
                StudentHistoryProcessor history = new StudentHistoryProcessor(builder, map, (semesterHistoryCache.ContainsKey(student.ID) ? semesterHistoryCache[student.ID] : null));
                #endregion

                #region 學期成績
                List <JHSemesterScoreRecord> semesterScoreList = null;
                if (semesterScoreCache.ContainsKey(student.ID))
                {
                    semesterScoreList = semesterScoreCache[student.ID];
                }
                else
                {
                    semesterScoreList = new List <JHSemesterScoreRecord>();
                }

                // 畢業成績
                K12.Data.GradScoreRecord StudGradScore = new GradScoreRecord();
                if (StudGradScoreDic.ContainsKey(student.ID))
                {
                    StudGradScore = StudGradScoreDic[student.ID];
                }

                StudentSemesterScoreProcessor semesterScoreProcessor = new StudentSemesterScoreProcessor(builder, map, domainSubjectSetup, domains, StudGradScore);
                semesterScoreProcessor.DegreeMapper = _degreeMapper;
                semesterScoreProcessor.PrintPeriod  = printPeriod;
                semesterScoreProcessor.PrintCredit  = printCredit;
                semesterScoreProcessor.SetData(semesterScoreList);
                #endregion

                #region 學習領域評量
                if (printText == true)
                {
                    StudentTextProcessor text = new StudentTextProcessor(builder, map);
                    text.SetData(semesterScoreList);
                }
                #endregion

                if (OneFileSave)
                {
                    each.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());

                    string fileName = "";
                    fileName = student.StudentNumber;

                    fileName += "_" + student.IDNumber;

                    if (!string.IsNullOrEmpty(student.RefClassID))
                    {
                        fileName += "_" + student.Class.Name;
                    }
                    else
                    {
                        fileName += "_";
                    }

                    fileName += "_" + (student.SeatNo.HasValue ? student.SeatNo.Value.ToString() : "");
                    fileName += "_" + student.Name;

                    if (!StudentDoc.ContainsKey(fileName))
                    {
                        StudentDoc.Add(fileName, each);
                    }
                }
                else
                {
                    foreach (Section sec in each.Sections)
                    {
                        _doc.Sections.Add(_doc.ImportNode(sec, true));
                    }
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            if (!OneFileSave)
            {
                _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            }

            #endregion
        }
Ejemplo n.º 21
0
 /// <summary>
 /// (Network Access)將目前學期的資料填入到 SemesterScores 變數中。
 /// </summary>
 private void FillSemestersData()
 {
     SemesterScores = JHSemesterScore.SelectByStudentIDs(Students.ToKeys());
 }
        public DataRationalityMessage Execute()
        {
            QueryHelper Helper = new QueryHelper();

            List <string> StudentIDs = new List <string>();

            DataTable StudentIDTable = Helper.Select("select ref_student_id from sems_subj_score where score_info like'%<SemesterSubjectScoreInfo/>%'  and score_info like'%<Domains/>%' and score_info like'%<LearnDomainScore/>%'");

            for (int i = 0; i < StudentIDTable.Rows.Count; i++)
            {
                StudentIDs.Add("" + StudentIDTable.Rows[i][0]);
            }

            List <JHSemesterScoreRecord> SemsScoreList = JHSemesterScore.SelectByStudentIDs(StudentIDs);

            CorrectableRecs.Clear();
            RATRecs.Clear();
            DataRationalityMessage retMsg = new DataRationalityMessage();

            try
            {
                foreach (JHSemesterScoreRecord SmesRec in SemsScoreList)
                {
                    if (SmesRec.Subjects.Count == 0 && SmesRec.Domains.Count == 0)
                    {
                        EmptySemesterScoreRATRec rec = new EmptySemesterScoreRATRec();
                        rec.學期成績系統編號 = SmesRec.ID;
                        rec.學生系統編號   = SmesRec.RefStudentID;
                        rec.身分證號     = SmesRec.Student.IDNumber;
                        rec.姓名       = SmesRec.Student.Name;
                        rec.狀態       = SmesRec.Student.StatusStr;
                        rec.座號       = K12.Data.Int.GetString(SmesRec.Student.SeatNo);
                        if (SmesRec.Student.Class != null)
                        {
                            rec.班級 = SmesRec.Student.Class.Name;
                        }
                        rec.學年度 = SmesRec.SchoolYear.ToString();
                        rec.學期  = SmesRec.Semester.ToString();
                        rec.學號  = SmesRec.Student.StudentNumber;

                        RATRecs.Add(rec);
                        CorrectableRecs.Add(SmesRec);
                    }
                }
            }
            catch (Exception ex)
            {
                retMsg.Message = ex.Message;

                return(retMsg);
            }

            StringBuilder strBuilder = new StringBuilder();

            strBuilder.AppendLine("檢查學期成績筆數:" + SemsScoreList.Count);
            strBuilder.AppendLine("學期科目與領域成績空值筆數:" + RATRecs.Count);

            var SortedRATRecords = from RATRecord in RATRecs orderby RATRecord.狀態, RATRecord.班級, K12.Data.Int.ParseAllowNull(RATRecord.座號), RATRecord.學年度, RATRecord.學期 select RATRecord;

            retMsg.Message = strBuilder.ToString();
            retMsg.Data    = SortedRATRecords.ToList();

            return(retMsg);
        }
Ejemplo n.º 23
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            List <JHPeriodMappingInfo>  periodList  = JHPeriodMapping.SelectAll();
            List <JHAbsenceMappingInfo> absenceList = JHAbsenceMapping.SelectAll();

            double total = _config.Students.Count;
            double count = 0;

            List <string> student_ids = new List <string>();

            foreach (JHStudentRecord item in _config.Students)
            {
                student_ids.Add(item.ID);
            }

            #region 快取資料
            Dictionary <string, List <AutoSummaryRecord> > autoSummaryCache = new Dictionary <string, List <AutoSummaryRecord> >();
            foreach (AutoSummaryRecord record in AutoSummary.Select(student_ids, null))
            {
                if (!autoSummaryCache.ContainsKey(record.RefStudentID))
                {
                    autoSummaryCache.Add(record.RefStudentID, new List <AutoSummaryRecord>());
                }
                autoSummaryCache[record.RefStudentID].Add(record);
            }

            Dictionary <string, List <JHUpdateRecordRecord> > updateRecordCache = new Dictionary <string, List <JHUpdateRecordRecord> >();
            foreach (var record in JHUpdateRecord.SelectByStudentIDs(student_ids))
            {
                if (!updateRecordCache.ContainsKey(record.StudentID))
                {
                    updateRecordCache.Add(record.StudentID, new List <JHUpdateRecordRecord>());
                }
                updateRecordCache[record.StudentID].Add(record);
            }

            Dictionary <string, List <JHSemesterScoreRecord> > semesterScoreCache = new Dictionary <string, List <JHSemesterScoreRecord> >();
            foreach (var record in JHSemesterScore.SelectByStudentIDs(student_ids))
            {
                if (!semesterScoreCache.ContainsKey(record.RefStudentID))
                {
                    semesterScoreCache.Add(record.RefStudentID, new List <JHSemesterScoreRecord>());
                }
                semesterScoreCache[record.RefStudentID].Add(record);
            }

            Dictionary <string, JHSemesterHistoryRecord> semesterHistoryCache = new Dictionary <string, JHSemesterHistoryRecord>();
            foreach (var record in JHSemesterHistory.SelectByStudentIDs(student_ids))
            {
                if (!semesterHistoryCache.ContainsKey(record.RefStudentID))
                {
                    semesterHistoryCache.Add(record.RefStudentID, record);
                }
            }
            #endregion

            #region 取得所有科目
            Dictionary <string, SubjectScore> subjectDict = new Dictionary <string, SubjectScore>();
            foreach (JHSemesterScoreRecord record in JHSemesterScore.SelectByStudentIDs(student_ids))
            {
                foreach (SubjectScore subject in record.Subjects.Values)
                {
                    string key = Bind(subject.Domain, subject.Subject);
                    if (!subjectDict.ContainsKey(key))
                    {
                        subjectDict.Add(key, subject);
                    }
                }
            }

            List <SubjectScore> subjectList = new List <SubjectScore>(subjectDict.Values);
            subjectList.Sort(delegate(SubjectScore x, SubjectScore y)
            {
                List <string> list = new List <string>(new string[] { "國語文", "國文", "英文", "英語", "數學", "歷史", "地理", "公民", "理化", "生物" });
                int ix             = list.IndexOf(x.Subject);
                int iy             = list.IndexOf(y.Subject);

                if (ix >= 0 && iy >= 0)
                {
                    return(ix.CompareTo(iy));
                }
                else if (ix >= 0)
                {
                    return(-1);
                }
                else if (iy >= 0)
                {
                    return(1);
                }
                else
                {
                    return(x.Subject.CompareTo(y.Subject));
                }
            });
            #endregion

            #region 判斷要列印的領域科目
            Dictionary <string, bool>           domains  = new Dictionary <string, bool>();
            Dictionary <string, List <string> > subjects = new Dictionary <string, List <string> >();

            if (_config.DomainSubjectSetup == "Domain")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, true);
                }
                if (domains.ContainsKey("語文"))
                {
                    domains["語文"] = false;
                }
                if (domains.ContainsKey("彈性課程"))
                {
                    domains["彈性課程"] = false;
                }
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", false);
                }
            }
            else if (_config.DomainSubjectSetup == "Subject")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, false);
                }
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", false);
                }
            }
            else
            {
                throw new Exception("請重新儲存列印設定");
            }

            foreach (var domain in JHSchool.Evaluation.Subject.Domains)
            {
                subjects.Add(domain, new List <string>());
            }
            if (!subjects.ContainsKey(""))
            {
                subjects.Add("", new List <string>());
            }

            foreach (SubjectScore ss in subjectList)
            {
                if (!subjects.ContainsKey(ss.Domain))
                {
                    subjects.Add(ss.Domain, new List <string>());
                }

                //很怪
                if (domains.ContainsKey(ss.Domain) && domains[ss.Domain] == true)
                {
                    continue;
                }

                if (!subjects[ss.Domain].Contains(ss.Subject))
                {
                    subjects[ss.Domain].Add(ss.Subject);
                }
            }

            _config.SetPrintDomains(domains);
            _config.SetPrintSubjects(subjects);
            #endregion

            #region 依節權數設定,在畫面上顯示
            DocumentBuilder templateBuilder = new DocumentBuilder(_template);

            string pcDisplay = string.Empty;
            if (_config.PrintPeriod && _config.PrintCredit)
            {
                pcDisplay = "節/權數";
            }
            else if (_config.PrintPeriod)
            {
                pcDisplay = "節數";
            }
            else if (_config.PrintCredit)
            {
                pcDisplay = "權數";
            }


            while (templateBuilder.MoveToMergeField("節權數"))
            {
                templateBuilder.Write(pcDisplay);
            }
            #endregion


            #region  務學習時數
            Config._SLRDict.Clear();
            Config._SLRDict = Utility.GetServiceLearningDetail(student_ids);
            #endregion


            #region 產生
            foreach (JHStudentRecord student in _config.Students)
            {
                count++;
                DocumentBuilder builder = null;

                #region 建立學期歷程對照
                List <SemesterHistoryItem> semesterHistoryList = null;
                if (semesterHistoryCache.ContainsKey(student.ID))
                {
                    semesterHistoryList = semesterHistoryCache[student.ID].SemesterHistoryItems;
                }
                else
                {
                    semesterHistoryList = new List <SemesterHistoryItem>();
                }

                SemesterMap map = new SemesterMap();
                map.SetData(semesterHistoryList);
                #endregion


                Document each = (Document)_template.Clone(true);

                builder = new DocumentBuilder(each);

                #region 基本資料
                StudentBasicInfo basic = new StudentBasicInfo();
                basic.SetStudent(student, semesterHistoryList);

                each.MailMerge.MergeField += delegate(object sender1, MergeFieldEventArgs e1)
                {
                    #region 處理照片
                    if (e1.FieldName == "照片粘貼處")
                    {
                        DocumentBuilder builder1 = new DocumentBuilder(e1.Document);
                        builder1.MoveToField(e1.Field, true);

                        byte[] photoBytes = null;
                        try
                        {
                            photoBytes = Convert.FromBase64String("" + e1.FieldValue);
                        }
                        catch (Exception ex)
                        {
                            builder1.Write("照片粘貼處");
                            e1.Field.Remove();
                            return;
                        }

                        if (photoBytes == null || photoBytes.Length == 0)
                        {
                            builder1.Write("照片粘貼處");
                            e1.Field.Remove();
                            return;
                        }

                        e1.Field.Remove();

                        Shape photoShape = new Shape(e1.Document, ShapeType.Image);
                        photoShape.ImageData.SetImage(photoBytes);
                        photoShape.WrapType = WrapType.Inline;

                        #region AutoResize

                        double origHWRate  = photoShape.ImageData.ImageSize.HeightPoints / photoShape.ImageData.ImageSize.WidthPoints;
                        double shapeHeight = (builder1.CurrentParagraph.ParentNode.ParentNode as Row).RowFormat.Height * 6;
                        double shapeWidth  = (builder1.CurrentParagraph.ParentNode as Cell).CellFormat.Width;
                        if ((shapeHeight / shapeWidth) < origHWRate)
                        {
                            shapeWidth = shapeHeight / origHWRate;
                        }
                        else
                        {
                            shapeHeight = shapeWidth * origHWRate;
                        }

                        #endregion

                        photoShape.Height = shapeHeight * 0.9;
                        photoShape.Width  = shapeWidth * 0.9;

                        builder1.InsertNode(photoShape);
                    }
                    #endregion
                };
                //each.MailMerge.FieldMergingCallback = new InsertDocumentAtMailMergeHandler();

                List <string> fieldName = new List <string>();
                fieldName.AddRange(basic.GetFieldName());
                List <string> fieldValue = new List <string>();
                fieldValue.AddRange(basic.GetFieldValue());
                each.MailMerge.Execute(fieldName.ToArray(), fieldValue.ToArray());
                #endregion

                #region 異動資料
                List <JHUpdateRecordRecord> updateRecordList = null;
                if (updateRecordCache.ContainsKey(student.ID))
                {
                    updateRecordList = updateRecordCache[student.ID];
                }
                else
                {
                    updateRecordList = new List <JHUpdateRecordRecord>();
                }

                StudentUpdateRecordProcessor updateRecordProcessor = new StudentUpdateRecordProcessor(each);
                updateRecordProcessor.SetData(updateRecordList);
                #endregion

                #region 成績資料
                List <JHSemesterScoreRecord> semesterScoreList = null;
                if (semesterScoreCache.ContainsKey(student.ID))
                {
                    semesterScoreList = semesterScoreCache[student.ID];
                }
                else
                {
                    semesterScoreList = new List <JHSemesterScoreRecord>();
                }

                StudentSemesterScoreProcessor semesterScoreProcessor = new StudentSemesterScoreProcessor(builder, map, _config);
                semesterScoreProcessor.SetData(semesterScoreList);
                #endregion

                List <AutoSummaryRecord> autoSummaryList = null;
                if (autoSummaryCache.ContainsKey(student.ID))
                {
                    autoSummaryList = autoSummaryCache[student.ID];
                }
                else
                {
                    autoSummaryList = new List <AutoSummaryRecord>();
                }

                #region 獎懲資料
                StudentDisciplineProcessor disciplineProcessor = new StudentDisciplineProcessor(builder, map);
                disciplineProcessor.SetData(autoSummaryList);
                #endregion

                #region 缺曠資料
                StudentAttendanceProcessor attendanceProcessor = new StudentAttendanceProcessor(builder, map);
                attendanceProcessor.SetData(autoSummaryList);
                #endregion

                #region 日常行為
                StudentTextScoreProcessor textScoreProcessor = new StudentTextScoreProcessor(builder, map);
                textScoreProcessor.SetData(autoSummaryList);
                #endregion

                SemesterHistoryProcessor semesterHistoryProcessor = new SemesterHistoryProcessor(builder, map);

                foreach (Section sec in each.Sections)
                {
                    _doc.Sections.Add(_doc.ImportNode(sec, true));
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(School.ChineseName);

            globalFieldName.Add("列印日期");
            globalFieldValue.Add(Common.CDate(DateTime.Now.ToString("yyyy/MM/dd")) + " " + DateTime.Now.ToString("HH:mm:ss"));

            string chancellor, eduDirector, stuDirector;
            chancellor = eduDirector = stuDirector = string.Empty;

            XmlElement info = School.Configuration["學校資訊"].PreviousData;
            XmlElement chancellorElement  = (XmlElement)info.SelectSingleNode("ChancellorChineseName");
            XmlElement eduDirectorElement = (XmlElement)info.SelectSingleNode("EduDirectorName");
            XmlElement stuDirectorElement = (XmlElement)info.SelectSingleNode("StuDirectorName");

            if (chancellorElement != null)
            {
                chancellor = chancellorElement.InnerText;
            }
            if (eduDirectorElement != null)
            {
                eduDirector = eduDirectorElement.InnerText;
            }
            if (stuDirectorElement != null)
            {
                stuDirector = stuDirectorElement.InnerText;
            }

            globalFieldName.Add("教務主任");
            globalFieldValue.Add(eduDirector);

            globalFieldName.Add("學務主任");
            globalFieldValue.Add(stuDirector);

            globalFieldName.Add("校長");
            globalFieldValue.Add(chancellor);

            _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            #endregion
        }
Ejemplo n.º 24
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!inputed)
            {
                MsgBox.Show("尚未輸入成績");
                return;
            }

            // 驗證所有權數欄位
            ValidAllPCTextBox();

            if (!IsValid())
            {
                return;
            }

            try
            {
                int schoolYear = int.Parse(cboSchoolYear.Text);
                int semester   = int.Parse(cboSemester.Text);
                //int gradeYear = 0;

                //SemesterScoreRecordEditor editor = new SemesterScoreRecordEditor(_student, schoolYear, semester, gradeYear);
                JHSemesterScoreRecord newRecord = new JHSemesterScoreRecord();
                newRecord.RefStudentID = _student.ID;
                newRecord.SchoolYear   = schoolYear;
                newRecord.Semester     = semester;

                List <string> checkSubjName = new List <string>();

                // 檢查科目名稱是否相同,因為科目名稱重複會造成新增錯誤,科目名稱是唯一值。
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    if (row.Cells[chsSubject.Index].Value != null)
                    {
                        string tmpSubjName = "" + row.Cells[chsSubject.Index].Value;
                        if (checkSubjName.Contains(tmpSubjName))
                        {
                            FISCA.Presentation.Controls.MsgBox.Show("科目名稱重複,無法儲存。");
                            return;
                        }
                        else
                        {
                            checkSubjName.Add(tmpSubjName);
                        }
                    }
                }

                //2018/4/16 穎驊因應高雄項目[02-03][06]學期成績,快速新增功能如無原始成績,則結算學期領域成績時快速新增的成績都會變成"0"分
                // 新增原始成績登錄、語文領域,另外看來以前不流行 datagridView 這土法煉鋼有點驚人呀!!。

                //2018/5/22 穎驊再次註解,恩正說不必新增原始成績欄位給屬用者輸入,直接抓分數就好,所以將上一版的輸入格拿掉

                if (CheckDomainValid(txtPC1, txtScore1, txtScore1, txtEffort1))
                {
                    newRecord.Domains.Add("國語文", GetDomainScore("國語文", txtPC1, txtScore1, txtScore1, txtEffort1, txtText1));
                }
                if (CheckDomainValid(txtPC2, txtScore2, txtScore2, txtEffort2))
                {
                    newRecord.Domains.Add("英語", GetDomainScore("英語", txtPC2, txtScore2, txtScore2, txtEffort2, txtText2));
                }
                if (CheckDomainValid(txtPC3, txtScore3, txtScore3, txtEffort3))
                {
                    newRecord.Domains.Add("數學", GetDomainScore("數學", txtPC3, txtScore3, txtScore3, txtEffort3, txtText3));
                }
                if (CheckDomainValid(txtPC4, txtScore4, txtScore4, txtEffort4))
                {
                    newRecord.Domains.Add("社會", GetDomainScore("社會", txtPC4, txtScore4, txtScore4, txtEffort4, txtText4));
                }
                //if (CheckDomainValid(txtPC5, txtScore5, txtScore5, txtEffort5))
                //    newRecord.Domains.Add("藝術與人文", GetDomainScore("藝術與人文", txtPC5, txtScore5, txtScore5, txtEffort5, txtText5));
                //if (CheckDomainValid(txtPC6, txtScore6, txtScore6, txtEffort6))
                //    newRecord.Domains.Add("自然與生活科技", GetDomainScore("自然與生活科技", txtPC6, txtScore6, txtScore6, txtEffort6, txtText6));
                if (CheckDomainValid(txtPC5, txtScore5, txtScore5, txtEffort5))
                {
                    newRecord.Domains.Add("自然科學", GetDomainScore("自然科學", txtPC5, txtScore5, txtScore5, txtEffort5, txtText5));
                }
                if (CheckDomainValid(txtPC6, txtScore6, txtScore6, txtEffort6))
                {
                    newRecord.Domains.Add("藝術", GetDomainScore("藝術", txtPC6, txtScore6, txtScore6, txtEffort6, txtText6));
                }
                if (CheckDomainValid(txtPC7, txtScore7, txtScore7, txtEffort7))
                {
                    newRecord.Domains.Add("健康與體育", GetDomainScore("健康與體育", txtPC7, txtScore7, txtScore7, txtEffort7, txtText7));
                }
                if (CheckDomainValid(txtPC8, txtScore8, txtScore8, txtEffort8))
                {
                    newRecord.Domains.Add("綜合活動", GetDomainScore("綜合活動", txtPC8, txtScore8, txtScore8, txtEffort8, txtText8));
                }
                if (CheckDomainValid(txtPC9, txtScore9, txtScore9, txtEffort9))
                {
                    newRecord.Domains.Add("語文", GetDomainScore("語文", txtPC9, txtScore9, txtScore9, txtEffort9, txtText9));
                }
                if (CheckDomainValid(txtPC10, txtScore10, txtScore10, txtEffort10))
                {
                    newRecord.Domains.Add("科技", GetDomainScore("科技", txtPC10, txtScore10, txtScore10, txtEffort10, txtText10));
                }

                foreach (DataGridViewRow row in dgv.Rows)
                {
                    if (row.IsNewRow)
                    {
                        continue;
                    }

                    PeriodCredit pc = new PeriodCredit();
                    pc.Parse("" + row.Cells[chsPeriodCredit.Index].Value);
                    K12.Data.SubjectScore subject = new K12.Data.SubjectScore();
                    subject.Domain      = "" + row.Cells[chsDomain.Index].Value;
                    subject.Subject     = "" + row.Cells[chsSubject.Index].Value;
                    subject.Period      = pc.Period;
                    subject.Credit      = pc.Credit;
                    subject.Score       = decimal.Parse("" + row.Cells[chsScore.Index].Value);
                    subject.ScoreOrigin = decimal.Parse("" + row.Cells[chsScore.Index].Value); // 2018/5/22 穎華聽從恩正建議,原始成績直接抓取成績即可
                    subject.Effort      = int.Parse("" + row.Cells[chsEffort.Index].Value);
                    subject.Text        = "" + row.Cells[chsText.Index].Value;

                    newRecord.Subjects.Add(subject.Subject, subject);
                }

                if (!string.IsNullOrEmpty(txtElastic.Text))
                {
                    newRecord.Domains.Add("彈性課程", GetElasticDomain());
                }
                if (!string.IsNullOrEmpty(txtLearnDomain.Text))
                {
                    newRecord.LearnDomainScore = decimal.Parse(txtLearnDomain.Text);
                }
                if (!string.IsNullOrEmpty(txtCourseLearn.Text))
                {
                    newRecord.CourseLearnScore = decimal.Parse(txtCourseLearn.Text);
                }

                JHSemesterScore.Insert(newRecord);
                SaveLog(newRecord);
            }
            catch (Exception ex)
            {
                MsgBox.Show("儲存失敗");
                this.DialogResult = DialogResult.Cancel;
                this.Close();
                return;
            }

            this.DialogResult = DialogResult.OK;
        }
Ejemplo n.º 25
0
        private void BgWorkerExport_DoWork(object sender, DoWorkEventArgs e)
        {
            bgWorkerExport.ReportProgress(1);
            try
            {
                // 取得預設樣板
                Workbook  wb  = new Workbook(new MemoryStream(Properties.Resources.Template));
                Worksheet wst = wb.Worksheets[0];


                // 取得學生基本資料
                List <StudentInfo> StudentInfoList = QueryData.GetStudentInfoList3();

                List <string> StudentIDList = new List <string>();
                foreach (StudentInfo si in StudentInfoList)
                {
                    StudentIDList.Add(si.StudentID);
                }

                // 取得地址資訊
                Dictionary <string, JHAddressRecord> AddressDict = new Dictionary <string, JHAddressRecord>();
                List <JHAddressRecord> tmpAddress = JHAddress.SelectByStudentIDs(StudentIDList);
                foreach (JHAddressRecord rec in tmpAddress)
                {
                    if (!AddressDict.ContainsKey(rec.RefStudentID))
                    {
                        AddressDict.Add(rec.RefStudentID, rec);
                    }
                }

                // 取得電話資料
                Dictionary <string, JHPhoneRecord> PhoneDict = new Dictionary <string, JHPhoneRecord>();
                List <JHPhoneRecord> tmpPhone = JHPhone.SelectByStudentIDs(StudentIDList);
                foreach (JHPhoneRecord rec in tmpPhone)
                {
                    if (!PhoneDict.ContainsKey(rec.RefStudentID))
                    {
                        PhoneDict.Add(rec.RefStudentID, rec);
                    }
                }

                bgWorkerExport.ReportProgress(20);

                // 取得監護人父母資訊
                Dictionary <string, JHParentRecord> ParentDict = new Dictionary <string, JHParentRecord>();
                List <JHParentRecord> tmpParent = JHParent.SelectByStudentIDs(StudentIDList);
                foreach (JHParentRecord rec in tmpParent)
                {
                    if (!ParentDict.ContainsKey(rec.RefStudentID))
                    {
                        ParentDict.Add(rec.RefStudentID, rec);
                    }
                }

                // 轉換各項類別對照值
                Dictionary <string, string> MappingTag1 = new Dictionary <string, string>();
                Dictionary <string, string> MappingTag2 = new Dictionary <string, string>();
                Dictionary <string, string> MappingTag3 = new Dictionary <string, string>();
                Dictionary <string, string> MappingTag4 = new Dictionary <string, string>();

                // 取得學生類別
                Dictionary <string, List <string> > StudentTagDict = QueryData.GetStudentTagName(StudentIDList);

                // 解析對照設定
                XElement elmRoot = XElement.Parse(_Configure.MappingContent);
                if (elmRoot != null)
                {
                    foreach (XElement elm in elmRoot.Elements("Group"))
                    {
                        string gpName = elm.Attribute("Name").Value;
                        if (gpName == "學生身分")
                        {
                            foreach (XElement elm1 in elm.Elements("Item"))
                            {
                                string tagName = elm1.Attribute("TagName").Value;
                                if (!MappingTag1.ContainsKey(tagName) && tagName.Length > 0)
                                {
                                    MappingTag1.Add(tagName, elm1.Attribute("Code").Value);
                                }
                            }
                        }

                        if (gpName == "身心障礙")
                        {
                            foreach (XElement elm1 in elm.Elements("Item"))
                            {
                                string tagName = elm1.Attribute("TagName").Value;
                                if (!MappingTag2.ContainsKey(tagName) && tagName.Length > 0)
                                {
                                    MappingTag2.Add(tagName, elm1.Attribute("Code").Value);
                                }
                            }
                        }

                        if (gpName == "學生報名身分設定")
                        {
                            foreach (XElement elm1 in elm.Elements("Item"))
                            {
                                string tagName = elm1.Attribute("TagName").Value;
                                if (!MappingTag3.ContainsKey(tagName) && tagName.Length > 0)
                                {
                                    MappingTag3.Add(tagName, elm1.Attribute("Code").Value);
                                }
                            }
                        }

                        if (gpName == "失業勞工子女")
                        {
                            foreach (XElement elm1 in elm.Elements("Item"))
                            {
                                string tagName = elm1.Attribute("TagName").Value;
                                if (!MappingTag4.ContainsKey(tagName) && tagName.Length > 0)
                                {
                                    MappingTag4.Add(tagName, elm1.Attribute("Code").Value);
                                }
                            }
                        }
                    }
                }



                bgWorkerExport.ReportProgress(40);

                // 取得成績相關資料
                Dictionary <string, List <JHSemesterScoreRecord> > SemesterScoreRecordDict = new Dictionary <string, List <JHSemesterScoreRecord> >();
                List <JHSemesterScoreRecord> tmpSemsScore = JHSemesterScore.SelectByStudentIDs(StudentIDList);
                foreach (JHSemesterScoreRecord rec in tmpSemsScore)
                {
                    if (!SemesterScoreRecordDict.ContainsKey(rec.RefStudentID))
                    {
                        SemesterScoreRecordDict.Add(rec.RefStudentID, new List <JHSemesterScoreRecord>());
                    }

                    SemesterScoreRecordDict[rec.RefStudentID].Add(rec);
                }

                // 取得功過紀錄
                // 功過對照表
                JHMeritDemeritReduceRecord DemeritReduceRecord = JHMeritDemeritReduce.Select();
                // 懲
                Dictionary <string, List <JHDemeritRecord> > DemeritRecordDict = new Dictionary <string, List <JHDemeritRecord> >();
                List <JHDemeritRecord> tmpDemeritRecord = JHDemerit.SelectByStudentIDs(StudentIDList);
                foreach (JHDemeritRecord rec in tmpDemeritRecord)
                {
                    if (rec.Cleared == "是")
                    {
                        continue;
                    }

                    if (rec.OccurDate > _Configure.EndDate)
                    {
                        continue;
                    }
                    else
                    {
                        if (!DemeritRecordDict.ContainsKey(rec.RefStudentID))
                        {
                            DemeritRecordDict.Add(rec.RefStudentID, new List <JHDemeritRecord>());
                        }

                        DemeritRecordDict[rec.RefStudentID].Add(rec);
                    }
                }
                // 獎
                Dictionary <string, List <JHMeritRecord> > MeritRecordDict = new Dictionary <string, List <JHMeritRecord> >();
                List <JHMeritRecord> tmpMeritRecord = JHMerit.SelectByStudentIDs(StudentIDList);
                foreach (JHMeritRecord rec in tmpMeritRecord)
                {
                    if (rec.OccurDate > _Configure.EndDate)
                    {
                        continue;
                    }
                    else
                    {
                        if (!MeritRecordDict.ContainsKey(rec.RefStudentID))
                        {
                            MeritRecordDict.Add(rec.RefStudentID, new List <JHMeritRecord>());
                        }

                        MeritRecordDict[rec.RefStudentID].Add(rec);
                    }
                }

                // 取得服務學習時數
                StudentInfoList = QueryData.FillServiceLearn(StudentIDList, StudentInfoList, _Configure.EndDate);

                // 填入中低收入戶
                StudentInfoList = QueryData.FillIncomeType(StudentIDList, StudentInfoList);


                // 取得學生體適能資料並填入,嘉義版不卡日期,日期傳入不會限制
                StudentInfoList = QueryData.FillStudentFitness(StudentIDList, StudentInfoList, _Configure.EndDate);

                // 取得競賽總積分並填入學生資料
                StudentInfoList = QueryData.FillStudentCompetitionPerformanceSum(StudentIDList, StudentInfoList);

                // 填入 Excel 資料
                int wstRIdx = 1;
                bgWorkerExport.ReportProgress(70);

                foreach (StudentInfo si in StudentInfoList)
                {
                    // 考區代碼 0,嘉義區 10
                    wst.Cells[wstRIdx, 0].PutValue(10);

                    // 集報單位代碼 1
                    wst.Cells[wstRIdx, 1].PutValue(K12.Data.School.Code);

                    // 序號 2
                    wst.Cells[wstRIdx, 2].PutValue(wstRIdx);

                    // 學號 3
                    wst.Cells[wstRIdx, 3].PutValue(si.StudentNumber);

                    // 班級 4
                    wst.Cells[wstRIdx, 4].PutValue(si.ClassName);

                    // 座號 5
                    wst.Cells[wstRIdx, 5].PutValue(si.SeatNo);

                    // 學生姓名 6  // 2021-12-27 有些學校會為了整齊把學生的名字+空白,這裡濾掉
                    wst.Cells[wstRIdx, 6].PutValue(si.StudentName.Replace(" ", "").Replace(" ", ""));

                    // 身分證統一編號 7
                    wst.Cells[wstRIdx, 7].PutValue(si.IDNumber);

                    // 非中華民國身分證號 8
                    if (si.isTaiwanID)
                    {
                        wst.Cells[wstRIdx, 8].PutValue("");
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 8].PutValue("V");
                    }

                    // 性別 9
                    wst.Cells[wstRIdx, 9].PutValue(si.GenderCode);

                    // 出生年(民國年) 10
                    wst.Cells[wstRIdx, 10].PutValue(si.BirthYear);

                    // 出生月 11
                    wst.Cells[wstRIdx, 11].PutValue(si.BirthMonth);

                    // 出生日 12
                    wst.Cells[wstRIdx, 12].PutValue(si.BirthDay);

                    // 畢業學校代碼 13
                    wst.Cells[wstRIdx, 13].PutValue(K12.Data.School.Code);

                    // 畢業年(民國年) 14
                    int gyear;
                    if (int.TryParse(K12.Data.School.DefaultSchoolYear, out gyear))
                    {
                        wst.Cells[wstRIdx, 14].PutValue(gyear + 1);
                    }

                    // 畢肄業 15
                    wst.Cells[wstRIdx, 15].PutValue(1);


                    wst.Cells[wstRIdx, 16].PutValue(0);
                    wst.Cells[wstRIdx, 17].PutValue(0);
                    wst.Cells[wstRIdx, 18].PutValue(0);
                    wst.Cells[wstRIdx, 22].PutValue(0);

                    if (StudentTagDict.ContainsKey(si.StudentID))
                    {
                        foreach (string tagName in StudentTagDict[si.StudentID])
                        {
                            if (MappingTag1.ContainsKey(tagName))
                            {
                                // 學生身分 16
                                wst.Cells[wstRIdx, 16].PutValue(MappingTag1[tagName]);
                            }

                            if (MappingTag2.ContainsKey(tagName))
                            {
                                si.isSpecial = true;
                                // 身心障礙 18
                                wst.Cells[wstRIdx, 18].PutValue(MappingTag2[tagName]);
                            }

                            if (MappingTag3.ContainsKey(tagName))
                            {
                                // 學生報名身分 17
                                wst.Cells[wstRIdx, 17].PutValue(MappingTag3[tagName]);
                            }
                            if (MappingTag4.ContainsKey(tagName))
                            {
                                // 失業勞工子女 22
                                wst.Cells[wstRIdx, 22].PutValue(MappingTag4[tagName]);
                            }
                        }
                    }


                    // 就學區 19,不處理

                    // 低收入戶 20
                    if (si.incomeType1)
                    {
                        wst.Cells[wstRIdx, 20].PutValue(1);
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 20].PutValue(0);
                    }

                    // 中低收入戶 21
                    if (si.incomeType2)
                    {
                        wst.Cells[wstRIdx, 21].PutValue(1);
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 21].PutValue(0);
                    }



                    // 資料授權 23
                    wst.Cells[wstRIdx, 23].PutValue(0);

                    string parentName = "";
                    // 家長姓名 24
                    if (ParentDict.ContainsKey(si.StudentID))
                    {
                        if (!string.IsNullOrWhiteSpace(ParentDict[si.StudentID].CustodianName))
                        {
                            parentName = ParentDict[si.StudentID].CustodianName;
                        }
                        else if (!string.IsNullOrWhiteSpace(ParentDict[si.StudentID].FatherName))
                        {
                            parentName = ParentDict[si.StudentID].FatherName;
                        }
                        else if (!string.IsNullOrWhiteSpace(ParentDict[si.StudentID].MotherName))
                        {
                            parentName = ParentDict[si.StudentID].MotherName;
                        }
                        else
                        {
                        }
                        wst.Cells[wstRIdx, 24].PutValue(parentName);
                    }


                    // 市內電話 25
                    // 市內電話分機 26
                    // 行動電話 27
                    if (PhoneDict.ContainsKey(si.StudentID))
                    {
                        wst.Cells[wstRIdx, 25].PutValue(PhoneDict[si.StudentID].Contact.Replace("-", "").Replace(")", "").Replace("(", ""));
                        wst.Cells[wstRIdx, 27].PutValue(PhoneDict[si.StudentID].Cell.Replace("-", "").Replace(")", "").Replace("(", ""));
                    }


                    // 郵遞區號 28
                    if (AddressDict.ContainsKey(si.StudentID))
                    {
                        if (AddressDict[si.StudentID].MailingZipCode != null)
                        {
                            string zipCode = AddressDict[si.StudentID].MailingZipCode;

                            if (zipCode.Length >= 3)
                            {
                                zipCode = zipCode.Substring(0, 3);
                            }

                            wst.Cells[wstRIdx, 28].PutValue(zipCode);
                        }

                        // 通訊地址 29
                        wst.Cells[wstRIdx, 29].PutValue(AddressDict[si.StudentID].MailingCounty + AddressDict[si.StudentID].MailingTown + AddressDict[si.StudentID].MailingDistrict + AddressDict[si.StudentID].MailingArea + AddressDict[si.StudentID].MailingDetail);
                    }

                    // 計算分數
                    if (SemesterScoreRecordDict.ContainsKey(si.StudentID))
                    {
                        si.CalcSemsScore5(SemesterScoreRecordDict[si.StudentID]);
                    }

                    // 健康與體育 30
                    if (si.isDomainHelPass)
                    {
                        wst.Cells[wstRIdx, 30].PutValue(1);
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 30].PutValue(0);
                    }

                    // 藝術 31
                    if (si.isDoaminArtPass)
                    {
                        wst.Cells[wstRIdx, 31].PutValue(1);
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 31].PutValue(0);
                    }

                    // 綜合活動 32
                    if (si.isDomainActPass)
                    {
                        wst.Cells[wstRIdx, 32].PutValue(1);
                    }
                    else
                    {
                        wst.Cells[wstRIdx, 32].PutValue(0);
                    }

                    // 品德表現 33
                    List <JHDemeritRecord> recD;
                    List <JHMeritRecord>   recM;

                    if (DemeritRecordDict.ContainsKey(si.StudentID))
                    {
                        recD = DemeritRecordDict[si.StudentID];
                    }
                    else
                    {
                        recD = new List <JHDemeritRecord>();
                    }

                    if (MeritRecordDict.ContainsKey(si.StudentID))
                    {
                        recM = MeritRecordDict[si.StudentID];
                    }
                    else
                    {
                        recM = new List <JHMeritRecord>();
                    }

                    si.CalcDemeritMemeritScore(recD, recM, DemeritReduceRecord);
                    wst.Cells[wstRIdx, 33].PutValue(si.MeritDemeritScore);

                    // 服務學習 34
                    wst.Cells[wstRIdx, 34].PutValue(si.ServiceLearnScore);

                    // 體適能 35
                    si.CalcFitnessScore();
                    wst.Cells[wstRIdx, 35].PutValue(si.FitnessScore);

                    // 競賽表現 36,使用者自行處理
                    if (si.CompPerfSum.HasValue)
                    {
                        wst.Cells[wstRIdx, 36].PutValue(si.CompPerfSum.Value);
                    }
                    else  // 2021-12-27 嘉義協同國中 見安老師要求預設值 0
                    {
                        wst.Cells[wstRIdx, 36].PutValue("0");
                    }

                    // 2021-12-27 嘉義協同國中 見安老師要求預設值全部填1
                    // https://3.basecamp.com/4399967/buckets/15765350/todos/4475736499#__recording_4477516175
                    // 家長意見_高中 37
                    wst.Cells[wstRIdx, 37].PutValue("1");
                    // 家長意見_高職 38
                    wst.Cells[wstRIdx, 38].PutValue("1");
                    // 導師意見_高中 39
                    wst.Cells[wstRIdx, 39].PutValue("1");
                    // 導師意見_高職 40
                    wst.Cells[wstRIdx, 40].PutValue("1");
                    // 輔導教師意見_高中 41
                    wst.Cells[wstRIdx, 41].PutValue("1");
                    // 輔導教師意見_高職 42
                    wst.Cells[wstRIdx, 42].PutValue("1");


                    wstRIdx++;
                }

                bgWorkerExport.ReportProgress(100);

                e.Result = wb;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 26
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(School.ChineseName);

            globalFieldName.Add("列印時間");
            globalFieldValue.Add(Global.CDate(DateTime.Now.ToString("yyyy/MM/dd")) + " " + DateTime.Now.ToString("HH:mm:ss"));

            ReportConfiguration _Dylanconfig = new ReportConfiguration(Global.OneFileSave);

            OneFileSave = _Dylanconfig.GetBoolean("單檔儲存", false);
            StudentDoc  = new Dictionary <string, Document>();


            List <JHPeriodMappingInfo>  periodList  = JHPeriodMapping.SelectAll();
            List <JHAbsenceMappingInfo> absenceList = JHAbsenceMapping.SelectAll();

            double total = Options.Students.Count;
            double count = 0;

            List <string> student_ids = new List <string>();

            foreach (JHStudentRecord item in Options.Students)
            {
                student_ids.Add(item.ID);
            }

            DocumentBuilder templateBuilder = new DocumentBuilder(_template);

            #region 變更節權數顯示
            string pcDisplay   = string.Empty;
            bool   printPeriod = Config.GetBoolean("列印節數", false);
            bool   printCredit = Config.GetBoolean("列印權數", false);
            if (printPeriod && printCredit)
            {
                pcDisplay = "節/權數";
            }
            else if (printPeriod)
            {
                pcDisplay = "節數";
            }
            else if (printCredit)
            {
                pcDisplay = "權數";
            }

            while (templateBuilder.MoveToMergeField("節權數"))
            {
                templateBuilder.Write(pcDisplay);
            }
            #endregion

            #region 快取資料
            // 取得學生缺曠
            Dictionary <string, List <AutoSummaryRecord> > autoSummaryCache = new Dictionary <string, List <AutoSummaryRecord> >();
            foreach (AutoSummaryRecord record in AutoSummary.Select(student_ids, null))
            {
                if (!autoSummaryCache.ContainsKey(record.RefStudentID))
                {
                    autoSummaryCache.Add(record.RefStudentID, new List <AutoSummaryRecord>());
                }
                autoSummaryCache[record.RefStudentID].Add(record);
            }

            // 取得學生異動
            Dictionary <string, List <JHUpdateRecordRecord> > updateRecordCache = new Dictionary <string, List <JHUpdateRecordRecord> >();
            foreach (var record in JHUpdateRecord.SelectByStudentIDs(student_ids))
            {
                if (!updateRecordCache.ContainsKey(record.StudentID))
                {
                    updateRecordCache.Add(record.StudentID, new List <JHUpdateRecordRecord>());
                }
                updateRecordCache[record.StudentID].Add(record);
            }

            // 取得學生學期成績
            Dictionary <string, List <JHSemesterScoreRecord> > semesterScoreCache = new Dictionary <string, List <JHSemesterScoreRecord> >();
            foreach (var record in JHSemesterScore.SelectByStudentIDs(student_ids))
            {
                if (!semesterScoreCache.ContainsKey(record.RefStudentID))
                {
                    semesterScoreCache.Add(record.RefStudentID, new List <JHSemesterScoreRecord>());
                }
                semesterScoreCache[record.RefStudentID].Add(record);
            }

            // 取得學生學期歷程
            Dictionary <string, JHSemesterHistoryRecord> semesterHistoryCache = new Dictionary <string, JHSemesterHistoryRecord>();
            foreach (var record in JHSemesterHistory.SelectByStudentIDs(student_ids))
            {
                if (!semesterHistoryCache.ContainsKey(record.RefStudentID))
                {
                    semesterHistoryCache.Add(record.RefStudentID, record);
                }
            }

            // 取得學生畢業成績
            Dictionary <string, K12.Data.GradScoreRecord> StudGradScoreDic = new Dictionary <string, GradScoreRecord>();
            foreach (GradScoreRecord score in GradScore.SelectByIDs <GradScoreRecord>(student_ids))
            {
                StudGradScoreDic.Add(score.RefStudentID, score);
            }


            #endregion

            #region 判斷要列印的領域科目
            Dictionary <string, bool> domains = new Dictionary <string, bool>();
            string domainSubjectSetup         = Config.GetString("領域科目設定", "Domain");
            if (domainSubjectSetup == "Domain")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, true);
                }
                if (domains.ContainsKey("語文"))
                {
                    domains["語文"] = false;
                }
                if (domains.ContainsKey("彈性課程"))
                {
                    domains["彈性課程"] = false;
                }
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", false);
                }
            }
            else if (domainSubjectSetup == "Subject")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, false);
                }
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", false);
                }
            }
            else
            {
                throw new Exception("請重新儲存列印設定");
            }


            //string domainSubjectSetup = Config.GetString("領域科目設定", "Domain");
            //if (domainSubjectSetup == "Domain")
            //{
            //    foreach (var domain in JHSchool.Evaluation.Subject.Domains)
            //        domains.Add(domain, DomainSubjectExpand.不展開);

            //    if (!domains.ContainsKey("")) domains.Add("", DomainSubjectExpand.展開);
            //}
            //else if (domainSubjectSetup == "Subject")
            //{
            //    foreach (var domain in JHSchool.Evaluation.Subject.Domains)
            //        domains.Add(domain, DomainSubjectExpand.展開);
            //    if (!domains.ContainsKey("")) domains.Add("", DomainSubjectExpand.展開);
            //}
            //else
            //    throw new Exception("請重新儲存一次列印設定");

            #endregion

            #region  務學習時數
            Global._SLRDict.Clear();
            Global._SLRDict = Utility.GetServiceLearningDetail(student_ids);
            #endregion

            #region 產生
            foreach (JHStudentRecord student in Options.Students)
            {
                count++;
                DocumentBuilder builder = null;
                Document        each    = (Document)_template.Clone(true);

                #region 建立學期歷程對照
                List <SemesterHistoryItem> semesterHistoryList = null;
                if (semesterHistoryCache.ContainsKey(student.ID))
                {
                    semesterHistoryList = semesterHistoryCache[student.ID].SemesterHistoryItems;
                }
                else
                {
                    semesterHistoryList = new List <SemesterHistoryItem>();
                }

                SemesterMap map = new SemesterMap();
                map.SetData(semesterHistoryList);
                #endregion

                #region Part1
                builder = new DocumentBuilder(each);

                StudentBasicInfo basic = new StudentBasicInfo();
                basic.SetStudent(student, semesterHistoryList);

                StudentSemesterHistory history = new StudentSemesterHistory();
                history.SetData(semesterHistoryList);

                each.MailMerge.MergeField += delegate(object sender1, MergeFieldEventArgs e1)
                {
                    #region 處理照片
                    if (e1.FieldName == "照片")
                    {
                        byte[] photoBytes = null;
                        try
                        {
                            photoBytes = Convert.FromBase64String("" + e1.FieldValue);
                        }
                        catch (Exception ex)
                        {
                            e1.Field.Remove();
                            return;
                        }

                        if (photoBytes == null || photoBytes.Length == 0)
                        {
                            e1.Field.Remove();
                            return;
                        }

                        DocumentBuilder builder1 = new DocumentBuilder(e1.Document);
                        builder1.MoveToField(e1.Field, true);
                        e1.Field.Remove();

                        Shape photoShape = new Shape(e1.Document, ShapeType.Image);
                        photoShape.ImageData.SetImage(photoBytes);
                        photoShape.WrapType = WrapType.Inline;

                        #region AutoResize

                        double origHWRate  = photoShape.ImageData.ImageSize.HeightPoints / photoShape.ImageData.ImageSize.WidthPoints;
                        double shapeHeight = (builder1.CurrentParagraph.ParentNode.ParentNode as Row).RowFormat.Height * 6;
                        double shapeWidth  = (builder1.CurrentParagraph.ParentNode as Cell).CellFormat.Width;
                        if ((shapeHeight / shapeWidth) < origHWRate)
                        {
                            shapeWidth = shapeHeight / origHWRate;
                        }
                        else
                        {
                            shapeHeight = shapeWidth * origHWRate;
                        }

                        #endregion

                        photoShape.Height = shapeHeight;
                        photoShape.Width  = shapeWidth;

                        builder1.InsertNode(photoShape);
                    }
                    #endregion
                };

                List <string> fieldName = new List <string>();
                fieldName.AddRange(basic.GetFieldName());
                fieldName.AddRange(history.GetFieldName());
                List <string> fieldValue = new List <string>();
                fieldValue.AddRange(basic.GetFieldValue());
                fieldValue.AddRange(history.GetFieldValue());

                each.MailMerge.Execute(fieldName.ToArray(), fieldValue.ToArray());

                builder.MoveToMergeField("異動");
                List <JHUpdateRecordRecord> updateRecordList = null;
                if (updateRecordCache.ContainsKey(student.ID))
                {
                    updateRecordList = updateRecordCache[student.ID];
                }
                else
                {
                    updateRecordList = new List <JHUpdateRecordRecord>();
                }
                StudentUpdateRecordProcessor updateRecordProcessor = new StudentUpdateRecordProcessor(builder);
                updateRecordProcessor.SetData(updateRecordList);

                builder.MoveToMergeField("成績");
                List <JHSemesterScoreRecord> semesterScoreList = null;
                if (semesterScoreCache.ContainsKey(student.ID))
                {
                    semesterScoreList = semesterScoreCache[student.ID];
                }
                else
                {
                    semesterScoreList = new List <JHSemesterScoreRecord>();
                }

                // 學生畢業成績
                K12.Data.GradScoreRecord studGradScore = new GradScoreRecord();
                if (StudGradScoreDic.ContainsKey(student.ID))
                {
                    studGradScore = StudGradScoreDic[student.ID];
                }

                StudentSemesterScoreProcessor semesterScoreProcessor = new StudentSemesterScoreProcessor(builder, map, domainSubjectSetup, domains, studGradScore);
                semesterScoreProcessor.DegreeMapper = _degreeMapper;
                semesterScoreProcessor.PrintPeriod  = printPeriod;
                semesterScoreProcessor.PrintCredit  = printCredit;
                semesterScoreProcessor.SetData(semesterScoreList);

                #endregion

                #region Part2
                //builder = new DocumentBuilder(each);

                builder.MoveToMergeField("領域文字描述");
                if (Config.GetBoolean("列印文字評語", true))
                {
                    StudentDomainTextProcessor domainTextProcessor = new StudentDomainTextProcessor(builder, map);
                    domainTextProcessor.SetData(semesterScoreList);
                }
                else
                {
                    Section deleteSection = builder.CurrentSection;
                    each.Sections.Remove(deleteSection);
                }

                #endregion

                #region Part3
                //Document part3 = (Document)_template_part3.Clone(true);
                //builder = new DocumentBuilder(each);

                builder.MoveToMergeField("日常行為");
                StudentMoralProcessor moralProcessor = new StudentMoralProcessor(builder, map, periodList, absenceList);

                List <AutoSummaryRecord> autoSummaryList = null;
                if (autoSummaryCache.ContainsKey(student.ID))
                {
                    autoSummaryList = autoSummaryCache[student.ID];
                }
                else
                {
                    autoSummaryList = new List <AutoSummaryRecord>();
                }

                moralProcessor.SetData(autoSummaryList);

                // 處理多出來 table row
                Cell  cel   = moralProcessor.GetCurrentCell();
                Table table = cel.ParentRow.ParentTable;
                for (int i = 47; i >= 20; i--)
                {
                    bool rm = true;
                    foreach (Aspose.Words.Cell cell in table.Rows[i].Cells)
                    {
                        if (cell.GetText() != "\a")
                        {
                            rm = false;
                            break;
                        }
                    }

                    if (rm)
                    {
                        table.Rows[i].Remove();
                    }
                }

                #endregion

                if (OneFileSave)
                {
                    each.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());

                    string fileName = "";
                    fileName = student.StudentNumber;

                    fileName += "_" + student.IDNumber;

                    if (!string.IsNullOrEmpty(student.RefClassID))
                    {
                        fileName += "_" + student.Class.Name;
                    }
                    else
                    {
                        fileName += "_";
                    }

                    fileName += "_" + (student.SeatNo.HasValue ? student.SeatNo.Value.ToString() : "");
                    fileName += "_" + student.Name;

                    if (!StudentDoc.ContainsKey(fileName))
                    {
                        StudentDoc.Add(fileName, each);
                    }
                }
                else
                {
                    foreach (Section sec in each.Sections)
                    {
                        _doc.Sections.Add(_doc.ImportNode(sec, true));
                    }
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            if (!OneFileSave)
            {
                _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            }

            #endregion
        }
Ejemplo n.º 27
0
        private void MasterWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //1.Goup By 可選擇的科目清單。
            //2.寫入成績資料到 ReportStudent 上。



            int schoolYear = Semester.SelectedSchoolYear;
            int semester   = Semester.SelectedSemester;
            FunctionSpliter <string, JHSemesterScoreRecord> selectData = new FunctionSpliter <string, JHSemesterScoreRecord>(1000, 5);

            selectData.Function = delegate(List <string> ps)
            {
                return(JHSemesterScore.SelectBySchoolYearAndSemester(ps, schoolYear, semester));
            };
            List <JHSemesterScoreRecord> semsScores = selectData.Execute(AllStudents.ToKeys());

            GroupBySubjects(semsScores);

            //先把學生身上的成績、排名相關資料清掉。
            foreach (ReportStudent each in AllStudents)
            {
                each.Clear();
                each.Scores.Add(Utilities.SubjectToken, new ScoreCollection()); //科目成績。
                each.Scores.Add(Utilities.DomainToken, new ScoreCollection());  //領域成績。
                each.Scores.Add(Utilities.SummaryToken, new ScoreCollection()); //運算後的成績。
            }

            //將成績填到學生身上。
            Dictionary <string, ReportStudent> dicAllStudent = AllStudents.ToDictionary();

            foreach (JHSemesterScoreRecord eachScore in semsScores)
            {
                //如果找不到該學生,跳到下一筆。
                if (!dicAllStudent.ContainsKey(eachScore.RefStudentID))
                {
                    continue;
                }

                ReportStudent student = dicAllStudent[eachScore.RefStudentID];

                //科目成績。
                foreach (SubjectScore each in eachScore.Subjects.Values)
                {
                    // 初始執
                    decimal ss = -1;

                    if (Perference.UserSelScoreType == "原始成績")
                    {
                        if (each.ScoreOrigin.HasValue)
                        {
                            ss = each.ScoreOrigin.Value;
                        }
                    }

                    if (Perference.UserSelScoreType == "原始補考擇優")
                    {
                        // 成績
                        if (each.Score.HasValue && each.Score.Value > ss)
                        {
                            ss = each.Score.Value;
                        }
                    }

                    //                    if (!each.Score.HasValue) continue; //沒有分數不處理。

                    if (ss == -1)
                    {
                        continue;
                    }

                    if (!each.Credit.HasValue || each.Credit.Value < 0)
                    {
                        continue;                                                  //沒有節數不處理。 //2021-07 要求權重0也要印出
                    }
                    if (!student.Scores[Utilities.SubjectToken].Contains(each.Subject))
                    {
                        student.Scores[Utilities.SubjectToken].Add(each.Subject, ss, each.Credit.Value);

                        if (Perference.UserSelScoreType == "原始補考擇優" && each.ScoreMakeup.HasValue)
                        {
                            student.Scores[Utilities.DomainToken].AddReExam(each.Subject, each.ScoreMakeup.Value);
                        }
                    }
                }

                //領域成績。
                foreach (DomainScore each in eachScore.Domains.Values)
                {
                    decimal dd = -1;
                    if (Perference.UserSelScoreType == "原始成績")
                    {
                        if (each.ScoreOrigin.HasValue)
                        {
                            dd = each.ScoreOrigin.Value;
                        }
                    }

                    if (Perference.UserSelScoreType == "原始補考擇優")
                    {
                        if (each.Score.HasValue && each.Score.Value > dd)
                        {
                            dd = each.Score.Value;
                        }
                    }

                    //if (!each.Score.HasValue) continue;
                    if (dd == -1)
                    {
                        continue;
                    }

                    if (!each.Credit.HasValue || each.Credit.Value < 0)
                    {
                        continue;                                                 //2021-07 要求權重0也要印出
                    }
                    if (!student.Scores[Utilities.DomainToken].Contains(each.Domain))
                    {
                        student.Scores[Utilities.DomainToken].Add(each.Domain, dd, each.Credit.Value);

                        if (Perference.UserSelScoreType == "原始補考擇優" && each.ScoreMakeup.HasValue)
                        {
                            student.Scores[Utilities.DomainToken].AddReExam(each.Domain, each.ScoreMakeup.Value);
                        }
                    }
                }

                //運算後成績是在使用者按下列印時才計算。
                //因為需要依據使用者選擇的科目進行計算。
            }
        }
Ejemplo n.º 28
0
        public void Save()
        {
            List <JHSemesterScoreRecord> addSemsScore      = new List <JHSemesterScoreRecord>();
            List <JHSemesterScoreRecord> updateSemsScore   = new List <JHSemesterScoreRecord>();
            SubjectScoreLogFormater      subjLogFormater   = new SubjectScoreLogFormater();
            DomainScoreLogFormater       domainLogFormater = new DomainScoreLogFormater();

            foreach (StudentScore student in Students)
            {
                #region 決定要新增還是更新。
                JHSemesterScoreRecord JHScore = GetJHSemesterScore(student.Id, student.SemestersScore[SemesterData.Empty]);
                SCSemsScore           SCScore = student.SemestersScore[SemesterData.Empty];

                if (string.IsNullOrEmpty(JHScore.ID))
                {
                    addSemsScore.Add(JHScore);
                }
                else
                {
                    updateSemsScore.Add(JHScore);
                }
                #endregion

                #region 產生科目資料。
                JHScore.Subjects.Clear();
                foreach (string strSubject in SCScore.Subject)
                {
                    SemesterSubjectScore objSCSubject = SCScore.Subject[strSubject];
                    SubjectScore         objJHSubject = GetJHSubjectScore(strSubject, objSCSubject);
                    LogData subjLog = new LogData(strSubject);
                    subjLog.Formater = subjLogFormater;

                    decimal?score = objSCSubject.Value.HasValue ? (decimal?)(double)objSCSubject.Value : null;

                    //記錄 Log
                    subjLog.Add(new LogData("成績", objJHSubject.Score + "", score.ToString()));
                    subjLog.Add(new LogData("權重", objJHSubject.Credit + "", objSCSubject.Weight + ""));
                    subjLog.Add(new LogData("節數", objJHSubject.Period + "", objSCSubject.Period + ""));
                    if (Program.Mode == ModuleMode.KaoHsiung)
                    {
                        subjLog.Add(new LogData("努力程度", objJHSubject.Effort + "", objSCSubject.Effort + ""));
                    }
                    subjLog.Add(new LogData("文字評量", objJHSubject.Text + "", objSCSubject.Text));
                    subjLog.Add(new LogData("領域", objJHSubject.Domain + "", objSCSubject.Domain));
                    SCScore.Subject.Log.Add(subjLog);

                    objJHSubject.Score  = score;
                    objJHSubject.Credit = objSCSubject.Weight;
                    objJHSubject.Period = objSCSubject.Period;
                    objJHSubject.Effort = objSCSubject.Effort;
                    objJHSubject.Text   = objSCSubject.Text;
                    objJHSubject.Domain = objSCSubject.Domain;

                    JHScore.Subjects.Add(strSubject, objJHSubject);
                }

                //排序科目名稱。
                Dictionary <string, SubjectScore> orderSubject = new Dictionary <string, SubjectScore>(JHScore.Subjects);
                JHScore.Subjects.Clear();
                foreach (string subjName in Util.SortSubjectDomain(orderSubject.Keys))
                {
                    JHScore.Subjects.Add(subjName, orderSubject[subjName]);
                }
                #endregion

                #region 產生領域資料。
                JHScore.Domains.Clear();
                foreach (string strDomain in SCScore.Domain)
                {
                    //彈性課程不記錄領域領域。
                    if (Util.IsVariableDomain(strDomain))
                    {
                        continue;
                    }

                    SemesterDomainScore objSCDomain = SCScore.Domain[strDomain];
                    DomainScore         objJHDomain = GetJHDomainScore(strDomain, objSCDomain);
                    LogData             domainLog   = new LogData(strDomain);
                    domainLog.Formater = subjLogFormater;

                    decimal?score = objSCDomain.Value.HasValue ? (decimal?)(double)objSCDomain.Value : null;

                    //記錄 Log
                    domainLog.Add(new LogData("成績", objJHDomain.Score + "", score + ""));
                    domainLog.Add(new LogData("權重", objJHDomain.Credit + "", objSCDomain.Weight + ""));
                    domainLog.Add(new LogData("節數", objJHDomain.Period + "", objSCDomain.Period + ""));
                    if (Program.Mode == ModuleMode.KaoHsiung)
                    {
                        domainLog.Add(new LogData("努力程度", objJHDomain.Effort + "", objSCDomain.Effort + ""));
                    }
                    domainLog.Add(new LogData("文字評量", objJHDomain.Text + "", objSCDomain.Text));
                    SCScore.Domain.Log.Add(domainLog);

                    objJHDomain.Score  = score;
                    objJHDomain.Credit = objSCDomain.Weight;
                    objJHDomain.Period = objSCDomain.Period;
                    objJHDomain.Effort = objSCDomain.Effort;
                    objJHDomain.Text   = objSCDomain.Text;

                    JHScore.Domains.Add(strDomain, objJHDomain);
                }

                //記錄 Log
                SCScore.LearningLog.Formater    = domainLogFormater;
                SCScore.LearningLog.OriginValue = JHScore.CourseLearnScore + "";
                SCScore.LearningLog.NewValue    = SCScore.LearnDomainScore + "";
                SCScore.CourseLog.Formater      = domainLogFormater;
                SCScore.CourseLog.OriginValue   = JHScore.CourseLearnScore + "";
                SCScore.CourseLog.NewValue      = SCScore.CourseLearnScore + "";

                JHScore.LearnDomainScore = SCScore.LearnDomainScore;
                JHScore.CourseLearnScore = SCScore.CourseLearnScore;

                //排序領域名稱。
                Dictionary <string, DomainScore> orderDomain = new Dictionary <string, DomainScore>(JHScore.Domains);
                JHScore.Domains.Clear();
                foreach (string domainName in Util.SortSubjectDomain(orderDomain.Keys))
                {
                    JHScore.Domains.Add(domainName, orderDomain[domainName]);
                }
                #endregion
            }

            #region 新增科目成績
            FunctionSpliter <JHSemesterScoreRecord, JHSemesterScoreRecord> addSpliter =
                new FunctionSpliter <JHSemesterScoreRecord, JHSemesterScoreRecord>(500, 5);
            addSpliter.Function = delegate(List <JHSemesterScoreRecord> part)
            {
                // 加入檢查當科目與領域成績筆數0不新增
                List <JHSemesterScoreRecord> insertPart = new List <JHSemesterScoreRecord> ();

                foreach (JHSemesterScoreRecord rec in part)
                {
                    // 沒有任何領域或科目成績
                    if (rec.Domains.Count == 0 && rec.Subjects.Count == 0)
                    {
                        continue;
                    }

                    insertPart.Add(rec);
                }

                if (insertPart.Count > 0)
                {
                    JHSemesterScore.Insert(insertPart);
                }

                return(new List <JHSemesterScoreRecord>());
            };
            addSpliter.ProgressChange = delegate(int progress)
            {
                Reporter.Feedback("新增科目成績...", Util.CalculatePercentage(addSemsScore.Count, progress));
            };
            addSpliter.Execute(addSemsScore);
            #endregion

            #region 更新科目成績
            FunctionSpliter <JHSemesterScoreRecord, JHSemesterScoreRecord> updateSpliter =
                new FunctionSpliter <JHSemesterScoreRecord, JHSemesterScoreRecord>(500, 5);
            updateSpliter.Function = delegate(List <JHSemesterScoreRecord> part)
            {
                JHSemesterScore.Update(part);
                return(new List <JHSemesterScoreRecord>());
            };
            updateSpliter.ProgressChange = delegate(int progress)
            {
                Reporter.Feedback("更新科目成績...", Util.CalculatePercentage(updateSemsScore.Count, progress));
            };
            updateSpliter.Execute(updateSemsScore);
            #endregion
        }
Ejemplo n.º 29
0
        public Dictionary <string, bool> Evaluate(IEnumerable <StudentRecord> list)
        {
            _result.Clear();

            Dictionary <string, bool> passList = new Dictionary <string, bool>();

            Dictionary <string, List <JHSemesterScoreRecord> > studentSemesterScoreCache = new Dictionary <string, List <JHSemesterScoreRecord> >();

            foreach (JHSemesterScoreRecord record in JHSemesterScore.SelectByStudentIDs(list.AsKeyList()))
            {
                if (!studentSemesterScoreCache.ContainsKey(record.RefStudentID))
                {
                    studentSemesterScoreCache.Add(record.RefStudentID, new List <JHSemesterScoreRecord>());
                }
                studentSemesterScoreCache[record.RefStudentID].Add(record);
            }

            //學生能被承認的學年度學期對照
            Dictionary <string, List <string> > studentSYSM = new Dictionary <string, List <string> >();

            #region 學期歷程
            foreach (K12.Data.SemesterHistoryRecord shr in K12.Data.SemesterHistory.SelectByStudentIDs(list.Select(x => x.ID)))
            {
                if (!studentSYSM.ContainsKey(shr.RefStudentID))
                {
                    studentSYSM.Add(shr.RefStudentID, new List <string>());
                }

                Dictionary <string, K12.Data.SemesterHistoryItem> check = new Dictionary <string, K12.Data.SemesterHistoryItem>()
                {
                    { "1a", null },
                    { "1b", null },
                    { "2a", null },
                    { "2b", null },
                    { "3a", null },
                    { "3b", null }
                };

                foreach (K12.Data.SemesterHistoryItem item in shr.SemesterHistoryItems)
                {
                    string grade = item.GradeYear + "";

                    if (grade == "7")
                    {
                        grade = "1";
                    }
                    if (grade == "8")
                    {
                        grade = "2";
                    }
                    if (grade == "9")
                    {
                        grade = "3";
                    }

                    if (grade == "1" || grade == "2" || grade == "3")
                    {
                        string key = "";
                        if (item.Semester == 1)
                        {
                            key = grade + "a";
                        }
                        else if (item.Semester == 2)
                        {
                            key = grade + "b";
                        }
                        else
                        {
                            continue;
                        }

                        //相同年級取較新的學年度
                        if (check[key] == null)
                        {
                            check[key] = item;
                        }
                        else if (item.SchoolYear > check[key].SchoolYear)
                        {
                            check[key] = item;
                        }
                    }
                }

                foreach (string key in check.Keys)
                {
                    if (check[key] == null)
                    {
                        continue;
                    }

                    K12.Data.SemesterHistoryItem item = check[key];

                    studentSYSM[shr.RefStudentID].Add(item.SchoolYear + "_" + item.Semester);
                }
            }

            #endregion

            foreach (StudentRecord each in list)
            {
                List <ResultDetail> resultList = new List <ResultDetail>();

                // 有學期成績
                if (studentSemesterScoreCache.ContainsKey(each.ID))
                {
                    // 存放符合標準畢業領域成績
                    List <decimal> passScoreList = new List <decimal>();

                    //每個學期整理後的成績
                    List <List <K12.Data.DomainScore> > GradeScoreList = new List <List <K12.Data.DomainScore> >();

                    // 取得學生學生領域成績填入計算畢業成績用
                    foreach (JHSemesterScoreRecord record in studentSemesterScoreCache[each.ID])
                    {
                        string key = record.SchoolYear + "_" + record.Semester;

                        //只處理承認的學年度學期
                        if (!studentSYSM.ContainsKey(each.ID) || !studentSYSM[each.ID].Contains(key))
                        {
                            continue;
                        }

                        //整理後的領域成績
                        List <K12.Data.DomainScore> domainScoreList = new List <K12.Data.DomainScore>();

                        K12.Data.DomainScore 語文 = new K12.Data.DomainScore();
                        語文.Domain = "語文";

                        decimal sum    = 0;
                        decimal credit = 0;


                        // 2017/5/25 穎驊新增, 因應 高雄客服 高雄小組 [05-01][--] 項目調整,
                        // 舊有邏輯無論該學期是否已經有教務作業期末結算完產生 "語文領域" 的領域成績,
                        // 皆會再額外再幫它算一次並且加入語文領域總分、語文領域權重,此行為容易造成資料的組成比重不對,產生錯誤無法解釋的語文領域分數,
                        // 現在加入新判斷,如果該學期已經有 語文領域成績, 則不會再另外計算、加入該學期的語文領域成績,
                        // 反之,如果該學期 沒有語文領域成績, 會再計算一次 補上,以作為畢業預警判斷使用。

                        bool hasLanguageDomain = false;

                        //跑一遍領域成績
                        foreach (K12.Data.DomainScore domain in record.Domains.Values)
                        {
                            if (domain.Domain == "語文")
                            {
                                hasLanguageDomain = true;
                            }

                            //這三種挑出來處理
                            if (domain.Domain == "國語文" || domain.Domain == "英語")
                            {
                                if (domain.Score.HasValue && domain.Credit.HasValue)
                                {
                                    sum    += domain.Score.Value * domain.Credit.Value;
                                    credit += domain.Credit.Value;

                                    //處理高雄語文顯示
                                    //  加權總分
                                    if (!TempData.tmpStudDomainScoreDict.ContainsKey(record.RefStudentID))
                                    {
                                        TempData.tmpStudDomainScoreDict.Add(record.RefStudentID, new Dictionary <string, decimal>());
                                    }

                                    if (!TempData.tmpStudDomainCreditDict.ContainsKey(record.RefStudentID))
                                    {
                                        TempData.tmpStudDomainCreditDict.Add(record.RefStudentID, new Dictionary <string, decimal>());
                                    }

                                    if (!TempData.tmpStudDomainScoreDict[record.RefStudentID].ContainsKey(domain.Domain))
                                    {
                                        TempData.tmpStudDomainScoreDict[record.RefStudentID].Add(domain.Domain, 0);
                                    }

                                    // 學分數
                                    if (!TempData.tmpStudDomainCreditDict[record.RefStudentID].ContainsKey(domain.Domain))
                                    {
                                        TempData.tmpStudDomainCreditDict[record.RefStudentID].Add(domain.Domain, 0);
                                    }

                                    TempData.tmpStudDomainScoreDict[record.RefStudentID][domain.Domain]  += (domain.Score.Value * domain.Credit.Value);
                                    TempData.tmpStudDomainCreditDict[record.RefStudentID][domain.Domain] += domain.Credit.Value;
                                }
                            }
                            else
                            {
                                domainScoreList.Add(domain);
                            }
                        }

                        if (!hasLanguageDomain && credit > 0)
                        {
                            語文.Score  = Math.Round(sum / credit, 2, MidpointRounding.AwayFromZero);
                            語文.Credit = credit;

                            domainScoreList.Add(語文);
                        }

                        //會被加入就代表承認了
                        GradeScoreList.Add(domainScoreList);
                    }

                    Dictionary <string, decimal> domainScoreSum   = new Dictionary <string, decimal>();
                    Dictionary <string, decimal> domainScoreCount = new Dictionary <string, decimal>();

                    foreach (List <K12.Data.DomainScore> scoreList in GradeScoreList)
                    {
                        foreach (K12.Data.DomainScore ds in scoreList)
                        {
                            string domainName = ds.Domain;

                            if (!domainScoreSum.ContainsKey(domainName))
                            {
                                domainScoreSum.Add(domainName, 0);
                            }
                            if (!domainScoreCount.ContainsKey(domainName))
                            {
                                domainScoreCount.Add(domainName, 0);
                            }

                            if (ds.Score.HasValue)
                            {
                                domainScoreSum[domainName] += ds.Score.Value;
                                //同一學期不會有相同領域名稱,可直接作++
                                domainScoreCount[domainName]++;
                            }
                        }
                    }

                    //2017/5/9 穎驊修正 ,因應 高雄 [08-05][03] 畢業資格判斷成績及格標準調整 項目,
                    // 領域 分數超過60分 ,以 四捨五入取到小數第二位 , 低於60分 採用 無條件進位至整數 (EX : 59.01 =60)
                    // (只有高雄版有如此機制,新竹版照舊不管分數高低都是四捨五入)
                    foreach (string domainName in domainScoreCount.Keys)
                    {
                        if (domainScoreCount[domainName] > 0)
                        {
                            decimal grScore = 0;

                            if (JHEvaluation.ScoreCalculation.Program.Mode == JHEvaluation.ScoreCalculation.ModuleMode.HsinChu)
                            {
                                grScore = Math.Round(domainScoreSum[domainName] / domainScoreCount[domainName], 2, MidpointRounding.AwayFromZero);
                            }


                            if (JHEvaluation.ScoreCalculation.Program.Mode == JHEvaluation.ScoreCalculation.ModuleMode.KaoHsiung)
                            {
                                if (domainScoreSum[domainName] / domainScoreCount[domainName] >= 60)
                                {
                                    grScore = Math.Round(domainScoreSum[domainName] / domainScoreCount[domainName], 2, MidpointRounding.AwayFromZero);
                                }
                                else
                                {
                                    grScore = Math.Ceiling(domainScoreSum[domainName] / domainScoreCount[domainName]);
                                }
                            }


                            if (grScore >= _score)
                            {
                                passScoreList.Add(grScore);
                            }

                            StudentDomainResult.AddDomain(each.ID, domainName, grScore, grScore >= _score);
                        }
                    }

                    // 當及格數小於標準數,標示不符格畢業規範
                    if (passScoreList.Count < _domain_count)
                    {
                        ResultDetail rd = new ResultDetail(each.ID, "0", "0");
                        rd.AddMessage("領域畢業加權總平均成績不符合畢業規範");
                        rd.AddDetail("領域畢業加權總平均成績不符合畢業規範");
                        resultList.Add(rd);
                    }
                }

                if (resultList.Count > 0)
                {
                    _result.Add(each.ID, resultList);
                    passList.Add(each.ID, false);
                }
                else
                {
                    passList.Add(each.ID, true);
                }
            }

            return(passList);
        }
Ejemplo n.º 30
0
        private void DataBuilding(object sender, DoWorkEventArgs e)
        {
            _BW.ReportProgress(0);

            //取得結束時間 並轉成 像是 2018/05/10 格式
            String endDate = dateTimeInput1.Value.ToString("yyyy/MM/dd");

            SaveSetting();
            //MappingData
            _MappingData = new Dictionary <string, List <string> >();
            foreach (DataGridViewRow row in dataGridViewX1.Rows)
            {
                if (row.Cells[0].Value != null)
                {
                    string tagName = row.Cells[0].Value.ToString();

                    if (!_MappingData.ContainsKey(tagName))
                    {
                        _MappingData.Add(tagName, new List <string>());
                    }

                    if (row.Cells[1].Value != null)
                    {
                        string tagText = row.Cells[1].Value.ToString();
                        if (_Column2Items.ContainsKey(tagText))
                        {
                            string tagId = _Column2Items[tagText];
                            if (!_MappingData[tagName].Contains(tagId))
                            {
                                _MappingData[tagName].Add(tagId);
                            }
                        }
                    }
                }
            }

            Dictionary <string, StudentObj> studentDic = new Dictionary <string, StudentObj>();
            List <string> students = K12.Presentation.NLDPanels.Student.SelectedSource;
            string        ids      = string.Join("','", students);

            _BW.ReportProgress(10);
            //基本資料
            DataTable dt = _Q.Select("SELECT student.id,student.name,student.id_number,class.class_name,student.seat_no,student.student_number,student.birthdate,student.contact_phone,student.sms_phone,student.mailing_address,student.permanent_address,class.grade_year FROM student LEFT JOIN class ON ref_class_id = class.id WHERE student.id IN ('" + ids + "')");

            foreach (DataRow row in dt.Rows)
            {
                StudentObj obj = new StudentObj(row);
                if (!studentDic.ContainsKey(obj.Id))
                {
                    studentDic.Add(obj.Id, obj);
                }
            }

            _BW.ReportProgress(15);
            //基本資料-TagId
            dt = _Q.Select("SELECT ref_student_id,ref_tag_id FROM tag_student WHERE ref_student_id IN ('" + ids + "')");
            foreach (DataRow row in dt.Rows)
            {
                string id    = row["ref_student_id"].ToString();
                string tagid = row["ref_tag_id"].ToString();
                if (studentDic.ContainsKey(id))
                {
                    if (!studentDic[id].TagIds.Contains(tagid))
                    {
                        studentDic[id].TagIds.Add(tagid);
                    }
                }
            }

            _BW.ReportProgress(20);
            //服務學習紀錄
            dt = _Q.Select("SELECT ref_student_id,hours FROM $k12.service.learning.record WHERE ref_student_id IN ('" + ids + "') AND occur_date <= '" + endDate + "' ::timestamp");
            foreach (DataRow row in dt.Rows)
            {
                string id = row["ref_student_id"].ToString();
                if (studentDic.ContainsKey(id))
                {
                    studentDic[id].ServiceHours += decimal.Parse(row["hours"].ToString());
                }
            }

            _BW.ReportProgress(30);
            //幹部紀錄
            dt = _Q.Select("SELECT studentid,schoolyear,semester,cadrename FROM $behavior.thecadre WHERE studentid IN ('" + ids + "')");
            List <string> checkList = new List <string>();

            foreach (DataRow row in dt.Rows)
            {
                string id         = row["studentid"].ToString();
                string schoolyear = row["schoolyear"].ToString();
                string semester   = row["semester"].ToString();
                string cadrename  = row["cadrename"].ToString();

                string key = id + "_" + schoolyear + "_" + semester;

                if (!checkList.Contains(key))
                {
                    if (studentDic.ContainsKey(id))
                    {
                        if (!cadrename.Contains("副"))
                        {
                            studentDic[id].CadreTimes++;
                            checkList.Add(key);
                            continue;
                        }

                        if (cadrename.Contains("副班") || cadrename.Contains("副社"))
                        {
                            studentDic[id].CadreTimes++;
                            checkList.Add(key);
                            continue;
                        }
                    }
                }
            }

            _BW.ReportProgress(40);
            ////獎懲紀錄
            //List<AutoSummaryRecord> records = AutoSummary.Select(students, null);
            //foreach (AutoSummaryRecord record in records)
            //{
            //    string id = record.RefStudentID;
            //    if (studentDic.ContainsKey(id))
            //    {
            //        studentDic[id].MeritA += record.MeritA;
            //        studentDic[id].MeritB += record.MeritB;
            //        studentDic[id].MeritC += record.MeritC;
            //        studentDic[id].DemeritA += record.DemeritA;
            //        studentDic[id].DemeritB += record.DemeritB;
            //        studentDic[id].DemeritC += record.DemeritC;
            //    }
            //}

            // 2018/5/15 穎驊新增,自羿均那邊拿到他調整好 高中職免試入學抓取資料的SQL
            // 提出其中 獎懲的部分稍作調整,作為新的五專免試入學學生獎懲資料抓取方式
            // 其最大的特色是,可以設定截止時間、過濾銷過紀錄、自動加總非明細資料(轉學生適用)、
            // 且無論該學期有無學習歷程,只要有計獎懲一律計算,不會因為該學期休學而不計算

            List <string> sidList = new List <string>();

            foreach (string sid in studentDic.Keys)
            {
                sidList.Add("SELECT " + sid + "::BIGINT AS id ");
            }

            string target_student_s = String.Join(" UNION ALL ", sidList);


            string      sql           = string.Format(@"WITH target_datetime AS(
	SELECT
		'{0}'::TIMESTAMP AS end_date
) ,target_student AS(
	{1}                 
) ,target_sems_demerit AS(
	SELECT
		target_student.id
		,CASE 
			WHEN SUM(大過) IS NULL 
			THEN 0 
			ELSE SUM(大過) 
		END AS 大過支數
		,CASE 
			WHEN SUM(小過) IS NULL 
			THEN 0 
			ELSE SUM(小過) 
		END AS 小過支數
		,CASE 
			WHEN SUM(警告) IS NULL 
			THEN 0 
			ELSE SUM(警告) 
		END AS 警告支數
	FROM
		target_student
		LEFT OUTER JOIN (
			SELECT
				sems_moral_score.ref_student_id
				, CAST( regexp_replace( xpath_string(sems_moral_score.initial_summary,'/InitialSummary/DisciplineStatistics/Demerit/@A'), '^$', '0') AS INTEGER) AS 大過
		        , CAST( regexp_replace( xpath_string(sems_moral_score.initial_summary,'/InitialSummary/DisciplineStatistics/Demerit/@B'), '^$', '0') AS INTEGER) AS 小過
		        , CAST( regexp_replace( xpath_string(sems_moral_score.initial_summary,'/InitialSummary/DisciplineStatistics/Demerit/@C'), '^$', '0') AS INTEGER) AS 警告
			FROM
				sems_moral_score
		) AS sems_demerit ON target_student.id = sems_demerit.ref_student_id
	GROUP BY 
		target_student.id
) ,target_demerit AS(
	SELECT
		target_student.id
		,CASE 
			WHEN SUM(大過) IS NULL 
			THEN 0 
			ELSE SUM(大過) 
		END AS 大過支數
		,CASE 
			WHEN SUM(小過) IS NULL 
			THEN 0 
			ELSE SUM(小過) 
		END AS 小過支數
		,CASE 
			WHEN SUM(警告) IS NULL 
			THEN 0 
			ELSE SUM(警告) 
		END AS 警告支數
	FROM
		target_student
		LEFT OUTER JOIN(
			SELECT
				discipline.ref_student_id
				, CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Demerit/@A'), '^$', '0') AS INTEGER) AS 大過
		        , CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Demerit/@B'), '^$', '0') AS INTEGER) AS 小過
		        , CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Demerit/@C'), '^$', '0') AS INTEGER) AS 警告
			FROM
				target_datetime
				LEFT OUTER JOIN discipline
					ON discipline.occur_date <= target_datetime.end_date 
			WHERE
				merit_flag = 0
				AND xpath_string(discipline.detail,'/Discipline/Demerit/@Cleared') <> '是'
				AND ref_student_id IN(SELECT * FROM target_student)		
			UNION ALL
			SELECT
				discipline.ref_student_id
				, CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Demerit/@A'), '^$', '0') AS INTEGER) AS 大過
		        , CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Demerit/@B'), '^$', '0') AS INTEGER) AS 小過
		        , CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Demerit/@C'), '^$', '0') AS INTEGER) AS 警告
			FROM
				target_datetime
				LEFT OUTER JOIN(
					SELECT
						*
						, CASE 
							WHEN xpath_string(discipline.detail,'/Discipline/Demerit/@ClearDate') = '' 
							THEN '1970/1/1'::TIMESTAMP 
							ELSE xpath_string(discipline.detail,'/Discipline/Demerit/@ClearDate')::TIMESTAMP
						END AS cleardate
					FROM
						discipline
				) discipline ON discipline.occur_date <= target_datetime.end_date 
			WHERE
				merit_flag = 0
				AND xpath_string(discipline.detail,'/Discipline/Demerit/@Cleared') = '是'
				AND discipline.cleardate > (SELECT end_date FROM target_datetime)
				AND ref_student_id IN(SELECT id FROM target_student)		
		) AS target_discipline ON target_student.id = target_discipline.ref_student_id
	GROUP BY target_student.id
) ,total_demerit AS(
	SELECT
		total.id
		, CASE WHEN SUM(大過支數) IS NULL THEN 0 ELSE SUM(大過支數) END AS 大過支數
		, CASE WHEN SUM(小過支數) IS NULL THEN 0 ELSE SUM(小過支數) END AS 小過支數
		, CASE WHEN SUM(警告支數) IS NULL THEN 0 ELSE SUM(警告支數) END AS 警告支數
	FROM(
		SELECT * FROM target_demerit
		UNION ALL
		SELECT * FROM target_sems_demerit	
		) AS total
	GROUP BY
		total.id
) ,target_sems_merit AS(
	SELECT
		target_student.id
		,CASE 
			WHEN SUM(大功) IS NULL 
			THEN 0 
			ELSE SUM(大功) 
		END AS 大功支數
		,CASE 
			WHEN SUM(小功) IS NULL 
			THEN 0 
			ELSE SUM(小功) 
		END AS 小功支數
		,CASE 
			WHEN SUM(嘉獎) IS NULL 
			THEN 0 
			ELSE SUM(嘉獎) 
		END AS 嘉獎支數
	FROM
		target_student
		LEFT OUTER JOIN (
			SELECT
				sems_moral_score.ref_student_id
				, CAST( regexp_replace( xpath_string(sems_moral_score.initial_summary,'/InitialSummary/DisciplineStatistics/Merit/@A'), '^$', '0') AS INTEGER) AS 大功
		        , CAST( regexp_replace( xpath_string(sems_moral_score.initial_summary,'/InitialSummary/DisciplineStatistics/Merit/@B'), '^$', '0') AS INTEGER) AS 小功
		        , CAST( regexp_replace( xpath_string(sems_moral_score.initial_summary,'/InitialSummary/DisciplineStatistics/Merit/@C'), '^$', '0') AS INTEGER) AS 嘉獎
			FROM
				sems_moral_score

		) AS sems_merit ON target_student.id = sems_merit.ref_student_id
	GROUP BY 
		target_student.id
) ,target_merit AS(
	SELECT
		ref_student_id AS id
		,CASE 
			WHEN SUM(大功) IS NULL 
			THEN 0 
			ELSE SUM(大功) 
		END AS 大功支數
		,CASE 
			WHEN SUM(小功) IS NULL 
			THEN 0 
			ELSE SUM(小功) 
		END AS 小功支數
		,CASE 
			WHEN SUM(嘉獎) IS NULL 
			THEN 0 
			ELSE SUM(嘉獎) 
		END AS 嘉獎支數
	FROM(
		SELECT
			discipline.ref_student_id
			, CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Merit/@A'), '^$', '0') AS INTEGER) AS 大功
	        , CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Merit/@B'), '^$', '0') AS INTEGER) AS 小功
	        , CAST( regexp_replace( xpath_string(discipline.detail,'/Discipline/Merit/@C'), '^$', '0') AS INTEGER) AS 嘉獎
		FROM
			target_datetime
			LEFT OUTER JOIN discipline
				ON discipline.occur_date <= target_datetime.end_date 
		WHERE
			merit_flag = 1
			AND ref_student_id IN(SELECT * FROM target_student)		
		) AS target_discipline
	GROUP BY ref_student_id
) ,total_merit AS (
	SELECT
		total.id
		, CASE WHEN SUM(大功支數) IS NULL THEN 0 ELSE SUM(大功支數) END AS 大功支數
		, CASE WHEN SUM(小功支數) IS NULL THEN 0 ELSE SUM(小功支數) END AS 小功支數
		, CASE WHEN SUM(嘉獎支數) IS NULL THEN 0 ELSE SUM(嘉獎支數) END AS 嘉獎支數
	FROM(
		SELECT * FROM target_merit
		UNION ALL
		SELECT * FROM target_sems_merit	
		) AS total
	GROUP BY
		total.id
) 
SELECT 
	target_student.id	
    ,CASE WHEN total_merit.大功支數 is null THEN 0 ELSE total_merit.大功支數 END as 大功支數    
    ,CASE WHEN total_merit.小功支數 is null THEN 0 ELSE total_merit.小功支數 END as 小功支數
    ,CASE WHEN total_merit.嘉獎支數 is null THEN 0 ELSE total_merit.嘉獎支數 END as 嘉獎支數    
    ,CASE WHEN total_demerit.大過支數 is null THEN 0 ELSE total_demerit.大過支數 END as 大過支數
    ,CASE WHEN total_demerit.小過支數 is null THEN 0 ELSE total_demerit.小過支數 END as 小過支數
    ,CASE WHEN total_demerit.警告支數 is null THEN 0 ELSE total_demerit.警告支數 END as 警告支數    
FROM 
	target_student	
	LEFT OUTER JOIN total_demerit
		ON total_demerit.id = target_student.id
	LEFT OUTER JOIN total_merit
		ON total_merit.id = target_student.id	
	"    , endDate, target_student_s);
            QueryHelper qh            = new QueryHelper();
            DataTable   dt_discipline = qh.Select(sql);

            foreach (DataRow row in dt_discipline.Rows)
            {
                string id = "" + row["id"];
                if (studentDic.ContainsKey(id))
                {
                    studentDic[id].MeritA   = int.Parse("" + row["大功支數"]);
                    studentDic[id].MeritB   = int.Parse("" + row["小功支數"]);
                    studentDic[id].MeritC   = int.Parse("" + row["嘉獎支數"]);
                    studentDic[id].DemeritA = int.Parse("" + row["大過支數"]);
                    studentDic[id].DemeritB = int.Parse("" + row["小過支數"]);
                    studentDic[id].DemeritC = int.Parse("" + row["警告支數"]);
                }
            }

            _BW.ReportProgress(45);

            _BW.ReportProgress(50);
            //獎懲紀錄功過相抵
            foreach (StudentObj obj in studentDic.Values)
            {
                obj.MeritDemeritTransfer();
            }

            _BW.ReportProgress(60);
            //體適能
            //先確認UDT存在
            dt = _Q.Select("SELECT name FROM _udt_table where name='ischool_student_fitness'");
            if (dt.Rows.Count > 0)
            {
                dt = _Q.Select("SELECT ref_student_id,sit_and_reach_degree, standing_long_jump_degree, sit_up_degree, cardiorespiratory_degree FROM $ischool_student_fitness WHERE ref_student_id IN ('" + ids + "')");
                foreach (DataRow row in dt.Rows)
                {
                    string id = row["ref_student_id"].ToString();
                    if (studentDic.ContainsKey(id))
                    {
                        //擇優判斷
                        if (GetScore(row) > studentDic[id].SportFitnessScore)
                        {
                            studentDic[id].sit_and_reach_degree      = row["sit_and_reach_degree"].ToString();
                            studentDic[id].sit_up_degree             = row["sit_up_degree"].ToString();
                            studentDic[id].standing_long_jump_degree = row["standing_long_jump_degree"].ToString();
                            studentDic[id].cardiorespiratory_degree  = row["cardiorespiratory_degree"].ToString();
                        }
                    }
                }
            }

            _BW.ReportProgress(65);
            //均衡學習-年級對照
            Dictionary <string, Dictionary <string, string> > SchoolyearSemesteerToGrade = new Dictionary <string, Dictionary <string, string> >();

            foreach (JHSemesterHistoryRecord record in JHSemesterHistory.SelectByStudentIDs(students))
            {
                foreach (SemesterHistoryItem item in record.SemesterHistoryItems)
                {
                    if (!SchoolyearSemesteerToGrade.ContainsKey(item.RefStudentID))
                    {
                        SchoolyearSemesteerToGrade.Add(item.RefStudentID, new Dictionary <string, string>());
                    }

                    string key = item.SchoolYear + "_" + item.Semester;
                    if (!SchoolyearSemesteerToGrade[item.RefStudentID].ContainsKey(key))
                    {
                        if (item.Semester == 1)
                        {
                            SchoolyearSemesteerToGrade[item.RefStudentID].Add(key, item.GradeYear + "上");
                        }
                        else if (item.Semester == 2)
                        {
                            SchoolyearSemesteerToGrade[item.RefStudentID].Add(key, item.GradeYear + "下");
                        }
                    }
                }
            }

            _BW.ReportProgress(70);
            //均衡學習-領域分數
            List <JHSemesterScoreRecord> recs = JHSemesterScore.SelectByStudentIDs(students);

            foreach (JHSemesterScoreRecord rec in recs)
            {
                foreach (DomainScore score in rec.Domains.Values)
                {
                    string id    = score.RefStudentID;
                    string key   = score.SchoolYear + "_" + score.Semester;
                    string grade = "";

                    if (SchoolyearSemesteerToGrade.ContainsKey(id))
                    {
                        if (SchoolyearSemesteerToGrade[id].ContainsKey(key))
                        {
                            grade = SchoolyearSemesteerToGrade[id][key];
                        }
                    }

                    if (studentDic.ContainsKey(id))
                    {
                        string domain = score.Domain;

                        if ((domain == "健康與體育" || domain == "藝術與人文" || domain == "綜合活動") && !string.IsNullOrWhiteSpace(grade))
                        {
                            if (!studentDic[id].DomainScores.ContainsKey(domain))
                            {
                                studentDic[id].DomainScores.Add(domain, new Dictionary <string, decimal>());
                            }

                            if (!studentDic[id].DomainScores[domain].ContainsKey(grade))
                            {
                                decimal value = score.Score.HasValue ? score.Score.Value : 0;
                                studentDic[id].DomainScores[domain].Add(grade, value);
                            }
                        }
                    }
                }
            }

            _BW.ReportProgress(80);
            //排序
            List <StudentObj> list = studentDic.Values.ToList();

            list.Sort(SortStudent);

            int     progress = 80;
            decimal per      = (decimal)(100 - progress) / studentDic.Count;
            int     count    = 0;
            //Objects轉Table
            Dictionary <string, int> CloumnIndex = new Dictionary <string, int>();

            CloumnIndex.Add("身分證字統一編號", 0);
            CloumnIndex.Add("學生姓名", 1);
            CloumnIndex.Add("出生年(民國年)", 2);
            CloumnIndex.Add("出生月", 3);
            CloumnIndex.Add("出生日", 4);
            CloumnIndex.Add("年級", 5);
            CloumnIndex.Add("班級", 6);
            CloumnIndex.Add("座號", 7);
            CloumnIndex.Add("報名資格", 8);
            CloumnIndex.Add("郵遞區號", 9);
            CloumnIndex.Add("地址", 10);
            CloumnIndex.Add("市內電話", 11);
            CloumnIndex.Add("行動電話", 12);
            CloumnIndex.Add("特種生加分類別", 13);
            CloumnIndex.Add("報名費減免身分", 14);
            CloumnIndex.Add("競賽", 15);
            CloumnIndex.Add("擔任幹部", 16);
            CloumnIndex.Add("服務時數", 17);
            CloumnIndex.Add("服務學習", 18);
            CloumnIndex.Add("累計嘉獎", 19);
            CloumnIndex.Add("累計小功", 20);
            CloumnIndex.Add("累計大功", 21);
            CloumnIndex.Add("累計警告", 22);
            CloumnIndex.Add("累計小過", 23);
            CloumnIndex.Add("累計大過", 24);
            CloumnIndex.Add("日常生活表現評量", 25);
            CloumnIndex.Add("肌耐力", 26);
            CloumnIndex.Add("柔軟度", 27);
            CloumnIndex.Add("瞬發力", 28);
            CloumnIndex.Add("心肺耐力", 29);
            CloumnIndex.Add("體適能", 30);
            CloumnIndex.Add("多元學習表現", 31);
            CloumnIndex.Add("技藝教育成績", 32);
            CloumnIndex.Add("技藝優良", 33);
            CloumnIndex.Add("弱勢身分", 34);
            CloumnIndex.Add("弱勢積分", 35);
            CloumnIndex.Add("健康與體育", 36);
            CloumnIndex.Add("藝術與人文", 37);
            CloumnIndex.Add("綜合活動", 38);
            CloumnIndex.Add("均衡學習", 39);
            CloumnIndex.Add("家長意見", 40);
            CloumnIndex.Add("導師意見", 41);
            CloumnIndex.Add("輔導教師意見", 42);
            CloumnIndex.Add("適性輔導", 43);
            CloumnIndex.Add("其他比序項目_全民英檢", 44);
            CloumnIndex.Add("合計", 45);
            CloumnIndex.Add("報名「北區」五專學校代碼", 46);
            CloumnIndex.Add("報名「中區」五專學校代碼", 47);
            CloumnIndex.Add("報名「南區」五專學校代碼", 48);
            CloumnIndex.Add("競賽名稱", 49);
            //CloumnIndex.Add("其他比序項目_多益測驗", 50);

            int      index = 1;
            Workbook wb    = new Workbook(new MemoryStream(Properties.Resources.Template));
            Cells    cs    = wb.Worksheets[0].Cells;

            foreach (StudentObj obj in list)
            {
                cs[index, CloumnIndex["身分證字統一編號"]].PutValue(obj.IdNumber);
                cs[index, CloumnIndex["學生姓名"]].PutValue(obj.Name);
                cs[index, CloumnIndex["出生年(民國年)"]].PutValue(obj.Birth_Year.ToString().PadLeft(3, '0'));
                cs[index, CloumnIndex["出生月"]].PutValue(obj.Birth_Month.ToString().PadLeft(2, '0'));
                cs[index, CloumnIndex["出生日"]].PutValue(obj.Birth_Day.ToString().PadLeft(2, '0'));
                cs[index, CloumnIndex["年級"]].PutValue(obj.GradeYear);
                cs[index, CloumnIndex["班級"]].PutValue(obj.ClassName);
                cs[index, CloumnIndex["座號"]].PutValue(obj.SeatNo);
                cs[index, CloumnIndex["報名資格"]].PutValue(CheckTagId(obj.TagIds, 報名資格));
                cs[index, CloumnIndex["郵遞區號"]].PutValue(obj.ZipCode);
                cs[index, CloumnIndex["地址"]].PutValue(obj.Address);
                cs[index, CloumnIndex["市內電話"]].PutValue(obj.Contact_Phone);
                cs[index, CloumnIndex["行動電話"]].PutValue(obj.SMS_Phone);
                cs[index, CloumnIndex["特種生加分類別"]].PutValue(CheckTagId(obj.TagIds, 特種生加分類別));
                cs[index, CloumnIndex["報名費減免身分"]].PutValue(CheckTagId(obj.TagIds, 報名費減免身分));
                cs[index, CloumnIndex["擔任幹部"]].PutValue(obj.CadreTimesScore);
                cs[index, CloumnIndex["服務時數"]].PutValue(obj.ServiceHours);
                cs[index, CloumnIndex["服務學習"]].PutValue(obj.ServiceLearningScore);
                cs[index, CloumnIndex["累計嘉獎"]].PutValue(obj.MeritC);
                cs[index, CloumnIndex["累計小功"]].PutValue(obj.MeritB);
                cs[index, CloumnIndex["累計大功"]].PutValue(obj.MeritA);
                cs[index, CloumnIndex["累計警告"]].PutValue(obj.DemeritC);
                cs[index, CloumnIndex["累計小過"]].PutValue(obj.DemeritB);
                cs[index, CloumnIndex["累計大過"]].PutValue(obj.DemeritA);
                cs[index, CloumnIndex["日常生活表現評量"]].PutValue(obj.MeritDemeritScore);
                cs[index, CloumnIndex["肌耐力"]].PutValue(obj.CheckScore("仰臥起坐"));
                cs[index, CloumnIndex["柔軟度"]].PutValue(obj.CheckScore("坐姿體前彎"));
                cs[index, CloumnIndex["瞬發力"]].PutValue(obj.CheckScore("立定跳遠"));
                cs[index, CloumnIndex["心肺耐力"]].PutValue(obj.CheckScore("心肺適能"));
                cs[index, CloumnIndex["體適能"]].PutValue(obj.SportFitnessScore);

                int    x       = index + 1;
                string formula = "=IF(P" + x + "+S" + x + "+Z" + x + "+AE" + x + ">16,16,P" + x + "+S" + x + "+Z" + x + "+AE" + x + ")";
                cs[index, CloumnIndex["多元學習表現"]].Formula = formula;

                string[] tag = CheckTagId(obj.TagIds);
                cs[index, CloumnIndex["弱勢身分"]].PutValue(tag[0]);
                cs[index, CloumnIndex["弱勢積分"]].PutValue(tag[1]);

                Dictionary <string, decimal> dic = obj.GetDomainScores();
                cs[index, CloumnIndex["健康與體育"]].PutValue(dic.ContainsKey("健康與體育") ? dic["健康與體育"] : 0);
                cs[index, CloumnIndex["藝術與人文"]].PutValue(dic.ContainsKey("藝術與人文") ? dic["藝術與人文"] : 0);
                cs[index, CloumnIndex["綜合活動"]].PutValue(dic.ContainsKey("綜合活動") ? dic["綜合活動"] : 0);
                cs[index, CloumnIndex["均衡學習"]].PutValue(obj.DomainItemScore);
                cs[index, CloumnIndex["其他比序項目_全民英檢"]].PutValue(CheckTagId(obj.TagIds, 其他比序項目_全民英檢));
                //cs[index, CloumnIndex["其他比序項目_多益測驗"]].PutValue(CheckTagId(obj.TagIds, 其他比序項目_多益測驗));

                formula = "=IF(AF" + x + "+AH" + x + "+AJ" + x + "+AN" + x + "+AR" + x + ">30,30,AF" + x + "+AH" + x + "+AJ" + x + "+AN" + x + "+AR" + x + ")";
                cs[index, CloumnIndex["合計"]].Formula = formula;

                index++;
                count++;
                progress += (int)(count * per);
                _BW.ReportProgress(progress);
            }

            //wb.Worksheets[0].AutoFitColumns();
            e.Result = wb;
        }