1200 lines
31 KiB
Go
1200 lines
31 KiB
Go
package controllers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"server/models"
|
|
"server/pkg/holiday"
|
|
"server/pkg/identity"
|
|
"server/pkg/jwtutil"
|
|
|
|
"github.com/beego/beego/v2/client/orm"
|
|
beego "github.com/beego/beego/v2/server/web"
|
|
)
|
|
|
|
type BackendOaScheduleController struct {
|
|
beego.Controller
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) oaScheduleClaims() (*jwtutil.Claims, error) {
|
|
return identity.Claims(c.Ctx.Request.Header.Get("Authorization"), identity.EndBackend)
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) oasJsonErr(httpStatus, bizCode int, msg string) {
|
|
c.Ctx.Output.SetStatus(httpStatus)
|
|
c.Data["json"] = map[string]interface{}{"code": bizCode, "msg": msg}
|
|
_ = c.ServeJSON()
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) oasOk(data interface{}) {
|
|
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success", "data": data}
|
|
_ = c.ServeJSON()
|
|
}
|
|
|
|
var (
|
|
oasDatePattern = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
|
|
oasTimePattern = regexp.MustCompile(`^\d{2}:\d{2}$`)
|
|
)
|
|
|
|
func isValidOaDate(s string) bool {
|
|
if !oasDatePattern.MatchString(s) {
|
|
return false
|
|
}
|
|
_, err := time.ParseInLocation("2006-01-02", s, time.Local)
|
|
return err == nil
|
|
}
|
|
|
|
func isValidOaTime(s string) bool {
|
|
if !oasTimePattern.MatchString(s) {
|
|
return false
|
|
}
|
|
_, err := time.ParseInLocation("15:04", s, time.Local)
|
|
return err == nil
|
|
}
|
|
|
|
func normalizeOaDate(s string) string {
|
|
s = strings.TrimSpace(s)
|
|
if len(s) >= 10 {
|
|
return s[:10]
|
|
}
|
|
return s
|
|
}
|
|
|
|
type oaScheduleFilter struct {
|
|
Keyword string
|
|
Priority int8
|
|
HasPriority bool
|
|
StartDate string
|
|
EndDate string
|
|
OnDate string
|
|
Status int8
|
|
HasStatus bool
|
|
Ongoing bool
|
|
}
|
|
|
|
func oaScheduleCond(tid int, userID int, f oaScheduleFilter) *orm.Condition {
|
|
cond := orm.NewCondition()
|
|
cond = cond.And("is_deleted", 0).And("tid", tid).And("user_id", userID)
|
|
if f.Keyword != "" {
|
|
cond = cond.And("title__icontains", f.Keyword)
|
|
}
|
|
if f.HasPriority {
|
|
cond = cond.And("priority", f.Priority)
|
|
}
|
|
if f.StartDate != "" {
|
|
cond = cond.And("schedule_date__gte", f.StartDate)
|
|
}
|
|
if f.EndDate != "" {
|
|
cond = cond.And("schedule_date__lte", f.EndDate)
|
|
}
|
|
if f.OnDate != "" {
|
|
cond = cond.And("schedule_date", f.OnDate)
|
|
}
|
|
if f.HasStatus {
|
|
cond = cond.And("status", f.Status)
|
|
}
|
|
if f.Ongoing {
|
|
sub := orm.NewCondition()
|
|
sub = sub.Or("source_id__gt", 0).Or("carry_over", 1)
|
|
cond = cond.AndCond(sub)
|
|
}
|
|
return cond
|
|
}
|
|
|
|
func oaScheduleQS(tid int, userID int, f oaScheduleFilter) orm.QuerySeter {
|
|
return models.Orm.QueryTable(new(models.OaSchedule)).
|
|
SetCond(oaScheduleCond(tid, userID, f))
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) List() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
page, _ := c.GetInt("page", 1)
|
|
pageSize, _ := c.GetInt("pageSize", 20)
|
|
keyword := strings.TrimSpace(c.GetString("keyword"))
|
|
status := strings.TrimSpace(c.GetString("status"))
|
|
priority := strings.TrimSpace(c.GetString("priority"))
|
|
startDate := strings.TrimSpace(c.GetString("start_date"))
|
|
endDate := strings.TrimSpace(c.GetString("end_date"))
|
|
category := strings.TrimSpace(c.GetString("category"))
|
|
|
|
data, code, msg := oaScheduleListData(claims.TenantId, claims.UserID,
|
|
page, pageSize, keyword, status, priority, startDate, endDate, category)
|
|
if msg != "" {
|
|
c.oasJsonErr(code, code, msg)
|
|
return
|
|
}
|
|
c.oasOk(data)
|
|
}
|
|
|
|
func oaScheduleListData(tid, userID, page, pageSize int,
|
|
keyword, status, priority, startDate, endDate, category string) (map[string]interface{}, int, string) {
|
|
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if pageSize < 1 || pageSize > 500 {
|
|
pageSize = 20
|
|
}
|
|
|
|
base := oaScheduleFilter{Keyword: keyword}
|
|
if status == "0" || status == "1" {
|
|
statusVal, _ := strconv.Atoi(status)
|
|
base.HasStatus = true
|
|
base.Status = int8(statusVal)
|
|
}
|
|
if priority == "0" || priority == "1" || priority == "2" {
|
|
priorityVal, _ := strconv.Atoi(priority)
|
|
base.HasPriority = true
|
|
base.Priority = int8(priorityVal)
|
|
}
|
|
|
|
countOf := func(f oaScheduleFilter) int64 {
|
|
n, _ := oaScheduleQS(tid, userID, f).Count()
|
|
return n
|
|
}
|
|
today := time.Now().Format("2006-01-02")
|
|
counts := map[string]interface{}{
|
|
"all": countOf(base),
|
|
"today": countOf(oaScheduleFilter{Keyword: base.Keyword, Priority: base.Priority, HasPriority: base.HasPriority, OnDate: today}),
|
|
"pending": countOf(oaScheduleFilter{Keyword: base.Keyword, Priority: base.Priority, HasPriority: base.HasPriority, HasStatus: true, Status: 0}),
|
|
"ongoing": countOf(oaScheduleFilter{Keyword: base.Keyword, Priority: base.Priority, HasPriority: base.HasPriority, Ongoing: true}),
|
|
"done": countOf(oaScheduleFilter{Keyword: base.Keyword, Priority: base.Priority, HasPriority: base.HasPriority, HasStatus: true, Status: 1}),
|
|
}
|
|
|
|
listFilter := base
|
|
if isValidOaDate(startDate) {
|
|
listFilter.StartDate = startDate
|
|
}
|
|
if isValidOaDate(endDate) {
|
|
listFilter.EndDate = endDate
|
|
}
|
|
switch category {
|
|
case "today":
|
|
listFilter.OnDate = today
|
|
case "pending":
|
|
listFilter.HasStatus = true
|
|
listFilter.Status = 0
|
|
case "ongoing":
|
|
listFilter.Ongoing = true
|
|
case "done":
|
|
listFilter.HasStatus = true
|
|
listFilter.Status = 1
|
|
}
|
|
|
|
qs := oaScheduleQS(tid, userID, listFilter)
|
|
total, _ := qs.Count()
|
|
|
|
var list []models.OaSchedule
|
|
_, err := qs.OrderBy("schedule_date", "start_time", "-id").
|
|
Limit(pageSize).Offset((page - 1) * pageSize).
|
|
All(&list)
|
|
if err != nil && err != orm.ErrNoRows {
|
|
return nil, 500, "查询失败"
|
|
}
|
|
if list == nil {
|
|
list = []models.OaSchedule{}
|
|
}
|
|
|
|
for i := range list {
|
|
list[i].ScheduleDate = normalizeOaDate(list[i].ScheduleDate)
|
|
}
|
|
|
|
return map[string]interface{}{
|
|
"list": list,
|
|
"total": total,
|
|
"counts": counts,
|
|
}, 200, ""
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) Holidays() {
|
|
if _, err := c.oaScheduleClaims(); err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
startDate := strings.TrimSpace(c.GetString("start_date"))
|
|
endDate := strings.TrimSpace(c.GetString("end_date"))
|
|
yearStr := strings.TrimSpace(c.GetString("year"))
|
|
|
|
var start, end string
|
|
if isValidOaDate(startDate) && isValidOaDate(endDate) && startDate <= endDate {
|
|
start, end = startDate, endDate
|
|
} else if y, err := strconv.Atoi(yearStr); err == nil && y >= 2000 && y <= 2100 {
|
|
start = fmt.Sprintf("%04d-01-01", y)
|
|
end = fmt.Sprintf("%04d-12-31", y)
|
|
} else {
|
|
now := time.Now()
|
|
start = now.Format("2006-01-01")
|
|
end = now.Format("2006") + "-12-31"
|
|
}
|
|
|
|
list := ensureOaHolidays(start, end)
|
|
|
|
c.oasOk(map[string]interface{}{
|
|
"list": list,
|
|
"start_date": start,
|
|
"end_date": end,
|
|
"builtin_years": holiday.Years(),
|
|
})
|
|
}
|
|
|
|
func ensureOaHolidays(start, end string) []holiday.Day {
|
|
list := make([]holiday.Day, 0, 64)
|
|
|
|
startYear, endYear := holidayYear(start), holidayYear(end)
|
|
for y := startYear; y <= endYear; y++ {
|
|
if y == 0 {
|
|
continue
|
|
}
|
|
items, src, ferr := holiday.FetchYear(y)
|
|
if ferr != nil || len(items) == 0 {
|
|
continue
|
|
}
|
|
if src == holiday.SourceHolidayCN {
|
|
saveOaHolidays(items)
|
|
}
|
|
for _, d := range items {
|
|
if d.Date >= start && d.Date <= end {
|
|
list = append(list, d)
|
|
}
|
|
}
|
|
}
|
|
|
|
return mergeOaHolidays(list)
|
|
}
|
|
|
|
func holidayYear(date string) int {
|
|
if len(date) < 4 {
|
|
return 0
|
|
}
|
|
y, err := strconv.Atoi(date[:4])
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return y
|
|
}
|
|
|
|
func saveOaHolidays(list []holiday.Day) {
|
|
now := time.Now()
|
|
for _, d := range list {
|
|
if !isValidOaDate(d.Date) {
|
|
continue
|
|
}
|
|
var exist models.OaHoliday
|
|
ferr := models.Orm.QueryTable(new(models.OaHoliday)).
|
|
Filter("date", d.Date).
|
|
One(&exist)
|
|
if ferr == nil {
|
|
if exist.Name == d.Name && exist.Type == d.Type && exist.Source == d.Source {
|
|
continue
|
|
}
|
|
exist.Name = d.Name
|
|
exist.Type = d.Type
|
|
exist.Year = d.Year
|
|
exist.Wage = d.Wage
|
|
exist.Source = d.Source
|
|
exist.UpdateTime = &now
|
|
_, _ = models.Orm.Update(&exist, "Name", "Type", "Year", "Wage", "Source", "UpdateTime")
|
|
continue
|
|
}
|
|
item := models.OaHoliday{
|
|
Date: d.Date,
|
|
Name: d.Name,
|
|
Type: d.Type,
|
|
Year: d.Year,
|
|
Wage: d.Wage,
|
|
Source: d.Source,
|
|
CreateTime: now,
|
|
UpdateTime: &now,
|
|
}
|
|
_, _ = models.Orm.Insert(&item)
|
|
}
|
|
}
|
|
|
|
func mergeOaHolidays(list []holiday.Day) []holiday.Day {
|
|
seen := make(map[string]bool, len(list))
|
|
out := make([]holiday.Day, 0, len(list))
|
|
for _, d := range list {
|
|
if d.Date == "" || seen[d.Date] {
|
|
continue
|
|
}
|
|
seen[d.Date] = true
|
|
out = append(out, d)
|
|
}
|
|
for i := 1; i < len(out); i++ {
|
|
cur := out[i]
|
|
j := i - 1
|
|
for j >= 0 && out[j].Date > cur.Date {
|
|
out[j+1] = out[j]
|
|
j--
|
|
}
|
|
out[j+1] = cur
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) Stats() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
now := time.Now()
|
|
today := now.Format("2006-01-02")
|
|
weekday := int(now.Weekday())
|
|
if weekday == 0 {
|
|
weekday = 7
|
|
}
|
|
weekStart := now.AddDate(0, 0, -(weekday - 1)).Format("2006-01-02")
|
|
weekEnd := now.AddDate(0, 0, 7-weekday).Format("2006-01-02")
|
|
monthStart := now.Format("2006-01") + "-01"
|
|
|
|
base := func() orm.QuerySeter {
|
|
return models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID)
|
|
}
|
|
|
|
todayTotal, _ := base().Filter("schedule_date", today).Count()
|
|
todayDone, _ := base().Filter("schedule_date", today).Filter("status", 1).Count()
|
|
weekTotal, _ := base().Filter("schedule_date__gte", weekStart).Filter("schedule_date__lte", weekEnd).Count()
|
|
weekDone, _ := base().Filter("schedule_date__gte", weekStart).Filter("schedule_date__lte", weekEnd).Filter("status", 1).Count()
|
|
monthTotal, _ := base().Filter("schedule_date__gte", monthStart).Count()
|
|
monthDone, _ := base().Filter("schedule_date__gte", monthStart).Filter("status", 1).Count()
|
|
overdue, _ := base().Filter("schedule_date__lt", today).Filter("status", 0).Count()
|
|
|
|
c.oasOk(map[string]interface{}{
|
|
"today_total": todayTotal,
|
|
"today_done": todayDone,
|
|
"week_total": weekTotal,
|
|
"week_done": weekDone,
|
|
"month_total": monthTotal,
|
|
"month_done": monthDone,
|
|
"overdue": overdue,
|
|
})
|
|
}
|
|
|
|
type oaSchedulePayload struct {
|
|
Title string `json:"title"`
|
|
Content string `json:"content"`
|
|
ScheduleDate string `json:"schedule_date"`
|
|
StartTime string `json:"start_time"`
|
|
EndTime string `json:"end_time"`
|
|
AllDay int8 `json:"all_day"`
|
|
Color string `json:"color"`
|
|
Priority int8 `json:"priority"`
|
|
ReminderEnabled bool `json:"reminder_enabled"`
|
|
ReminderTime string `json:"reminder_time"`
|
|
RemindChannels []string `json:"remind_channels"`
|
|
AdvanceMinutes int `json:"advance_minutes"`
|
|
}
|
|
|
|
var oaReminderChannels = map[string]bool{
|
|
"SMS": true, "EMAIL": true, "BARK": true, "SITE_MSG": true,
|
|
}
|
|
|
|
func createOaScheduleReminder(tid int, userID uint64, title, content, reminderTime string, channels []string, advanceMinutes int) (uint64, error) {
|
|
if strings.TrimSpace(reminderTime) == "" {
|
|
return 0, fmt.Errorf("提醒时间不能为空")
|
|
}
|
|
schedTime, err := time.ParseInLocation("2006-01-02 15:04:05", reminderTime, time.Local)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("提醒时间格式不合法")
|
|
}
|
|
if advanceMinutes < 0 {
|
|
advanceMinutes = 0
|
|
}
|
|
title = strings.TrimSpace(title)
|
|
if title == "" {
|
|
title = "日程提醒"
|
|
}
|
|
|
|
bs := models.BackendSchedule{
|
|
Tid: tid,
|
|
Title: title,
|
|
Content: content,
|
|
ScheduleTime: schedTime,
|
|
UserID: userID,
|
|
}
|
|
schedID, err := models.Orm.Insert(&bs)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("创建提醒任务失败: %v", err)
|
|
}
|
|
|
|
now := time.Now()
|
|
for _, ch := range channels {
|
|
ch = strings.ToUpper(strings.TrimSpace(ch))
|
|
if !oaReminderChannels[ch] {
|
|
continue
|
|
}
|
|
firstSend := schedTime.Add(-time.Duration(advanceMinutes) * time.Minute)
|
|
reminder := models.BackendScheduleReminder{
|
|
Tid: tid,
|
|
ScheduleID: uint64(schedID),
|
|
RemindChannel: ch,
|
|
AdvanceMinutes: advanceMinutes,
|
|
NextRemindTime: firstSend,
|
|
ReceiverUserID: userID,
|
|
RemindStatus: 0,
|
|
CreateTime: now,
|
|
UpdateTime: now,
|
|
}
|
|
if ch == "EMAIL" || ch == "BARK" {
|
|
token := backendGenerateToken()
|
|
reminder.AckToken = &token
|
|
reminder.RepeatIntervalMinutes = 10
|
|
reminder.MaxSendCount = 5
|
|
} else {
|
|
reminder.RepeatIntervalMinutes = 0
|
|
reminder.MaxSendCount = 1
|
|
}
|
|
if _, err := models.Orm.Insert(&reminder); err != nil {
|
|
return 0, fmt.Errorf("创建提醒失败: %v", err)
|
|
}
|
|
}
|
|
return uint64(schedID), nil
|
|
}
|
|
|
|
func deleteBoundReminder(scheduleID uint64) {
|
|
if scheduleID == 0 {
|
|
return
|
|
}
|
|
_, _ = models.Orm.QueryTable(new(models.BackendSchedule)).
|
|
Filter("id", scheduleID).Delete()
|
|
_, _ = models.Orm.QueryTable(new(models.BackendScheduleReminder)).
|
|
Filter("schedule_id", scheduleID).
|
|
Update(map[string]interface{}{"IsDeleted": 1, "UpdateTime": time.Now()})
|
|
}
|
|
|
|
type oaScheduleImage struct {
|
|
ID uint64 `json:"id"`
|
|
URL string `json:"url"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
const (
|
|
oaScheduleMaxImages = 20
|
|
oaScheduleMaxImageURL = 500
|
|
oaScheduleMaxImageName = 120
|
|
)
|
|
|
|
func normalizeOaScheduleImages(list []oaScheduleImage) (string, bool) {
|
|
if len(list) > oaScheduleMaxImages {
|
|
return "", false
|
|
}
|
|
out := make([]oaScheduleImage, 0, len(list))
|
|
for _, img := range list {
|
|
img.URL = strings.TrimSpace(img.URL)
|
|
if img.URL == "" || len(img.URL) > oaScheduleMaxImageURL {
|
|
continue
|
|
}
|
|
img.Name = strings.TrimSpace(img.Name)
|
|
if utf8.RuneCountInString(img.Name) > oaScheduleMaxImageName {
|
|
img.Name = string([]rune(img.Name)[:oaScheduleMaxImageName])
|
|
}
|
|
out = append(out, img)
|
|
}
|
|
raw, err := json.Marshal(out)
|
|
if err != nil {
|
|
return "", false
|
|
}
|
|
return string(raw), true
|
|
}
|
|
|
|
func parseOaScheduleImages(raw string) []oaScheduleImage {
|
|
list := make([]oaScheduleImage, 0)
|
|
_ = json.Unmarshal([]byte(raw), &list)
|
|
return list
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) parseOaSchedulePayload() (oaSchedulePayload, bool) {
|
|
raw, err := io.ReadAll(c.Ctx.Request.Body)
|
|
if err != nil {
|
|
c.oasJsonErr(400, 400, "参数错误")
|
|
return oaSchedulePayload{}, false
|
|
}
|
|
payload, msg := parseOaSchedulePayloadBody(raw)
|
|
if msg != "" {
|
|
c.oasJsonErr(400, 400, msg)
|
|
return payload, false
|
|
}
|
|
return payload, true
|
|
}
|
|
|
|
func parseOaSchedulePayloadBody(raw []byte) (oaSchedulePayload, string) {
|
|
var payload oaSchedulePayload
|
|
if len(raw) == 0 || json.Unmarshal(raw, &payload) != nil {
|
|
return payload, "参数错误"
|
|
}
|
|
|
|
payload.Title = strings.TrimSpace(payload.Title)
|
|
if payload.Title == "" {
|
|
return payload, "请输入日程标题"
|
|
}
|
|
if utf8.RuneCountInString(payload.Title) > 80 {
|
|
return payload, "日程标题不能超过80字"
|
|
}
|
|
if !isValidOaDate(payload.ScheduleDate) {
|
|
return payload, "日程日期无效"
|
|
}
|
|
if payload.AllDay != 0 {
|
|
payload.AllDay = 1
|
|
payload.StartTime = ""
|
|
payload.EndTime = ""
|
|
} else {
|
|
if !isValidOaTime(payload.StartTime) {
|
|
return payload, "开始时间无效"
|
|
}
|
|
if payload.EndTime != "" {
|
|
if !isValidOaTime(payload.EndTime) {
|
|
return payload, "结束时间无效"
|
|
}
|
|
if payload.EndTime < payload.StartTime {
|
|
return payload, "结束时间不能早于开始时间"
|
|
}
|
|
}
|
|
}
|
|
if payload.Priority < 0 || payload.Priority > 2 {
|
|
payload.Priority = 0
|
|
}
|
|
payload.Color = strings.TrimSpace(payload.Color)
|
|
if payload.Color == "" {
|
|
payload.Color = "#409EFF"
|
|
}
|
|
|
|
if payload.ReminderEnabled {
|
|
validChannels := make([]string, 0, len(payload.RemindChannels))
|
|
for _, ch := range payload.RemindChannels {
|
|
ch = strings.ToUpper(strings.TrimSpace(ch))
|
|
if oaReminderChannels[ch] {
|
|
validChannels = append(validChannels, ch)
|
|
}
|
|
}
|
|
payload.RemindChannels = validChannels
|
|
if len(validChannels) == 0 {
|
|
return payload, "请至少选择一个提醒渠道"
|
|
}
|
|
if _, err := time.ParseInLocation("2006-01-02 15:04:05", payload.ReminderTime, time.Local); err != nil {
|
|
return payload, "提醒时间格式不合法,支持 YYYY-MM-DD HH:mm:ss"
|
|
}
|
|
if payload.AdvanceMinutes < 0 {
|
|
payload.AdvanceMinutes = 0
|
|
}
|
|
}
|
|
return payload, ""
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) Create() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
payload, ok := c.parseOaSchedulePayload()
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
item, code, msg := oaScheduleCreateCore(claims, payload)
|
|
if msg != "" {
|
|
c.oasJsonErr(code, code, msg)
|
|
return
|
|
}
|
|
c.oasOk(item)
|
|
}
|
|
|
|
func oaScheduleCreateCore(claims *jwtutil.Claims, payload oaSchedulePayload) (*models.OaSchedule, int, string) {
|
|
now := time.Now()
|
|
item := &models.OaSchedule{
|
|
Tid: claims.TenantId,
|
|
UserID: uint64(claims.UserID),
|
|
UserName: claims.Username,
|
|
Title: payload.Title,
|
|
Content: payload.Content,
|
|
ScheduleDate: payload.ScheduleDate,
|
|
StartTime: payload.StartTime,
|
|
EndTime: payload.EndTime,
|
|
AllDay: payload.AllDay,
|
|
Color: payload.Color,
|
|
Priority: payload.Priority,
|
|
Status: 0,
|
|
IsDeleted: 0,
|
|
CreateTime: now,
|
|
UpdateTime: &now,
|
|
}
|
|
if _, err := models.Orm.Insert(item); err != nil {
|
|
return nil, 500, "保存失败"
|
|
}
|
|
|
|
if payload.ReminderEnabled {
|
|
rid, rerr := createOaScheduleReminder(
|
|
claims.TenantId,
|
|
uint64(claims.UserID),
|
|
payload.Title,
|
|
payload.Content,
|
|
payload.ReminderTime,
|
|
payload.RemindChannels,
|
|
payload.AdvanceMinutes,
|
|
)
|
|
if rerr != nil {
|
|
_, _ = models.Orm.QueryTable(new(models.OaSchedule)).Filter("id", item.ID).Delete()
|
|
return nil, 500, rerr.Error()
|
|
}
|
|
item.ReminderID = rid
|
|
if _, err := models.Orm.Update(item, "ReminderID"); err != nil {
|
|
return nil, 500, "保存失败"
|
|
}
|
|
}
|
|
|
|
return item, 200, ""
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) Update() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
c.oasJsonErr(400, 400, "无效ID")
|
|
return
|
|
}
|
|
|
|
payload, ok := c.parseOaSchedulePayload()
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
item, code, msg := oaScheduleUpdateCore(claims, id, payload)
|
|
if msg != "" {
|
|
c.oasJsonErr(code, code, msg)
|
|
return
|
|
}
|
|
c.oasOk(item)
|
|
}
|
|
|
|
func oaScheduleUpdateCore(claims *jwtutil.Claims, id uint64, payload oaSchedulePayload) (*models.OaSchedule, int, string) {
|
|
var item models.OaSchedule
|
|
err := models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("id", id).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID).
|
|
One(&item)
|
|
if err != nil {
|
|
return nil, 404, "日程不存在"
|
|
}
|
|
|
|
now := time.Now()
|
|
item.Title = payload.Title
|
|
item.Content = payload.Content
|
|
item.ScheduleDate = payload.ScheduleDate
|
|
item.StartTime = payload.StartTime
|
|
item.EndTime = payload.EndTime
|
|
item.AllDay = payload.AllDay
|
|
item.Color = payload.Color
|
|
item.Priority = payload.Priority
|
|
item.UpdateTime = &now
|
|
|
|
if payload.ReminderEnabled {
|
|
rid, rerr := createOaScheduleReminder(
|
|
claims.TenantId,
|
|
uint64(claims.UserID),
|
|
payload.Title,
|
|
payload.Content,
|
|
payload.ReminderTime,
|
|
payload.RemindChannels,
|
|
payload.AdvanceMinutes,
|
|
)
|
|
if rerr != nil {
|
|
return nil, 500, rerr.Error()
|
|
}
|
|
if item.ReminderID > 0 {
|
|
deleteBoundReminder(item.ReminderID)
|
|
}
|
|
item.ReminderID = rid
|
|
} else if item.ReminderID > 0 {
|
|
deleteBoundReminder(item.ReminderID)
|
|
item.ReminderID = 0
|
|
}
|
|
|
|
if _, err := models.Orm.Update(&item,
|
|
"Title", "Content", "ScheduleDate", "StartTime", "EndTime",
|
|
"AllDay", "Color", "Priority", "ReminderID", "UpdateTime"); err != nil {
|
|
return nil, 500, "保存失败"
|
|
}
|
|
|
|
return &item, 200, ""
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) SetImages() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
c.oasJsonErr(400, 400, "无效ID")
|
|
return
|
|
}
|
|
|
|
var payload struct {
|
|
Images []oaScheduleImage `json:"images"`
|
|
}
|
|
raw, _ := io.ReadAll(c.Ctx.Request.Body)
|
|
if len(raw) > 0 && json.Unmarshal(raw, &payload) != nil {
|
|
c.oasJsonErr(400, 400, "参数错误")
|
|
return
|
|
}
|
|
|
|
images, code, msg := oaScheduleSetImagesCore(claims, id, payload.Images)
|
|
if msg != "" {
|
|
c.oasJsonErr(code, code, msg)
|
|
return
|
|
}
|
|
c.oasOk(map[string]interface{}{"images": images})
|
|
}
|
|
|
|
func oaScheduleSetImagesCore(claims *jwtutil.Claims, id uint64, images []oaScheduleImage) ([]oaScheduleImage, int, string) {
|
|
imagesJSON, ok := normalizeOaScheduleImages(images)
|
|
if !ok {
|
|
return nil, 400, "图片数量过多"
|
|
}
|
|
|
|
var item models.OaSchedule
|
|
err := models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("id", id).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID).
|
|
One(&item)
|
|
if err != nil {
|
|
return nil, 404, "日程不存在"
|
|
}
|
|
|
|
now := time.Now()
|
|
item.Images = imagesJSON
|
|
item.UpdateTime = &now
|
|
if _, err := models.Orm.Update(&item, "Images", "UpdateTime"); err != nil {
|
|
return nil, 500, "保存失败"
|
|
}
|
|
|
|
return parseOaScheduleImages(imagesJSON), 200, ""
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) UpdateContent() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
c.oasJsonErr(400, 400, "无效ID")
|
|
return
|
|
}
|
|
|
|
var payload struct {
|
|
Content string `json:"content"`
|
|
}
|
|
raw, _ := io.ReadAll(c.Ctx.Request.Body)
|
|
if len(raw) > 0 && json.Unmarshal(raw, &payload) != nil {
|
|
c.oasJsonErr(400, 400, "参数错误")
|
|
return
|
|
}
|
|
|
|
var item models.OaSchedule
|
|
err = models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("id", id).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID).
|
|
One(&item)
|
|
if err != nil {
|
|
c.oasJsonErr(404, 404, "日程不存在")
|
|
return
|
|
}
|
|
|
|
now := time.Now()
|
|
item.Content = payload.Content
|
|
item.UpdateTime = &now
|
|
if _, err := models.Orm.Update(&item, "Content", "UpdateTime"); err != nil {
|
|
c.oasJsonErr(500, 500, "保存失败")
|
|
return
|
|
}
|
|
|
|
c.oasOk(map[string]interface{}{"content": item.Content})
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) Delete() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
c.oasJsonErr(400, 400, "无效ID")
|
|
return
|
|
}
|
|
|
|
code, msg := oaScheduleDeleteCore(claims, id)
|
|
if msg != "" {
|
|
c.oasJsonErr(code, code, msg)
|
|
return
|
|
}
|
|
c.oasOk(nil)
|
|
}
|
|
|
|
func oaScheduleDeleteCore(claims *jwtutil.Claims, id uint64) (int, string) {
|
|
now := time.Now()
|
|
var item models.OaSchedule
|
|
err := models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("id", id).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID).
|
|
One(&item)
|
|
if err != nil {
|
|
return 404, "日程不存在或已删除"
|
|
}
|
|
|
|
if item.ReminderID > 0 {
|
|
deleteBoundReminder(item.ReminderID)
|
|
}
|
|
|
|
item.IsDeleted = 1
|
|
item.DeleteTime = &now
|
|
item.UpdateTime = &now
|
|
if _, err := models.Orm.Update(&item, "IsDeleted", "DeleteTime", "UpdateTime"); err != nil {
|
|
return 500, "删除失败"
|
|
}
|
|
|
|
return 200, ""
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) FinishSchedule() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
c.oasJsonErr(400, 400, "无效ID")
|
|
return
|
|
}
|
|
|
|
newStatus, code, msg := oaScheduleToggleCore(claims, id)
|
|
if msg != "" {
|
|
c.oasJsonErr(code, code, msg)
|
|
return
|
|
}
|
|
c.oasOk(map[string]interface{}{"status": newStatus})
|
|
}
|
|
|
|
func oaScheduleToggleCore(claims *jwtutil.Claims, id uint64) (int8, int, string) {
|
|
var item models.OaSchedule
|
|
err := models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("id", id).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID).
|
|
One(&item)
|
|
if err != nil {
|
|
return 0, 404, "日程不存在"
|
|
}
|
|
|
|
now := time.Now()
|
|
newStatus := int8(1)
|
|
var finishTime *time.Time
|
|
if item.Status == 1 {
|
|
newStatus = 0
|
|
} else {
|
|
finishTime = &now
|
|
}
|
|
|
|
item.Status = newStatus
|
|
item.FinishTime = finishTime
|
|
item.UpdateTime = &now
|
|
|
|
if _, err := models.Orm.Update(&item, "Status", "FinishTime", "UpdateTime"); err != nil {
|
|
return 0, 500, "操作失败"
|
|
}
|
|
|
|
return newStatus, 200, ""
|
|
}
|
|
|
|
func nextOaDate(dateStr string, days int) string {
|
|
t, err := time.ParseInLocation("2006-01-02", dateStr, time.Local)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return t.AddDate(0, 0, days).Format("2006-01-02")
|
|
}
|
|
|
|
func oaScheduleRootID(item *models.OaSchedule) uint64 {
|
|
if item.SourceID > 0 {
|
|
return item.SourceID
|
|
}
|
|
return item.ID
|
|
}
|
|
|
|
func carryOaSchedule(item *models.OaSchedule, targetDate string, claims *jwtutil.Claims, now time.Time) (*models.OaSchedule, string) {
|
|
if item.Status == 1 {
|
|
return nil, "该日程已完成,无需顺延"
|
|
}
|
|
if !isValidOaDate(targetDate) {
|
|
return nil, "顺延日期无效"
|
|
}
|
|
if targetDate <= normalizeOaDate(item.ScheduleDate) {
|
|
return nil, "顺延日期需晚于当前日程日期"
|
|
}
|
|
|
|
rootID := oaScheduleRootID(item)
|
|
|
|
exist := models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID).
|
|
Filter("source_id", rootID).
|
|
Filter("schedule_date", targetDate).
|
|
Exist()
|
|
if exist {
|
|
return nil, "该日期已存在顺延的日程"
|
|
}
|
|
|
|
next := &models.OaSchedule{
|
|
Tid: item.Tid,
|
|
UserID: item.UserID,
|
|
UserName: item.UserName,
|
|
Title: item.Title,
|
|
Content: item.Content,
|
|
Images: item.Images,
|
|
ScheduleDate: targetDate,
|
|
StartTime: item.StartTime,
|
|
EndTime: item.EndTime,
|
|
AllDay: item.AllDay,
|
|
Color: item.Color,
|
|
Priority: item.Priority,
|
|
Status: 0,
|
|
SourceID: rootID,
|
|
CarryCount: item.CarryCount + 1,
|
|
IsDeleted: 0,
|
|
CreateTime: now,
|
|
UpdateTime: &now,
|
|
}
|
|
if _, err := models.Orm.Insert(next); err != nil {
|
|
return nil, "生成顺延日程失败"
|
|
}
|
|
|
|
item.Status = 1
|
|
item.FinishTime = &now
|
|
item.CarryOver = 1
|
|
item.CarryToDate = targetDate
|
|
item.UpdateTime = &now
|
|
if _, err := models.Orm.Update(item,
|
|
"Status", "FinishTime", "CarryOver", "CarryToDate", "UpdateTime"); err != nil {
|
|
return nil, "标记原日程完成失败"
|
|
}
|
|
|
|
return next, ""
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) CarrySchedule() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
|
|
if err != nil || id == 0 {
|
|
c.oasJsonErr(400, 400, "无效ID")
|
|
return
|
|
}
|
|
|
|
var payload struct {
|
|
TargetDate string `json:"target_date"`
|
|
Mode string `json:"mode"`
|
|
}
|
|
if raw, e := io.ReadAll(c.Ctx.Request.Body); e == nil && len(raw) > 0 {
|
|
_ = json.Unmarshal(raw, &payload)
|
|
}
|
|
payload.TargetDate = strings.TrimSpace(payload.TargetDate)
|
|
|
|
var item models.OaSchedule
|
|
err = models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("id", id).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID).
|
|
One(&item)
|
|
if err != nil {
|
|
c.oasJsonErr(404, 404, "日程不存在")
|
|
return
|
|
}
|
|
|
|
targetDate := payload.TargetDate
|
|
if targetDate == "" {
|
|
targetDate = nextOaDate(normalizeOaDate(item.ScheduleDate), 1)
|
|
}
|
|
|
|
mode := strings.TrimSpace(payload.Mode)
|
|
if mode != "" && mode != "to" && mode != "through" {
|
|
c.oasJsonErr(400, 400, "延期方式无效")
|
|
return
|
|
}
|
|
|
|
now := time.Now()
|
|
if mode == "through" {
|
|
startDate := normalizeOaDate(item.ScheduleDate)
|
|
if targetDate <= startDate {
|
|
c.oasJsonErr(400, 400, "延期至日期需晚于当前日程日期")
|
|
return
|
|
}
|
|
rootID := oaScheduleRootID(&item)
|
|
created := 0
|
|
for date := nextOaDate(startDate, 1); date != "" && date <= targetDate; date = nextOaDate(date, 1) {
|
|
exists := models.Orm.QueryTable(new(models.OaSchedule)).Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).Filter("user_id", claims.UserID).
|
|
Filter("source_id", rootID).Filter("schedule_date", date).Exist()
|
|
if exists {
|
|
continue
|
|
}
|
|
next := &models.OaSchedule{
|
|
Tid: item.Tid, UserID: item.UserID, UserName: item.UserName,
|
|
Title: item.Title, Content: item.Content, Images: item.Images,
|
|
ScheduleDate: date, StartTime: item.StartTime, EndTime: item.EndTime,
|
|
AllDay: item.AllDay, Color: item.Color, Priority: item.Priority,
|
|
Status: 0, SourceID: rootID, CarryCount: item.CarryCount + 1,
|
|
IsDeleted: 0, CreateTime: now, UpdateTime: &now,
|
|
}
|
|
if _, insertErr := models.Orm.Insert(next); insertErr != nil {
|
|
c.oasJsonErr(500, 500, "生成延期日程失败")
|
|
return
|
|
}
|
|
created++
|
|
}
|
|
item.Status = 1
|
|
item.FinishTime = &now
|
|
item.CarryOver = 1
|
|
item.CarryToDate = targetDate
|
|
item.UpdateTime = &now
|
|
if _, updateErr := models.Orm.Update(&item, "Status", "FinishTime", "CarryOver", "CarryToDate", "UpdateTime"); updateErr != nil {
|
|
c.oasJsonErr(500, 500, "更新原日程失败")
|
|
return
|
|
}
|
|
c.oasOk(map[string]interface{}{"created": created, "schedule_date": targetDate, "mode": "through"})
|
|
return
|
|
}
|
|
|
|
next, msg := carryOaSchedule(&item, targetDate, claims, now)
|
|
if msg != "" {
|
|
c.oasJsonErr(400, 400, msg)
|
|
return
|
|
}
|
|
|
|
c.oasOk(map[string]interface{}{
|
|
"new_id": next.ID,
|
|
"schedule_date": next.ScheduleDate,
|
|
"carry_count": next.CarryCount,
|
|
})
|
|
}
|
|
|
|
func (c *BackendOaScheduleController) CarryPending() {
|
|
claims, err := c.oaScheduleClaims()
|
|
if err != nil {
|
|
code := identity.Status(err)
|
|
c.oasJsonErr(code, code, err.Error())
|
|
return
|
|
}
|
|
|
|
var payload struct {
|
|
Date string `json:"date"`
|
|
TargetDate string `json:"target_date"`
|
|
}
|
|
if raw, e := io.ReadAll(c.Ctx.Request.Body); e == nil && len(raw) > 0 {
|
|
_ = json.Unmarshal(raw, &payload)
|
|
}
|
|
payload.Date = strings.TrimSpace(payload.Date)
|
|
payload.TargetDate = strings.TrimSpace(payload.TargetDate)
|
|
|
|
now := time.Now()
|
|
date := payload.Date
|
|
if !isValidOaDate(date) {
|
|
date = now.Format("2006-01-02")
|
|
}
|
|
targetDate := payload.TargetDate
|
|
if !isValidOaDate(targetDate) {
|
|
targetDate = nextOaDate(date, 1)
|
|
}
|
|
if !isValidOaDate(targetDate) {
|
|
c.oasJsonErr(400, 400, "顺延日期无效")
|
|
return
|
|
}
|
|
|
|
var list []models.OaSchedule
|
|
_, err = models.Orm.QueryTable(new(models.OaSchedule)).
|
|
Filter("is_deleted", 0).
|
|
Filter("tid", claims.TenantId).
|
|
Filter("user_id", claims.UserID).
|
|
Filter("schedule_date", date).
|
|
Filter("status", 0).
|
|
OrderBy("start_time", "id").
|
|
All(&list)
|
|
if err != nil && err != orm.ErrNoRows {
|
|
c.oasJsonErr(500, 500, "查询失败")
|
|
return
|
|
}
|
|
|
|
success, skipped := 0, 0
|
|
lastDate := targetDate
|
|
for i := range list {
|
|
if _, msg := carryOaSchedule(&list[i], targetDate, claims, now); msg != "" {
|
|
skipped++
|
|
continue
|
|
}
|
|
success++
|
|
lastDate = targetDate
|
|
}
|
|
|
|
c.oasOk(map[string]interface{}{
|
|
"success": success,
|
|
"skipped": skipped,
|
|
"schedule_date": lastDate,
|
|
})
|
|
}
|