fix: support existing meal planning bridge tables

This commit is contained in:
OpenClaw Bot
2026-05-11 23:36:52 +02:00
parent ba534cb864
commit 1828bef8f1
3 changed files with 133 additions and 35 deletions
+22 -10
View File
@@ -6,6 +6,7 @@
import { createLogger } from '../logger.js';
import express from 'express';
import crypto from 'node:crypto';
import * as db from '../db.js';
import { str, oneOf, date, num, collectErrors, MAX_TITLE, MAX_TEXT, MAX_SHORT, DATE_RE } from '../middleware/validate.js';
@@ -70,21 +71,32 @@ function validateCookUserId(raw) {
return { present: true, value: id, error: null };
}
function tableColumns(table) {
return new Set(db.get().prepare(`PRAGMA table_info(${table})`).all().map((row) => row.name));
}
function saveCookAssignment(meal, cookUserId, sourcePlanId, createdBy) {
if (cookUserId === null) {
db.get().prepare('DELETE FROM planned_meal_cooks WHERE meal_id = ?').run(meal.id);
return;
}
db.get().prepare(`
INSERT INTO planned_meal_cooks (meal_id, user_id, planned_for_date, meal_type, source_plan_id, created_by, updated_at)
VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
ON CONFLICT(meal_id) DO UPDATE SET
user_id = excluded.user_id,
planned_for_date = excluded.planned_for_date,
meal_type = excluded.meal_type,
source_plan_id = excluded.source_plan_id,
updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
`).run(meal.id, cookUserId, meal.date, meal.meal_type, sourcePlanId || null, createdBy);
const update = db.get().prepare(`
UPDATE planned_meal_cooks
SET user_id = ?, planned_for_date = ?, meal_type = ?, source_plan_id = ?, created_by = COALESCE(created_by, ?), updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE meal_id = ?
`).run(cookUserId, meal.date, meal.meal_type, sourcePlanId || null, createdBy, meal.id);
if (update.changes > 0) return;
const columns = tableColumns('planned_meal_cooks');
const insertColumns = ['meal_id', 'user_id', 'planned_for_date', 'meal_type', 'source_plan_id', 'created_by', 'updated_at'];
const values = [meal.id, cookUserId, meal.date, meal.meal_type, sourcePlanId || null, createdBy, new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')];
if (columns.has('id')) {
insertColumns.unshift('id');
values.unshift(crypto.randomUUID());
}
const placeholders = insertColumns.map(() => '?').join(', ');
db.get().prepare(`INSERT INTO planned_meal_cooks (${insertColumns.join(', ')}) VALUES (${placeholders})`).run(...values);
}
function syncCookAssignmentSlot(meal) {