feat: 首页改成记录时间轴,计划可自己管,花销独立成页

## 首页
原来是任务卡 + 日期带/日历 + 接下来 + AI建议 + 快速记录 + 新手内容的堆叠,
六张聚合卡,唯独看不到「我记了什么」。改成:

  宠物名片(品种·年龄·星座 + 性别徽章叠头像 + 一起生活的第 N 天)
  两个入口(管理计划 / 记花销)
  今日任务(有才显示)
  记录时间轴 —— 竖线 + 圆点 + 卡片,往下翻,长按删

日历挪回计划页了:它本来就属于那儿。Phase B 当时把它并进首页是因为计划还是
个 tab;现在计划是二级页,日历跟着回去更合理。

情绪点那几样字段后端早就返回了,只是没人用。抽了 utils/petmeta.js:
星座七个边界(含 12/22 跨年那个)+ 天数(到家日优先于建档日,
「一起生活」说的是它到你家之后的日子)+ 性别徽章,都在 node 里跑过。

顺带 stat-ring 组件和 homeSummary 接口现在没人用了,先留着没删。

## 两个入口取代竞品那一排
竞品是买商品/上豪车/记花销/领猫砂盆——除了记花销全是电商和广告位。
副标题给了真信息:「还有 5 件没做」「本月 ¥128」,不然就是两个没信息量的图标。

## 计划页:用户自己能管了
后端原来只有 toggle,节点全靠内置模板生成,用户加不了自己的事。补了

  POST   /api/pets/:id/plan-tasks
  PUT    /api/plan-tasks/:id
  DELETE /api/plan-tasks/:id

三件事值得说:

**30 天边界硬拦在服务端**(dayOffset)。只在前端拦的话,改个请求就能塞一条
第 200 天的节点,日历上没有那格、它就永远不显示也删不掉。

**归属校验单独抽了 ownedPlanTask**。PUT/DELETE /plan-tasks/:id 这种按资源 id
的路由最容易漏——不校验的话拿到别人的 task id 就能改删别人的计划。验过:
别人的 token 改和删都返回「无权操作」。

**边界差一天,是验证时撞出来的**:内置模板生成到 day=30(第 31 天),
我一开始按 0-29 卡,结果模板自己的最后一个节点(生成月度报告)落在窗口外——
日历上没有那一格,用户看得到却改不动也删不掉。前后端都改成 [0,30],
两边各留了一句注释指向对方,别再单方面改。

日历只画计划覆盖的 31 天,不画整月:整月会多出一堆空白格子、跨月还要翻页。

## 花销独立成页
写的是同一张表(type='cost',金额进 num_value、类别进 category),
报告页的账单聚合照样认——独立页的价值在专门的录入体验和当页就有月度汇总,
不是另存一份数据。

类别预置读 record_types 里 cost 的字段配置,后台改一处这页和 addrecord
同时生效,不会出现两套类别把账单切开。另外允许自定义类别,验过「寄养」
(不在预置里)能落库、账单也认。

## 检查器又抓到一次跨页借用
我在计划页复用了花销页的 ex-ph(placeholder 类),检查器直接报了位置。
顺手把三个页面的私有 placeholder 类统一到 app.wxss 已有的 .placeholder。
cal-* 现在首页没有了、计划页在用,也提到了 app.wxss。

## 验证(预生产库实跑)
  计划 CRUD    加/改/删 全过;空标题拒;越权改删拒
  30 天边界     day=30 通过、day=31 拒、day=-1 拒
  模板 day=30   现在能原地改了(修边界前会被自己的规则拒掉)
  首页时间轴    8 条记录按 occurred_at 倒序,type/tone/图标都取到
  两个入口副标题 「还有 5 件没做」「本月 ¥128」
  花销自定义类别 「寄养」落库,账单分类变成 [(医疗,128),(寄养,60)]
  petmeta      星座 7 个边界 + 天数 3 种情况,node 单测全过

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Blizzard
2026-07-30 10:43:08 +08:00
parent 3ea50efb7d
commit 15b52eebd0
20 changed files with 998 additions and 428 deletions
+103 -229
View File
@@ -3,104 +3,47 @@ const api = require('../../utils/api.js');
const { toastErr } = require('../../utils/ui.js');
const { syncTabBar } = require('../../utils/tabbar.js');
const recordTypes = require('../../utils/recordTypes.js');
function todayStr() {
const d = new Date();
const p = (n) => (n < 10 ? '0' + n : '' + n);
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate());
}
function pad2(n) {
return n < 10 ? '0' + n : '' + n;
}
// 整月网格。周一为一周起点,前面补空格子对齐星期。
// 与计划页原来的实现同源——计划页的日历 tab 已并到这里,那边删掉了
function buildCells(year, month, taskedDays, today) {
const first = new Date(year, month - 1, 1);
const lead = (first.getDay() + 6) % 7;
const daysInMonth = new Date(year, month, 0).getDate();
const set = {};
(taskedDays || []).forEach((d) => (set[d] = true));
const cells = [];
for (let i = 0; i < lead; i++) cells.push({ day: 0 });
for (let d = 1; d <= daysInMonth; d++) {
cells.push({ day: d, date: year + '-' + pad2(month) + '-' + pad2(d), tasked: !!set[d], today: d === today });
}
return cells;
}
// 「接下来」用的相对日期,比 7月31日 更好读
function whenLabel(date, today) {
if (!date) return '';
const diff = Math.round((new Date(date + 'T00:00:00') - new Date(today + 'T00:00:00')) / 86400000);
if (diff <= 0) return '今天';
if (diff === 1) return '明天';
if (diff === 2) return '后天';
if (diff < 7) return diff + ' 天后';
const p = date.split('-');
return +p[1] + '月' + +p[2] + '日';
}
const petmeta = require('../../utils/petmeta.js');
function mapTask(t) {
return {
id: t.id,
title: t.title,
sub: t.description,
priority: t.priority,
done: t.done,
sheet: t.sheet_type,
};
return { id: t.id, title: t.title, sub: t.description, priority: t.priority, done: t.done, sheet: t.sheet_type };
}
// 快速记录入口取后端类型表的前 8 个(按分组顺序再按 sort)。
// 原来这里是 8 项写死的,后台加一种类型首页看不到;现在调 sort 就能换首屏露出哪几个。
// 首页只放 8 个是版式限制(4 列 2 行),全部 24 种在记录页
function quickFrom(groups) {
const flat = [];
(groups || []).forEach((g) => g.items.forEach((t) => flat.push(t)));
return flat.slice(0, 8);
// 时间轴上的相对时间。首页关心的是「什么时候记的」,精确到分只在今天有意义
function fmtWhen(iso) {
if (!iso) return '';
const d = new Date(iso);
if (isNaN(d.getTime())) return '';
const p = (n) => (n < 10 ? '0' + n : '' + n);
const now = new Date();
const sameDay = d.toDateString() === now.toDateString();
if (sameDay) return '今天 ' + p(d.getHours()) + ':' + p(d.getMinutes());
const y = new Date(now.getTime() - 86400000);
if (d.toDateString() === y.toDateString()) return '昨天 ' + p(d.getHours()) + ':' + p(d.getMinutes());
return d.getMonth() + 1 + '月' + d.getDate() + '日';
}
// 门面上的状态 chip:健康状态 + 最多两条洞察
function heroChips(summary) {
const chips = [];
if (summary.health_status) {
chips.push({ text: summary.health_status, icon: 'check', tone: 'green' });
}
(summary.insights || []).slice(0, 2).forEach((it) => {
if (it && it.bold) chips.push({ text: it.bold, icon: 'trend', tone: '' });
});
return chips;
}
const TL_PAGE = 10;
Page({
data: {
pet: {},
summary: { greeting: '', insights: [], week: [], advice: '', health_pct: 0, health_status: '正常' },
zodiac: '',
daysTogether: 0,
sexIcon: '',
sexTone: '',
tasks: [],
quickItems: [],
heroChips: [],
undoneText: '',
firstArticle: null,
selectedDate: '',
taskLabel: '今日任务',
todayDate: '',
calOpen: false,
calCells: [],
calLabel: '',
dayNodes: [],
dayReminders: [],
upcoming: [],
planPct: -1,
planUndone: 0,
monthCost: 0,
timeline: [],
tlPage: 1,
hasMore: false,
sheetShow: false,
sheetType: '',
},
onLoad() {
this.setData({ todayDate: todayStr() });
this._unsub = store.subscribe((pet) => {
this.setData({ pet });
// 首次由 onShow 统一加载,这里只处理之后的「切换宠物 / 数据变更」,避免重复请求
this.applyPet(pet);
if (!this._inited) return;
this.loadAll();
});
@@ -110,143 +53,103 @@ Page({
},
onShow() {
syncTabBar(this);
this.loadTypes();
recordTypes.load().catch(() => {});
store
.ready()
.then(() => {
this._inited = true;
this.setData({ pet: store.getPet() });
this.applyPet(store.getPet());
this.loadAll();
})
.catch((e) => wx.showToast({ title: e.message || '加载失败', icon: 'none' }));
},
loadTypes() {
if (this.data.quickItems.length) return;
recordTypes
.load()
.then((groups) => this.setData({ quickItems: quickFrom(groups) }))
.catch(() => {});
// 门面上那几样都是本地算的,不用等接口
applyPet(pet) {
const p = pet || {};
const badge = petmeta.genderBadge(p.gender);
this.setData({
pet: p,
zodiac: petmeta.zodiac(p.birthday),
daysTogether: petmeta.daysTogether(p),
sexIcon: badge.icon,
sexTone: badge.tone,
});
},
loadAll() {
this.loadSummary();
this.loadTasks();
this.loadDayExtra();
this.loadUpcoming();
// 日历只在展开过之后才跟着刷新,没展开就别白拉一次
if (this.data.calOpen) this.loadCalendar();
if (!this.data.firstArticle) {
api
.listArticles()
.then((list) => {
if (list && list[0]) {
this.setData({ firstArticle: { id: list[0].id, icon: list[0].icon, title: list[0].title, desc: list[0].description } });
}
})
.catch(() => {});
}
},
loadSummary() {
const id = store.currentPetId();
if (!id) return;
api
.homeSummary(id)
.then((summary) => this.setData({ summary, heroChips: heroChips(summary) }))
.catch((e) => toastErr(e));
this.loadTimeline(1);
this.loadEntries();
},
loadTasks() {
const id = store.currentPetId();
if (!id) return;
const date = this.data.selectedDate || this.data.todayDate;
api
.getTasks(id, date)
.then((tasks) => this.setTasks((tasks || []).map(mapTask)))
.getTasks(id)
.then((tasks) => this.setData({ tasks: (tasks || []).map(mapTask) }))
.catch((e) => toastErr(e));
},
// 任务列表落地时顺手算「还有几件事没做完」,门面上要用
setTasks(tasks) {
const undone = tasks.filter((t) => !t.done).length;
this.setData({
tasks,
undoneText: tasks.length === 0
? '这天还没有安排'
: undone > 0 ? '还有 ' + undone + ' 件事没做完' : '今天的事都做完啦',
});
},
// 这天挂着的计划节点和到期提醒。任务列表仍走 /tasks(那边会补生成当天任务),
// day-plan 只取 tasks 之外的两类,不拿它的 tasks 覆盖列表
loadDayExtra() {
// 两个入口上的副标题:计划还剩几件、本月花了多少。
// 空着的话入口就是两个没有信息量的图标
loadEntries() {
const id = store.currentPetId();
if (!id) return;
const date = this.data.selectedDate || this.data.todayDate;
api
.dayPlan(id, date)
.then((res) => {
this.setData({
dayNodes: (res.plan_nodes || []).map((n) => ({ title: n.title, done: n.done })),
dayReminders: (res.reminders || []).map((r) => ({ title: r.title })),
});
})
.catch(() => this.setData({ dayNodes: [], dayReminders: [] }));
},
// 30 天计划里最近 3 个还没做的节点
loadUpcoming() {
const id = store.currentPetId();
if (!id) return;
const today = this.data.todayDate;
api
.getPlan(id)
.then((plan) => {
const list = ((plan && plan.tasks) || [])
.filter((t) => !t.done && t.date && t.date >= today)
.sort((a, b) => (a.date < b.date ? -1 : 1))
.slice(0, 3)
.map((t) => ({ id: t.id, title: t.title, description: t.description, whenLabel: whenLabel(t.date, today) }));
this.setData({ upcoming: list, planPct: plan ? plan.completion_pct || 0 : -1 });
})
.catch(() => this.setData({ upcoming: [], planPct: -1 }));
.then((plan) => this.setData({ planUndone: ((plan && plan.tasks) || []).filter((t) => !t.done).length }))
.catch(() => this.setData({ planUndone: 0 }));
api
.getBill(id, 'month')
.then((b) => this.setData({ monthCost: (b && b.total) || 0 }))
.catch(() => this.setData({ monthCost: 0 }));
},
loadCalendar() {
loadTimeline(page) {
const id = store.currentPetId();
if (!id) return;
api
.planCalendar(id)
.getRecords(id, { page, pageSize: TL_PAGE })
.then((res) => {
this.setData({
calCells: buildCells(res.year, res.month, res.tasked_days, res.today),
calLabel: `${res.year}${res.month}`,
});
const list = (res.list || []).map((r) => ({
id: r.id,
type: r.type,
tone: (recordTypes.get(r.type) || {}).tone || 'tone-1',
title: r.title,
description: r.description,
image: r.image_url || '',
timeText: fmtWhen(r.occurred_at),
}));
const merged = page === 1 ? list : this.data.timeline.concat(list);
this.setData({ timeline: merged, tlPage: page, hasMore: merged.length < (res.total || 0) });
})
.catch(() => {});
},
toggleCal() {
const open = !this.data.calOpen;
this.setData({ calOpen: open });
if (open && !this.data.calCells.length) this.loadCalendar();
loadMore() {
if (this.data.hasMore) this.loadTimeline(this.data.tlPage + 1);
},
onTapDay(e) {
const { date, active } = e.currentTarget.dataset;
if (!date) return;
const parts = date.split('-');
this.setData({
selectedDate: date,
taskLabel: active ? '今日任务' : +parts[1] + '月' + +parts[2] + '日',
previewImage(e) {
const url = e.currentTarget.dataset.url;
if (url) wx.previewImage({ urls: [url], current: url });
},
onDeleteRecord(e) {
const id = e.currentTarget.dataset.id;
wx.showModal({
title: '删掉这条记录?',
content: '趋势和统计会跟着变。',
confirmColor: '#EE7D73',
success: (r) => {
if (!r.confirm) return;
api
.deleteRecord(id)
.then(() => this.loadTimeline(1))
.catch((err) => toastErr(err, '删除失败'));
},
});
this.loadTasks();
this.loadDayExtra();
},
backToToday() {
this.setData({ selectedDate: this.data.todayDate, taskLabel: '今日任务' });
this.loadTasks();
this.loadDayExtra();
},
goPlan() {
wx.navigateTo({ url: '/pages/plan/plan' });
},
onTapTask(e) {
const i = e.currentTarget.dataset.index;
const t = this.data.tasks[i];
// 任务关联了记录类型就直接去记那一笔
if (t.sheet) {
this.openSheetType(t.sheet);
wx.navigateTo({ url: '/pages/addrecord/addrecord?type=' + t.sheet });
return;
}
api
@@ -254,74 +157,45 @@ Page({
.then((res) => {
const tasks = this.data.tasks.slice();
tasks[i] = Object.assign({}, tasks[i], { done: res.done });
this.setTasks(tasks);
this.loadSummary();
this.setData({ tasks });
})
.catch((e) => toastErr(e, '操作失败'));
.catch((err) => toastErr(err, '操作失败'));
},
completeTasks() {
const id = store.currentPetId();
if (!id) return;
api
.completeAllTasks(id)
.then((tasks) => {
this.setTasks((tasks || []).map(mapTask));
this.loadSummary();
})
.then((tasks) => this.setData({ tasks: (tasks || []).map(mapTask) }))
.catch((e) => toastErr(e, '操作失败'));
},
// 记一笔的每一项都进独立页面。原来是开弹层——24 项的表单塞弹层里太挤,
// 而且弹层高度受 sheet-scroll 的 78vh 限制,字段一多就变成内滚
goAdd(e) {
wx.navigateTo({ url: '/pages/addrecord/addrecord?type=' + e.currentTarget.dataset.type });
goPlan() {
wx.navigateTo({ url: '/pages/plan/plan' });
},
goExpense() {
wx.navigateTo({ url: '/pages/expense/expense' });
},
goRecord() {
wx.navigateTo({ url: '/pages/record/record' });
},
onQuickRecord() {
wx.navigateTo({ url: '/pages/record/record' });
},
openSheet(e) {
this.openSheetType(e.currentTarget.dataset.type);
},
openSheetType(type) {
this.setData({ sheetType: type, sheetShow: true });
this.setData({ sheetType: e.currentTarget.dataset.type, sheetShow: true });
},
closeSheet() {
// 只关闭。数据变更由 bind:saved 或 store 的宠物变更通知触发刷新,
// 不必每次关弹层(哪怕只是看了眼 AI)都全量重拉一遍
this.setData({ sheetShow: false });
},
onSheetSave() {
this.loadTasks();
this.loadSummary();
this.loadDayExtra();
if (this.data.calOpen) this.loadCalendar(); // 加了任务,格子上的圆点要跟着变
this.loadTimeline(1);
},
onAddPet() {
this.openSheetType('addPet');
this.setData({ sheetType: 'addPet', sheetShow: true });
},
// 没建档时点门面卡应该去「添加」,而不是打开一个空的编辑表单
onHeroTap() {
if (this.data.pet && this.data.pet.id) this.openSheetType('editPet');
else this.openSheetType('addPet');
},
onEditPet() {
this.openSheetType('editPet');
},
// 右下角悬浮键:进记录页。原来做成弹层里的选择器,弹层装 24 项太挤了;
// 记录页顶部本来就是那个宫格,再单独建一个只放宫格的页面等于维护两份
onQuickRecord() {
wx.navigateTo({ url: '/pages/record/record' });
},
goSettings() {
wx.navigateTo({ url: '/pages/settings/settings' });
},
goLearn() {
wx.navigateTo({ url: '/pages/learn/learn' });
},
// 首页那张卡片直接打开这篇文章正文
openFirstArticle() {
const a = this.data.firstArticle;
if (a && a.id) wx.navigateTo({ url: `/pages/article/article?id=${a.id}` });
else this.goLearn();
},
goRecord() {
wx.navigateTo({ url: '/pages/record/record' });
this.setData({ sheetType: this.data.pet && this.data.pet.id ? 'editPet' : 'addPet', sheetShow: true });
},
onShareAppMessage() {
return { title: '肉垫计划 · 每天照顾好毛孩子', path: '/pages/home/home' };