feat: 开发收藏和下载功能

This commit is contained in:
R524809
2026-05-06 18:32:15 +08:00
parent 9bdf850f20
commit c0b1bfddb0
17 changed files with 1262 additions and 127 deletions
+6
View File
@@ -1,4 +1,5 @@
import { defaultPrintConfig } from './config/config';
import { getUser } from './utils/auth';
import { generateUUID, getAppUUID, setAppUUID } from './utils/uuid';
const STORAGE_KEY_PAGE_CONFIG = 'pageConfig';
@@ -39,6 +40,11 @@ App<IAppOption>({
this.globalData.printConfig = printConfig;
}
// 静默登录(不阻塞页面渲染)
getUser().catch((err) => {
console.error('静默登录失败', err);
});
void this.loadPageConfig();
},
@@ -22,7 +22,7 @@ import {
} from '../shared/data/fontProfiles';
import { loadLetterFont } from '../shared/draw/drawTools';
import type { DebugPublishMeta } from '../../utils/debugPublish';
import { incrementWorksheetLikes } from '../../utils/worksheetStats';
import { addFavorite, removeFavorite, batchCheckFavorited } from '../../utils/favorites';
/** 三字母精练分组:26 字母每 3 个一组 */
const TRIPLE_GROUPS: { title: string; letters: string[] }[] = [];
@@ -82,6 +82,7 @@ createPage(
boxWidth: 0,
drawService: null as LetterTracingDraw | null,
fontProfile: DEFAULT_LETTER_PROFILE as FontProfile,
_favoritedMap: {} as Record<string, boolean>,
data: {
pageTitle: '字母描红',
@@ -147,6 +148,8 @@ createPage(
updates as Partial<PageData> & WechatMiniprogram.IAnyObject,
);
}
this.loadFavoritedMap();
},
/** 用户点击模式选择器时切换 worksheet */
@@ -275,8 +278,14 @@ createPage(
async onPreviewFavorite() {
const next = !this.data.isPreviewFavorite;
this.setData({ isPreviewFavorite: next });
if (next) {
incrementWorksheetLikes(this.data.worksheetId);
const id = this.data.worksheetId;
if (id) {
this._favoritedMap[id] = next;
if (next) {
addFavorite(id);
} else {
removeFavorite(id);
}
}
wx.showToast({
title: next ? '收藏成功' : '已取消收藏',
@@ -284,6 +293,15 @@ createPage(
});
},
async loadFavoritedMap() {
const ids = LETTER_TRACING_MODE_OPTIONS.map((d) => d.id);
this._favoritedMap = await batchCheckFavorited(ids);
const currentId = this.data.worksheetId;
if (this._favoritedMap[currentId]) {
this.setData({ isPreviewFavorite: true });
}
},
getPublishMeta(): DebugPublishMeta {
const meta = getPublishMetaByMode(this.data.worksheetId);
if (!meta) {
@@ -358,7 +376,7 @@ createPage(
worksheetId,
functionId: worksheetId,
traceMode,
isPreviewFavorite: false,
isPreviewFavorite: !!this._favoritedMap[worksheetId],
selectedLetter,
selectedLetterPair: `${selectedLetter}${selectedLetter.toLowerCase()}`,
letterCaseLower,
+35 -7
View File
@@ -6,9 +6,9 @@ import {
type FocusTypeConfig,
type FocusTypeAction,
} from './registry';
import { getPublishMetaByFocusState } from './focusDraw.config';
import { getPublishMetaByFocusState, FOCUS_WORKSHEET_DEFINITIONS } from './focusDraw.config';
import type { DebugPublishMeta } from '../../utils/debugPublish';
import { incrementWorksheetLikes } from '../../utils/worksheetStats';
import { addFavorite, removeFavorite, batchCheckFavorited } from '../../utils/favorites';
const TYPE_LIST = FOCUS_TYPE_CONFIGS.map((t) => ({
id: t.id,
@@ -24,6 +24,7 @@ createFocusPage({
drawService: null as BaseDrawService | null,
currentTypeConfig: null as FocusTypeConfig | null,
currentData: null as any,
_favoritedMap: {} as Record<string, boolean>,
data: {
pageTitle: '专注力练习',
@@ -73,6 +74,8 @@ createFocusPage({
});
this.initPageInfo(routeId, title);
this.loadFavoritedMap();
},
onCanvasReady(e: WechatMiniprogram.CustomEvent) {
@@ -121,7 +124,9 @@ createFocusPage({
selectedTypeId: id,
functionId: id,
pageTitle: title,
isPreviewFavorite: false,
isPreviewFavorite: !!this._favoritedMap[
getPublishMetaByFocusState(id, id, mode)?.id || id
],
showActions: !!typeConfig.actions,
currentActions: typeConfig.actions || [],
actionsTitle: typeConfig.actionsTitle || '选择模式',
@@ -158,7 +163,7 @@ createFocusPage({
this.setData({
currentMode: value,
pageTitle: title,
isPreviewFavorite: false,
isPreviewFavorite: !!this._favoritedMap[this.getWorksheetStatsIdFor(value)],
});
this.initPageInfo(this.data.functionId, title);
@@ -202,9 +207,14 @@ createFocusPage({
async onPreviewFavorite() {
const next = !this.data.isPreviewFavorite;
this.setData({ isPreviewFavorite: next });
if (next) {
const id = this.getWorksheetStatsId();
if (id) incrementWorksheetLikes(id);
const id = this.getWorksheetStatsId();
if (id) {
this._favoritedMap[id] = next;
if (next) {
addFavorite(id);
} else {
removeFavorite(id);
}
}
wx.showToast({
title: next ? '收藏成功' : '已取消收藏',
@@ -221,6 +231,24 @@ createFocusPage({
return meta?.id || this.data.functionId;
},
getWorksheetStatsIdFor(mode: string): string {
const meta = getPublishMetaByFocusState(
this.data.functionId,
this.data.selectedTypeId,
mode,
);
return meta?.id || this.data.functionId;
},
async loadFavoritedMap() {
const ids = FOCUS_WORKSHEET_DEFINITIONS.map((d) => d.id);
this._favoritedMap = await batchCheckFavorited(ids);
const currentId = this.getWorksheetStatsId();
if (this._favoritedMap[currentId]) {
this.setData({ isPreviewFavorite: true });
}
},
getPublishMeta(): DebugPublishMeta {
const meta = getPublishMetaByFocusState(
this.data.functionId,
+37 -7
View File
@@ -6,9 +6,9 @@ import {
type MathTypeConfig,
type MathTypeAction,
} from './registry';
import { getPublishMetaByMathState } from './mathDraw.config';
import { getPublishMetaByMathState, MATH_WORKSHEET_DEFINITIONS } from './mathDraw.config';
import type { DebugPublishMeta } from '../../utils/debugPublish';
import { incrementWorksheetLikes } from '../../utils/worksheetStats';
import { addFavorite, removeFavorite, batchCheckFavorited } from '../../utils/favorites';
const TYPE_LIST = MATH_TYPE_CONFIGS.map((t) => ({
id: t.id,
@@ -25,6 +25,7 @@ createMathPage({
currentTypeConfig: null as MathTypeConfig | null,
currentData: null as any,
routeExtra: null as Record<string, any> | null,
_favoritedMap: {} as Record<string, boolean>,
data: {
pageTitle: '数学练习',
@@ -82,6 +83,9 @@ createMathPage({
});
this.initPageInfo(routeId, title);
// 加载收藏状态
this.loadFavoritedMap();
},
onCanvasReady(e: WechatMiniprogram.CustomEvent) {
@@ -131,7 +135,9 @@ createMathPage({
selectedTypeId: id,
functionId: id,
pageTitle: title,
isPreviewFavorite: false,
isPreviewFavorite: !!this._favoritedMap[
getPublishMetaByMathState(id, id, mode)?.id || id
],
showActions: !!typeConfig.actions,
currentActions: typeConfig.actions || [],
actionsTitle: typeConfig.actionsTitle || '选择模式',
@@ -172,7 +178,7 @@ createMathPage({
this.setData({
currentMode: value,
pageTitle: title,
isPreviewFavorite: false,
isPreviewFavorite: !!this._favoritedMap[this.getWorksheetStatsIdFor(value)],
});
this.initPageInfo(this.data.functionId, title);
@@ -266,9 +272,14 @@ createMathPage({
async onPreviewFavorite() {
const next = !this.data.isPreviewFavorite;
this.setData({ isPreviewFavorite: next });
if (next) {
const id = this.getWorksheetStatsId();
if (id) incrementWorksheetLikes(id);
const id = this.getWorksheetStatsId();
if (id) {
this._favoritedMap[id] = next;
if (next) {
addFavorite(id);
} else {
removeFavorite(id);
}
}
wx.showToast({
title: next ? '收藏成功' : '已取消收藏',
@@ -285,6 +296,25 @@ createMathPage({
return meta?.id || this.data.functionId;
},
getWorksheetStatsIdFor(mode: string): string {
const meta = getPublishMetaByMathState(
this.data.functionId,
this.data.selectedTypeId,
mode,
);
return meta?.id || this.data.functionId;
},
async loadFavoritedMap() {
const ids = MATH_WORKSHEET_DEFINITIONS.map((d) => d.id);
this._favoritedMap = await batchCheckFavorited(ids);
// 回显当前选中的收藏状态
const currentId = this.getWorksheetStatsId();
if (this._favoritedMap[currentId]) {
this.setData({ isPreviewFavorite: true });
}
},
getPublishMeta(): DebugPublishMeta {
const meta = getPublishMetaByMathState(
this.data.functionId,
+133 -96
View File
@@ -1,27 +1,24 @@
import { NAV_INNER_PX } from '../../utils/navMetrics';
import { getFavoriteList, removeFavorite } from '../../utils/favorites';
import { getDownloadLogs } from '../../utils/downloadLogs';
import type { FavoriteRecord } from '../../utils/favorites';
import type { DownloadLogRecord } from '../../utils/downloadLogs';
const { statusBarHeight } = wx.getWindowInfo();
const NAV_BLOCK_HEIGHT = statusBarHeight + NAV_INNER_PX;
type FavoritesTab = 'favorites' | 'downloads';
type FavoriteItem =
| {
id: string;
variant: 'standard';
title: string;
metaLine: string;
stars: number;
timeBadge: string;
thumb: string;
}
| {
id: string;
variant: 'featured';
title: string;
metaLine: string;
tags: string[];
};
type FavoriteItem = {
id: string;
worksheetId: string;
variant: 'standard';
title: string;
metaLine: string;
stars: number;
timeBadge: string;
thumb: string;
};
type DownloadRow = {
id: string;
@@ -39,88 +36,94 @@ type DownloadSection = {
items: DownloadRow[];
};
const MOCK_FAVORITES: FavoriteItem[] = [
{
id: '1',
variant: 'standard',
title: '10以内加法',
metaLine: '数学启蒙 · 4-6岁 · ',
stars: 2,
timeBadge: '收藏于 3 天前',
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuD7khp0rJABfa9yFrMt9ZgIhAPyN44XmJ2pXNBgCzbgBvwA5ptFZVty013JedVzbE9_VvCQnToN7QETLDKjtiX22igzK-a5h4E8wjKrembFW4eVuk1RsJIbHjx3_cCz0hJ7_t76hF8t-Qdod_5R9sNMor1ZEjf6dGNp6UI_eIBjsN9b22iCTJ2VB-IEh0Rmil6_iC4Og-4I03IcQDV2rTHYIXcZxjiay1IiYGXw3wJ3bfo2SF2N7ZFT00akTgYU-9JyF7xJ6n15Yzc',
},
{
id: '2',
variant: 'standard',
title: '图形连连看',
metaLine: '逻辑思维 · 3-5岁 · ',
stars: 1,
timeBadge: '收藏于 5 天前',
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBY_0Rr153ZBT4IHcMyFtrcgl-y2ZRyVnOuGecnn7f4PZKoAx2lOuCorsMmfRa72s0JmbXrt4XT3QU1x7cIbZUyhv_EXwCfMaNxtkHc-ymIBIQ5jqm5oiQebrEWH4kjv14JdkCiziT4xzac4TdVN5yqpk7Wlg80QBl_ldDmAQqIgcUeN2PvlVvhmpOYmFeWE2HS3I_e4vV1J8s_cfV9_4g7y8SbxlSfnTmgQNeXrVbcdwaNEAGQWp92Iif0d2pVIqdfuUHO1pTw8oQ',
},
{
id: '3',
variant: 'standard',
title: '拼音字母认读',
metaLine: '语文基础 · 5-7岁 · ',
stars: 3,
timeBadge: '收藏于 1 周前',
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuC54mXQ8620XwIsWmUHBHJGdmpF8uE4cSYxwR2NLJTsa6gYdTCHz2tqrKbGOye-y0CGgCPPWwJXzEuB2ZYrQ3CWWPlamvbjhTUDYf8yoA9Lyapll1t2w17AqzSHrbBPNFrq931IUCis64b51kslQZoq3c0KslZsBQiky-YSnuE7xUuNsgiF4hOak_ReFFufWE53h1sPkjHFeRM-H34b-e1MCNxGObGPhI0mNlJ_qz0c8aCuS-jdnDocSvIYda-iVcJLWcIT-mO6klw',
},
{
id: '4',
variant: 'featured',
title: '趣味英语单词卡',
metaLine: '语言学习 · 4-8岁 · ⭐⭐⭐',
tags: ['畅销经典', '全彩打印'],
},
];
function mapFavoriteToItem(record: FavoriteRecord): FavoriteItem {
const ws = record.worksheet;
const title = ws?.title || '未知题型';
const category = ws?.category || '';
const ageRange = ws ? `${ws.ageMin}-${ws.ageMax}` : '';
const metaLine = [category, ageRange].filter(Boolean).join(' · ') + ' · ';
const difficulty = ws?.difficulty || 0;
const timeBadge = formatTimeBadge(record.createdAt);
const MOCK_DOWNLOADS: DownloadSection[] = [
{
key: 'today',
label: '今天',
items: [
{
id: 'd1',
title: '拼音描红 · 声母表',
time: '14:32',
status: '已保存相册',
statusHighlight: true,
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBCm6X4rhibw2_WxP-U0dDyOsiYol3y12OnEXHRkPONZYMQBUcr3Grqo1IbwH3sdWPg5jIUeIbr_AEwv_hFwUOMMz9jTIIMc6Pke1bzSvlQcgdDq-zMEIU4A--IQFX59ac-8BscCajXZcd4v8rE6JEZFf1-aztKclPTkE_Rrgj-nbVCy5V6bOE6yDOB67VdTbcqiOdaFN18ju_MgWVo3FQZLwIUZOBahkPl0vDIKA0mkiaGK9eiFpfnERYxkYG3eWJZ40umTYp46Jo',
},
{
id: 'd2',
title: '趣味口算题卡',
time: '09:15',
status: '已下载 PDF',
statusHighlight: false,
thumb: 'https://lh3.googleusercontent.com/aida-public/AB6AXuBxNORxN_vftYMLaMjZVscL-o9bZnBrfUi7IAqOrFATIztGV12_0ggwgae-fmk0cORWtysZWJJDcAzj0NEyniFxbREoGDuq9U4kytprJkA70_k0MCzPgStmq0bRwu1Gx1j4peglFam8PH6IlPvOMbiHQ7-fMFfYTSBtA1p7Dp06NDOzS2VrMlF8VxjEgihVmhHUrHePVvXlktUkXBKNzrXEXrogO3iOyouTUKyvJh0TeChKUv3KohMoD5ol7C3fjBhdHf7QD4StOQ4',
},
],
},
{
key: 'yesterday',
label: '昨天',
items: [
{
id: 'd3',
title: '汉字笔画基础训练',
time: '16:40',
status: '已发送邮件',
statusHighlight: false,
placeholder: 'draw',
},
],
},
];
return {
id: record._id,
worksheetId: record.worksheetId,
variant: 'standard',
title,
metaLine,
stars: Math.min(difficulty, 3),
timeBadge,
thumb: ws?.previewImg || '',
};
}
function formatTimeBadge(dateStr: string): string {
const date = new Date(dateStr);
const now = new Date();
const diff = now.getTime() - date.getTime();
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days === 0) return '收藏于今天';
if (days === 1) return '收藏于昨天';
if (days < 7) return `收藏于 ${days} 天前`;
if (days < 30) return `收藏于 ${Math.floor(days / 7)} 周前`;
return `收藏于 ${Math.floor(days / 30)} 个月前`;
}
function groupDownloadsByDate(records: DownloadLogRecord[]): DownloadSection[] {
const now = new Date();
const todayStr = formatDateKey(now);
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const yesterdayStr = formatDateKey(yesterday);
const groups: Record<string, { label: string; items: DownloadRow[] }> = {};
for (const record of records) {
const date = new Date(record.createdAt);
const key = formatDateKey(date);
let label: string;
if (key === todayStr) {
label = '今天';
} else if (key === yesterdayStr) {
label = '昨天';
} else {
label = `${date.getMonth() + 1}${date.getDate()}`;
}
if (!groups[key]) {
groups[key] = { label, items: [] };
}
const ws = record.worksheet;
groups[key].items.push({
id: record._id,
title: ws?.title || '未知题型',
time: `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`,
status: '已保存相册',
statusHighlight: true,
thumb: ws?.previewImg,
});
}
return Object.keys(groups).map((key) => ({
key,
label: groups[key].label,
items: groups[key].items,
}));
}
function formatDateKey(date: Date): string {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
Page({
data: {
favScrollHeight: 0,
activeTab: 'favorites' as FavoritesTab,
favoriteList: MOCK_FAVORITES as FavoriteItem[],
downloadSections: MOCK_DOWNLOADS as DownloadSection[],
favoriteList: [] as FavoriteItem[],
downloadSections: [] as DownloadSection[],
loading: false,
},
onLoad() {
@@ -136,6 +139,7 @@ Page({
this.setData({ activeTab: tab });
wx.removeStorageSync('favorites_active_tab');
}
this.loadData();
},
onTabSwitch(e: WechatMiniprogram.TouchEvent) {
@@ -144,6 +148,24 @@ Page({
this.setData({ activeTab: tab });
},
async loadData() {
this.setData({ loading: true });
await Promise.all([this.loadFavorites(), this.loadDownloads()]);
this.setData({ loading: false });
},
async loadFavorites() {
const records = await getFavoriteList();
const list = records.map((r) => mapFavoriteToItem(r));
this.setData({ favoriteList: list });
},
async loadDownloads() {
const records = await getDownloadLogs();
const sections = groupDownloadsByDate(records);
this.setData({ downloadSections: sections });
},
onDiscoverTap() {
wx.switchTab({ url: '/pages/home/home' });
},
@@ -152,12 +174,24 @@ Page({
wx.showToast({ title: '搜索功能开发中', icon: 'none' });
},
onRemoveFavorite(e: WechatMiniprogram.TouchEvent) {
async onRemoveFavorite(e: WechatMiniprogram.TouchEvent) {
const id = e.currentTarget.dataset.id as string | undefined;
if (!id) return;
const list = (this.data.favoriteList as FavoriteItem[]).filter((item) => item.id !== id);
const item = (this.data.favoriteList as FavoriteItem[]).find(
(i) => i.id === id,
);
if (!item) return;
// 乐观更新 UI
const list = (this.data.favoriteList as FavoriteItem[]).filter(
(i) => i.id !== id,
);
this.setData({ favoriteList: list });
wx.showToast({ title: '已取消收藏', icon: 'none' });
// 调用云端
await removeFavorite(item.worksheetId);
},
onClearHistory() {
@@ -174,6 +208,9 @@ Page({
onDownloadMore(e: WechatMiniprogram.TouchEvent) {
const id = e.currentTarget.dataset.id as string | undefined;
wx.showToast({ title: id ? `更多操作:${id}` : '更多', icon: 'none' });
wx.showToast({
title: id ? `更多操作:${id}` : '更多',
icon: 'none',
});
},
});
+111
View File
@@ -0,0 +1,111 @@
interface UserInfo {
_id: string;
openid: string;
unionid: string | null;
nickName: string | null;
avatarUrl: string | null;
totalDownloads: number;
createdAt: string;
lastActiveAt: string;
}
const STORAGE_KEY = 'user_info';
const STORAGE_EXPIRE_KEY = 'user_info_expire';
const EXPIRE_DURATION = 7 * 24 * 60 * 60 * 1000; // 7 天
/** 内存中的用户数据(App 生命周期内有效) */
let currentUser: UserInfo | null = null;
/** 登录进行中的 Promise(防止并发重复调用) */
let loginPromise: Promise<UserInfo> | null = null;
/**
* 获取当前用户,优先内存 → Storage → 云函数登录
*/
export async function getUser(): Promise<UserInfo> {
// 1. 内存中有,直接返回
if (currentUser) return currentUser;
// 2. 尝试从 Storage 读取
const cached = loadFromStorage();
if (cached) {
currentUser = cached;
return cached;
}
// 3. 静默登录(防止并发)
if (!loginPromise) {
loginPromise = silentLogin().finally(() => {
loginPromise = null;
});
}
return loginPromise;
}
/**
* 静默登录:调用云函数
*/
async function silentLogin(): Promise<UserInfo> {
const res = await wx.cloud.callFunction({
name: 'userLogin',
});
const result = (res?.result as any) || {};
if (result.code !== 0) {
throw new Error('登录失败');
}
const user = result.data as UserInfo;
currentUser = user;
saveToStorage(user);
return user;
}
/**
* 从 Storage 读取用户数据(检查过期)
*/
function loadFromStorage(): UserInfo | null {
try {
const expire = wx.getStorageSync(STORAGE_EXPIRE_KEY);
if (!expire || Date.now() > expire) {
wx.removeStorageSync(STORAGE_KEY);
wx.removeStorageSync(STORAGE_EXPIRE_KEY);
return null;
}
const user = wx.getStorageSync(STORAGE_KEY);
return user || null;
} catch {
return null;
}
}
/**
* 写入 Storage
*/
function saveToStorage(user: UserInfo): void {
try {
wx.setStorageSync(STORAGE_KEY, user);
wx.setStorageSync(STORAGE_EXPIRE_KEY, Date.now() + EXPIRE_DURATION);
} catch {
// Storage 写入失败不影响主流程
}
}
/**
* 清除登录状态
*/
export function clearUser(): void {
currentUser = null;
wx.removeStorageSync(STORAGE_KEY);
wx.removeStorageSync(STORAGE_EXPIRE_KEY);
}
/**
* 强制刷新用户数据(跳过缓存)
*/
export async function refreshUser(): Promise<UserInfo> {
clearUser();
return await silentLogin();
}
export type { UserInfo };
+56
View File
@@ -0,0 +1,56 @@
import { getUser } from './auth';
export interface DownloadLogRecord {
_id: string;
userId: string;
worksheetId: string;
createdAt: string;
worksheet?: {
_id: string;
title: string;
subtitle: string;
category: string;
subcategory: string;
previewImg: string;
} | null;
}
/**
* 记录下载日志
*/
export async function addDownloadLog(worksheetId: string): Promise<boolean> {
if (!worksheetId) return false;
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userDownloadLogs',
data: { action: 'add', worksheetId },
});
const result = (res?.result as any) || {};
return result.code === 0;
} catch (e) {
console.error('addDownloadLog failed', e);
return false;
}
}
/**
* 获取下载历史
*/
export async function getDownloadLogs(
page = 1,
pageSize = 20,
): Promise<DownloadLogRecord[]> {
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userDownloadLogs',
data: { action: 'list', page, pageSize },
});
const result = (res?.result as any) || {};
return result.code === 0 ? result.data : [];
} catch (e) {
console.error('getDownloadLogs failed', e);
return [];
}
}
+2 -2
View File
@@ -5,7 +5,7 @@
import { checkAndSaveImage } from './saveImage';
import tracker from './tracker';
import { incrementWorksheetDownloads } from './worksheetStats';
import { addDownloadLog } from './downloadLogs';
// 存储键名
const STORAGE_KEY_DOWNLOAD_COUNT = 'downloadCount';
@@ -212,7 +212,7 @@ function doDownload(
if (saved) {
incrementDownloadCount();
if (options.worksheetId) {
incrementWorksheetDownloads(options.worksheetId);
addDownloadLog(options.worksheetId);
}
}
return saved;
+116
View File
@@ -0,0 +1,116 @@
import { getUser } from './auth';
export interface FavoriteRecord {
_id: string;
userId: string;
worksheetId: string;
createdAt: string;
worksheet?: {
_id: string;
title: string;
subtitle: string;
category: string;
subcategory: string;
ageMin: number;
ageMax: number;
difficulty: number;
previewImg: string;
tags: string[];
} | null;
}
/**
* 添加收藏
*/
export async function addFavorite(worksheetId: string): Promise<boolean> {
try {
await getUser(); // 确保已登录
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'add', worksheetId },
});
const result = (res?.result as any) || {};
return result.code === 0;
} catch (e) {
console.error('addFavorite failed', e);
return false;
}
}
/**
* 取消收藏
*/
export async function removeFavorite(worksheetId: string): Promise<boolean> {
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'remove', worksheetId },
});
const result = (res?.result as any) || {};
return result.code === 0;
} catch (e) {
console.error('removeFavorite failed', e);
return false;
}
}
/**
* 获取收藏列表
*/
export async function getFavoriteList(
page = 1,
pageSize = 20,
): Promise<FavoriteRecord[]> {
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'list', page, pageSize },
});
const result = (res?.result as any) || {};
return result.code === 0 ? result.data : [];
} catch (e) {
console.error('getFavoriteList failed', e);
return [];
}
}
/**
* 检查是否已收藏
*/
export async function checkFavorited(worksheetId: string): Promise<boolean> {
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'check', worksheetId },
});
const result = (res?.result as any) || {};
return result.code === 0 && result.data?.favorited;
} catch (e) {
console.error('checkFavorited failed', e);
return false;
}
}
/**
* 批量检查是否已收藏,返回 { worksheetId: true } 的 map
*/
export async function batchCheckFavorited(
worksheetIds: string[],
): Promise<Record<string, boolean>> {
if (!worksheetIds.length) return {};
try {
await getUser();
const res = await wx.cloud.callFunction({
name: 'userFavorites',
data: { action: 'batchCheck', worksheetIds },
});
const result = (res?.result as any) || {};
return result.code === 0 ? result.data : {};
} catch (e) {
console.error('batchCheckFavorited failed', e);
return {};
}
}