来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
236 lines
7.2 KiB
JavaScript
236 lines
7.2 KiB
JavaScript
/**
|
|
* CommonJS 版:生产机无 tsx 时用 node 直接跑(依赖已部署的 dist/)。
|
|
* 顺序:复制新键 → 回写库表 → 删旧键。
|
|
*/
|
|
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
|
|
|
|
const path = require('path');
|
|
const { pool } = require('../dist/db');
|
|
const {
|
|
INSPECTION_PHOTO_BUCKETS,
|
|
INSPECTION_RESULT_FOLDERS,
|
|
buildInspectionResultObjectName,
|
|
mimeFromFilename,
|
|
parseProductSlugFromResultBasename,
|
|
} = require('../dist/services/storageBucketConfig');
|
|
const { getStorageProvider } = require('../dist/services/storageProvider');
|
|
|
|
function parseArgs() {
|
|
const args = process.argv.slice(2);
|
|
const dryRun = args.includes('--dry-run');
|
|
const bucketArg = args.find((arg) => arg.startsWith('--bucket='));
|
|
const buckets = bucketArg
|
|
? bucketArg
|
|
.split('=')[1]
|
|
.split(',')
|
|
.map((item) => item.trim())
|
|
.filter(Boolean)
|
|
: [...INSPECTION_PHOTO_BUCKETS];
|
|
return { dryRun, buckets };
|
|
}
|
|
|
|
function isResultFolder(name) {
|
|
return INSPECTION_RESULT_FOLDERS.includes(name);
|
|
}
|
|
|
|
function planDestKey(filename) {
|
|
const key = String(filename || '')
|
|
.replace(/\\/g, '/')
|
|
.replace(/^\/+/, '');
|
|
const parts = key.split('/').filter(Boolean);
|
|
if (parts.length !== 2) return null;
|
|
if (!isResultFolder(parts[0])) return null;
|
|
if (parts[1] === '.keep') return null;
|
|
|
|
const folder = parts[0];
|
|
const base = parts[1];
|
|
const slug = parseProductSlugFromResultBasename(base) || 'unknown';
|
|
let destBase = base;
|
|
if (slug !== 'unknown' && base.toLowerCase().startsWith(`${slug}-`)) {
|
|
destBase = base.slice(slug.length + 1);
|
|
}
|
|
if (!destBase || destBase.includes('/')) destBase = base;
|
|
const to = buildInspectionResultObjectName(folder, slug, destBase);
|
|
if (to === key) return null;
|
|
return { from: key, to };
|
|
}
|
|
|
|
async function listPhotoTableSchemas() {
|
|
const result = await pool.query(
|
|
`SELECT n.nspname AS schema
|
|
FROM pg_class c
|
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
WHERE c.relkind = 'r'
|
|
AND c.relname = 'inspections'
|
|
AND n.nspname <> 'tenant_template'
|
|
ORDER BY n.nspname`
|
|
);
|
|
return result.rows.map((row) => String(row.schema));
|
|
}
|
|
|
|
async function rewriteDbPhotoPaths(pathMap, dryRun) {
|
|
if (pathMap.size === 0) return { inspections: 0, processing: 0 };
|
|
const fromKeys = [...pathMap.keys()];
|
|
let inspections = 0;
|
|
let processing = 0;
|
|
const schemas = await listPhotoTableSchemas();
|
|
console.log(`DB schemas: ${schemas.join(', ') || '(none)'}`);
|
|
|
|
for (const schema of schemas) {
|
|
const insp = await pool.query(
|
|
`SELECT id, inspection_photos
|
|
FROM ${quoteIdent(schema)}.inspections
|
|
WHERE inspection_photos IS NOT NULL
|
|
AND cardinality(inspection_photos) > 0
|
|
AND inspection_photos && $1::text[]`,
|
|
[fromKeys]
|
|
);
|
|
for (const row of insp.rows) {
|
|
const photos = Array.isArray(row.inspection_photos) ? row.inspection_photos : [];
|
|
const next = photos.map((p) => pathMap.get(String(p)) || p);
|
|
if (next.every((p, i) => p === photos[i])) continue;
|
|
inspections += 1;
|
|
if (!dryRun) {
|
|
await pool.query(
|
|
`UPDATE ${quoteIdent(schema)}.inspections SET inspection_photos = $2 WHERE id = $1`,
|
|
[row.id, next]
|
|
);
|
|
}
|
|
}
|
|
|
|
const hasProcessing = await pool.query(
|
|
`SELECT to_regclass($1) IS NOT NULL AS ok`,
|
|
[`${schema}.processing_tasks`]
|
|
);
|
|
if (!hasProcessing.rows[0]?.ok) continue;
|
|
|
|
const proc = await pool.query(
|
|
`SELECT id, processing_inspection_photos
|
|
FROM ${quoteIdent(schema)}.processing_tasks
|
|
WHERE processing_inspection_photos IS NOT NULL
|
|
AND cardinality(processing_inspection_photos) > 0
|
|
AND processing_inspection_photos && $1::text[]`,
|
|
[fromKeys]
|
|
);
|
|
for (const row of proc.rows) {
|
|
const photos = Array.isArray(row.processing_inspection_photos)
|
|
? row.processing_inspection_photos
|
|
: [];
|
|
const next = photos.map((p) => pathMap.get(String(p)) || p);
|
|
if (next.every((p, i) => p === photos[i])) continue;
|
|
processing += 1;
|
|
if (!dryRun) {
|
|
await pool.query(
|
|
`UPDATE ${quoteIdent(schema)}.processing_tasks
|
|
SET processing_inspection_photos = $2, updated_at = NOW()
|
|
WHERE id = $1`,
|
|
[row.id, next]
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
return { inspections, processing };
|
|
}
|
|
|
|
function quoteIdent(name) {
|
|
return `"${String(name).replace(/"/g, '""')}"`;
|
|
}
|
|
|
|
async function main() {
|
|
const options = parseArgs();
|
|
// 生产 tenant 表 FORCE RLS,维护脚本需关闭行安全
|
|
await pool.query('SET row_security = off');
|
|
const storage = getStorageProvider();
|
|
const moves = [];
|
|
const pathMap = new Map();
|
|
let copied = 0;
|
|
let skipped = 0;
|
|
let failed = 0;
|
|
|
|
console.log(`模式: ${options.dryRun ? 'dry-run' : 'migrate'}`);
|
|
console.log(`桶: ${options.buckets.join(', ')}`);
|
|
|
|
for (const bucket of options.buckets) {
|
|
if (!INSPECTION_PHOTO_BUCKETS.includes(bucket)) {
|
|
console.warn(`跳过非验收照片桶: ${bucket}`);
|
|
continue;
|
|
}
|
|
const objects = await storage.listObjects(bucket);
|
|
console.log(`\n[${bucket}] ${objects.length} 个对象`);
|
|
|
|
for (const obj of objects) {
|
|
const plan = planDestKey(obj.filename);
|
|
if (!plan) {
|
|
skipped += 1;
|
|
continue;
|
|
}
|
|
|
|
console.log(` ${plan.from} -> ${plan.to}`);
|
|
pathMap.set(plan.from, plan.to);
|
|
moves.push({ bucket, from: plan.from, to: plan.to });
|
|
|
|
if (options.dryRun) {
|
|
copied += 1;
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
if (await storage.exists(bucket, plan.to)) {
|
|
copied += 1;
|
|
continue;
|
|
}
|
|
const existing = await storage.getObject(bucket, plan.from);
|
|
if (!existing?.buffer?.byteLength) {
|
|
console.warn(` 跳过空对象 ${plan.from}`);
|
|
skipped += 1;
|
|
pathMap.delete(plan.from);
|
|
continue;
|
|
}
|
|
await storage.putObject(
|
|
bucket,
|
|
plan.to,
|
|
existing.buffer,
|
|
existing.contentType || mimeFromFilename(plan.to)
|
|
);
|
|
copied += 1;
|
|
} catch (err) {
|
|
failed += 1;
|
|
pathMap.delete(plan.from);
|
|
console.error(` 复制失败 ${plan.from}:`, err);
|
|
}
|
|
}
|
|
}
|
|
|
|
const db = await rewriteDbPhotoPaths(pathMap, options.dryRun);
|
|
console.log(`DB updated: inspections=${db.inspections} processing=${db.processing}`);
|
|
|
|
if (!options.dryRun) {
|
|
let deleted = 0;
|
|
for (const move of moves) {
|
|
if (!pathMap.has(move.from) || move.from === move.to) continue;
|
|
try {
|
|
if (await storage.exists(move.bucket, move.to)) {
|
|
await storage.deleteObject(move.bucket, move.from);
|
|
deleted += 1;
|
|
}
|
|
} catch (err) {
|
|
console.warn(` 删除旧键失败 ${move.bucket}/${move.from}:`, err);
|
|
}
|
|
}
|
|
console.log(`Deleted old keys: ${deleted}`);
|
|
}
|
|
|
|
console.log(
|
|
`\n完成: copied=${copied} skipped=${skipped} failed=${failed} db_inspections=${db.inspections} db_processing=${db.processing}`
|
|
);
|
|
await pool.end().catch(() => undefined);
|
|
if (failed > 0) process.exitCode = 1;
|
|
}
|
|
|
|
main().catch(async (err) => {
|
|
console.error(err);
|
|
await pool.end().catch(() => undefined);
|
|
process.exit(1);
|
|
});
|