初步完成附件查询

dev
truthhun 2 years ago
parent 10f00542d5
commit a99ccb3643

@ -0,0 +1,81 @@
syntax = "proto3";
import "google/protobuf/timestamp.proto";
import "gogoproto/gogo.proto";
// import "validate/validate.proto";
import "google/api/annotations.proto";
import "google/protobuf/empty.proto";
package api.v1;
option go_package = "moredoc/api/v1;v1";
option java_multiple_files = true;
option java_package = "api.v1";
message Attachment {
int64 id = 1;
string hash = 2;
int64 user_id = 3;
int64 type_id = 4;
int32 type = 5;
int32 is_approved = 6;
string path = 7;
string name = 8;
int64 size = 9;
int64 width = 10;
int64 height = 11;
string ext = 12;
string ip = 13;
string username = 16; //
string type_name = 17; //
google.protobuf.Timestamp created_at = 14 [ (gogoproto.stdtime) = true ];
google.protobuf.Timestamp updated_at = 15 [ (gogoproto.stdtime) = true ];
}
message DeleteAttachmentRequest { repeated int64 id = 1; }
message GetAttachmentRequest { int64 id = 1; }
message ListAttachmentRequest {
int64 page = 1;
int64 size = 2;
string wd = 3; //
repeated int64 is_approved = 4;
repeated int64 user_id = 5; // ID
repeated int64 type = 6; //
string ext = 7; //
}
message ListAttachmentReply {
int64 total = 1;
repeated Attachment attachment = 2;
}
//
service AttachmentAPI {
rpc UpdateAttachment(Attachment) returns (Attachment) {
option (google.api.http) = {
put : '/api/v1/attachment',
body : '*',
};
}
rpc DeleteAttachment(DeleteAttachmentRequest)
returns (google.protobuf.Empty) {
option (google.api.http) = {
delete : '/api/v1/attachment',
};
}
rpc GetAttachment(GetAttachmentRequest) returns (Attachment) {
option (google.api.http) = {
get : '/api/v1/attachment',
};
}
rpc ListAttachment(ListAttachmentRequest) returns (ListAttachmentReply) {
option (google.api.http) = {
get : '/api/v1/attachment/list',
};
}
}

@ -0,0 +1,149 @@
package biz
import (
"context"
"strings"
pb "moredoc/api/v1"
"moredoc/middleware/auth"
"moredoc/model"
"moredoc/util"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
)
type AttachmentAPIService struct {
pb.UnimplementedAttachmentAPIServer
dbModel *model.DBModel
logger *zap.Logger
}
func NewAttachmentAPIService(dbModel *model.DBModel, logger *zap.Logger) (service *AttachmentAPIService) {
return &AttachmentAPIService{dbModel: dbModel, logger: logger.Named("AttachmentAPIService")}
}
// checkPermission 检查用户权限
func (s *AttachmentAPIService) checkPermission(ctx context.Context) (userClaims *auth.UserClaims, err error) {
var ok bool
userClaims, ok = ctx.Value(auth.CtxKeyUserClaims).(*auth.UserClaims)
if !ok {
return nil, status.Errorf(codes.Unauthenticated, ErrorMessageInvalidToken)
}
fullMethod, _ := ctx.Value(auth.CtxKeyFullMethod).(string)
if yes := s.dbModel.CheckPermissionByUserId(userClaims.UserId, fullMethod); !yes {
return nil, status.Errorf(codes.PermissionDenied, ErrorMessagePermissionDenied)
}
return
}
func (s *AttachmentAPIService) UpdateAttachment(ctx context.Context, req *pb.Attachment) (*pb.Attachment, error) {
return &pb.Attachment{}, nil
}
func (s *AttachmentAPIService) DeleteAttachment(ctx context.Context, req *pb.DeleteAttachmentRequest) (*emptypb.Empty, error) {
_, err := s.checkPermission(ctx)
if err != nil {
return nil, err
}
err = s.dbModel.DeleteAttachment(req.Id)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
return &emptypb.Empty{}, nil
}
func (s *AttachmentAPIService) GetAttachment(ctx context.Context, req *pb.GetAttachmentRequest) (*pb.Attachment, error) {
return &pb.Attachment{}, nil
}
func (s *AttachmentAPIService) ListAttachment(ctx context.Context, req *pb.ListAttachmentRequest) (*pb.ListAttachmentReply, error) {
_, err := s.checkPermission(ctx)
if err != nil {
return nil, err
}
opt := &model.OptionGetAttachmentList{
Page: int(req.Page),
Size: int(req.Size_),
WithCount: true,
QueryIn: make(map[string][]interface{}),
}
if len(req.UserId) > 0 {
opt.QueryIn["user_id"] = util.Slice2Interface(req.UserId)
}
if len(req.IsApproved) > 0 {
opt.QueryIn["is_approved"] = util.Slice2Interface(req.IsApproved)
}
if len(req.Type) > 0 {
opt.QueryIn["type"] = util.Slice2Interface(req.Type)
}
req.Wd = strings.TrimSpace(req.Wd)
if req.Wd != "" {
wd := "%" + req.Wd + "%"
opt.QueryLike = map[string][]interface{}{"name": {wd}}
}
attachments, total, err := s.dbModel.GetAttachmentList(opt)
if err != nil {
return nil, status.Errorf(codes.Internal, err.Error())
}
var pbAttachments []*pb.Attachment
util.CopyStruct(&attachments, &pbAttachments)
var (
userIds []interface{}
userIdIndexMap = make(map[int64][]int)
)
for idx, attchment := range pbAttachments {
attchment.TypeName = s.dbModel.GetAttachmentTypeName(int(attchment.Type))
userIds = append(userIds, attchment.UserId)
userIdIndexMap[attchment.UserId] = append(userIdIndexMap[attchment.UserId], idx)
pbAttachments[idx] = attchment
}
if size := len(userIds); size > 0 {
users, _, _ := s.dbModel.GetUserList(&model.OptionGetUserList{Ids: userIds, Page: 1, Size: size, SelectFields: []string{"id", "username"}})
s.logger.Debug("GetUserList", zap.Any("users", users))
for _, user := range users {
if indexes, ok := userIdIndexMap[user.Id]; ok {
for _, idx := range indexes {
pbAttachments[idx].Username = user.Username
}
}
}
}
return &pb.ListAttachmentReply{Total: total, Attachment: pbAttachments}, nil
}
// 上传头像
func (s *AttachmentAPIService) UploadAvatar() {
}
// 上传横幅
func (s *AttachmentAPIService) UploadBanner() {
}
// 上传文档
func (s *AttachmentAPIService) UploadDocument() {
}
// 上传文档分类封面
func (s *AttachmentAPIService) UploadCategoryCover() {
}

@ -134,11 +134,7 @@ func (s *FriendlinkAPIService) ListFriendlink(ctx context.Context, req *pb.ListF
}
// 管理员可查询指定状态的友链
if len(req.Status) > 0 {
var statues []interface{}
for _, status := range req.Status {
statues = append(statues, status)
}
opt.QueryIn = map[string][]interface{}{"status": statues}
opt.QueryIn = map[string][]interface{}{"status": util.Slice2Interface(req.Status)}
}
} else {
// 非管理员可查询的字段

@ -270,7 +270,7 @@ func (s *UserAPIService) ListUser(ctx context.Context, req *pb.ListUserRequest)
userId = userClaims.UserId
}
opt := model.OptionGetUserList{
opt := &model.OptionGetUserList{
Page: int(req.Page),
Size: int(req.Size_),
WithCount: true,
@ -286,19 +286,11 @@ func (s *UserAPIService) ListUser(ctx context.Context, req *pb.ListUserRequest)
}
if len(req.GroupId) > 0 {
var groupIds []interface{}
for _, groupId := range req.GroupId {
groupIds = append(groupIds, groupId)
}
opt.QueryIn = map[string][]interface{}{"group_id": groupIds}
opt.QueryIn = map[string][]interface{}{"group_id": util.Slice2Interface(req.GroupId)}
}
if len(req.Status) > 0 {
var statuses []interface{}
for _, status := range req.Status {
statuses = append(statuses, status)
}
opt.QueryIn = map[string][]interface{}{"status": statuses}
opt.QueryIn = map[string][]interface{}{"status": util.Slice2Interface(req.Status)}
}
if req.Sort != "" {

@ -1,50 +1,47 @@
package model
import (
"fmt"
"strings"
"time"
"go.uber.org/zap"
"gorm.io/gorm"
)
type Attachment struct {
Id int64 `form:"id" json:"id,omitempty" gorm:"primaryKey;autoIncrement;column:id;comment:附件 id;"`
Hash string `form:"hash" json:"hash,omitempty" gorm:"column:hash;type:char(32);size:32;index:hash;comment:文件MD5;"`
UserId int64 `form:"user_id" json:"user_id,omitempty" gorm:"column:user_id;type:bigint(20) unsigned;default:0;index:user_id;comment:用户 id;"`
TypeId int64 `form:"type_id" json:"type_id,omitempty" gorm:"column:type_id;type:bigint(20) unsigned;default:0;comment:类型数据ID对应与用户头像时则为用户id对应为文档时则为文档ID;"`
Type int `form:"type" json:"type,omitempty" gorm:"column:type;type:smallint(5) unsigned;default:0;comment:附件类型(0 头像1 文档2 文章附件 ...);"`
IsApproved int8 `form:"is_approved" json:"is_approved,omitempty" gorm:"column:is_approved;type:tinyint(3) unsigned;default:1;comment:是否合法;"`
Path string `form:"path" json:"path,omitempty" gorm:"column:path;type:varchar(255);size:255;comment:文件存储路径;"`
Name string `form:"name" json:"name,omitempty" gorm:"column:name;type:varchar(255);size:255;comment:文件原名称;"`
Size int64 `form:"size" json:"size,omitempty" gorm:"column:size;type:bigint(20) unsigned;default:0;comment:文件大小;"`
Width int64 `form:"width" json:"width,omitempty" gorm:"column:width;type:bigint(20) unsigned;default:0;comment:宽度;"`
Height int64 `form:"height" json:"height,omitempty" gorm:"column:height;type:bigint(20) unsigned;default:0;comment:高度;"`
Ext string `form:"ext" json:"ext,omitempty" gorm:"column:ext;type:varchar(32);size:32;comment:文件类型,如 .pdf 。统一处理成小写;"`
Ip string `form:"ip" json:"ip,omitempty" gorm:"column:ip;type:varchar(16);size:16;comment:上传文档的用户IP地址;"`
CreatedAt *time.Time `form:"created_at" json:"created_at,omitempty" gorm:"column:created_at;type:datetime;comment:创建时间;"`
UpdatedAt *time.Time `form:"updated_at" json:"updated_at,omitempty" gorm:"column:updated_at;type:datetime;comment:更新时间;"`
const (
AttachmentTypeAvatar = iota // 用户头像
AttachmentTypeDocument // 文档
AttachmentTypeArticle // 文章
AttachmentTypeComment // 评论
AttachmentTypeBanner // 横幅
AttachmentTypeCategoryCover // 分类封面
)
var attachmentTypeName = map[int]string{
AttachmentTypeAvatar: "头像",
AttachmentTypeArticle: "文章",
AttachmentTypeBanner: "横幅",
AttachmentTypeCategoryCover: "分类封面",
AttachmentTypeComment: "评论",
AttachmentTypeDocument: "文档",
}
// 这里是proto文件中的结构体可以根据需要删除或者调整
//message Attachment {
// int64 id = 1;
// string hash = 2;
// int64 user_id = 3;
// int64 type_id = 4;
// int32 type = 5;
// int32 is_approved = 6;
// string path = 7;
// string name = 8;
// int64 size = 9;
// int64 width = 10;
// int64 height = 11;
// string ext = 12;
// string ip = 13;
// google.protobuf.Timestamp created_at = 14 [ (gogoproto.stdtime) = true ];
// google.protobuf.Timestamp updated_at = 15 [ (gogoproto.stdtime) = true ];
//}
type Attachment struct {
Id int64 `form:"id" json:"id,omitempty" gorm:"primaryKey;autoIncrement;column:id;comment:附件 id;"`
Hash string `form:"hash" json:"hash,omitempty" gorm:"column:hash;type:char(32);size:32;index:hash;comment:文件MD5;"`
UserId int64 `form:"user_id" json:"user_id,omitempty" gorm:"column:user_id;type:bigint(20) unsigned;default:0;index:user_id;comment:用户 id;"`
TypeId int64 `form:"type_id" json:"type_id,omitempty" gorm:"column:type_id;type:bigint(20) unsigned;default:0;comment:类型数据ID对应与用户头像时则为用户id对应为文档时则为文档ID;"`
Type int `form:"type" json:"type,omitempty" gorm:"column:type;type:smallint(5) unsigned;default:0;comment:附件类型(0 头像1 文档2 文章附件 ...);"`
IsApproved int8 `form:"is_approved" json:"is_approved,omitempty" gorm:"column:is_approved;type:tinyint(3) unsigned;default:1;comment:是否合法;"`
Path string `form:"path" json:"path,omitempty" gorm:"column:path;type:varchar(255);size:255;comment:文件存储路径;"`
Name string `form:"name" json:"name,omitempty" gorm:"column:name;type:varchar(255);size:255;comment:文件原名称;"`
Size int64 `form:"size" json:"size,omitempty" gorm:"column:size;type:bigint(20) unsigned;default:0;comment:文件大小;"`
Width int64 `form:"width" json:"width,omitempty" gorm:"column:width;type:bigint(20) unsigned;default:0;comment:宽度;"`
Height int64 `form:"height" json:"height,omitempty" gorm:"column:height;type:bigint(20) unsigned;default:0;comment:高度;"`
Ext string `form:"ext" json:"ext,omitempty" gorm:"column:ext;type:varchar(32);size:32;comment:文件类型,如 .pdf 。统一处理成小写;"`
Ip string `form:"ip" json:"ip,omitempty" gorm:"column:ip;type:varchar(16);size:16;comment:上传文档的用户IP地址;"`
CreatedAt time.Time `form:"created_at" json:"created_at,omitempty" gorm:"column:created_at;type:datetime;comment:创建时间;"`
UpdatedAt time.Time `form:"updated_at" json:"updated_at,omitempty" gorm:"column:updated_at;type:datetime;comment:更新时间;"`
}
func (Attachment) TableName() string {
return tablePrefix + "attachment"
@ -61,13 +58,22 @@ func (m *DBModel) CreateAttachment(attachment *Attachment) (err error) {
return
}
// GetAttachmentTypeName 获取附件类型名称
func (m *DBModel) GetAttachmentTypeName(typ int) string {
name, _ := attachmentTypeName[typ]
return name
}
// UpdateAttachment 更新Attachment如果需要更新指定字段则请指定updateFields参数
func (m *DBModel) UpdateAttachment(attachment *Attachment, updateFields ...string) (err error) {
db := m.db.Model(attachment)
tableName := Attachment{}.TableName()
updateFields = m.FilterValidFields(Attachment{}.TableName(), updateFields...)
updateFields = m.FilterValidFields(tableName, updateFields...)
if len(updateFields) > 0 { // 更新指定字段
db = db.Select(updateFields)
} else { // 更新全部字段,包括零值字段
db = db.Select(m.GetTableFields(tableName))
}
err = db.Where("id = ?", attachment.Id).Updates(attachment).Error
@ -103,37 +109,12 @@ type OptionGetAttachmentList struct {
}
// GetAttachmentList 获取Attachment列表
func (m *DBModel) GetAttachmentList(opt OptionGetAttachmentList) (attachmentList []Attachment, total int64, err error) {
func (m *DBModel) GetAttachmentList(opt *OptionGetAttachmentList) (attachmentList []Attachment, total int64, err error) {
tableName := Attachment{}.TableName()
db := m.db.Model(&Attachment{})
for field, rangeValue := range opt.QueryRange {
fields := m.FilterValidFields(Attachment{}.TableName(), field)
if len(fields) == 0 {
continue
}
if rangeValue[0] != nil {
db = db.Where(fmt.Sprintf("%s >= ?", field), rangeValue[0])
}
if rangeValue[1] != nil {
db = db.Where(fmt.Sprintf("%s <= ?", field), rangeValue[1])
}
}
for field, values := range opt.QueryIn {
fields := m.FilterValidFields(Attachment{}.TableName(), field)
if len(fields) == 0 {
continue
}
db = db.Where(fmt.Sprintf("%s in (?)", field), values)
}
for field, values := range opt.QueryLike {
fields := m.FilterValidFields(Attachment{}.TableName(), field)
if len(fields) == 0 {
continue
}
db = db.Where(strings.TrimSuffix(fmt.Sprintf(strings.Join(make([]string, len(values)+1), "%s like ? or"), field), "or"), values...)
}
db = m.generateQueryRange(db, tableName, opt.QueryRange)
db = m.generateQueryIn(db, tableName, opt.QueryIn)
db = m.generateQueryLike(db, tableName, opt.QueryLike)
if len(opt.Ids) > 0 {
db = db.Where("id in (?)", opt.Ids)
@ -147,29 +128,13 @@ func (m *DBModel) GetAttachmentList(opt OptionGetAttachmentList) (attachmentList
}
}
opt.SelectFields = m.FilterValidFields(Attachment{}.TableName(), opt.SelectFields...)
opt.SelectFields = m.FilterValidFields(tableName, opt.SelectFields...)
if len(opt.SelectFields) > 0 {
db = db.Select(opt.SelectFields)
}
if len(opt.Sort) > 0 {
var sorts []string
for _, sort := range opt.Sort {
slice := strings.Split(sort, " ")
if len(m.FilterValidFields(Attachment{}.TableName(), slice[0])) == 0 {
continue
}
if len(slice) == 2 {
sorts = append(sorts, fmt.Sprintf("%s %s", slice[0], slice[1]))
} else {
sorts = append(sorts, fmt.Sprintf("%s desc", slice[0]))
}
}
if len(sorts) > 0 {
db = db.Order(strings.Join(sorts, ","))
}
}
// TODO: 没有排序参数的话,可以自行指定排序字段
db = m.generateQuerySort(db, tableName, opt.Sort)
db = db.Offset((opt.Page - 1) * opt.Size).Limit(opt.Size)
@ -182,7 +147,8 @@ func (m *DBModel) GetAttachmentList(opt OptionGetAttachmentList) (attachmentList
// DeleteAttachment 删除数据
// TODO: 删除数据之后,存在 attachment_id 的关联表,需要删除对应数据,同时相关表的统计数值,也要随着减少
func (m *DBModel) DeleteAttachment(ids []interface{}) (err error) {
// TODO: 检查是否有相同hash的文件存在没有的话需要同时删除文件
func (m *DBModel) DeleteAttachment(ids []int64) (err error) {
err = m.db.Where("id in (?)", ids).Delete(&Attachment{}).Error
if err != nil {
m.logger.Error("DeleteAttachment", zap.Error(err))

@ -193,7 +193,7 @@ type OptionGetUserList struct {
}
// GetUserList 获取User列表
func (m *DBModel) GetUserList(opt OptionGetUserList) (userList []User, total int64, err error) {
func (m *DBModel) GetUserList(opt *OptionGetUserList) (userList []User, total int64, err error) {
db := m.db.Model(&User{})
for field, rangeValue := range opt.QueryRange {
@ -252,7 +252,7 @@ func (m *DBModel) GetUserList(opt OptionGetUserList) (userList []User, total int
}
opt.Page = util.LimitMin(opt.Page, 1)
opt.Size = util.LimitRange(opt.Size, 10, 200)
opt.Size = util.LimitRange(opt.Size, 10, 1000)
db = db.Offset((opt.Page - 1) * opt.Size).Limit(opt.Size)

@ -41,5 +41,14 @@ func RegisterGRPCService(dbModel *model.DBModel, logger *zap.Logger, endpoint st
return
}
// 附件API接口服务
attachmentAPIService := biz.NewAttachmentAPIService(dbModel, logger)
v1.RegisterAttachmentAPIServer(grpcServer, attachmentAPIService)
err = v1.RegisterAttachmentAPIHandlerFromEndpoint(context.Background(), gwmux, endpoint, dialOpts)
if err != nil {
logger.Error("RegisterAttachmentAPIHandlerFromEndpoint", zap.Error(err))
return
}
return
}

@ -66,3 +66,15 @@ func LimitRange(number int, min, max int) int {
}
return number
}
type Any interface {
~int | ~int64 | ~int32
}
// Slice2Interface 切片转interface切片
func Slice2Interface[T Any](slice []T) (values []interface{}) {
for _, item := range slice {
values = append(values, item)
}
return
}

@ -0,0 +1,35 @@
import service from '~/utils/request'
export const updateAttachment = (data) => {
return service({
url: '/api/v1/attachment',
method: 'put',
data,
})
}
export const deleteAttachment = (params) => {
return service({
url: '/api/v1/attachment',
method: 'delete',
params,
})
}
export const getAttachment = (params) => {
return service({
url: '/api/v1/attachment',
method: 'get',
params,
})
}
export const listAttachment = (params) => {
return service({
url: '/api/v1/attachment/list',
method: 'get',
params,
})
}

@ -1,10 +1,232 @@
<template>
<div>{{ $route.name }}</div>
<div>
<el-card shadow="never" class="search-card">
<FormSearch
:fields="searchFormFields"
:loading="loading"
:show-create="false"
:show-delete="true"
:disabled-delete="selectedRow.length === 0"
@onSearch="onSearch"
@onDelete="batchDelete"
/>
</el-card>
<el-card shadow="never" class="mgt-20px">
<TableList
:table-data="listData"
:fields="tableListFields"
:show-actions="true"
:show-view="false"
:show-edit="true"
:show-delete="true"
:show-select="true"
@selectRow="selectRow"
@editRow="editRow"
@deleteRow="deleteRow"
/>
</el-card>
<el-card shadow="never" class="mgt-20px">
<div class="text-right">
<el-pagination
background
:current-page="search.page"
:page-sizes="[10, 20, 50, 100, 200]"
:page-size="search.size"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
@size-change="handleSizeChange"
@current-change="handlePageChange"
>
</el-pagination>
</div>
</el-card>
<el-dialog
:title="friendlink.id ? '编辑附件' : '新增附件'"
:visible.sync="formVisible"
>
<FormFriendlink
ref="friendlinkForm"
:init-friendlink="friendlink"
@success="formFriendlinkSuccess"
/>
</el-dialog>
</div>
</template>
<script>
import { listAttachment, deleteAttachment } from '~/api/attachment'
import TableList from '~/components/TableList.vue'
import FormSearch from '~/components/FormSearch.vue'
import FormFriendlink from '~/components/FormFriendlink.vue'
import { attachmentTypeOptions } from '~/utils/enum'
export default {
components: { TableList, FormSearch, FormFriendlink },
layout: 'admin',
created() {},
data() {
return {
loading: false,
formVisible: false,
search: {
wd: '',
page: 1,
status: [],
size: 10,
},
listData: [],
total: 0,
searchFormFields: [],
tableListFields: [],
selectedRow: [],
friendlink: { id: 0 },
attachmentTypeOptions,
}
},
async created() {
this.initSearchForm()
this.initTableListFields()
await this.listAttachment()
},
methods: {
async listAttachment() {
this.loading = true
const res = await listAttachment(this.search)
if (res.status === 200) {
this.listData = res.data.attachment
this.total = res.data.total
} else {
this.$message.error(res.data.message)
}
this.loading = false
},
handleSizeChange(val) {
this.search.size = val
this.listAttachment()
},
handlePageChange(val) {
this.search.page = val
this.listAttachment()
},
onSearch(search) {
this.search = { ...this.search, page: 1, ...search }
this.listAttachment()
},
onCreate() {
this.friendlink = { id: 0 }
this.formVisible = true
this.$nextTick(() => {
this.$refs.friendlinkForm.reset()
})
},
editRow(row) {
this.formVisible = true
this.$nextTick(() => {
this.$refs.friendlinkForm.clearValidate()
this.friendlink = row
})
},
formFriendlinkSuccess() {
this.formVisible = false
this.listAttachment()
},
batchDelete() {
this.$confirm(
`您确定要删除选中的【${this.selectedRow.length}个】附件吗?删除之后不可恢复!`,
'温馨提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(async () => {
const ids = this.selectedRow.map((item) => item.id)
const res = await deleteAttachment({ id: ids })
if (res.status === 200) {
this.$message.success('删除成功')
this.listAttachment()
} else {
this.$message.error(res.data.message)
}
})
.catch(() => {})
},
deleteRow(row) {
this.$confirm(
`您确定要删除附件【${row.name}】吗?删除之后不可恢复!`,
'温馨提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(async () => {
const res = await deleteAttachment({ id: row.id })
if (res.status === 200) {
this.$message.success('删除成功')
this.listAttachment()
} else {
this.$message.error(res.data.message)
}
})
.catch(() => {})
},
selectRow(rows) {
this.selectedRow = rows
},
initSearchForm() {
this.searchFormFields = [
{
type: 'text',
label: '关键字',
name: 'wd',
placeholder: '请输入关键字',
},
{
type: 'select',
label: '附件类型',
name: 'type',
placeholder: '请选择附件类型',
multiple: true,
options: this.attachmentTypeOptions,
},
{
type: 'select',
label: '是否合法',
name: 'is_approved',
placeholder: '请选择是否合法',
multiple: true,
options: [
{ label: '是', value: 1 },
{ label: '否', value: 0 },
],
},
]
},
initTableListFields() {
this.tableListFields = [
{ prop: 'id', label: 'ID', width: 80, type: 'number', fixed: 'left' },
{ prop: 'type_name', label: '类型', width: 80, fixed: 'left' },
{ prop: 'name', label: '名称', minWidth: 150, fixed: 'left' },
{
prop: 'is_approved',
label: '是否合法',
width: 80,
type: 'bool',
},
{ prop: 'hash', label: 'HASH', width: 150 },
{ prop: 'username', label: '上传者', width: 120 },
{ prop: 'size', label: '大小', width: 80, type: 'number' },
{ prop: 'width', label: '宽', width: 80 },
{ prop: 'height', label: '高', width: 80 },
{ prop: 'ext', label: '扩展', width: 80 },
{ prop: 'ip', label: 'IP', width: 120 },
{ prop: 'created_at', label: '创建时间', width: 160, type: 'datetime' },
{ prop: 'updated_at', label: '更新时间', width: 160, type: 'datetime' },
]
},
},
}
</script>
<style></style>

@ -1,10 +1,223 @@
<template>
<div>{{ $route.name }}</div>
<div>
<el-card shadow="never" class="search-card">
<FormSearch
:fields="searchFormFields"
:loading="loading"
:show-create="true"
:show-delete="true"
:disabled-delete="selectedRow.length === 0"
@onSearch="onSearch"
@onCreate="onCreate"
@onDelete="batchDelete"
/>
</el-card>
<el-card shadow="never" class="mgt-20px">
<TableList
:table-data="friendlinks"
:fields="tableListFields"
:show-actions="true"
:show-view="false"
:show-edit="true"
:show-delete="true"
:show-select="true"
@selectRow="selectRow"
@editRow="editRow"
@deleteRow="deleteRow"
/>
</el-card>
<el-card shadow="never" class="mgt-20px">
<div class="text-right">
<el-pagination
background
:current-page="search.page"
:page-sizes="[10, 20, 50, 100, 200]"
:page-size="search.size"
layout="total, sizes, prev, pager, next, jumper"
:total="total"
@size-change="handleSizeChange"
@current-change="handlePageChange"
>
</el-pagination>
</div>
</el-card>
<el-dialog
:title="friendlink.id ? '编辑友链' : '新增友链'"
:visible.sync="formFriendlinkVisible"
>
<FormFriendlink
ref="friendlinkForm"
:init-friendlink="friendlink"
@success="formFriendlinkSuccess"
/>
</el-dialog>
</div>
</template>
<script>
import { listFriendlink, deleteFriendlink } from '~/api/friendlink'
import TableList from '~/components/TableList.vue'
import FormSearch from '~/components/FormSearch.vue'
import FormFriendlink from '~/components/FormFriendlink.vue'
export default {
components: { TableList, FormSearch, FormFriendlink },
layout: 'admin',
created() {},
data() {
return {
loading: false,
formFriendlinkVisible: false,
search: {
wd: '',
page: 1,
status: [],
size: 10,
},
friendlinks: [],
total: 0,
searchFormFields: [],
tableListFields: [],
selectedRow: [],
friendlink: { id: 0 },
}
},
async created() {
this.initSearchForm()
this.initTableListFields()
await this.listFriendlink()
},
methods: {
async listFriendlink() {
this.loading = true
const res = await listFriendlink(this.search)
if (res.status === 200) {
this.friendlinks = res.data.friendlink
this.total = res.data.total
} else {
this.$message.error(res.data.message)
}
this.loading = false
},
handleSizeChange(val) {
this.search.size = val
this.listFriendlink()
},
handlePageChange(val) {
this.search.page = val
this.listFriendlink()
},
onSearch(search) {
this.search = { ...this.search, page: 1, ...search }
this.listFriendlink()
},
onCreate() {
this.friendlink = { id: 0 }
this.formFriendlinkVisible = true
this.$nextTick(() => {
this.$refs.friendlinkForm.reset()
})
},
editRow(row) {
this.formFriendlinkVisible = true
this.$nextTick(() => {
this.$refs.friendlinkForm.clearValidate()
this.friendlink = row
})
},
formFriendlinkSuccess() {
this.formFriendlinkVisible = false
this.listFriendlink()
},
batchDelete() {
this.$confirm(
`您确定要删除选中的【${this.selectedRow.length}条】友链吗?删除之后不可恢复!`,
'温馨提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(async () => {
const ids = this.selectedRow.map((item) => item.id)
const res = await deleteFriendlink({ id: ids })
if (res.status === 200) {
this.$message.success('删除成功')
this.listFriendlink()
} else {
this.$message.error(res.data.message)
}
})
.catch(() => {})
},
deleteRow(row) {
this.$confirm(
`您确定要删除友链【${row.title}】吗?删除之后不可恢复!`,
'温馨提示',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
)
.then(async () => {
const res = await deleteFriendlink({ id: row.id })
if (res.status === 200) {
this.$message.success('删除成功')
this.listFriendlink()
} else {
this.$message.error(res.data.message)
}
})
.catch(() => {})
},
selectRow(rows) {
this.selectedRow = rows
},
initSearchForm() {
this.searchFormFields = [
{
type: 'text',
label: '关键字',
name: 'wd',
placeholder: '请输入关键字',
},
{
type: 'select',
label: '状态',
name: 'status',
placeholder: '请选择状态',
multiple: true,
options: [
{ label: '启用', value: 0 },
{ label: '禁用', value: 1 },
],
},
]
},
initTableListFields() {
this.tableListFields = [
{ prop: 'id', label: 'ID', width: 80, type: 'number', fixed: 'left' },
{
prop: 'status',
label: '状态',
width: 80,
type: 'enum',
enum: {
1: { label: '禁用', type: 'danger' },
0: { label: '启用', type: 'success' },
},
fixed: 'left',
},
{ prop: 'title', label: '名称', minWidth: 150, fixed: 'left' },
{ prop: 'link', label: '链接', minWidth: 250 },
{ prop: 'sort', label: '排序', width: 80, type: 'number' },
{ prop: 'description', label: '描述', minWidth: 250 },
{ prop: 'created_at', label: '创建时间', width: 160, type: 'datetime' },
{ prop: 'updated_at', label: '更新时间', width: 160, type: 'datetime' },
]
},
},
}
</script>
<style></style>

@ -5,3 +5,12 @@ export const userStatusOptions = [
{ label: '拒绝', value: 3 },
{ label: '忽略', value: 4 },
]
export const attachmentTypeOptions = [
{ label: '头像', value: 0 },
{ label: '文档', value: 1 },
{ label: '文章', value: 2 },
{ label: '评论', value: 3 },
{ label: '横幅', value: 4 },
{ label: '分类封面', value: 5 },
]

Loading…
Cancel
Save