|
| 1 | +#!/usr/bin/env node |
| 2 | +/** |
| 3 | + * 激活码管理 CLI(对接 Supabase licenses 池) |
| 4 | + * |
| 5 | + * @ai-context: 单人运维工具:导入激活码 CSV → 池、按订单对账、撤销、状态查询。 |
| 6 | + * 需要环境变量 SUPABASE_URL + SUPABASE_SERVICE_KEY(service key 仅服务端/本脚本持有)。 |
| 7 | + * |
| 8 | + * 用法: |
| 9 | + * node scripts/license-admin.mjs import ./codes.csv # 导入 CSV(code,type,tier,duration_days,generated_at) |
| 10 | + * node scripts/license-admin.mjs status ENTROPY-PRO-XXXX-XXXX # 查询单个激活码状态 |
| 11 | + * node scripts/license-admin.mjs revoke ENTROPY-PRO-XXXX-XXXX # 撤销激活码 |
| 12 | + * node scripts/license-admin.mjs reconcile MB-1001 # 按订单号对账(标记 sold) |
| 13 | + */ |
| 14 | + |
| 15 | +import { readFileSync } from 'node:fs'; |
| 16 | +import { fileURLToPath } from 'node:url'; |
| 17 | +import path from 'node:path'; |
| 18 | + |
| 19 | +const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 20 | + |
| 21 | +// 环境变量:脚本直接读进程环境(.env 由调用方注入) |
| 22 | +const SUPABASE_URL = (process.env.SUPABASE_URL || '').replace(/\/$/, ''); |
| 23 | +const SUPABASE_SERVICE_KEY = process.env.SUPABASE_SERVICE_KEY || ''; |
| 24 | + |
| 25 | +function requireEnv() { |
| 26 | + if (!SUPABASE_URL || !SUPABASE_SERVICE_KEY) { |
| 27 | + console.error('❌ 缺少环境变量 SUPABASE_URL / SUPABASE_SERVICE_KEY'); |
| 28 | + console.error(' powershell: $env:SUPABASE_URL=\"https://xxx.supabase.co\"; $env:SUPABASE_SERVICE_KEY=\"...\"'); |
| 29 | + process.exit(1); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/** PostgREST 请求(service key) */ |
| 34 | +async function pg(method, pathname, body) { |
| 35 | + const resp = await fetch(`${SUPABASE_URL}/rest/v1${pathname}`, { |
| 36 | + method, |
| 37 | + headers: { |
| 38 | + apikey: SUPABASE_SERVICE_KEY, |
| 39 | + Authorization: `Bearer ${SUPABASE_SERVICE_KEY}`, |
| 40 | + 'Content-Type': 'application/json', |
| 41 | + Prefer: 'return=representation', |
| 42 | + }, |
| 43 | + body: body ? JSON.stringify(body) : undefined, |
| 44 | + }); |
| 45 | + if (!resp.ok) { |
| 46 | + const text = await resp.text(); |
| 47 | + throw new Error(`Supabase ${method} ${pathname} → ${resp.status}: ${text.slice(0, 200)}`); |
| 48 | + } |
| 49 | + const text = await resp.text(); |
| 50 | + return text ? JSON.parse(text) : []; |
| 51 | +} |
| 52 | + |
| 53 | +/** 解析 CSV 行(code,type,tier,duration_days,generated_at) */ |
| 54 | +function parseCsv(content) { |
| 55 | + const rows = []; |
| 56 | + for (const line of content.split(/\r?\n/)) { |
| 57 | + if (!line.trim()) continue; |
| 58 | + const [code, type, , durationDays] = line.split(','); |
| 59 | + if (!code || !code.startsWith('ENTROPY-')) continue; |
| 60 | + rows.push({ |
| 61 | + code: code.trim(), |
| 62 | + type: (type || 'PRO').trim().toLowerCase(), |
| 63 | + duration_days: parseInt(durationDays, 10) || 30, |
| 64 | + }); |
| 65 | + } |
| 66 | + return rows; |
| 67 | +} |
| 68 | + |
| 69 | +async function cmdImport(csvPath) { |
| 70 | + requireEnv(); |
| 71 | + const content = readFileSync(csvPath, 'utf-8'); |
| 72 | + const rows = parseCsv(content); |
| 73 | + if (rows.length === 0) { |
| 74 | + console.error('❌ 未解析到任何激活码(CSV 表头: code,type,tier,duration_days,generated_at)'); |
| 75 | + process.exit(1); |
| 76 | + } |
| 77 | + let inserted = 0; |
| 78 | + for (const row of rows) { |
| 79 | + try { |
| 80 | + await pg('POST', '/licenses', row); |
| 81 | + inserted++; |
| 82 | + } catch (err) { |
| 83 | + // 唯一键冲突 = 已存在,跳过(幂等导入) |
| 84 | + if (String(err.message).includes('23505') || String(err.message).includes('duplicate')) { |
| 85 | + console.warn(`⏭ 已存在,跳过: ${row.code}`); |
| 86 | + } else { |
| 87 | + console.error(`✗ 导入失败 ${row.code}: ${err.message}`); |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + console.log(`✅ 导入完成: ${inserted}/${rows.length} 条(unsold 状态)`); |
| 92 | +} |
| 93 | + |
| 94 | +async function cmdStatus(code) { |
| 95 | + requireEnv(); |
| 96 | + const rows = await pg('GET', `/licenses?code=eq.${encodeURIComponent(code)}&select=*`); |
| 97 | + if (rows.length === 0) { |
| 98 | + console.log(`🔍 未找到激活码: ${code}`); |
| 99 | + return; |
| 100 | + } |
| 101 | + const r = rows[0]; |
| 102 | + console.log(JSON.stringify({ |
| 103 | + code: r.code, |
| 104 | + type: r.type, |
| 105 | + status: r.status, |
| 106 | + order_id: r.order_id, |
| 107 | + duration_days: r.duration_days, |
| 108 | + bound_user_id: r.bound_user_id, |
| 109 | + machine_id: r.machine_id, |
| 110 | + expires_at: r.expires_at, |
| 111 | + sold_at: r.sold_at, |
| 112 | + activated_at: r.activated_at, |
| 113 | + revoked_at: r.revoked_at, |
| 114 | + }, null, 2)); |
| 115 | +} |
| 116 | + |
| 117 | +async function cmdRevoke(code) { |
| 118 | + requireEnv(); |
| 119 | + const now = new Date().toISOString(); |
| 120 | + const rows = await pg('PATCH', `/licenses?code=eq.${encodeURIComponent(code)}`, { |
| 121 | + status: 'revoked', |
| 122 | + revoked_at: now, |
| 123 | + }); |
| 124 | + if (rows.length === 0) { |
| 125 | + console.error(`✗ 激活码不存在: ${code}`); |
| 126 | + process.exit(1); |
| 127 | + } |
| 128 | + console.log(`✅ 已撤销: ${code}(此前状态: ${rows[0].status})`); |
| 129 | +} |
| 130 | + |
| 131 | +async function cmdReconcile(orderId) { |
| 132 | + requireEnv(); |
| 133 | + // 按订单号查池记录;不存在 → 提示先确认订单在面包多已支付 |
| 134 | + const rows = await pg('GET', `/licenses?order_id=eq.${encodeURIComponent(orderId)}&select=*`); |
| 135 | + if (rows.length === 0) { |
| 136 | + console.error(`✗ 未找到订单 ${orderId} 关联的激活码——请先在面包多后台确认订单状态,再手动补标。`); |
| 137 | + console.error(' 可先执行 status 查询确认激活码,然后 revoke 或重发。'); |
| 138 | + process.exit(1); |
| 139 | + } |
| 140 | + for (const r of rows) { |
| 141 | + if (r.status === 'sold' || r.status === 'bound') { |
| 142 | + console.log(`⏭ 激活码 ${r.code} 已处于 ${r.status} 状态,无需处理`); |
| 143 | + continue; |
| 144 | + } |
| 145 | + await pg('PATCH', `/licenses?code=eq.${encodeURIComponent(r.code)}`, { status: 'sold', sold_at: new Date().toISOString() }); |
| 146 | + console.log(`✅ 对账完成: 订单 ${orderId} → ${r.code} 已标记 sold`); |
| 147 | + } |
| 148 | +} |
| 149 | + |
| 150 | +const [subcommand, arg] = process.argv.slice(2); |
| 151 | + |
| 152 | +switch (subcommand) { |
| 153 | + case 'import': |
| 154 | + if (!arg) { console.error('用法: license-admin.mjs import <codes.csv>'); process.exit(1); } |
| 155 | + cmdImport(arg); |
| 156 | + break; |
| 157 | + case 'status': |
| 158 | + if (!arg) { console.error('用法: license-admin.mjs status <ENTROPY-CODE>'); process.exit(1); } |
| 159 | + cmdStatus(arg); |
| 160 | + break; |
| 161 | + case 'revoke': |
| 162 | + if (!arg) { console.error('用法: license-admin.mjs revoke <ENTROPY-CODE>'); process.exit(1); } |
| 163 | + cmdRevoke(arg); |
| 164 | + break; |
| 165 | + case 'reconcile': |
| 166 | + if (!arg) { console.error('用法: license-admin.mjs reconcile <ORDER_ID>'); process.exit(1); } |
| 167 | + cmdReconcile(arg); |
| 168 | + break; |
| 169 | + default: |
| 170 | + console.log('用法: license-admin.mjs <import|status|revoke|reconcile> <参数>'); |
| 171 | + process.exit(1); |
| 172 | +} |
0 commit comments