feat: 支持先绑定设备后关联儿童档案

- 绑定模型新增 owner_user_id,支持 child_id 为空\n- 新增绑定后设置儿童接口 /bindings/{device_id}/child\n- 前端绑定页改为先绑设备后补充儿童\n- 补充数据库迁移脚本与 DAO 测试用例
This commit is contained in:
ChengCan
2026-04-14 12:47:52 +08:00
parent a22fcafea9
commit 1b4c47f77a
11 changed files with 699 additions and 246 deletions

View File

@@ -48,7 +48,8 @@ CREATE TABLE IF NOT EXISTS parent_child_relations (
CREATE TABLE IF NOT EXISTS device_bindings (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
device_id VARCHAR(64) NOT NULL,
child_id BIGINT NOT NULL,
owner_user_id BIGINT NOT NULL,
child_id BIGINT,
status TINYINT NOT NULL DEFAULT 1,
bound_at DATETIME NOT NULL,
unbound_at DATETIME,
@@ -58,6 +59,8 @@ CREATE TABLE IF NOT EXISTS device_bindings (
UNIQUE (child_id)
);
CREATE INDEX IF NOT EXISTS idx_device_bindings_owner_user_id ON device_bindings(owner_user_id);
-- device_bind_sessions table
CREATE TABLE IF NOT EXISTS device_bind_sessions (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
@@ -81,7 +84,7 @@ CREATE TABLE IF NOT EXISTS device_bind_sessions (
CREATE TABLE IF NOT EXISTS device_bind_history (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
device_id VARCHAR(64) NOT NULL,
child_id BIGINT NOT NULL,
child_id BIGINT,
bound_by_user_id BIGINT NOT NULL,
unbound_by_user_id BIGINT,
bind_source TINYINT NOT NULL DEFAULT 1,
@@ -211,4 +214,4 @@ CREATE TABLE IF NOT EXISTS child_location_history (
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_child_loc_hist_child ON child_location_history(child_id, created_at);
CREATE INDEX IF NOT EXISTS idx_child_loc_hist_child ON child_location_history(child_id, created_at);

View File

@@ -0,0 +1,46 @@
-- Migration: support "bind device first, then set child profile"
-- Target: MySQL 8.x
-- 1) Add owner_user_id on device_bindings.
ALTER TABLE device_bindings
ADD COLUMN owner_user_id BIGINT NULL AFTER device_id;
-- 2) Backfill owner_user_id from active parent-child relation (prefer primary relation).
UPDATE device_bindings b
SET owner_user_id = (
SELECT r.user_id
FROM parent_child_relations r
WHERE r.child_id = b.child_id
AND r.status = 1
ORDER BY r.is_primary DESC, r.id ASC
LIMIT 1
)
WHERE b.owner_user_id IS NULL;
-- 3) Fallback backfill from latest bind history.
UPDATE device_bindings b
SET owner_user_id = (
SELECT h.bound_by_user_id
FROM device_bind_history h
WHERE h.device_id = b.device_id
ORDER BY h.bound_at DESC, h.id DESC
LIMIT 1
)
WHERE b.owner_user_id IS NULL;
-- 4) Ensure no NULL owner before setting NOT NULL.
-- If this query returns rows, handle manually before continuing:
-- SELECT id, device_id, child_id FROM device_bindings WHERE owner_user_id IS NULL;
-- 5) Make schema changes for new flow.
ALTER TABLE device_bindings
MODIFY COLUMN owner_user_id BIGINT NOT NULL;
ALTER TABLE device_bindings
MODIFY COLUMN child_id BIGINT NULL;
ALTER TABLE device_bindings
ADD INDEX idx_device_bindings_owner_user_id (owner_user_id);
ALTER TABLE device_bind_history
MODIFY COLUMN child_id BIGINT NULL;