Compare commits
2 Commits
192867a8d5
...
e9c7330f31
| Author | SHA1 | Date | |
|---|---|---|---|
| e9c7330f31 | |||
| 1943fd5c1a |
@@ -0,0 +1,106 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## 项目简介
|
||||||
|
|
||||||
|
微信小程序「生日提醒」+ 自建 Node.js 后端。小程序管理人员和纪念日,后端负责 openid 换取、数据云端备份、定时推送订阅消息。
|
||||||
|
|
||||||
|
## 常用命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 后端本地开发(进 server 目录)
|
||||||
|
cd server
|
||||||
|
npm install
|
||||||
|
npm run dev # node --watch 热重载,监听 3000
|
||||||
|
|
||||||
|
# 后端生产启动
|
||||||
|
npm start
|
||||||
|
|
||||||
|
# Docker 部署
|
||||||
|
docker compose up -d --build
|
||||||
|
|
||||||
|
# 手动触发一次提醒任务(调试用)
|
||||||
|
curl -X POST http://localhost:3000/api/reminder/run
|
||||||
|
```
|
||||||
|
|
||||||
|
小程序侧无构建命令,用**微信开发者工具**直接打开项目根目录。
|
||||||
|
|
||||||
|
## 架构总览
|
||||||
|
|
||||||
|
### 两个独立部分
|
||||||
|
|
||||||
|
| 部分 | 路径 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| 微信小程序 | `pages/` `utils/` `app.js` | 原生微信小程序,无框架 |
|
||||||
|
| 自建后端 | `server/` | Express + better-sqlite3,Node ≥18 |
|
||||||
|
|
||||||
|
> `cloudfunctions/` 目录是早期云开发遗留,已被 `server/` 取代,**不再使用**。
|
||||||
|
|
||||||
|
### 小程序数据流
|
||||||
|
|
||||||
|
```
|
||||||
|
本地 wx.Storage(主存储)
|
||||||
|
↕ 写时 fire-and-forget
|
||||||
|
自建后端 SQLite(云端备份)
|
||||||
|
```
|
||||||
|
|
||||||
|
- **本地是主真相源**:所有读写先操作 wx.Storage 内存缓存(`utils/storage.js`),再异步同步后端。
|
||||||
|
- **失败入队**:`utils/sync.js` 维护 `pending_sync_queue`,同步失败的操作下次启动时 `flush()`。
|
||||||
|
- **新设备恢复**:`app.js` 启动时,若本地为空则调用 `storage.pullFromCloudIfEmpty()` 从后端拉取全量数据。
|
||||||
|
|
||||||
|
### 后端 API 协议
|
||||||
|
|
||||||
|
所有接口用统一的 `action` 字段区分操作,openid 通过 `x-openid` 请求头传递:
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /api/login # wx.login code → openid
|
||||||
|
POST /api/person # action: add / update / delete / sync / get
|
||||||
|
POST /api/anniversary # action: add / update / delete / sync / get
|
||||||
|
POST /api/reminder/run # 手动触发定时任务
|
||||||
|
```
|
||||||
|
|
||||||
|
前端 URL 自动选择:开发者工具 → `http://localhost:3000`;体验版/正式版 → `https://wxserver.ymxixi.space`(见 `utils/api.js:resolveBaseUrl`)。
|
||||||
|
|
||||||
|
### 后端主要模块
|
||||||
|
|
||||||
|
| 文件 | 职责 |
|
||||||
|
|------|------|
|
||||||
|
| `server/src/index.js` | Express 路由 + 所有 CRUD 函数 |
|
||||||
|
| `server/src/db.js` | better-sqlite3 初始化、建表、旧库 ALTER 迁移 |
|
||||||
|
| `server/src/reminder.js` | cron 定时任务,扫描 `remindEnabled=1` 的纪念日并发微信订阅消息 |
|
||||||
|
| `server/src/wx.js` | 微信接口封装(code2session、sendSubscribeMessage) |
|
||||||
|
| `server/src/lunar.js` | 农历转公历,与前端 `utils/lunar.js` 算法一致 |
|
||||||
|
|
||||||
|
### 农历处理
|
||||||
|
|
||||||
|
`utils/lunar.js`(小程序)和 `server/src/lunar.js`(后端)是同一套寿星万年历算法,覆盖 1900–2100 年。纪念日记录同时存储公历字段(`solarMonth/solarDay`)和农历字段(`lunarMonth/lunarDay/isLeapMonth`),`isLunar` 标志决定展示和计算逻辑用哪套。
|
||||||
|
|
||||||
|
### 纪念日数据结构关键字段
|
||||||
|
|
||||||
|
```js
|
||||||
|
{
|
||||||
|
id, personId, personName,
|
||||||
|
type, // 'birthday' | 'wedding' | 'engagement' | 'other'
|
||||||
|
customTypeName, // type='other' 时的自定义名称
|
||||||
|
isLunar, // true = 农历生日
|
||||||
|
solarMonth, solarDay, // 公历月日(必填,农历纪念日也存转换后的公历供排序)
|
||||||
|
lunarMonth, lunarDay, isLeapMonth, // 农历字段(isLunar=true 时有效)
|
||||||
|
importance, // 'high' | 'medium' | 'low'
|
||||||
|
remindEnabled, remindDays
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`lunar_birthday` 是老数据兼容类型,与 `birthday` 等效,由 `isLunar` 决定是否农历,常量和后端均有兼容映射。
|
||||||
|
|
||||||
|
## 后端环境变量
|
||||||
|
|
||||||
|
参考 `server/.env.example`,关键变量:
|
||||||
|
|
||||||
|
```
|
||||||
|
WX_APPID # 微信小程序 AppID
|
||||||
|
WX_APPSECRET # 微信小程序 AppSecret
|
||||||
|
WX_TEMPLATE_ID # 订阅消息模板 ID
|
||||||
|
REMINDER_CRON # 默认 "0 9 * * *"(每天9点,Asia/Shanghai)
|
||||||
|
DB_PATH # SQLite 路径,Docker 中挂载到 ./data/birthday.db
|
||||||
|
```
|
||||||
@@ -1,25 +1,15 @@
|
|||||||
const api = require('./utils/api')
|
const api = require('./utils/api')
|
||||||
const storage = require('./utils/storage')
|
const storage = require('./utils/storage')
|
||||||
const sync = require('./utils/sync')
|
const sync = require('./utils/sync')
|
||||||
|
const migrate = require('./utils/migrate')
|
||||||
|
|
||||||
App({
|
App({
|
||||||
onLaunch() {
|
onLaunch() {
|
||||||
const logs = wx.getStorageSync('logs') || []
|
// 先修一遍本地数据,再走网络流程
|
||||||
logs.unshift(Date.now())
|
migrate.run()
|
||||||
wx.setStorageSync('logs', logs)
|
|
||||||
|
|
||||||
this.initData()
|
|
||||||
this.getUserOpenId()
|
this.getUserOpenId()
|
||||||
},
|
},
|
||||||
|
|
||||||
initData() {
|
|
||||||
const persons = wx.getStorageSync('persons') || []
|
|
||||||
const anniversaries = wx.getStorageSync('anniversaries') || []
|
|
||||||
if (persons.length === 0 && anniversaries.length === 0) {
|
|
||||||
console.log('初始化数据结构')
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
// 获取 openid:调自建后端 /api/login
|
// 获取 openid:调自建后端 /api/login
|
||||||
async getUserOpenId() {
|
async getUserOpenId() {
|
||||||
let openid = wx.getStorageSync('openid')
|
let openid = wx.getStorageSync('openid')
|
||||||
@@ -38,7 +28,11 @@ App({
|
|||||||
|
|
||||||
// 拿到 openid 后,本地无数据时从云端拉一次(新设备/重装恢复场景)
|
// 拿到 openid 后,本地无数据时从云端拉一次(新设备/重装恢复场景)
|
||||||
const pulled = await storage.pullFromCloudIfEmpty()
|
const pulled = await storage.pullFromCloudIfEmpty()
|
||||||
if (pulled) console.log('已从云端恢复数据')
|
if (pulled) {
|
||||||
|
console.log('已从云端恢复数据')
|
||||||
|
// 云端可能存着老版本写上去的坏数据,拉回来后再修一遍(run 是幂等的)
|
||||||
|
migrate.run()
|
||||||
|
}
|
||||||
|
|
||||||
// flush 之前同步失败的待重试队列
|
// flush 之前同步失败的待重试队列
|
||||||
sync.flush()
|
sync.flush()
|
||||||
|
|||||||
@@ -4,16 +4,12 @@ const dateUtils = require('../../utils/date')
|
|||||||
const lunar = require('../../utils/lunar')
|
const lunar = require('../../utils/lunar')
|
||||||
const { TYPE_NAMES, TYPE_ICONS, IMPORTANCE_COLORS } = require('../../utils/constants')
|
const { TYPE_NAMES, TYPE_ICONS, IMPORTANCE_COLORS } = require('../../utils/constants')
|
||||||
|
|
||||||
// 算出某条纪念日在指定年份的公历 (month, day)
|
// 算出某条纪念日在指定公历年份的 (month, day)
|
||||||
// 公历纪念日:每年同月同日,直接用录入时的 solarMonth/solarDay
|
// 具体的公历/农历分支逻辑统一在 utils/date.js 的 getOccurrenceInYear 里,这里只做取值
|
||||||
// 农历纪念日:把农历月日转回当年公历,因为农历对应的公历日期每年都不同
|
|
||||||
function getAnniversaryDateInYear(a, year) {
|
function getAnniversaryDateInYear(a, year) {
|
||||||
if (a.isLunar && a.lunarMonth && a.lunarDay) {
|
const date = dateUtils.getOccurrenceInYear(a, year)
|
||||||
const date = lunar.lunarToSolar(year, a.lunarMonth, a.lunarDay, !!a.isLeapMonth)
|
|
||||||
return { month: date.getMonth() + 1, day: date.getDate() }
|
return { month: date.getMonth() + 1, day: date.getDate() }
|
||||||
}
|
}
|
||||||
return { month: a.solarMonth, day: a.solarDay }
|
|
||||||
}
|
|
||||||
|
|
||||||
Page({
|
Page({
|
||||||
data: {
|
data: {
|
||||||
@@ -29,6 +25,12 @@ Page({
|
|||||||
currentYear: today.getFullYear(),
|
currentYear: today.getFullYear(),
|
||||||
currentMonth: today.getMonth() + 1
|
currentMonth: today.getMonth() + 1
|
||||||
})
|
})
|
||||||
|
},
|
||||||
|
|
||||||
|
// 渲染放在 onShow:日历是 tabBar 页面,实例常驻,
|
||||||
|
// 只在 onLoad 渲染会导致新增/删除纪念日后切回来看不到变化。
|
||||||
|
// 这里不重置 currentYear/currentMonth,保留用户当前翻到的月份。
|
||||||
|
onShow() {
|
||||||
this.renderCalendar()
|
this.renderCalendar()
|
||||||
this.loadMonthEvents()
|
this.loadMonthEvents()
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ Page({
|
|||||||
if (personAnniversaries.length > 0) {
|
if (personAnniversaries.length > 0) {
|
||||||
const upcoming = personAnniversaries
|
const upcoming = personAnniversaries
|
||||||
.map(a => {
|
.map(a => {
|
||||||
const { date, daysUntil } = dateUtils.getNextOccurrence(a.solarMonth, a.solarDay)
|
// 农历纪念日的公历日期每年都不同,必须走 getNextOccurrenceOf 而不是直接用 solarMonth/solarDay
|
||||||
|
const { date, daysUntil } = dateUtils.getNextOccurrenceOf(a)
|
||||||
return { ...a, date, daysUntil }
|
return { ...a, date, daysUntil }
|
||||||
})
|
})
|
||||||
.sort((a, b) => a.daysUntil - b.daysUntil)
|
.sort((a, b) => a.daysUntil - b.daysUntil)
|
||||||
|
|||||||
@@ -51,14 +51,16 @@ Page({
|
|||||||
|
|
||||||
// 格式化纪念日数据
|
// 格式化纪念日数据
|
||||||
const formatted = anniversaries.map(a => {
|
const formatted = anniversaries.map(a => {
|
||||||
const date = new Date(a.solarYear, a.solarMonth - 1, a.solarDay)
|
// 「日期」一行展示录入时的原始日期(出生日/结婚日,本身有信息价值)
|
||||||
const daysUntil = dateUtils.getDaysUntil(date)
|
const originDate = new Date(a.solarYear, a.solarMonth - 1, a.solarDay)
|
||||||
const ld = lunar.solarToLunar(date)
|
const ld = lunar.solarToLunar(originDate)
|
||||||
|
// 倒计时必须按「下一次发生」算,原先直接用原始日期导致永远显示「已过 N 天」
|
||||||
|
const { date, daysUntil } = dateUtils.getNextOccurrenceOf(a)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...a,
|
...a,
|
||||||
date,
|
date,
|
||||||
dateText: dateUtils.formatDate(date, 'YYYY年MM月DD日'),
|
dateText: dateUtils.formatDate(originDate, 'YYYY年MM月DD日'),
|
||||||
lunarText: `农历 ${ld.year}年 ${ld.lunarText}`,
|
lunarText: `农历 ${ld.year}年 ${ld.lunarText}`,
|
||||||
daysUntil,
|
daysUntil,
|
||||||
daysUntilAbs: Math.abs(daysUntil),
|
daysUntilAbs: Math.abs(daysUntil),
|
||||||
|
|||||||
+24
-13
@@ -19,7 +19,7 @@ Page({
|
|||||||
personsCount: 0,
|
personsCount: 0,
|
||||||
anniversariesCount: 0,
|
anniversariesCount: 0,
|
||||||
lastBackupText: '从未备份',
|
lastBackupText: '从未备份',
|
||||||
version: 'v2.1.6'
|
version: 'v2.1.8'
|
||||||
},
|
},
|
||||||
|
|
||||||
onLoad() {
|
onLoad() {
|
||||||
@@ -92,23 +92,34 @@ Page({
|
|||||||
onClearData() {
|
onClearData() {
|
||||||
wx.showModal({
|
wx.showModal({
|
||||||
title: '确认清空',
|
title: '确认清空',
|
||||||
content: '确定要清空所有数据吗?此操作不可恢复!',
|
content: '本地和云端备份都会被清空,此操作不可恢复!',
|
||||||
confirmText: '确认清空',
|
confirmText: '确认清空',
|
||||||
confirmColor: '#C8412F',
|
confirmColor: '#C8412F',
|
||||||
success: (res) => {
|
success: async (res) => {
|
||||||
if (res.confirm) {
|
if (!res.confirm) return
|
||||||
const success = storage.clearAllData()
|
|
||||||
if (success) {
|
// 先清云端再清本地:顺序反了的话,本地清空后下次启动会从云端把数据整份拉回来
|
||||||
wx.showToast({
|
wx.showLoading({ title: '正在清空...', mask: true })
|
||||||
title: '已清空',
|
const cloud = await storage.clearCloudData()
|
||||||
icon: 'success'
|
wx.hideLoading()
|
||||||
|
|
||||||
|
if (!cloud.success) {
|
||||||
|
// 云端没清干净就不动本地,否则会出现「清了又自己回来」的诡异现象
|
||||||
|
wx.showModal({
|
||||||
|
title: '清空失败',
|
||||||
|
content: `云端数据未能清除(${cloud.error}),本地数据已保留。请检查网络后重试。`,
|
||||||
|
showCancel: false
|
||||||
})
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (storage.clearAllData()) {
|
||||||
|
wx.showToast({ title: '已清空', icon: 'success' })
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
wx.reLaunch({
|
wx.reLaunch({ url: '/pages/index/index' })
|
||||||
url: '/pages/index/index'
|
|
||||||
})
|
|
||||||
}, 1500)
|
}, 1500)
|
||||||
}
|
} else {
|
||||||
|
wx.showToast({ title: '本地清空失败,请重试', icon: 'none' })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
Generated
+1475
File diff suppressed because it is too large
Load Diff
+11
-3
@@ -117,9 +117,13 @@ function addAnniversary(openid, anniv) {
|
|||||||
return { success: true, id }
|
return { success: true, id }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 记录不存在时退化为插入(upsert)。
|
||||||
|
// Why:本地 wx.Storage 才是主真相源,云端只是备份。若某条记录当初的 add 没同步成功,
|
||||||
|
// 之后所有 update 都会失败,并卡在前端 pending_sync_queue 里每次启动无限重试。
|
||||||
|
// 与 deleteAnniversary 的幂等处理是同一类问题。
|
||||||
function updateAnniversary(openid, anniv) {
|
function updateAnniversary(openid, anniv) {
|
||||||
const existing = db.prepare('SELECT * FROM anniversaries WHERE id = ? AND openid = ?').get(anniv.id, openid)
|
const existing = db.prepare('SELECT * FROM anniversaries WHERE id = ? AND openid = ?').get(anniv.id, openid)
|
||||||
if (!existing) return { success: false, error: '纪念日不存在' }
|
if (!existing) return addAnniversary(openid, anniv)
|
||||||
|
|
||||||
const merged = {
|
const merged = {
|
||||||
...existing,
|
...existing,
|
||||||
@@ -136,9 +140,12 @@ function updateAnniversary(openid, anniv) {
|
|||||||
return { success: true }
|
return { success: true }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 删除是幂等的:记录本来就不存在时也算成功。
|
||||||
|
// Why:前端 sync.js 把 success:false 当作失败重新入队,若这里对「已不存在」返回 false,
|
||||||
|
// 那条删除操作会永远留在 pending_sync_queue 里,每次启动重试且永远清不掉。
|
||||||
function deleteAnniversary(openid, id) {
|
function deleteAnniversary(openid, id) {
|
||||||
const info = db.prepare('DELETE FROM anniversaries WHERE id = ? AND openid = ?').run(id, openid)
|
const info = db.prepare('DELETE FROM anniversaries WHERE id = ? AND openid = ?').run(id, openid)
|
||||||
return { success: info.changes > 0 }
|
return { success: true, deleted: info.changes }
|
||||||
}
|
}
|
||||||
|
|
||||||
function syncAnniversaries(openid, list) {
|
function syncAnniversaries(openid, list) {
|
||||||
@@ -180,9 +187,10 @@ function addPerson(openid, person) {
|
|||||||
return { success: true, id: row.id }
|
return { success: true, id: row.id }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 同 updateAnniversary:记录不存在时退化为插入,避免同步队列里的 update 永远重试
|
||||||
function updatePerson(openid, person) {
|
function updatePerson(openid, person) {
|
||||||
const existing = db.prepare('SELECT * FROM persons WHERE id = ? AND openid = ?').get(person.id, openid)
|
const existing = db.prepare('SELECT * FROM persons WHERE id = ? AND openid = ?').get(person.id, openid)
|
||||||
if (!existing) return { success: false, error: '人员不存在' }
|
if (!existing) return addPerson(openid, person)
|
||||||
const merged = { ...existing, ...person, openid, updateTime: Date.now() }
|
const merged = { ...existing, ...person, openid, updateTime: Date.now() }
|
||||||
const sets = PERSON_FIELDS.filter(f => f !== 'id' && f !== 'openid' && f !== 'createTime')
|
const sets = PERSON_FIELDS.filter(f => f !== 'id' && f !== 'openid' && f !== 'createTime')
|
||||||
.map(f => `${f} = @${f}`).join(', ')
|
.map(f => `${f} = @${f}`).join(', ')
|
||||||
|
|||||||
+36
-9
@@ -2,6 +2,8 @@
|
|||||||
* 日期工具函数
|
* 日期工具函数
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
const lunar = require('./lunar')
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 格式化日期
|
* 格式化日期
|
||||||
* @param {Date} date - 日期对象
|
* @param {Date} date - 日期对象
|
||||||
@@ -104,18 +106,42 @@ function parseDate(dateString) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 计算指定月日的下一次发生日期(今年或明年)
|
* 算出某条纪念日在指定年份的公历日期
|
||||||
* @param {Number} month - 月份 (1-12)
|
* 公历纪念日:每年同月同日,直接用录入时的 solarMonth/solarDay
|
||||||
* @param {Number} day - 日 (1-31)
|
* 农历纪念日:把农历月日转回当年公历,因为农历对应的公历日期每年都不同
|
||||||
|
* @param {Object} anniv - 纪念日记录
|
||||||
|
* @param {Number} year - 目标公历年份
|
||||||
|
* @returns {Date}
|
||||||
|
*/
|
||||||
|
function getOccurrenceInYear(anniv, year) {
|
||||||
|
if (anniv.isLunar && anniv.lunarMonth && anniv.lunarDay) {
|
||||||
|
const isLeap = !!anniv.isLeapMonth
|
||||||
|
// 农历年和公历年不对齐:农历腊月通常落到下一个公历年(如农历2026年腊月十五 = 公历2027年1月)。
|
||||||
|
// 所以要同时试 year-1 / year 两个农历年,取真正落在公历 year 年内的那个;
|
||||||
|
// 先试 year-1 保证返回的是该公历年内最早的一次。
|
||||||
|
for (const lunarYear of [year - 1, year]) {
|
||||||
|
const d = lunar.lunarToSolar(lunarYear, anniv.lunarMonth, anniv.lunarDay, isLeap)
|
||||||
|
if (d.getFullYear() === year) return d
|
||||||
|
}
|
||||||
|
// 兜底(理论上不会走到,农历年跨度必然覆盖整个公历年)
|
||||||
|
return lunar.lunarToSolar(year, anniv.lunarMonth, anniv.lunarDay, isLeap)
|
||||||
|
}
|
||||||
|
return new Date(year, anniv.solarMonth - 1, anniv.solarDay)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 算出某条纪念日的下一次发生(今年或明年),农历/公历都适用
|
||||||
|
* Why:首页、详情页、日历页原先各算一套,农历纪念日只有日历页算对了。
|
||||||
|
* 统一走这里,避免三处口径不一致。
|
||||||
|
* @param {Object} anniv - 纪念日记录
|
||||||
* @returns {{ date: Date, daysUntil: Number }}
|
* @returns {{ date: Date, daysUntil: Number }}
|
||||||
*/
|
*/
|
||||||
function getNextOccurrence(month, day) {
|
function getNextOccurrenceOf(anniv) {
|
||||||
const today = new Date()
|
const currentYear = new Date().getFullYear()
|
||||||
const currentYear = today.getFullYear()
|
let date = getOccurrenceInYear(anniv, currentYear)
|
||||||
let date = new Date(currentYear, month - 1, day)
|
|
||||||
let daysUntil = getDaysUntil(date)
|
let daysUntil = getDaysUntil(date)
|
||||||
if (daysUntil < 0) {
|
if (daysUntil < 0) {
|
||||||
date = new Date(currentYear + 1, month - 1, day)
|
date = getOccurrenceInYear(anniv, currentYear + 1)
|
||||||
daysUntil = getDaysUntil(date)
|
daysUntil = getDaysUntil(date)
|
||||||
}
|
}
|
||||||
return { date, daysUntil }
|
return { date, daysUntil }
|
||||||
@@ -124,7 +150,8 @@ function getNextOccurrence(month, day) {
|
|||||||
module.exports = {
|
module.exports = {
|
||||||
formatDate,
|
formatDate,
|
||||||
getDaysUntil,
|
getDaysUntil,
|
||||||
getNextOccurrence,
|
getOccurrenceInYear,
|
||||||
|
getNextOccurrenceOf,
|
||||||
isToday,
|
isToday,
|
||||||
isPast,
|
isPast,
|
||||||
isUpcoming,
|
isUpcoming,
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
/**
|
||||||
|
* 数据自愈迁移
|
||||||
|
*
|
||||||
|
* Why 放在客户端而不是后端跑一次 SQL:
|
||||||
|
* 本项目「本地 wx.Storage 是主真相源,云端只是备份」。在服务端改数据,客户端下次同步
|
||||||
|
* 又会把本地的坏数据推上去覆盖掉。只有在每台设备上修,才能真正修干净。
|
||||||
|
*
|
||||||
|
* Why 每次启动都跑而不是用版本号只跑一次:
|
||||||
|
* 本函数是纯检测式的——没有坏数据时不写库、不发请求、零副作用,成本只是遍历一遍数组
|
||||||
|
* (量级是个位数到几十条)。每次都跑还能顺带覆盖「从云端拉回来的坏数据」这种情况,
|
||||||
|
* 比记版本号更稳。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const storage = require('./storage')
|
||||||
|
const sync = require('./sync')
|
||||||
|
const lunar = require('./lunar')
|
||||||
|
|
||||||
|
const REBUILT_PERSON_REMARK = '自动恢复的联系人'
|
||||||
|
const FALLBACK_PERSON_NAME = '未命名'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 迁移一:补齐老数据缺失的农历字段
|
||||||
|
*
|
||||||
|
* 背景:早期版本有独立的 lunar_birthday 类型,只记公历日期,没有 lunarMonth/lunarDay。
|
||||||
|
* 后来改成用 isLunar 标志决定农历与否,这批老数据就变成了「声称是农历、却没有农历字段」。
|
||||||
|
* 这种记录会被日期计算安全降级成按公历算——不会崩,但每年的日期是错的。
|
||||||
|
* 用它存着的公历日期反算回农历,即可补齐。
|
||||||
|
*
|
||||||
|
* @returns {Array} 被修复的纪念日(已带上新字段)
|
||||||
|
*/
|
||||||
|
function _patchMissingLunarFields(anniversaries) {
|
||||||
|
const patched = []
|
||||||
|
const next = anniversaries.map(a => {
|
||||||
|
if (!a.isLunar) return a
|
||||||
|
if (a.lunarMonth && a.lunarDay) return a
|
||||||
|
// 没有公历基准就无从反算,保持原样(不制造假数据)
|
||||||
|
if (!a.solarYear || !a.solarMonth || !a.solarDay) return a
|
||||||
|
|
||||||
|
const ld = lunar.solarToLunar(new Date(a.solarYear, a.solarMonth - 1, a.solarDay))
|
||||||
|
const fixed = {
|
||||||
|
...a,
|
||||||
|
lunarYear: ld.year,
|
||||||
|
lunarMonth: ld.month,
|
||||||
|
lunarDay: ld.day,
|
||||||
|
isLeapMonth: ld.isLeap,
|
||||||
|
updateTime: Date.now()
|
||||||
|
}
|
||||||
|
patched.push(fixed)
|
||||||
|
return fixed
|
||||||
|
})
|
||||||
|
return { next, patched }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 迁移二:为孤儿纪念日重建人员
|
||||||
|
*
|
||||||
|
* 背景:有些纪念日的 personId 指向已不存在的人员(历史上删人没级联干净)。
|
||||||
|
* 首页按 persons 遍历,所以这些记录是隐形的;日历页按 anniversaries 遍历,会显示成「未知」。
|
||||||
|
*
|
||||||
|
* 做法:用纪念日自带的 personName 重建人员,并且**沿用原来的 personId**,
|
||||||
|
* 这样纪念日记录一个字段都不用改,风险最小。
|
||||||
|
*
|
||||||
|
* @returns {Array} 新建出来的人员
|
||||||
|
*/
|
||||||
|
function _rebuildMissingPersons(persons, anniversaries) {
|
||||||
|
const known = new Set(persons.map(p => p.id))
|
||||||
|
const missing = new Map() // personId -> name
|
||||||
|
|
||||||
|
for (const a of anniversaries) {
|
||||||
|
if (!a.personId || known.has(a.personId)) continue
|
||||||
|
const name = (a.personName || '').trim()
|
||||||
|
const recorded = missing.get(a.personId)
|
||||||
|
// 同一个失踪 personId 可能对应多条纪念日,优先采用非空的姓名
|
||||||
|
if (!recorded || (recorded === FALLBACK_PERSON_NAME && name)) {
|
||||||
|
missing.set(a.personId, name || FALLBACK_PERSON_NAME)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missing.size === 0) return []
|
||||||
|
|
||||||
|
const now = Date.now()
|
||||||
|
return Array.from(missing.entries()).map(([id, name]) => ({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
nickname: '',
|
||||||
|
avatar: '',
|
||||||
|
remark: REBUILT_PERSON_REMARK,
|
||||||
|
createTime: now,
|
||||||
|
updateTime: now
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行迁移。幂等,可重复调用。
|
||||||
|
* 任何异常都吞掉,绝不能因为迁移失败导致小程序起不来。
|
||||||
|
* @returns {{ lunarPatched: Number, personsRebuilt: Number }|null}
|
||||||
|
*/
|
||||||
|
function run() {
|
||||||
|
try {
|
||||||
|
const anniversaries = storage.getAnniversaries()
|
||||||
|
const { next, patched } = _patchMissingLunarFields(anniversaries)
|
||||||
|
if (patched.length > 0) {
|
||||||
|
storage.saveAnniversaries(next)
|
||||||
|
// 逐条推送更新;失败会自动入队,下次启动 flush
|
||||||
|
patched.forEach(a => sync.syncOrEnqueue({ kind: 'anniversary', action: 'update', data: a }))
|
||||||
|
}
|
||||||
|
|
||||||
|
const persons = storage.getPersons()
|
||||||
|
const rebuilt = _rebuildMissingPersons(persons, next)
|
||||||
|
if (rebuilt.length > 0) {
|
||||||
|
storage.savePersons(persons.concat(rebuilt))
|
||||||
|
rebuilt.forEach(p => sync.syncOrEnqueue({ kind: 'person', action: 'add', data: p }))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (patched.length > 0 || rebuilt.length > 0) {
|
||||||
|
console.log(`[migrate] 补齐农历字段 ${patched.length} 条,重建人员 ${rebuilt.length} 个`)
|
||||||
|
}
|
||||||
|
return { lunarPatched: patched.length, personsRebuilt: rebuilt.length }
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[migrate] 迁移失败,已跳过(不影响启动)', e)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { run }
|
||||||
+44
-1
@@ -12,6 +12,15 @@ function _syncPerson(action, data) {
|
|||||||
sync.syncOrEnqueue({ kind: 'person', action, data })
|
sync.syncOrEnqueue({ kind: 'person', action, data })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 异步同步纪念日到后端;失败自动入队,启动时 flush
|
||||||
|
// 注:add/update 的同步在 pages/add-anniversary 页面里做(那里才拿得到完整的表单数据),
|
||||||
|
// 这里只负责 delete,避免同一条操作被同步两次。
|
||||||
|
function _syncAnniversary(action, data) {
|
||||||
|
const openid = wx.getStorageSync('openid')
|
||||||
|
if (!openid) return
|
||||||
|
sync.syncOrEnqueue({ kind: 'anniversary', action, data })
|
||||||
|
}
|
||||||
|
|
||||||
// 内存缓存
|
// 内存缓存
|
||||||
const _cache = {
|
const _cache = {
|
||||||
persons: null,
|
persons: null,
|
||||||
@@ -180,7 +189,11 @@ function updateAnniversary(id, updates) {
|
|||||||
*/
|
*/
|
||||||
function deleteAnniversary(id) {
|
function deleteAnniversary(id) {
|
||||||
const anniversaries = getAnniversaries()
|
const anniversaries = getAnniversaries()
|
||||||
return saveAnniversaries(anniversaries.filter(a => a.id !== id)).success
|
const ok = saveAnniversaries(anniversaries.filter(a => a.id !== id)).success
|
||||||
|
// 必须同步删除云端,否则后端那条记录仍是 remindEnabled=1,定时任务会继续推送已删除的纪念日,
|
||||||
|
// 且换设备恢复时它会被重新拉回本地
|
||||||
|
if (ok) _syncAnniversary('delete', { id })
|
||||||
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -295,8 +308,37 @@ async function pullFromCloudIfEmpty() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空云端数据(用空数组走 sync,后端会先 DELETE 该 openid 的全部记录)
|
||||||
|
* Why:只清本地的话,下次启动 pullFromCloudIfEmpty() 会把云端数据整份拉回来,
|
||||||
|
* 用户以为清空了其实没清。所以清本地之前必须先把云端清掉。
|
||||||
|
* @returns {Promise<{success: boolean, error?: string}>}
|
||||||
|
*/
|
||||||
|
async function clearCloudData() {
|
||||||
|
const openid = wx.getStorageSync('openid')
|
||||||
|
// 从未登录过 → 云端本来就没有这个用户的数据,直接算成功
|
||||||
|
if (!openid) return { success: true }
|
||||||
|
try {
|
||||||
|
const [personRes, annivRes] = await Promise.all([
|
||||||
|
api.person('sync', []),
|
||||||
|
api.anniversary('sync', [])
|
||||||
|
])
|
||||||
|
if (!personRes || personRes.success === false) {
|
||||||
|
return { success: false, error: (personRes && personRes.error) || '清空云端人员失败' }
|
||||||
|
}
|
||||||
|
if (!annivRes || annivRes.success === false) {
|
||||||
|
return { success: false, error: (annivRes && annivRes.error) || '清空云端纪念日失败' }
|
||||||
|
}
|
||||||
|
return { success: true }
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[clearCloudData] 失败', e)
|
||||||
|
return { success: false, error: e.message || '网络异常' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 清空所有数据
|
* 清空所有数据
|
||||||
|
* 注:会连 openid 和待同步队列一起清掉,下次启动会重新 login 拿 openid
|
||||||
*/
|
*/
|
||||||
function clearAllData() {
|
function clearAllData() {
|
||||||
try {
|
try {
|
||||||
@@ -332,5 +374,6 @@ module.exports = {
|
|||||||
exportData,
|
exportData,
|
||||||
importData,
|
importData,
|
||||||
clearAllData,
|
clearAllData,
|
||||||
|
clearCloudData,
|
||||||
pullFromCloudIfEmpty
|
pullFromCloudIfEmpty
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user