1771 lines
45 KiB
Go
1771 lines
45 KiB
Go
package services
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"sort"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"server/models"
|
|
|
|
"github.com/beego/beego/v2/client/orm"
|
|
)
|
|
|
|
var (
|
|
ErrDocCategoryNotFound = errors.New("分类不存在")
|
|
ErrDocCategoryHasChild = errors.New("存在子分类,请先删除子分类")
|
|
ErrDocCategoryHasDoc = errors.New("分类下仍有文档,请先移动或删除")
|
|
ErrDocCategoryNameEmpty = errors.New("请输入分类名称")
|
|
ErrDocCategoryCircular = errors.New("不能将分类移动到自己或其子分类下")
|
|
ErrDocCategorySystem = errors.New("系统内置分类不可删除")
|
|
ErrDocCategoryNameKept = errors.New("该分类名称为系统保留,不可使用")
|
|
ErrDocCategorySystemLocked = errors.New("系统内置分类固定为一级分类,不可移动")
|
|
ErrDocNotFound = errors.New("文档不存在")
|
|
ErrDocTitleEmpty = errors.New("请输入文档标题")
|
|
ErrDocCategoryInvalid = errors.New("所属分类不存在")
|
|
ErrDocLinkSelf = errors.New("不能关联文档自身")
|
|
ErrDocLinkDuplicate = errors.New("该关联关系已存在")
|
|
ErrDocLinkTargetNotFound = errors.New("被关联的文档不存在")
|
|
ErrDocLinkNotFound = errors.New("关联关系不存在")
|
|
ErrDocIDEmpty = errors.New("请选择要操作的文档")
|
|
ErrDocNoPermission = errors.New("无权操作该私密文档")
|
|
)
|
|
|
|
type OaDocActor struct {
|
|
Tid int
|
|
UID uint64
|
|
OrgIDs []uint64
|
|
IsAdmin bool
|
|
}
|
|
|
|
func NewOaDocActor(tid int, uid uint64) OaDocActor {
|
|
models.EnsureOaDocDefaultCategories(tid)
|
|
|
|
actor := OaDocActor{Tid: tid, UID: uid, OrgIDs: []uint64{}}
|
|
|
|
var user models.SystemTenantUser
|
|
if err := models.Orm.QueryTable(new(models.SystemTenantUser)).
|
|
Filter("tid", tid).
|
|
Filter("uid", ResolveTenantUID(uint64(tid), uid)).
|
|
Filter("delete_time__isnull", true).
|
|
One(&user); err != nil {
|
|
return actor
|
|
}
|
|
actor.IsAdmin = user.GroupID == 0
|
|
if user.OrgID > 0 {
|
|
actor.OrgIDs = oaDocOrgSubTree(tid, user.OrgID)
|
|
}
|
|
return actor
|
|
}
|
|
|
|
func oaDocOrgSubTree(tid int, rootID uint64) []uint64 {
|
|
var orgs []models.BackendOrganization
|
|
if _, err := models.Orm.QueryTable(new(models.BackendOrganization)).
|
|
Filter("tid", tid).
|
|
Filter("delete_time__isnull", true).
|
|
All(&orgs); err != nil {
|
|
return []uint64{rootID}
|
|
}
|
|
|
|
children := make(map[uint64][]uint64, len(orgs))
|
|
for _, o := range orgs {
|
|
children[o.ParentID] = append(children[o.ParentID], o.ID)
|
|
}
|
|
|
|
result := []uint64{rootID}
|
|
var walk func(id uint64)
|
|
walk = func(id uint64) {
|
|
for _, cid := range children[id] {
|
|
if cid == rootID {
|
|
continue
|
|
}
|
|
result = append(result, cid)
|
|
walk(cid)
|
|
}
|
|
}
|
|
walk(rootID)
|
|
return result
|
|
}
|
|
|
|
func oaDocSharedDocIDs(a OaDocActor) []uint64 {
|
|
if a.UID == 0 && len(a.OrgIDs) == 0 {
|
|
return nil
|
|
}
|
|
orgIDs := a.OrgIDs
|
|
if len(orgIDs) == 0 {
|
|
orgIDs = []uint64{0}
|
|
}
|
|
|
|
userCond := orm.NewCondition().
|
|
And("share_type", models.DocShareTypeUser).
|
|
And("target_id", a.UID)
|
|
orgCond := orm.NewCondition().
|
|
And("share_type", models.DocShareTypeOrg).
|
|
And("target_id__in", orgIDs)
|
|
cond := orm.NewCondition().
|
|
And("tid", a.Tid).
|
|
AndCond(orm.NewCondition().OrCond(userCond).OrCond(orgCond))
|
|
|
|
var rows []models.OaDocShare
|
|
if _, err := models.Orm.QueryTable(new(models.OaDocShare)).SetCond(cond).All(&rows); err != nil {
|
|
return nil
|
|
}
|
|
|
|
seen := make(map[uint64]bool, len(rows))
|
|
ids := make([]uint64, 0, len(rows))
|
|
for _, r := range rows {
|
|
if !seen[r.DocID] {
|
|
seen[r.DocID] = true
|
|
ids = append(ids, r.DocID)
|
|
}
|
|
}
|
|
return ids
|
|
}
|
|
|
|
func oaDocVisibleCond(a OaDocActor) *orm.Condition {
|
|
if a.IsAdmin {
|
|
return nil
|
|
}
|
|
shared := oaDocSharedDocIDs(a)
|
|
if len(shared) == 0 {
|
|
shared = []uint64{0}
|
|
}
|
|
return orm.NewCondition().
|
|
Or("visibility", models.DocVisibilityPublic).
|
|
Or("creator_id", a.UID).
|
|
Or("id__in", shared)
|
|
}
|
|
|
|
func oaDocApplyVisible(qs orm.QuerySeter, a OaDocActor) orm.QuerySeter {
|
|
cond := oaDocVisibleCond(a)
|
|
if cond == nil {
|
|
return qs
|
|
}
|
|
return qs.SetCond(qs.GetCond().AndCond(cond))
|
|
}
|
|
|
|
func oaDocVisibilityRestrictSQL(a OaDocActor, prefix string) (string, []interface{}) {
|
|
if a.IsAdmin {
|
|
return "", nil
|
|
}
|
|
shared := oaDocSharedDocIDs(a)
|
|
if len(shared) == 0 {
|
|
shared = []uint64{0}
|
|
}
|
|
placeholders := make([]string, len(shared))
|
|
for i := range shared {
|
|
placeholders[i] = "?"
|
|
}
|
|
args := []interface{}{a.UID}
|
|
for _, id := range shared {
|
|
args = append(args, id)
|
|
}
|
|
return fmt.Sprintf(
|
|
" AND (%svisibility = 0 OR %screator_id = ? OR %sid IN (%s))",
|
|
prefix, prefix, prefix, strings.Join(placeholders, ",")), args
|
|
}
|
|
|
|
func oaDocApplyVisibility(qs orm.QuerySeter, v int) orm.QuerySeter {
|
|
switch v {
|
|
case 0:
|
|
return qs.Filter("visibility", models.DocVisibilityPublic)
|
|
case 1:
|
|
return qs.Filter("visibility", models.DocVisibilityPrivate)
|
|
default:
|
|
return qs
|
|
}
|
|
}
|
|
|
|
func oaDocVisibleIDSet(a OaDocActor, ids []uint64) map[uint64]bool {
|
|
out := make(map[uint64]bool, len(ids))
|
|
if len(ids) == 0 {
|
|
return out
|
|
}
|
|
var idList orm.ParamsList
|
|
qs := oaDocApplyVisible(oaDocBase(a.Tid).Filter("id__in", ids), a)
|
|
if _, err := qs.ValuesFlat(&idList, "Id"); err != nil {
|
|
return out
|
|
}
|
|
for _, v := range idList {
|
|
if id, err := strconv.ParseUint(fmt.Sprint(v), 10, 64); err == nil {
|
|
out[id] = true
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func oaDocCanManage(a OaDocActor, doc *models.OaDoc) bool {
|
|
if a.IsAdmin || doc.Visibility != models.DocVisibilityPrivate {
|
|
return true
|
|
}
|
|
return doc.CreatorID == a.UID
|
|
}
|
|
|
|
var docRelationLabel = map[string]string{
|
|
models.DocRelationReference: "引用",
|
|
models.DocRelationRelated: "相关",
|
|
models.DocRelationVersion: "版本",
|
|
models.DocRelationBelong: "从属",
|
|
}
|
|
|
|
func DocRelationLabel(relation string) string {
|
|
if v, ok := docRelationLabel[relation]; ok {
|
|
return v
|
|
}
|
|
return relation
|
|
}
|
|
|
|
type OaDocCategoryItem struct {
|
|
models.OaDocCategory
|
|
DocCount int64 `json:"doc_count"`
|
|
Children []*OaDocCategoryItem `json:"children"`
|
|
}
|
|
|
|
func oaDocScopeOf(scope string) string {
|
|
if scope == models.DocScopePersonal {
|
|
return models.DocScopePersonal
|
|
}
|
|
if scope == models.DocScopeAll {
|
|
return models.DocScopeAll
|
|
}
|
|
return models.DocScopeShared
|
|
}
|
|
|
|
func oaDocScopeVisibility(scope string) int8 {
|
|
if scope == models.DocScopePersonal {
|
|
return models.DocVisibilityPrivate
|
|
}
|
|
return models.DocVisibilityPublic
|
|
}
|
|
|
|
func oaDocScopeOfVisibility(v int8) string {
|
|
if v == models.DocVisibilityPrivate {
|
|
return models.DocScopePersonal
|
|
}
|
|
return models.DocScopeShared
|
|
}
|
|
|
|
func oaDocCategoryUserID(a OaDocActor, scope string) uint64 {
|
|
if scope == models.DocScopePersonal {
|
|
return a.UID
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func oaDocCategoryBaseAny(tid int) orm.QuerySeter {
|
|
return models.Orm.QueryTable(new(models.OaDocCategory)).
|
|
Filter("tid", tid).
|
|
Filter("is_deleted", 0)
|
|
}
|
|
|
|
func oaDocCategoryBase(a OaDocActor, scope string) orm.QuerySeter {
|
|
s := oaDocScopeOf(scope)
|
|
if s == models.DocScopeAll {
|
|
return oaDocCategoryBaseAny(a.Tid)
|
|
}
|
|
qs := oaDocCategoryBaseAny(a.Tid).Filter("scope", s)
|
|
if s == models.DocScopePersonal {
|
|
qs = qs.Filter("user_id", a.UID)
|
|
} else if s == models.DocScopeShared {
|
|
qs = qs.Filter("user_id", 0)
|
|
}
|
|
return qs
|
|
}
|
|
|
|
func oaDocCategoryIDs(a OaDocActor, scope string) ([]uint64, error) {
|
|
var list []models.OaDocCategory
|
|
qs := oaDocCategoryBaseAny(a.Tid)
|
|
if scope != models.DocScopeAll {
|
|
s := oaDocScopeOf(scope)
|
|
qs = qs.Filter("scope", s)
|
|
if s == models.DocScopePersonal {
|
|
qs = qs.Filter("user_id", a.UID)
|
|
} else if s == models.DocScopeShared {
|
|
qs = qs.Filter("user_id", 0)
|
|
}
|
|
}
|
|
if _, err := qs.All(&list); err != nil && err != orm.ErrNoRows {
|
|
return nil, err
|
|
}
|
|
ids := make([]uint64, 0, len(list))
|
|
for _, c := range list {
|
|
ids = append(ids, c.ID)
|
|
}
|
|
return ids, nil
|
|
}
|
|
|
|
func oaDocApplyUncategorized(qs orm.QuerySeter, a OaDocActor, scope string) orm.QuerySeter {
|
|
ids, err := oaDocCategoryIDs(a, scope)
|
|
if err != nil || len(ids) == 0 {
|
|
return qs
|
|
}
|
|
return qs.Exclude("category_id__in", ids)
|
|
}
|
|
|
|
func OaDocCategoryTree(a OaDocActor, scope string) ([]*OaDocCategoryItem, error) {
|
|
|
|
scope = oaDocScopeOf(scope)
|
|
var list []models.OaDocCategory
|
|
if _, err := oaDocCategoryBase(a, scope).OrderBy("-is_system", "sort", "id").All(&list); err != nil && err != orm.ErrNoRows {
|
|
return nil, err
|
|
}
|
|
|
|
counts, err := OaDocCountByCategory(a, scope, -1)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
nodes := make(map[uint64]*OaDocCategoryItem, len(list))
|
|
roots := make([]*OaDocCategoryItem, 0, len(list))
|
|
for i := range list {
|
|
item := &OaDocCategoryItem{
|
|
OaDocCategory: list[i],
|
|
DocCount: counts[list[i].ID],
|
|
Children: []*OaDocCategoryItem{},
|
|
}
|
|
nodes[item.ID] = item
|
|
}
|
|
for i := range list {
|
|
item := nodes[list[i].ID]
|
|
if parent, ok := nodes[list[i].ParentID]; ok && list[i].ParentID != 0 {
|
|
parent.Children = append(parent.Children, item)
|
|
} else {
|
|
roots = append(roots, item)
|
|
}
|
|
}
|
|
var rollup func(item *OaDocCategoryItem) int64
|
|
rollup = func(item *OaDocCategoryItem) int64 {
|
|
total := item.DocCount
|
|
for _, child := range item.Children {
|
|
total += rollup(child)
|
|
}
|
|
item.DocCount = total
|
|
return total
|
|
}
|
|
for _, root := range roots {
|
|
rollup(root)
|
|
}
|
|
return roots, nil
|
|
}
|
|
|
|
func OaDocCountByCategory(a OaDocActor, scope string, visibility int) (map[uint64]int64, error) {
|
|
|
|
scope = oaDocScopeOf(scope)
|
|
sql := "SELECT category_id, COUNT(*) AS cnt FROM yz_backend_oa_doc WHERE tid = ? AND is_deleted = 0"
|
|
args := []interface{}{a.Tid}
|
|
if scope != models.DocScopeAll {
|
|
vis := int8(0)
|
|
if visibility >= 0 {
|
|
vis = int8(visibility)
|
|
} else {
|
|
vis = oaDocScopeVisibility(scope)
|
|
}
|
|
sql += fmt.Sprintf(" AND visibility = %d", vis)
|
|
}
|
|
extra, extraArgs := oaDocVisibilityRestrictSQL(a, "")
|
|
sql += extra
|
|
args = append(args, extraArgs...)
|
|
sql += " GROUP BY category_id"
|
|
|
|
var rows []struct {
|
|
CategoryID uint64 `orm:"column(category_id)"`
|
|
Cnt int64 `orm:"column(cnt)"`
|
|
}
|
|
if _, err := models.Orm.Raw(sql, args...).QueryRows(&rows); err != nil {
|
|
return nil, err
|
|
}
|
|
result := make(map[uint64]int64, len(rows))
|
|
for _, r := range rows {
|
|
result[r.CategoryID] = r.Cnt
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
func oaDocIsReservedName(name string) bool {
|
|
name = strings.TrimSpace(name)
|
|
return name == "未分类" || name == models.DocCategoryNameProject
|
|
}
|
|
|
|
func OaDocCategoryCreate(a OaDocActor, scope string, parentID uint64, name, remark string, sort int) (*models.OaDocCategory, error) {
|
|
|
|
scope = oaDocScopeOf(scope)
|
|
name = strings.TrimSpace(name)
|
|
if name == "" {
|
|
return nil, ErrDocCategoryNameEmpty
|
|
}
|
|
if oaDocIsReservedName(name) {
|
|
return nil, ErrDocCategoryNameKept
|
|
}
|
|
if parentID != 0 {
|
|
ok, err := oaDocCategoryExists(a, scope, parentID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !ok {
|
|
return nil, ErrDocCategoryNotFound
|
|
}
|
|
}
|
|
|
|
item := &models.OaDocCategory{
|
|
Tid: a.Tid,
|
|
UserID: oaDocCategoryUserID(a, scope),
|
|
ParentID: parentID,
|
|
Name: name,
|
|
Remark: strings.TrimSpace(remark),
|
|
Sort: sort,
|
|
Scope: scope,
|
|
IsDeleted: 0,
|
|
}
|
|
if _, err := models.Orm.Insert(item); err != nil {
|
|
return nil, err
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
func OaDocCategoryUpdate(a OaDocActor, id uint64, name, remark string, sort int, parentID int64) (*models.OaDocCategory, error) {
|
|
|
|
var item models.OaDocCategory
|
|
if err := oaDocCategoryBaseAny(a.Tid).Filter("id", id).One(&item); err != nil {
|
|
return nil, ErrDocCategoryNotFound
|
|
}
|
|
if err := oaDocCheckCategoryOwner(a, &item); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
fields := []string{"UpdateTime"}
|
|
if name = strings.TrimSpace(name); name != "" && name != item.Name {
|
|
if item.IsSystem != models.DocCategorySystem && oaDocIsReservedName(name) {
|
|
return nil, ErrDocCategoryNameKept
|
|
}
|
|
item.Name = name
|
|
fields = append(fields, "Name")
|
|
}
|
|
if remark = strings.TrimSpace(remark); remark != item.Remark {
|
|
item.Remark = remark
|
|
fields = append(fields, "Remark")
|
|
}
|
|
if sort >= 0 && sort != item.Sort {
|
|
item.Sort = sort
|
|
fields = append(fields, "Sort")
|
|
}
|
|
if parentID >= 0 && uint64(parentID) != item.ParentID {
|
|
if item.IsSystem == models.DocCategorySystem {
|
|
return nil, ErrDocCategorySystemLocked
|
|
}
|
|
newParent := uint64(parentID)
|
|
if newParent == id {
|
|
return nil, ErrDocCategoryCircular
|
|
}
|
|
if newParent != 0 {
|
|
ok, err := oaDocCategoryExists(a, item.Scope, newParent)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !ok {
|
|
return nil, ErrDocCategoryNotFound
|
|
}
|
|
childIDs, err := OaDocCategoryDescendants(a, newParent)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, cid := range childIDs {
|
|
if cid == newParent {
|
|
return nil, ErrDocCategoryCircular
|
|
}
|
|
}
|
|
}
|
|
item.ParentID = newParent
|
|
fields = append(fields, "ParentID")
|
|
}
|
|
|
|
if len(fields) == 1 {
|
|
return &item, nil
|
|
}
|
|
now := time.Now()
|
|
item.UpdateTime = &now
|
|
if _, err := models.Orm.Update(&item, fields...); err != nil {
|
|
return nil, err
|
|
}
|
|
return &item, nil
|
|
}
|
|
|
|
func OaDocCategoryDescendants(a OaDocActor, rootID uint64) ([]uint64, error) {
|
|
var list []models.OaDocCategory
|
|
if _, err := oaDocCategoryBaseAny(a.Tid).All(&list); err != nil && err != orm.ErrNoRows {
|
|
return nil, err
|
|
}
|
|
children := make(map[uint64][]uint64)
|
|
for _, c := range list {
|
|
children[c.ParentID] = append(children[c.ParentID], c.ID)
|
|
}
|
|
|
|
result := make([]uint64, 0, len(list))
|
|
var walk func(id uint64)
|
|
walk = func(id uint64) {
|
|
for _, cid := range children[id] {
|
|
if cid == rootID {
|
|
continue
|
|
}
|
|
result = append(result, cid)
|
|
walk(cid)
|
|
}
|
|
}
|
|
walk(rootID)
|
|
return result, nil
|
|
}
|
|
|
|
func oaDocCategoryIDsWithChildren(a OaDocActor, scope string, rootID uint64) ([]uint64, error) {
|
|
if rootID == 0 {
|
|
return nil, nil
|
|
}
|
|
children, err := OaDocCategoryDescendants(a, rootID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return append([]uint64{rootID}, children...), nil
|
|
}
|
|
|
|
func OaDocCategoryDelete(a OaDocActor, id uint64) error {
|
|
|
|
var item models.OaDocCategory
|
|
if err := oaDocCategoryBaseAny(a.Tid).Filter("id", id).One(&item); err != nil {
|
|
return ErrDocCategoryNotFound
|
|
}
|
|
if item.IsSystem == models.DocCategorySystem {
|
|
return ErrDocCategorySystem
|
|
}
|
|
if err := oaDocCheckCategoryOwner(a, &item); err != nil {
|
|
return err
|
|
}
|
|
|
|
childCount, err := oaDocCategoryBase(a, item.Scope).Filter("parent_id", id).Count()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if childCount > 0 {
|
|
return ErrDocCategoryHasChild
|
|
}
|
|
|
|
docCount, err := oaDocBase(a.Tid).Filter("category_id", id).Count()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if docCount > 0 {
|
|
return ErrDocCategoryHasDoc
|
|
}
|
|
|
|
now := time.Now()
|
|
_, err = oaDocCategoryBaseAny(a.Tid).Filter("id", id).Update(orm.Params{
|
|
"IsDeleted": 1,
|
|
"DeleteTime": now,
|
|
"UpdateTime": now,
|
|
})
|
|
return err
|
|
}
|
|
|
|
func oaDocCategoryExists(a OaDocActor, scope string, id uint64) (bool, error) {
|
|
n, err := oaDocCategoryBase(a, scope).Filter("id", id).Count()
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
return n > 0, nil
|
|
}
|
|
|
|
func oaDocCheckCategoryOwner(a OaDocActor, item *models.OaDocCategory) error {
|
|
if item.UserID == 0 {
|
|
return nil
|
|
}
|
|
if item.UserID == a.UID && a.UID != 0 {
|
|
return nil
|
|
}
|
|
return ErrDocCategoryNotFound
|
|
}
|
|
|
|
func oaDocCategoryUsable(a OaDocActor, scope string, id uint64) (models.OaDocCategory, bool, error) {
|
|
var item models.OaDocCategory
|
|
if err := oaDocCategoryBase(a, scope).Filter("id", id).One(&item); err != nil {
|
|
return item, false, nil
|
|
}
|
|
return item, true, nil
|
|
}
|
|
|
|
func oaDocBase(tid int) orm.QuerySeter {
|
|
return models.Orm.QueryTable(new(models.OaDoc)).
|
|
Filter("tid", tid).
|
|
Filter("is_deleted", 0)
|
|
}
|
|
|
|
type OaDocListParams struct {
|
|
Actor OaDocActor
|
|
Scope string
|
|
Keyword string
|
|
CategoryID uint64
|
|
Uncategorized bool
|
|
Visibility int
|
|
Mine bool
|
|
Status int
|
|
DocType int
|
|
Tag string
|
|
Star int
|
|
Page int
|
|
PageSize int
|
|
}
|
|
|
|
func OaDocList(a OaDocActor, p OaDocListParams) ([]models.OaDoc, int64, error) {
|
|
|
|
scope := oaDocScopeOf(p.Scope)
|
|
qs := oaDocApplyVisible(oaDocBase(a.Tid), a)
|
|
if scope != models.DocScopeAll {
|
|
qs = qs.Filter("visibility", oaDocScopeVisibility(scope))
|
|
}
|
|
if p.Mine {
|
|
qs = qs.Filter("creator_id", a.UID)
|
|
}
|
|
if kw := strings.TrimSpace(p.Keyword); kw != "" {
|
|
cond := orm.NewCondition()
|
|
cond = cond.Or("title__icontains", kw).
|
|
Or("file_name__icontains", kw).
|
|
Or("tags__icontains", kw).
|
|
Or("summary__icontains", kw).
|
|
Or("owner_name__icontains", kw)
|
|
qs = qs.SetCond(qs.GetCond().AndCond(cond))
|
|
}
|
|
if p.Uncategorized {
|
|
qs = oaDocApplyUncategorized(qs, a, scope)
|
|
} else if p.CategoryID > 0 {
|
|
ids, err := oaDocCategoryIDsWithChildren(a, scope, p.CategoryID)
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
if len(ids) > 0 {
|
|
qs = qs.Filter("category_id__in", ids)
|
|
} else {
|
|
qs = qs.Filter("category_id__in", []uint64{})
|
|
}
|
|
}
|
|
if p.Status >= 0 {
|
|
qs = qs.Filter("status", int8(p.Status))
|
|
}
|
|
if p.DocType >= 0 {
|
|
qs = qs.Filter("doc_type", int8(p.DocType))
|
|
}
|
|
if tag := strings.TrimSpace(p.Tag); tag != "" {
|
|
qs = qs.Filter("tags__icontains", tag)
|
|
}
|
|
if p.Star == 1 {
|
|
qs = qs.Filter("is_star", 1)
|
|
}
|
|
|
|
total, err := qs.Count()
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
page, pageSize := p.Page, p.PageSize
|
|
if page < 1 {
|
|
page = 1
|
|
}
|
|
if pageSize < 1 {
|
|
pageSize = 20
|
|
}
|
|
|
|
var list []models.OaDoc
|
|
_, err = qs.OrderBy("-is_star", "-update_time", "-id").
|
|
Limit(pageSize).Offset((page - 1) * pageSize).
|
|
All(&list)
|
|
if err != nil && err != orm.ErrNoRows {
|
|
return nil, 0, err
|
|
}
|
|
if list == nil {
|
|
list = []models.OaDoc{}
|
|
}
|
|
for i := range list {
|
|
if strings.TrimSpace(list[i].Content) != "" {
|
|
list[i].IsOnline = 1
|
|
}
|
|
list[i].Content = ""
|
|
}
|
|
return list, total, nil
|
|
}
|
|
|
|
func OaDocGet(a OaDocActor, id uint64) (*models.OaDoc, error) {
|
|
|
|
var item models.OaDoc
|
|
qs := oaDocApplyVisible(oaDocBase(a.Tid).Filter("id", id), a)
|
|
if err := qs.One(&item); err != nil {
|
|
return nil, ErrDocNotFound
|
|
}
|
|
return &item, nil
|
|
}
|
|
|
|
func OaDocView(a OaDocActor, id uint64) (*models.OaDoc, error) {
|
|
item, err := OaDocGet(a, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
_, _ = models.Orm.Raw(
|
|
"UPDATE yz_backend_oa_doc SET view_count = view_count + 1 WHERE id = ?", id).Exec()
|
|
item.ViewCount++
|
|
return item, nil
|
|
}
|
|
|
|
func OaDocDownload(a OaDocActor, id uint64) (*models.OaDoc, error) {
|
|
item, err := OaDocGet(a, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
_, _ = models.Orm.Raw(
|
|
"UPDATE yz_backend_oa_doc SET download_count = download_count + 1 WHERE id = ?", id).Exec()
|
|
item.DownCount++
|
|
return item, nil
|
|
}
|
|
|
|
type OaDocSaveParams struct {
|
|
SetCategory bool
|
|
CategoryID uint64
|
|
SetVisibility bool
|
|
Title string
|
|
FileID uint64
|
|
FileURL string
|
|
FileName string
|
|
Ext string
|
|
Size uint64
|
|
Tags string
|
|
Summary string
|
|
SetContent bool
|
|
Content string
|
|
Status int8
|
|
Version int
|
|
OwnerID uint64
|
|
OwnerName string
|
|
IsStar int8
|
|
Visibility int8
|
|
}
|
|
|
|
func OaDocCreate(a OaDocActor, operatorName string, p OaDocSaveParams) (*models.OaDoc, error) {
|
|
tid := a.Tid
|
|
|
|
title := strings.TrimSpace(p.Title)
|
|
if title == "" {
|
|
title = strings.TrimSpace(strings.TrimSuffix(p.FileName, "."+p.Ext))
|
|
}
|
|
if title == "" {
|
|
return nil, ErrDocTitleEmpty
|
|
}
|
|
if p.CategoryID > 0 {
|
|
scope := oaDocScopeOfVisibility(p.Visibility)
|
|
if _, ok, err := oaDocCategoryUsable(a, scope, p.CategoryID); err != nil {
|
|
return nil, err
|
|
} else if !ok {
|
|
return nil, ErrDocCategoryInvalid
|
|
}
|
|
}
|
|
|
|
ext := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(p.Ext), "."))
|
|
version := p.Version
|
|
if version < 1 {
|
|
version = 1
|
|
}
|
|
if p.Status < 0 || p.Status > 2 {
|
|
p.Status = models.DocStatusDraft
|
|
}
|
|
if p.IsStar != 1 {
|
|
p.IsStar = 0
|
|
}
|
|
|
|
item := &models.OaDoc{
|
|
Tid: tid,
|
|
CategoryID: p.CategoryID,
|
|
Title: title,
|
|
FileID: p.FileID,
|
|
FileURL: strings.TrimSpace(p.FileURL),
|
|
FileName: strings.TrimSpace(p.FileName),
|
|
Ext: ext,
|
|
Size: p.Size,
|
|
DocType: models.DocTypeByExt(ext),
|
|
Tags: strings.TrimSpace(p.Tags),
|
|
Summary: strings.TrimSpace(p.Summary),
|
|
Content: p.Content,
|
|
Status: p.Status,
|
|
Version: version,
|
|
IsStar: p.IsStar,
|
|
OwnerID: p.OwnerID,
|
|
OwnerName: strings.TrimSpace(p.OwnerName),
|
|
CreatorID: a.UID,
|
|
CreatorName: operatorName,
|
|
Visibility: visibilityOf(p.Visibility),
|
|
IsDeleted: 0,
|
|
}
|
|
if _, err := models.Orm.Insert(item); err != nil {
|
|
return nil, err
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
func visibilityOf(v int8) int8 {
|
|
if v == 1 {
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func OaDocUpdate(a OaDocActor, id uint64, p OaDocSaveParams) (*models.OaDoc, error) {
|
|
|
|
var item models.OaDoc
|
|
if err := oaDocApplyVisible(oaDocBase(a.Tid).Filter("id", id), a).One(&item); err != nil {
|
|
return nil, ErrDocNotFound
|
|
}
|
|
if !oaDocCanManage(a, &item) {
|
|
return nil, ErrDocNoPermission
|
|
}
|
|
|
|
fields := []string{"UpdateTime"}
|
|
if p.SetCategory && p.CategoryID != item.CategoryID {
|
|
if p.CategoryID > 0 {
|
|
v := item.Visibility
|
|
if p.SetVisibility {
|
|
v = p.Visibility
|
|
}
|
|
scope := oaDocScopeOfVisibility(v)
|
|
if _, ok, err := oaDocCategoryUsable(a, scope, p.CategoryID); err != nil {
|
|
return nil, err
|
|
} else if !ok {
|
|
return nil, ErrDocCategoryInvalid
|
|
}
|
|
}
|
|
item.CategoryID = p.CategoryID
|
|
fields = append(fields, "CategoryID")
|
|
}
|
|
if p.SetVisibility {
|
|
if v := visibilityOf(p.Visibility); v != item.Visibility {
|
|
item.Visibility = v
|
|
fields = append(fields, "Visibility")
|
|
}
|
|
}
|
|
if title := strings.TrimSpace(p.Title); title != "" && title != item.Title {
|
|
item.Title = title
|
|
fields = append(fields, "Title")
|
|
}
|
|
if url := strings.TrimSpace(p.FileURL); url != "" {
|
|
item.FileURL = url
|
|
fields = append(fields, "FileURL")
|
|
if p.FileID > 0 {
|
|
item.FileID = p.FileID
|
|
fields = append(fields, "FileID")
|
|
}
|
|
if name := strings.TrimSpace(p.FileName); name != "" {
|
|
item.FileName = name
|
|
fields = append(fields, "FileName")
|
|
}
|
|
if ext := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(p.Ext), ".")); ext != "" {
|
|
item.Ext = ext
|
|
item.DocType = models.DocTypeByExt(ext)
|
|
fields = append(fields, "Ext", "DocType")
|
|
}
|
|
if p.Size > 0 {
|
|
item.Size = p.Size
|
|
fields = append(fields, "Size")
|
|
}
|
|
}
|
|
if tags := strings.TrimSpace(p.Tags); tags != item.Tags {
|
|
item.Tags = tags
|
|
fields = append(fields, "Tags")
|
|
}
|
|
if summary := strings.TrimSpace(p.Summary); summary != item.Summary {
|
|
item.Summary = summary
|
|
fields = append(fields, "Summary")
|
|
}
|
|
if p.Status >= 0 && p.Status <= 2 && p.Status != item.Status {
|
|
item.Status = p.Status
|
|
fields = append(fields, "Status")
|
|
}
|
|
if p.Version > 0 && p.Version != item.Version {
|
|
item.Version = p.Version
|
|
fields = append(fields, "Version")
|
|
}
|
|
if p.IsStar == 0 || p.IsStar == 1 {
|
|
if p.IsStar != item.IsStar {
|
|
item.IsStar = p.IsStar
|
|
fields = append(fields, "IsStar")
|
|
}
|
|
}
|
|
if p.OwnerID > 0 {
|
|
item.OwnerID = p.OwnerID
|
|
fields = append(fields, "OwnerID")
|
|
}
|
|
if owner := strings.TrimSpace(p.OwnerName); owner != "" && owner != item.OwnerName {
|
|
item.OwnerName = owner
|
|
fields = append(fields, "OwnerName")
|
|
}
|
|
if p.SetContent && p.Content != item.Content {
|
|
item.Content = p.Content
|
|
fields = append(fields, "Content")
|
|
}
|
|
|
|
if len(fields) == 1 {
|
|
return &item, nil
|
|
}
|
|
now := time.Now()
|
|
item.UpdateTime = &now
|
|
if _, err := models.Orm.Update(&item, fields...); err != nil {
|
|
return nil, err
|
|
}
|
|
return &item, nil
|
|
}
|
|
|
|
func OaDocDelete(a OaDocActor, ids []uint64) (int64, error) {
|
|
|
|
ids = normalizeIDs(ids)
|
|
if len(ids) == 0 {
|
|
return 0, ErrDocIDEmpty
|
|
}
|
|
|
|
var list []models.OaDoc
|
|
if _, err := oaDocApplyVisible(oaDocBase(a.Tid).Filter("id__in", ids), a).All(&list); err != nil && err != orm.ErrNoRows {
|
|
return 0, err
|
|
}
|
|
allowed := make([]uint64, 0, len(list))
|
|
for _, d := range list {
|
|
if oaDocCanManage(a, &d) {
|
|
allowed = append(allowed, d.ID)
|
|
}
|
|
}
|
|
if len(allowed) == 0 {
|
|
return 0, ErrDocNoPermission
|
|
}
|
|
|
|
now := time.Now()
|
|
n, err := oaDocBase(a.Tid).Filter("id__in", allowed).Update(orm.Params{
|
|
"IsDeleted": 1,
|
|
"DeleteTime": now,
|
|
"UpdateTime": now,
|
|
})
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
// 清理被删文档参与的全部关联关系,避免图谱出现悬挂连线
|
|
// 注意:SetCond 会整体替换查询条件,tid 必须写进 cond,否则会误删其它租户的数据
|
|
cond := orm.NewCondition().
|
|
And("tid", a.Tid).
|
|
AndCond(orm.NewCondition().
|
|
Or("source_id__in", allowed).
|
|
Or("target_id__in", allowed))
|
|
_, _ = models.Orm.QueryTable(new(models.OaDocLink)).SetCond(cond).Delete()
|
|
|
|
return n, nil
|
|
}
|
|
|
|
func OaDocMove(a OaDocActor, ids []uint64, categoryID uint64) (int64, error) {
|
|
|
|
ids = normalizeIDs(ids)
|
|
if len(ids) == 0 {
|
|
return 0, ErrDocIDEmpty
|
|
}
|
|
if categoryID > 0 {
|
|
var sample models.OaDoc
|
|
if _, err := oaDocApplyVisible(oaDocBase(a.Tid).Filter("id__in", ids), a).OrderBy("id").Limit(1).All(&sample); err == nil {
|
|
scope := oaDocScopeOfVisibility(sample.Visibility)
|
|
if _, ok, err := oaDocCategoryUsable(a, scope, categoryID); err != nil {
|
|
return 0, err
|
|
} else if !ok {
|
|
return 0, ErrDocCategoryInvalid
|
|
}
|
|
}
|
|
}
|
|
|
|
var list []models.OaDoc
|
|
if _, err := oaDocApplyVisible(oaDocBase(a.Tid).Filter("id__in", ids), a).All(&list); err != nil && err != orm.ErrNoRows {
|
|
return 0, err
|
|
}
|
|
allowed := make([]uint64, 0, len(list))
|
|
for _, d := range list {
|
|
if oaDocCanManage(a, &d) {
|
|
allowed = append(allowed, d.ID)
|
|
}
|
|
}
|
|
if len(allowed) == 0 {
|
|
return 0, ErrDocNoPermission
|
|
}
|
|
|
|
now := time.Now()
|
|
params := orm.Params{
|
|
"CategoryID": categoryID,
|
|
"UpdateTime": now,
|
|
}
|
|
return oaDocBase(a.Tid).Filter("id__in", allowed).Update(params)
|
|
}
|
|
|
|
func OaDocToggleStar(a OaDocActor, id uint64) (int8, error) {
|
|
|
|
var item models.OaDoc
|
|
if err := oaDocApplyVisible(oaDocBase(a.Tid).Filter("id", id), a).One(&item); err != nil {
|
|
return 0, ErrDocNotFound
|
|
}
|
|
if item.IsStar == 1 {
|
|
item.IsStar = 0
|
|
} else {
|
|
item.IsStar = 1
|
|
}
|
|
if _, err := models.Orm.Update(&item, "IsStar"); err != nil {
|
|
return 0, err
|
|
}
|
|
return item.IsStar, nil
|
|
}
|
|
|
|
type OaDocStatsResult struct {
|
|
Total int64 `json:"total"`
|
|
Published int64 `json:"published"`
|
|
Draft int64 `json:"draft"`
|
|
Archived int64 `json:"archived"`
|
|
Starred int64 `json:"starred"`
|
|
Uncategorized int64 `json:"uncategorized"`
|
|
LinkCount int64 `json:"link_count"`
|
|
PublicCount int64 `json:"public_count"`
|
|
PrivateCount int64 `json:"private_count"`
|
|
MineCount int64 `json:"mine_count"`
|
|
TypeCounts []OaDocTypeCount `json:"type_counts"`
|
|
RecentDocs []models.OaDoc `json:"recent_docs"`
|
|
HotDocs []models.OaDoc `json:"hot_docs"`
|
|
}
|
|
|
|
type OaDocTypeCount struct {
|
|
DocType int8 `json:"doc_type"`
|
|
Count int64 `json:"count"`
|
|
}
|
|
|
|
func OaDocStats(a OaDocActor, scope string) (*OaDocStatsResult, error) {
|
|
|
|
scope = oaDocScopeOf(scope)
|
|
vis := int8(-1)
|
|
if scope != models.DocScopeAll {
|
|
vis = oaDocScopeVisibility(scope)
|
|
}
|
|
|
|
allVisible := oaDocApplyVisible(oaDocBase(a.Tid), a)
|
|
if vis >= 0 {
|
|
allVisible = allVisible.Filter("visibility", vis)
|
|
}
|
|
mineCount, _ := allVisible.Filter("creator_id", a.UID).Count()
|
|
|
|
base := allVisible
|
|
total, _ := base.Count()
|
|
published, _ := base.Filter("status", models.DocStatusPublish).Count()
|
|
draft, _ := base.Filter("status", models.DocStatusDraft).Count()
|
|
archived, _ := base.Filter("status", models.DocStatusArchive).Count()
|
|
starred, _ := base.Filter("is_star", 1).Count()
|
|
uncategorized, _ := oaDocApplyUncategorized(base, a, scope).Count()
|
|
|
|
linkCount := int64(0)
|
|
linkExtra, linkExtraArgs := oaDocVisibilityRestrictSQL(a, "d.")
|
|
linkArgs := []interface{}{a.Tid}
|
|
if vis >= 0 {
|
|
linkArgs = append(linkArgs, vis)
|
|
}
|
|
linkArgs = append(linkArgs, linkExtraArgs...)
|
|
var linkRows []struct {
|
|
Cnt int64 `orm:"column(cnt)"`
|
|
}
|
|
visClause := ""
|
|
if vis >= 0 {
|
|
visClause = " AND d.visibility = ?"
|
|
}
|
|
_, _ = models.Orm.Raw(
|
|
`SELECT COUNT(*) AS cnt FROM yz_backend_oa_doc_link l
|
|
WHERE l.tid = ?`+visClause+` AND EXISTS (
|
|
SELECT 1 FROM yz_backend_oa_doc d
|
|
WHERE d.id = l.source_id AND d.is_deleted = 0`+linkExtra+")",
|
|
linkArgs...).QueryRows(&linkRows)
|
|
if len(linkRows) > 0 {
|
|
linkCount = linkRows[0].Cnt
|
|
}
|
|
|
|
var rows []struct {
|
|
DocType int8 `orm:"column(doc_type)"`
|
|
Cnt int64 `orm:"column(cnt)"`
|
|
}
|
|
typeExtra, typeExtraArgs := oaDocVisibilityRestrictSQL(a, "")
|
|
typeArgs := []interface{}{a.Tid}
|
|
if vis >= 0 {
|
|
typeArgs = append(typeArgs, vis)
|
|
}
|
|
typeArgs = append(typeArgs, typeExtraArgs...)
|
|
_, _ = models.Orm.Raw(
|
|
"SELECT doc_type, COUNT(*) AS cnt FROM yz_backend_oa_doc WHERE tid = ? AND is_deleted = 0"+
|
|
visClause+typeExtra+" GROUP BY doc_type ORDER BY cnt DESC",
|
|
typeArgs...).QueryRows(&rows)
|
|
typeCounts := make([]OaDocTypeCount, 0, len(rows))
|
|
for _, r := range rows {
|
|
typeCounts = append(typeCounts, OaDocTypeCount{DocType: r.DocType, Count: r.Cnt})
|
|
}
|
|
|
|
var recent []models.OaDoc
|
|
_, _ = base.OrderBy("-update_time", "-id").Limit(8).All(&recent)
|
|
if recent == nil {
|
|
recent = []models.OaDoc{}
|
|
}
|
|
var hot []models.OaDoc
|
|
_, _ = base.OrderBy("-view_count", "-id").Limit(8).All(&hot)
|
|
if hot == nil {
|
|
hot = []models.OaDoc{}
|
|
}
|
|
|
|
publicCount, privateCount := int64(0), int64(0)
|
|
switch scope {
|
|
case models.DocScopeShared:
|
|
publicCount = total
|
|
case models.DocScopePersonal:
|
|
privateCount = total
|
|
case models.DocScopeAll:
|
|
publicCount, _ = oaDocApplyVisible(oaDocBase(a.Tid), a).Filter("visibility", models.DocVisibilityPublic).Count()
|
|
privateCount, _ = oaDocApplyVisible(oaDocBase(a.Tid), a).Filter("visibility", models.DocVisibilityPrivate).Count()
|
|
}
|
|
|
|
return &OaDocStatsResult{
|
|
Total: total,
|
|
Published: published,
|
|
Draft: draft,
|
|
Archived: archived,
|
|
Starred: starred,
|
|
Uncategorized: uncategorized,
|
|
LinkCount: linkCount,
|
|
PublicCount: publicCount,
|
|
PrivateCount: privateCount,
|
|
MineCount: mineCount,
|
|
TypeCounts: typeCounts,
|
|
RecentDocs: recent,
|
|
HotDocs: hot,
|
|
}, nil
|
|
}
|
|
|
|
type OaDocLinkItem struct {
|
|
ID uint64 `json:"id"`
|
|
Tid int `json:"tid"`
|
|
SourceID uint64 `json:"source_id"`
|
|
TargetID uint64 `json:"target_id"`
|
|
Relation string `json:"relation"`
|
|
RelationCN string `json:"relation_cn"`
|
|
Remark string `json:"remark"`
|
|
CreateTime time.Time `json:"create_time"`
|
|
|
|
SourceTitle string `json:"source_title"`
|
|
TargetTitle string `json:"target_title"`
|
|
}
|
|
|
|
func OaDocLinkCreate(a OaDocActor, creatorID, sourceID, targetID uint64, relation, remark string) (*models.OaDocLink, error) {
|
|
tid := a.Tid
|
|
|
|
if sourceID == 0 || targetID == 0 {
|
|
return nil, ErrDocNotFound
|
|
}
|
|
if sourceID == targetID {
|
|
return nil, ErrDocLinkSelf
|
|
}
|
|
relation = strings.TrimSpace(relation)
|
|
if relation == "" {
|
|
relation = models.DocRelationRelated
|
|
}
|
|
|
|
for _, id := range []uint64{sourceID, targetID} {
|
|
if _, err := OaDocGet(a, id); err != nil {
|
|
return nil, ErrDocLinkTargetNotFound
|
|
}
|
|
}
|
|
|
|
qs := models.Orm.QueryTable(new(models.OaDocLink)).
|
|
Filter("tid", tid).
|
|
Filter("source_id", sourceID).
|
|
Filter("target_id", targetID).
|
|
Filter("relation", relation)
|
|
if qs.Exist() {
|
|
return nil, ErrDocLinkDuplicate
|
|
}
|
|
|
|
item := &models.OaDocLink{
|
|
Tid: tid,
|
|
SourceID: sourceID,
|
|
TargetID: targetID,
|
|
Relation: relation,
|
|
Remark: strings.TrimSpace(remark),
|
|
CreatorID: creatorID,
|
|
}
|
|
if _, err := models.Orm.Insert(item); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
reverse := *item
|
|
reverse.ID = 0
|
|
reverse.SourceID, reverse.TargetID = targetID, sourceID
|
|
if _, err := models.Orm.Insert(&reverse); err != nil {
|
|
_ = err
|
|
}
|
|
return item, nil
|
|
}
|
|
|
|
func OaDocLinkDelete(a OaDocActor, id uint64) error {
|
|
tid := a.Tid
|
|
|
|
var item models.OaDocLink
|
|
if err := models.Orm.QueryTable(new(models.OaDocLink)).
|
|
Filter("tid", tid).Filter("id", id).One(&item); err != nil {
|
|
return ErrDocLinkNotFound
|
|
}
|
|
if _, err := OaDocGet(a, item.SourceID); err != nil {
|
|
return ErrDocNoPermission
|
|
}
|
|
if _, err := OaDocGet(a, item.TargetID); err != nil {
|
|
return ErrDocNoPermission
|
|
}
|
|
|
|
forward := orm.NewCondition().
|
|
And("source_id", item.SourceID).
|
|
And("target_id", item.TargetID).
|
|
And("relation", item.Relation)
|
|
backward := orm.NewCondition().
|
|
And("source_id", item.TargetID).
|
|
And("target_id", item.SourceID).
|
|
And("relation", item.Relation)
|
|
cond := orm.NewCondition().
|
|
And("tid", tid).
|
|
AndCond(orm.NewCondition().OrCond(forward).OrCond(backward))
|
|
_, err := models.Orm.QueryTable(new(models.OaDocLink)).SetCond(cond).Delete()
|
|
return err
|
|
}
|
|
|
|
func OaDocLinkList(a OaDocActor, docID uint64, all bool) ([]OaDocLinkItem, error) {
|
|
|
|
sql := `
|
|
SELECT l.id, l.tid, l.source_id, l.target_id, l.relation, l.remark, l.create_time,
|
|
IFNULL(s.title, '') AS source_title, IFNULL(t.title, '') AS target_title
|
|
FROM yz_backend_oa_doc_link l
|
|
LEFT JOIN yz_backend_oa_doc s ON s.id = l.source_id AND s.is_deleted = 0
|
|
LEFT JOIN yz_backend_oa_doc t ON t.id = l.target_id AND t.is_deleted = 0
|
|
`
|
|
args := []interface{}{}
|
|
if all {
|
|
sql += "WHERE l.tid = ? ORDER BY l.id DESC LIMIT 500"
|
|
args = append(args, a.Tid)
|
|
} else {
|
|
sql += "WHERE l.tid = ? AND (l.source_id = ? OR l.target_id = ?) ORDER BY l.id DESC LIMIT 200"
|
|
args = append(args, a.Tid, docID, docID)
|
|
}
|
|
|
|
var rows []OaDocLinkItem
|
|
if _, err := models.Orm.Raw(sql, args...).QueryRows(&rows); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
endpointIDs := make([]uint64, 0, len(rows)*2)
|
|
seen := make(map[uint64]bool, len(rows)*2)
|
|
for _, r := range rows {
|
|
if !seen[r.SourceID] {
|
|
seen[r.SourceID] = true
|
|
endpointIDs = append(endpointIDs, r.SourceID)
|
|
}
|
|
if !seen[r.TargetID] {
|
|
seen[r.TargetID] = true
|
|
endpointIDs = append(endpointIDs, r.TargetID)
|
|
}
|
|
}
|
|
visible := oaDocVisibleIDSet(a, endpointIDs)
|
|
|
|
out := make([]OaDocLinkItem, 0, len(rows))
|
|
for _, r := range rows {
|
|
if !visible[r.SourceID] || !visible[r.TargetID] {
|
|
continue
|
|
}
|
|
r.RelationCN = DocRelationLabel(r.Relation)
|
|
out = append(out, r)
|
|
}
|
|
if out == nil {
|
|
out = []OaDocLinkItem{}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
type OaDocShareItem struct {
|
|
ShareType int8 `json:"share_type"`
|
|
TargetID uint64 `json:"target_id"`
|
|
}
|
|
|
|
type OaDocShareView struct {
|
|
ID uint64 `json:"id"`
|
|
DocID uint64 `json:"doc_id"`
|
|
ShareType int8 `json:"share_type"`
|
|
TargetID uint64 `json:"target_id"`
|
|
TargetName string `json:"target_name"`
|
|
}
|
|
|
|
func OaDocShareList(a OaDocActor, docID uint64) ([]OaDocShareView, error) {
|
|
if _, err := OaDocGet(a, docID); err != nil {
|
|
return nil, err
|
|
}
|
|
var rows []models.OaDocShare
|
|
if _, err := models.Orm.QueryTable(new(models.OaDocShare)).
|
|
Filter("tid", a.Tid).Filter("doc_id", docID).OrderBy("id").All(&rows); err != nil && err != orm.ErrNoRows {
|
|
return nil, err
|
|
}
|
|
views := make([]OaDocShareView, 0, len(rows))
|
|
for _, r := range rows {
|
|
views = append(views, OaDocShareView{
|
|
ID: r.ID,
|
|
DocID: r.DocID,
|
|
ShareType: r.ShareType,
|
|
TargetID: r.TargetID,
|
|
TargetName: oaDocShareTargetName(a.Tid, r.ShareType, r.TargetID),
|
|
})
|
|
}
|
|
if views == nil {
|
|
views = []OaDocShareView{}
|
|
}
|
|
return views, nil
|
|
}
|
|
|
|
func oaDocShareTargetName(tid int, shareType int8, targetID uint64) string {
|
|
if targetID == 0 {
|
|
return ""
|
|
}
|
|
if shareType == models.DocShareTypeOrg {
|
|
var org models.BackendOrganization
|
|
if err := models.Orm.QueryTable(new(models.BackendOrganization)).
|
|
Filter("tid", tid).Filter("id", targetID).One(&org); err == nil {
|
|
return org.OrgName
|
|
}
|
|
return ""
|
|
}
|
|
var u models.SystemTenantUser
|
|
if err := models.Orm.QueryTable(new(models.SystemTenantUser)).
|
|
Filter("tid", tid).Filter("uid", ResolveTenantUID(uint64(tid), targetID)).Filter("delete_time__isnull", true).One(&u); err == nil {
|
|
if u.Name != nil {
|
|
return *u.Name
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func OaDocShareSet(a OaDocActor, docID uint64, items []OaDocShareItem) ([]OaDocShareView, error) {
|
|
doc, err := OaDocGet(a, docID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !oaDocCanManage(a, doc) {
|
|
return nil, ErrDocNoPermission
|
|
}
|
|
|
|
seen := make(map[string]bool, len(items))
|
|
clean := make([]OaDocShareItem, 0, len(items))
|
|
for _, it := range items {
|
|
if it.TargetID == 0 {
|
|
continue
|
|
}
|
|
st := it.ShareType
|
|
if st != models.DocShareTypeUser && st != models.DocShareTypeOrg {
|
|
st = models.DocShareTypeUser
|
|
}
|
|
key := fmt.Sprintf("%d_%d", st, it.TargetID)
|
|
if seen[key] {
|
|
continue
|
|
}
|
|
seen[key] = true
|
|
clean = append(clean, OaDocShareItem{ShareType: st, TargetID: it.TargetID})
|
|
}
|
|
|
|
if _, err := models.Orm.QueryTable(new(models.OaDocShare)).
|
|
Filter("tid", a.Tid).Filter("doc_id", docID).Delete(); err != nil {
|
|
return nil, err
|
|
}
|
|
for _, it := range clean {
|
|
rec := models.OaDocShare{
|
|
Tid: a.Tid,
|
|
DocID: docID,
|
|
ShareType: it.ShareType,
|
|
TargetID: it.TargetID,
|
|
CreatorID: a.UID,
|
|
}
|
|
if _, err := models.Orm.Insert(&rec); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return OaDocShareList(a, docID)
|
|
}
|
|
|
|
func OaDocShareRemove(a OaDocActor, id uint64) error {
|
|
var item models.OaDocShare
|
|
if err := models.Orm.QueryTable(new(models.OaDocShare)).
|
|
Filter("tid", a.Tid).Filter("id", id).One(&item); err != nil {
|
|
return ErrDocLinkNotFound
|
|
}
|
|
doc, err := OaDocGet(a, item.DocID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !oaDocCanManage(a, doc) {
|
|
return ErrDocNoPermission
|
|
}
|
|
_, err = models.Orm.QueryTable(new(models.OaDocShare)).
|
|
Filter("tid", a.Tid).Filter("id", id).Delete()
|
|
return err
|
|
}
|
|
|
|
type OaDocMemberItem struct {
|
|
UID uint64 `json:"uid"`
|
|
Name string `json:"name"`
|
|
Account string `json:"account"`
|
|
OrgID uint64 `json:"org_id"`
|
|
OrgName string `json:"org_name"`
|
|
}
|
|
|
|
func OaDocMembers(tid int, keyword string, limit int) ([]OaDocMemberItem, error) {
|
|
if limit < 1 || limit > 200 {
|
|
limit = 100
|
|
}
|
|
qs := models.Orm.QueryTable(new(models.SystemTenantUser)).
|
|
Filter("tid", tid).
|
|
Filter("status", 1).
|
|
Filter("delete_time__isnull", true)
|
|
if kw := strings.TrimSpace(keyword); kw != "" {
|
|
cond := orm.NewCondition().
|
|
Or("name__icontains", kw).
|
|
Or("account__icontains", kw)
|
|
qs = qs.SetCond(qs.GetCond().AndCond(cond))
|
|
}
|
|
var users []models.SystemTenantUser
|
|
if _, err := qs.OrderBy("-id").Limit(limit).All(&users); err != nil && err != orm.ErrNoRows {
|
|
return nil, err
|
|
}
|
|
orgIDs := make([]uint64, 0, len(users))
|
|
for _, u := range users {
|
|
if u.OrgID > 0 {
|
|
orgIDs = append(orgIDs, u.OrgID)
|
|
}
|
|
}
|
|
orgName := make(map[uint64]string, len(orgIDs))
|
|
if len(orgIDs) > 0 {
|
|
var orgs []models.BackendOrganization
|
|
if _, err := models.Orm.QueryTable(new(models.BackendOrganization)).
|
|
Filter("tid", tid).Filter("id__in", orgIDs).All(&orgs); err == nil {
|
|
for _, o := range orgs {
|
|
orgName[o.ID] = o.OrgName
|
|
}
|
|
}
|
|
}
|
|
out := make([]OaDocMemberItem, 0, len(users))
|
|
for _, u := range users {
|
|
name := ""
|
|
if u.Name != nil {
|
|
name = *u.Name
|
|
}
|
|
account := ""
|
|
if u.Account != nil {
|
|
account = *u.Account
|
|
}
|
|
out = append(out, OaDocMemberItem{
|
|
UID: u.Uid,
|
|
Name: name,
|
|
Account: account,
|
|
OrgID: u.OrgID,
|
|
OrgName: orgName[u.OrgID],
|
|
})
|
|
}
|
|
if out == nil {
|
|
out = []OaDocMemberItem{}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
type OaDocGraphParams struct {
|
|
Keyword string
|
|
CategoryID uint64
|
|
Relation string
|
|
IncludeCategory bool
|
|
OnlyLinked bool
|
|
Limit int
|
|
}
|
|
|
|
type OaDocGraphNode struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Category int `json:"category"`
|
|
DocID uint64 `json:"doc_id"`
|
|
CategoryID uint64 `json:"category_id"`
|
|
Ext string `json:"ext"`
|
|
DocType int8 `json:"doc_type"`
|
|
Status int8 `json:"status"`
|
|
Tags string `json:"tags"`
|
|
OwnerName string `json:"owner_name"`
|
|
ViewCount int `json:"view_count"`
|
|
Degree int `json:"degree"`
|
|
Value int `json:"value"`
|
|
}
|
|
|
|
type OaDocGraphLink struct {
|
|
Source string `json:"source"`
|
|
Target string `json:"target"`
|
|
Relation string `json:"relation"`
|
|
Remark string `json:"remark"`
|
|
Label string `json:"label"`
|
|
Kind string `json:"kind"`
|
|
}
|
|
|
|
type OaDocRelationCount struct {
|
|
Relation string `json:"relation"`
|
|
Label string `json:"label"`
|
|
Count int64 `json:"count"`
|
|
}
|
|
|
|
type OaDocGraphStats struct {
|
|
DocCount int64 `json:"doc_count"`
|
|
LinkCount int64 `json:"link_count"`
|
|
CategoryCount int64 `json:"category_count"`
|
|
IsolatedCount int64 `json:"isolated_count"`
|
|
AvgDegree float64 `json:"avg_degree"`
|
|
RelationCounts []OaDocRelationCount `json:"relation_counts"`
|
|
TopNodes []OaDocGraphNode `json:"top_nodes"`
|
|
}
|
|
|
|
type OaDocGraphResult struct {
|
|
Nodes []OaDocGraphNode `json:"nodes"`
|
|
Links []OaDocGraphLink `json:"links"`
|
|
Categories []string `json:"categories"`
|
|
Stats OaDocGraphStats `json:"stats"`
|
|
}
|
|
|
|
func OaDocGraph(a OaDocActor, p OaDocGraphParams) (*OaDocGraphResult, error) {
|
|
|
|
limit := p.Limit
|
|
if limit < 1 || limit > 1000 {
|
|
limit = 300
|
|
}
|
|
|
|
docs, _, err := OaDocList(a, OaDocListParams{
|
|
Actor: a,
|
|
Scope: models.DocScopeAll,
|
|
Keyword: p.Keyword,
|
|
CategoryID: p.CategoryID,
|
|
Status: -1,
|
|
DocType: -1,
|
|
Star: -1,
|
|
Page: 1,
|
|
PageSize: limit,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
docIDs := make([]uint64, 0, len(docs))
|
|
for _, d := range docs {
|
|
docIDs = append(docIDs, d.ID)
|
|
}
|
|
|
|
nodes := make([]OaDocGraphNode, 0, len(docs)+8)
|
|
links := make([]OaDocGraphLink, 0, len(docs)*2)
|
|
degree := make(map[string]int)
|
|
|
|
for _, d := range docs {
|
|
nodes = append(nodes, OaDocGraphNode{
|
|
ID: fmt.Sprintf("d%d", d.ID),
|
|
Name: d.Title,
|
|
Category: 0,
|
|
DocID: d.ID,
|
|
CategoryID: d.CategoryID,
|
|
Ext: d.Ext,
|
|
DocType: d.DocType,
|
|
Status: d.Status,
|
|
Tags: d.Tags,
|
|
OwnerName: d.OwnerName,
|
|
ViewCount: d.ViewCount,
|
|
})
|
|
}
|
|
|
|
if len(docIDs) > 0 {
|
|
cond := orm.NewCondition().
|
|
And("tid", a.Tid).
|
|
And("source_id__in", docIDs).
|
|
And("target_id__in", docIDs)
|
|
qs := models.Orm.QueryTable(new(models.OaDocLink)).SetCond(cond)
|
|
if rel := strings.TrimSpace(p.Relation); rel != "" {
|
|
qs = qs.Filter("relation", rel)
|
|
}
|
|
var linkList []models.OaDocLink
|
|
if _, err := qs.OrderBy("id").All(&linkList); err != nil && err != orm.ErrNoRows {
|
|
return nil, err
|
|
}
|
|
for _, l := range linkList {
|
|
if l.SourceID > l.TargetID {
|
|
continue
|
|
}
|
|
links = append(links, OaDocGraphLink{
|
|
Source: fmt.Sprintf("d%d", l.SourceID),
|
|
Target: fmt.Sprintf("d%d", l.TargetID),
|
|
Relation: l.Relation,
|
|
Remark: l.Remark,
|
|
Label: DocRelationLabel(l.Relation),
|
|
Kind: "doc",
|
|
})
|
|
degree[fmt.Sprintf("d%d", l.SourceID)]++
|
|
degree[fmt.Sprintf("d%d", l.TargetID)]++
|
|
}
|
|
}
|
|
|
|
categoryCount := int64(0)
|
|
if p.IncludeCategory {
|
|
catCond := orm.NewCondition().
|
|
And("tid", a.Tid).
|
|
And("is_deleted", 0).
|
|
AndCond(orm.NewCondition().Or("user_id", 0).Or("user_id", a.UID))
|
|
var cats []models.OaDocCategory
|
|
if _, err := models.Orm.QueryTable(new(models.OaDocCategory)).SetCond(catCond).OrderBy("sort", "id").All(&cats); err != nil && err != orm.ErrNoRows {
|
|
return nil, err
|
|
}
|
|
categoryCount = int64(len(cats))
|
|
|
|
catByID := make(map[uint64]models.OaDocCategory, len(cats))
|
|
for _, c := range cats {
|
|
catByID[c.ID] = c
|
|
}
|
|
|
|
for _, d := range docs {
|
|
if d.CategoryID == 0 {
|
|
continue
|
|
}
|
|
if _, ok := catByID[d.CategoryID]; !ok {
|
|
continue
|
|
}
|
|
links = append(links, OaDocGraphLink{
|
|
Source: fmt.Sprintf("d%d", d.ID),
|
|
Target: fmt.Sprintf("c%d", d.CategoryID),
|
|
Relation: models.DocRelationBelong,
|
|
Label: DocRelationLabel(models.DocRelationBelong),
|
|
Kind: "belong",
|
|
})
|
|
degree[fmt.Sprintf("d%d", d.ID)]++
|
|
degree[fmt.Sprintf("c%d", d.CategoryID)]++
|
|
}
|
|
|
|
for _, c := range cats {
|
|
if c.ParentID == 0 {
|
|
continue
|
|
}
|
|
if _, ok := catByID[c.ParentID]; !ok {
|
|
continue
|
|
}
|
|
links = append(links, OaDocGraphLink{
|
|
Source: fmt.Sprintf("c%d", c.ID),
|
|
Target: fmt.Sprintf("c%d", c.ParentID),
|
|
Relation: models.DocRelationBelong,
|
|
Label: "子分类",
|
|
Kind: "cate",
|
|
})
|
|
degree[fmt.Sprintf("c%d", c.ID)]++
|
|
degree[fmt.Sprintf("c%d", c.ParentID)]++
|
|
}
|
|
|
|
for _, c := range cats {
|
|
catKind := 1
|
|
if c.UserID != 0 {
|
|
catKind = 2
|
|
}
|
|
nodes = append(nodes, OaDocGraphNode{
|
|
ID: fmt.Sprintf("c%d", c.ID),
|
|
Name: c.Name,
|
|
Category: catKind,
|
|
CategoryID: c.ID,
|
|
})
|
|
}
|
|
}
|
|
|
|
if p.OnlyLinked {
|
|
kept := make([]OaDocGraphNode, 0, len(nodes))
|
|
for _, n := range nodes {
|
|
if degree[n.ID] > 0 {
|
|
kept = append(kept, n)
|
|
}
|
|
}
|
|
nodes = kept
|
|
}
|
|
|
|
for i := range nodes {
|
|
nodes[i].Degree = degree[nodes[i].ID]
|
|
nodes[i].Value = degree[nodes[i].ID] + 1
|
|
}
|
|
|
|
stats := OaDocGraphStats{
|
|
DocCount: int64(len(docs)),
|
|
CategoryCount: categoryCount,
|
|
}
|
|
isolated := int64(0)
|
|
for _, n := range nodes {
|
|
if n.Category == 0 && n.Degree == 0 {
|
|
isolated++
|
|
}
|
|
}
|
|
stats.IsolatedCount = isolated
|
|
docLinkCount := int64(0)
|
|
for _, l := range links {
|
|
if l.Kind == "doc" {
|
|
docLinkCount++
|
|
}
|
|
}
|
|
stats.LinkCount = docLinkCount
|
|
if len(docs) > 0 {
|
|
stats.AvgDegree = float64(docLinkCount*2) / float64(len(docs))
|
|
}
|
|
|
|
relCountMap := make(map[string]int64, 4)
|
|
for _, l := range links {
|
|
if l.Kind != "doc" {
|
|
continue
|
|
}
|
|
relCountMap[l.Relation]++
|
|
}
|
|
stats.RelationCounts = make([]OaDocRelationCount, 0, len(relCountMap))
|
|
for rel, cnt := range relCountMap {
|
|
stats.RelationCounts = append(stats.RelationCounts, OaDocRelationCount{
|
|
Relation: rel,
|
|
Label: DocRelationLabel(rel),
|
|
Count: cnt,
|
|
})
|
|
}
|
|
sort.Slice(stats.RelationCounts, func(i, j int) bool {
|
|
return stats.RelationCounts[i].Count > stats.RelationCounts[j].Count
|
|
})
|
|
|
|
sorted := make([]OaDocGraphNode, 0, len(nodes))
|
|
for _, n := range nodes {
|
|
if n.Category == 0 {
|
|
sorted = append(sorted, n)
|
|
}
|
|
}
|
|
for i := 0; i < len(sorted); i++ {
|
|
for j := i + 1; j < len(sorted); j++ {
|
|
if sorted[j].Degree > sorted[i].Degree {
|
|
sorted[i], sorted[j] = sorted[j], sorted[i]
|
|
}
|
|
}
|
|
}
|
|
if len(sorted) > 8 {
|
|
sorted = sorted[:8]
|
|
}
|
|
stats.TopNodes = sorted
|
|
|
|
return &OaDocGraphResult{
|
|
Nodes: nodes,
|
|
Links: links,
|
|
Categories: []string{"文档", "分类"},
|
|
Stats: stats,
|
|
}, nil
|
|
}
|
|
|
|
func normalizeIDs(ids []uint64) []uint64 {
|
|
seen := make(map[uint64]bool, len(ids))
|
|
result := make([]uint64, 0, len(ids))
|
|
for _, id := range ids {
|
|
if id > 0 && !seen[id] {
|
|
seen[id] = true
|
|
result = append(result, id)
|
|
}
|
|
}
|
|
return result
|
|
}
|