112 lines
2.8 KiB
TypeScript
112 lines
2.8 KiB
TypeScript
import { Context, LarkServer } from "../../types"
|
|
|
|
/**
|
|
* 创建键值多维表格
|
|
* 实际上是从模版复制出来一个
|
|
* @param ctx - Context
|
|
*/
|
|
const create = async ({
|
|
larkService,
|
|
logger,
|
|
}: Context): Promise<LarkServer.BaseRes> => {
|
|
const copyRes = await larkService.drive.copyFile(
|
|
"D6ETfzaU9lN08adVDz3kjLey4Bx",
|
|
"bask4drDOy7zc3nDVyZb5RYDzOe",
|
|
"xxx 项目 KV管理",
|
|
"bitable"
|
|
)
|
|
if (copyRes.code !== 0) return copyRes
|
|
|
|
const fileToken = copyRes.data.file.token
|
|
|
|
const tableRes = await larkService.sheet.getTables(fileToken)
|
|
if (tableRes.code !== 0) return tableRes
|
|
|
|
const tableId = tableRes.data[0].table_id
|
|
|
|
const viewRes = await larkService.sheet.getViews(fileToken, tableId)
|
|
if (viewRes.code !== 0) return viewRes
|
|
const viewId = viewRes.data[0].view_id
|
|
|
|
const link = `https://xiaomi.f.mioffice.cn/base/${fileToken}?table=${tableId}&view=${viewId}`
|
|
|
|
const token = `${fileToken}|${tableId}|${viewId}`
|
|
|
|
logger.info(`create KV bitable successfully: ${{ link, token }}`)
|
|
|
|
return {
|
|
code: 0,
|
|
data: {
|
|
link,
|
|
token,
|
|
fileToken,
|
|
tableId,
|
|
viewId,
|
|
},
|
|
message: "success",
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 从事件创建键值多维表格
|
|
* @param ctx - Context
|
|
*/
|
|
const createFromEvent = async (ctx: Context) => {
|
|
const {
|
|
larkBody: { chatId, chatType, userId },
|
|
larkService,
|
|
larkCard,
|
|
logger,
|
|
} = ctx
|
|
if (!chatId) return
|
|
// 先发一条消息告诉用户正在创建
|
|
larkService.message.sendText2Chat(chatId, "正在为您创建多维表格,请稍等片刻~")
|
|
const cardGender = larkCard.child("sheetDB")
|
|
try {
|
|
const createRes = await create(ctx)
|
|
// 错误处理,发送错误消息
|
|
if (createRes.code !== 0) throw new Error(createRes.message)
|
|
|
|
// 创建成功,根据消息类型添加协作者
|
|
if (chatType === "p2p") {
|
|
const addRes = await larkService.drive.addCollaborator(
|
|
createRes.data.fileToken,
|
|
"bitable",
|
|
"userid",
|
|
userId!,
|
|
"full_access"
|
|
)
|
|
if (addRes.code !== 0) throw new Error(addRes.message)
|
|
}
|
|
// 为群组添加协作者
|
|
else {
|
|
const addRes = await larkService.drive.addCollaborator(
|
|
createRes.data.fileToken,
|
|
"bitable",
|
|
"openchat",
|
|
chatId,
|
|
"full_access"
|
|
)
|
|
if (addRes.code !== 0) throw new Error(addRes.message)
|
|
}
|
|
// 全部成功,发送成功消息
|
|
larkService.message.sendCard2Chat(
|
|
chatId,
|
|
cardGender.genTempCard("createKVSuccess", createRes.data) as string
|
|
)
|
|
} catch (e: any) {
|
|
logger.error(`create KV bitable failed: ${e.message}`)
|
|
larkService.message.sendCard2Chat(
|
|
chatId,
|
|
cardGender.genErrorCard(`创建失败:${e.message}`) as string
|
|
)
|
|
}
|
|
}
|
|
|
|
const createKVTemp = {
|
|
create,
|
|
createFromEvent,
|
|
}
|
|
|
|
export default createKVTemp
|