fix: apply quota point conversion
This commit is contained in:
1 parent
2553e482a9
commit
ad66ae5f10
12 files changed
+205
-25
No files matched your search
+1
-1
@@ -8,7 +8,7 @@ ADMIN_PASSWORD=admin123456
|
|||||||
PAY_MASTER_KEY=
|
PAY_MASTER_KEY=
|
||||||
# 本地联调业务回调时可设为 true;生产环境请保持 false,避免 SSRF。
|
# 本地联调业务回调时可设为 true;生产环境请保持 false,避免 SSRF。
|
||||||
ALLOW_PRIVATE_CALLBACKS=false
|
ALLOW_PRIVATE_CALLBACKS=false
|
||||||
# 外部 PostgreSQL 用于读取 users,并在支付确认后由服务端原子增加 users.quota;Docker Compose 内可设 postgres
|
# 外部 PostgreSQL 用于读取 users;1 积分对应 5000 quota,支付确认后服务端按此比例原子更新 users.quota;Docker Compose 内可设 postgres
|
||||||
EXTERNAL_POSTGRES_HOST=localhost
|
EXTERNAL_POSTGRES_HOST=localhost
|
||||||
EXTERNAL_POSTGRES_PORT=5432
|
EXTERNAL_POSTGRES_PORT=5432
|
||||||
EXTERNAL_POSTGRES_DATABASE=new-api
|
EXTERNAL_POSTGRES_DATABASE=new-api
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ sign = HMAC-SHA256(merchant_secret, content).hex()
|
|||||||
|
|
||||||
## 支付成功业务回调
|
## 支付成功业务回调
|
||||||
|
|
||||||
支付页只轮询本平台订单状态,不直接修改业务数据。支付宝、微信等渠道经服务端查单或验签通知确认实付成功后,服务端先按订单绑定的用户 ID 原子增加 PostgreSQL `users.quota`;只有积分入账成功,订单才会变为 `paid` 并返回充值成功。业务入账使用独立的唯一订单流水表 `multipay_recharge_credits`,重复通知和重复轮询不会重复增加积分。
|
支付页只轮询本平台订单状态,不直接修改业务数据。支付宝、微信等渠道经服务端查单或验签通知确认实付成功后,服务端先按订单绑定的用户 ID 原子增加 PostgreSQL `users.quota`;换算比例固定为 `1 积分 = 5000 quota`,页面积分按 `Math.ceil(quota / 5000)` 显示。只有积分入账成功,订单才会变为 `paid` 并返回充值成功。业务入账使用独立的唯一订单流水表 `multipay_recharge_credits`,重复通知和重复轮询不会重复增加积分。
|
||||||
|
|
||||||
平台向 `notify_url` 发送 JSON:
|
平台向 `notify_url` 发送 JSON:
|
||||||
|
|
||||||
@@ -103,7 +103,7 @@ sign = HMAC-SHA256(merchant_secret, content).hex()
|
|||||||
|
|
||||||
- 后台“用户管理”用于创建和停用本地用户,并查看积分余额、成功充值次数和累计金额。
|
- 后台“用户管理”用于创建和停用本地用户,并查看积分余额、成功充值次数和累计金额。
|
||||||
- 后台“充值套餐”可配置套餐名称、显示金额、到账积分、启用状态和展示顺序。
|
- 后台“充值套餐”可配置套餐名称、显示金额、到账积分、启用状态和展示顺序。
|
||||||
- 支付渠道确认成功后,服务端将套餐积分增加到 PostgreSQL `users.quota`;入账成功后才向支付页返回成功。
|
- 支付渠道确认成功后,服务端按“套餐积分 × 5000”增加 PostgreSQL `users.quota`;入账成功后才向支付页返回成功。
|
||||||
- 每个支付订单只允许生成一条业务入账流水;支付平台重复通知和页面重复轮询不会重复增加积分。
|
- 每个支付订单只允许生成一条业务入账流水;支付平台重复通知和页面重复轮询不会重复增加积分。
|
||||||
- 收银台默认展示该用户最近六个月的成功充值记录。
|
- 收银台默认展示该用户最近六个月的成功充值记录。
|
||||||
- 初始演示用户为 `demo-user`,仅用于本地验收,正式使用时请创建业务用户并停用演示用户。
|
- 初始演示用户为 `demo-user`,仅用于本地验收,正式使用时请创建业务用户并停用演示用户。
|
||||||
@@ -112,10 +112,18 @@ sign = HMAC-SHA256(merchant_secret, content).hex()
|
|||||||
|
|
||||||
- 充值记录中的已支付订单可以由管理员发起原路全额退款。
|
- 充值记录中的已支付订单可以由管理员发起原路全额退款。
|
||||||
- 管理员可选择是否回退积分;默认回退该订单充值时到账的积分,也可以填写其他非负整数。
|
- 管理员可选择是否回退积分;默认回退该订单充值时到账的积分,也可以填写其他非负整数。
|
||||||
- 支付渠道确认退款后,服务端按订单绑定的用户 ID 从 PostgreSQL `users.quota` 扣减积分,网页不会直接操作业务数据库。
|
- 支付渠道确认退款后,服务端按“回退积分 × 5000”从订单用户的 PostgreSQL `users.quota` 扣减额度,网页不会直接操作业务数据库。
|
||||||
- 退款请求号与积分回退流水均按订单保持唯一;重复点击、网络重试或渠道重复响应不会重复退款、重复扣减积分。
|
- 退款请求号与积分回退流水均按订单保持唯一;重复点击、网络重试或渠道重复响应不会重复退款、重复扣减积分。
|
||||||
- 微信退款处于处理中时,可在充值记录中点击“查询退款”继续确认状态。
|
- 微信退款处于处理中时,可在充值记录中点击“查询退款”继续确认状态。
|
||||||
|
|
||||||
|
历史版本曾按 `1 积分 = 1 quota` 写入流水。升级后在 PostgreSQL 可连接时执行一次:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
bun run migrate:quota-scale
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本只修复能够通过本地订单明确验证的旧比例流水;已经符合 5000 倍比例的数据会跳过,其他不一致会停止并回滚。
|
||||||
|
|
||||||
## 官方支付配置
|
## 官方支付配置
|
||||||
|
|
||||||
### 支付宝
|
### 支付宝
|
||||||
|
|||||||
+2
-1
@@ -6,7 +6,8 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "bun --watch src/server.ts",
|
"dev": "bun --watch src/server.ts",
|
||||||
"start": "bun src/server.ts",
|
"start": "bun src/server.ts",
|
||||||
"test": "bun test"
|
"test": "bun test",
|
||||||
|
"migrate:quota-scale": "bun scripts/migrate-quota-scale.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"pg": "^8.23.1",
|
"pg": "^8.23.1",
|
||||||
|
|||||||
+1
-1
@@ -20,6 +20,6 @@
|
|||||||
</section>
|
</section>
|
||||||
<div id="toast" class="toast"></div>
|
<div id="toast" class="toast"></div>
|
||||||
<div id="modal" class="modal hidden"><div class="modal-backdrop" data-close></div><div class="modal-card"><button class="modal-close" data-close>×</button><div id="modalContent"></div></div></div>
|
<div id="modal" class="modal hidden"><div class="modal-backdrop" data-close></div><div class="modal-card"><button class="modal-close" data-close>×</button><div id="modalContent"></div></div></div>
|
||||||
<script src="/assets/admin.js?v=20261102-scanqr" defer></script>
|
<script src="/assets/admin.js?v=20261109-quota-map" defer></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+1
-1
@@ -33,7 +33,7 @@ function openRefund(order,search=''){
|
|||||||
openModal();
|
openModal();
|
||||||
}
|
}
|
||||||
function wireFilters(fn){$('#filters').onsubmit=e=>{e.preventDefault();fn(new URLSearchParams(new FormData(e.target)).toString())}}
|
function wireFilters(fn){$('#filters').onsubmit=e=>{e.preventDefault();fn(new URLSearchParams(new FormData(e.target)).toString())}}
|
||||||
async function renderUsers(search=''){const d=await api(`/api/admin/users?search=${encodeURIComponent(search)}`);$('#content').innerHTML=`<div class="section-lead"><div><h2>用户管理</h2><p>数据来源:PostgreSQL users 表;支付确认后由服务端自动增加 quota 积分。</p></div></div><form id="userSearch" class="filter-bar"><label>用户 ID 或用户名<input name="search" value="${esc(search)}" placeholder="输入关键词"></label><button class="secondary-btn">查询</button></form><section class="panel"><div class="table-wrap"><table><thead><tr><th>用户 ID</th><th>用户名</th><th>可用积分</th><th>累计已使用</th><th>成功充值</th><th>累计金额</th><th>同步时间</th></tr></thead><tbody>${d.rows.length?d.rows.map(u=>`<tr><td><code>${esc(u.id)}</code></td><td><b>${esc(u.username||u.display_name)}</b></td><td class="points-cell">${Number(u.quota||0).toLocaleString('zh-CN')}</td><td class="points-cell">${Number(u.used_quota||0).toLocaleString('zh-CN')}</td><td>${u.paid_orders||0} 笔</td><td>${fmtMoney(u.paid_cents)}</td><td>${fmtTime(u.updated_at)}</td></tr>`).join(''):empty(7)}</tbody></table></div></section>`;$('#userSearch').onsubmit=e=>{e.preventDefault();renderUsers(new FormData(e.target).get('search')||'')}}
|
async function renderUsers(search=''){const d=await api(`/api/admin/users?search=${encodeURIComponent(search)}`);$('#content').innerHTML=`<div class="section-lead"><div><h2>用户管理</h2><p>数据来源:PostgreSQL users 表;每 1 积分对应 5000 quota。</p></div></div><form id="userSearch" class="filter-bar"><label>用户 ID 或用户名<input name="search" value="${esc(search)}" placeholder="输入关键词"></label><button class="secondary-btn">查询</button></form><section class="panel"><div class="table-wrap"><table><thead><tr><th>用户 ID</th><th>用户名</th><th>可用积分</th><th>累计已使用</th><th>成功充值</th><th>累计金额</th><th>同步时间</th></tr></thead><tbody>${d.rows.length?d.rows.map(u=>`<tr><td><code>${esc(u.id)}</code></td><td><b>${esc(u.username||u.display_name)}</b></td><td class="points-cell">${Number(u.points_balance||0).toLocaleString('zh-CN')}</td><td class="points-cell">${Number(u.used_points||0).toLocaleString('zh-CN')}</td><td>${u.paid_orders||0} 笔</td><td>${fmtMoney(u.paid_cents)}</td><td>${fmtTime(u.updated_at)}</td></tr>`).join(''):empty(7)}</tbody></table></div></section>`;$('#userSearch').onsubmit=e=>{e.preventDefault();renderUsers(new FormData(e.target).get('search')||'')}}
|
||||||
function openUser(user={}){const isNew=!user.id;$('#modalContent').innerHTML=`<span class="eyebrow">${isNew?'新增':'编辑'}用户</span><h2>用户资料</h2><form id="userForm" class="settings-form"><label class="field">用户 ID<input name="id" value="${esc(user.id||'')}" ${isNew?'':'readonly'} placeholder="业务系统中的唯一 ID" required></label><label class="field">显示名称<input name="display_name" value="${esc(user.display_name||'')}" required></label><label class="field">积分余额<input name="points_balance" type="number" min="0" step="1" value="${Number(user.points_balance||0)}"></label><label class="toggle-field"><input name="enabled" type="checkbox" ${isNew||user.enabled?'checked':''}><span></span>允许该用户充值</label><button class="primary-btn wide">保存用户</button></form>`;const form=$('#userForm');form.onsubmit=async e=>{e.preventDefault();const f=new FormData(form);const id=f.get('id');try{await api(`/api/admin/users/${encodeURIComponent(id)}`,{method:'PUT',body:JSON.stringify({...Object.fromEntries(f),enabled:f.has('enabled')})});closeModal();toast('用户已保存');renderUsers()}catch(err){toast(err.message,'error')}};openModal()}
|
function openUser(user={}){const isNew=!user.id;$('#modalContent').innerHTML=`<span class="eyebrow">${isNew?'新增':'编辑'}用户</span><h2>用户资料</h2><form id="userForm" class="settings-form"><label class="field">用户 ID<input name="id" value="${esc(user.id||'')}" ${isNew?'':'readonly'} placeholder="业务系统中的唯一 ID" required></label><label class="field">显示名称<input name="display_name" value="${esc(user.display_name||'')}" required></label><label class="field">积分余额<input name="points_balance" type="number" min="0" step="1" value="${Number(user.points_balance||0)}"></label><label class="toggle-field"><input name="enabled" type="checkbox" ${isNew||user.enabled?'checked':''}><span></span>允许该用户充值</label><button class="primary-btn wide">保存用户</button></form>`;const form=$('#userForm');form.onsubmit=async e=>{e.preventDefault();const f=new FormData(form);const id=f.get('id');try{await api(`/api/admin/users/${encodeURIComponent(id)}`,{method:'PUT',body:JSON.stringify({...Object.fromEntries(f),enabled:f.has('enabled')})});closeModal();toast('用户已保存');renderUsers()}catch(err){toast(err.message,'error')}};openModal()}
|
||||||
async function renderPackages(){const d=await api('/api/admin/packages');$('#content').innerHTML=`<div class="section-lead"><div><h2>充值套餐</h2><p>配置前台显示的充值金额、到账积分和展示顺序。</p></div><button id="addPackage" class="primary-btn">+ 新增套餐</button></div><div class="package-admin-grid">${d.rows.map(p=>`<article class="package-admin-card ${p.enabled?'':'disabled'}"><span>${esc(p.name)}</span><strong>${fmtMoney(p.amount_cents)}</strong><p>到账 <b>${Number(p.points).toLocaleString('zh-CN')}</b> 积分</p><small>排序 ${p.sort_order} · ${p.enabled?'已启用':'已停用'}</small><button class="secondary-btn wide" data-package="${p.id}">编辑套餐</button></article>`).join('')}</div>`;$('#addPackage').onclick=()=>openPackage();document.querySelectorAll('[data-package]').forEach(b=>b.onclick=()=>openPackage(d.rows.find(p=>String(p.id)===b.dataset.package)))}
|
async function renderPackages(){const d=await api('/api/admin/packages');$('#content').innerHTML=`<div class="section-lead"><div><h2>充值套餐</h2><p>配置前台显示的充值金额、到账积分和展示顺序。</p></div><button id="addPackage" class="primary-btn">+ 新增套餐</button></div><div class="package-admin-grid">${d.rows.map(p=>`<article class="package-admin-card ${p.enabled?'':'disabled'}"><span>${esc(p.name)}</span><strong>${fmtMoney(p.amount_cents)}</strong><p>到账 <b>${Number(p.points).toLocaleString('zh-CN')}</b> 积分</p><small>排序 ${p.sort_order} · ${p.enabled?'已启用':'已停用'}</small><button class="secondary-btn wide" data-package="${p.id}">编辑套餐</button></article>`).join('')}</div>`;$('#addPackage').onclick=()=>openPackage();document.querySelectorAll('[data-package]').forEach(b=>b.onclick=()=>openPackage(d.rows.find(p=>String(p.id)===b.dataset.package)))}
|
||||||
function openPackage(pkg={}){const isNew=!pkg.id;$('#modalContent').innerHTML=`<span class="eyebrow">${isNew?'新增':'编辑'}充值套餐</span><h2>套餐配置</h2><form id="packageForm" class="settings-form"><label class="field">套餐名称<input name="name" value="${esc(pkg.name||'')}" placeholder="例如 超值充值" required></label><div class="inline-fields"><label class="field">显示金额(元)<input name="amount" type="number" min="0.01" step="0.01" value="${pkg.id?(pkg.amount_cents/100).toFixed(2):''}" required></label><label class="field">到账积分<input name="points" type="number" min="0" step="1" value="${Number(pkg.points||0)}" required></label></div><label class="field">展示顺序<input name="sort_order" type="number" step="1" value="${Number(pkg.sort_order||0)}"></label><label class="toggle-field"><input name="enabled" type="checkbox" ${isNew||pkg.enabled?'checked':''}><span></span>在充值页显示</label><button class="primary-btn wide">保存套餐</button></form>`;const form=$('#packageForm');form.onsubmit=async e=>{e.preventDefault();const f=new FormData(form);try{await api(`/api/admin/packages/${pkg.id||'new'}`,{method:'PUT',body:JSON.stringify({...Object.fromEntries(f),enabled:f.has('enabled')})});closeModal();toast('充值套餐已保存');renderPackages()}catch(err){toast(err.message,'error')}};openModal()}
|
function openPackage(pkg={}){const isNew=!pkg.id;$('#modalContent').innerHTML=`<span class="eyebrow">${isNew?'新增':'编辑'}充值套餐</span><h2>套餐配置</h2><form id="packageForm" class="settings-form"><label class="field">套餐名称<input name="name" value="${esc(pkg.name||'')}" placeholder="例如 超值充值" required></label><div class="inline-fields"><label class="field">显示金额(元)<input name="amount" type="number" min="0.01" step="0.01" value="${pkg.id?(pkg.amount_cents/100).toFixed(2):''}" required></label><label class="field">到账积分<input name="points" type="number" min="0" step="1" value="${Number(pkg.points||0)}" required></label></div><label class="field">展示顺序<input name="sort_order" type="number" step="1" value="${Number(pkg.sort_order||0)}"></label><label class="toggle-field"><input name="enabled" type="checkbox" ${isNew||pkg.enabled?'checked':''}><span></span>在充值页显示</label><button class="primary-btn wide">保存套餐</button></form>`;const form=$('#packageForm');form.onsubmit=async e=>{e.preventDefault();const f=new FormData(form);try{await api(`/api/admin/packages/${pkg.id||'new'}`,{method:'PUT',body:JSON.stringify({...Object.fromEntries(f),enabled:f.has('enabled')})});closeModal();toast('充值套餐已保存');renderPackages()}catch(err){toast(err.message,'error')}};openModal()}
|
||||||
|
|||||||
@@ -48,6 +48,6 @@
|
|||||||
<div class="history-table-wrap"><table><thead><tr><th>充值时间</th><th>订单号</th><th>支付渠道</th><th>充值金额</th><th>获得积分</th></tr></thead><tbody id="historyBody"></tbody></table></div>
|
<div class="history-table-wrap"><table><thead><tr><th>充值时间</th><th>订单号</th><th>支付渠道</th><th>充值金额</th><th>获得积分</th></tr></thead><tbody id="historyBody"></tbody></table></div>
|
||||||
</section>
|
</section>
|
||||||
<footer class="checkout-footer"><span>支付过程受签名验证与金额校验保护</span><span>如有疑问请联系商户</span></footer>
|
<footer class="checkout-footer"><span>支付过程受签名验证与金额校验保护</span><span>如有疑问请联系商户</span></footer>
|
||||||
<script src="/assets/checkout.js?v=20261102-quota5000" defer></script>
|
<script src="/assets/checkout.js?v=20261109-quota-map" defer></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+3
-6
@@ -14,10 +14,7 @@ function showInvalidUser(value) { $('#userGate').classList.add('hidden'); $('#ch
|
|||||||
function channelName(channel) { return ({ alipay: '支付宝', wechat: '微信支付', mock: '本地模拟' })[channel] || channel; }
|
function channelName(channel) { return ({ alipay: '支付宝', wechat: '微信支付', mock: '本地模拟' })[channel] || channel; }
|
||||||
function channelIcon(channel) { return channel === 'alipay' ? '支' : channel === 'wechat' ? '微' : 'M'; }
|
function channelIcon(channel) { return channel === 'alipay' ? '支' : channel === 'wechat' ? '微' : 'M'; }
|
||||||
function formatTime(value) { return new Date(value).toLocaleString('zh-CN', { hour12: false }); }
|
function formatTime(value) { return new Date(value).toLocaleString('zh-CN', { hour12: false }); }
|
||||||
function formatAvailablePoints(value) {
|
function formatAvailablePoints(value) { return Number(value ?? 0).toLocaleString('zh-CN'); }
|
||||||
const quota = Number(value ?? 0);
|
|
||||||
return Math.ceil((Number.isFinite(quota) ? quota : 0) / 5000).toLocaleString('zh-CN');
|
|
||||||
}
|
|
||||||
|
|
||||||
function syncAmount() {
|
function syncAmount() {
|
||||||
const amount = state.selectedPackage ? (state.selectedPackage.amount_cents / 100).toFixed(2) : '0.00';
|
const amount = state.selectedPackage ? (state.selectedPackage.amount_cents / 100).toFixed(2) : '0.00';
|
||||||
@@ -63,7 +60,7 @@ async function init() {
|
|||||||
const response = await fetch(`/api/checkout/users/${encodeURIComponent(userId)}`); const data = await response.json();
|
const response = await fetch(`/api/checkout/users/${encodeURIComponent(userId)}`); const data = await response.json();
|
||||||
if (!response.ok) return showInvalidUser(userId);
|
if (!response.ok) return showInvalidUser(userId);
|
||||||
state.user = data.user; state.packages = data.packages;
|
state.user = data.user; state.packages = data.packages;
|
||||||
$('#userName').textContent = data.user.username || data.user.displayName; $('#userAvatar').textContent = (data.user.username || data.user.displayName || data.user.id).slice(0, 1).toUpperCase(); $('#pointsBalance').textContent = formatAvailablePoints(data.user.quota);
|
$('#userName').textContent = data.user.username || data.user.displayName; $('#userAvatar').textContent = (data.user.username || data.user.displayName || data.user.id).slice(0, 1).toUpperCase(); $('#pointsBalance').textContent = formatAvailablePoints(data.user.pointsBalance);
|
||||||
renderPackages(); renderHistory(data.history); await loadGateways(); syncAmount();
|
renderPackages(); renderHistory(data.history); await loadGateways(); syncAmount();
|
||||||
$('#userGate').classList.add('hidden'); $('#checkoutMain').classList.remove('hidden'); $('#historyPanel').classList.remove('hidden');
|
$('#userGate').classList.add('hidden'); $('#checkoutMain').classList.remove('hidden'); $('#historyPanel').classList.remove('hidden');
|
||||||
} catch { showInvalidUser(userId); }
|
} catch { showInvalidUser(userId); }
|
||||||
@@ -101,7 +98,7 @@ async function checkStatus() {
|
|||||||
async function refreshUserBalance() {
|
async function refreshUserBalance() {
|
||||||
try {
|
try {
|
||||||
const data = await fetch(`/api/checkout/users/${encodeURIComponent(state.user.id)}`).then((response) => response.json());
|
const data = await fetch(`/api/checkout/users/${encodeURIComponent(state.user.id)}`).then((response) => response.json());
|
||||||
if (data.user) { state.user = { ...state.user, ...data.user }; $('#pointsBalance').textContent = formatAvailablePoints(data.user.quota); }
|
if (data.user) { state.user = { ...state.user, ...data.user }; $('#pointsBalance').textContent = formatAvailablePoints(data.user.pointsBalance); }
|
||||||
} catch { /* 保留最后一次已加载的额度 */ }
|
} catch { /* 保留最后一次已加载的额度 */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { db, initializeDatabase } from "../src/db";
|
||||||
|
import { closeExternalDatabase, repairLegacyQuotaMappings } from "../src/external-db";
|
||||||
|
|
||||||
|
await initializeDatabase();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const rows = db.query(`SELECT id, user_id, points, refund_points, refund_points_enabled
|
||||||
|
FROM orders
|
||||||
|
WHERE user_id IS NOT NULL AND user_id <> ''
|
||||||
|
AND (points_credited=1 OR refund_status='success' OR status='refunded')`).all() as Array<{
|
||||||
|
id: string;
|
||||||
|
user_id: string;
|
||||||
|
points: number;
|
||||||
|
refund_points: number;
|
||||||
|
refund_points_enabled: number;
|
||||||
|
}>;
|
||||||
|
const result = await repairLegacyQuotaMappings(rows.map((row) => ({
|
||||||
|
orderId: String(row.id),
|
||||||
|
userId: String(row.user_id),
|
||||||
|
points: Number(row.points || 0),
|
||||||
|
refundPoints: row.refund_points_enabled ? Number(row.refund_points || 0) : 0
|
||||||
|
})));
|
||||||
|
console.log(`quota 映射迁移完成:修复入账 ${result.creditsRepaired} 条,修复退款 ${result.refundsRepaired} 条。`);
|
||||||
|
} finally {
|
||||||
|
await closeExternalDatabase();
|
||||||
|
db.close();
|
||||||
|
}
|
||||||
+106
-6
@@ -1,4 +1,5 @@
|
|||||||
import pg from "pg";
|
import pg from "pg";
|
||||||
|
import { pointsToQuota } from "./quota";
|
||||||
|
|
||||||
const pool = new pg.Pool({
|
const pool = new pg.Pool({
|
||||||
host: process.env.EXTERNAL_POSTGRES_HOST || "localhost",
|
host: process.env.EXTERNAL_POSTGRES_HOST || "localhost",
|
||||||
@@ -38,6 +39,13 @@ export type ExternalQuotaRefund = {
|
|||||||
providerRefundNo: string;
|
providerRefundNo: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type LegacyQuotaRepairOrder = {
|
||||||
|
orderId: string;
|
||||||
|
userId: string;
|
||||||
|
points: number;
|
||||||
|
refundPoints: number;
|
||||||
|
};
|
||||||
|
|
||||||
let creditTableReady: Promise<unknown> | null = null;
|
let creditTableReady: Promise<unknown> | null = null;
|
||||||
let refundTableReady: Promise<unknown> | null = null;
|
let refundTableReady: Promise<unknown> | null = null;
|
||||||
|
|
||||||
@@ -109,6 +117,7 @@ export async function searchExternalUsers(search = ""): Promise<ExternalUser[]>
|
|||||||
export async function creditExternalUserQuota(input: ExternalQuotaCredit): Promise<ExternalQuotaCreditResult> {
|
export async function creditExternalUserQuota(input: ExternalQuotaCredit): Promise<ExternalQuotaCreditResult> {
|
||||||
if (!Number.isSafeInteger(input.points) || input.points < 0) throw new Error("充值积分必须是非负整数");
|
if (!Number.isSafeInteger(input.points) || input.points < 0) throw new Error("充值积分必须是非负整数");
|
||||||
if (!input.orderId || !input.providerTradeNo) throw new Error("业务入账缺少支付订单标识");
|
if (!input.orderId || !input.providerTradeNo) throw new Error("业务入账缺少支付订单标识");
|
||||||
|
const quotaDelta = pointsToQuota(input.points);
|
||||||
await ensureCreditTable();
|
await ensureCreditTable();
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
@@ -122,7 +131,7 @@ export async function creditExternalUserQuota(input: ExternalQuotaCredit): Promi
|
|||||||
VALUES ($1, $2, $3::bigint, $4)
|
VALUES ($1, $2, $3::bigint, $4)
|
||||||
ON CONFLICT (order_id) DO NOTHING
|
ON CONFLICT (order_id) DO NOTHING
|
||||||
RETURNING user_id, quota_delta, provider_trade_no`,
|
RETURNING user_id, quota_delta, provider_trade_no`,
|
||||||
[input.orderId, input.userId, input.points, input.providerTradeNo]);
|
[input.orderId, input.userId, quotaDelta, input.providerTradeNo]);
|
||||||
|
|
||||||
if (!inserted.rowCount) {
|
if (!inserted.rowCount) {
|
||||||
const existing = await client.query<{
|
const existing = await client.query<{
|
||||||
@@ -134,10 +143,23 @@ export async function creditExternalUserQuota(input: ExternalQuotaCredit): Promi
|
|||||||
const credit = existing.rows[0];
|
const credit = existing.rows[0];
|
||||||
if (!credit
|
if (!credit
|
||||||
|| credit.user_id !== input.userId
|
|| credit.user_id !== input.userId
|
||||||
|| toNumber(credit.quota_delta) !== input.points
|
|
||||||
|| credit.provider_trade_no !== input.providerTradeNo) {
|
|| credit.provider_trade_no !== input.providerTradeNo) {
|
||||||
throw new Error("订单已存在不一致的业务入账记录");
|
throw new Error("订单已存在不一致的业务入账记录");
|
||||||
}
|
}
|
||||||
|
const storedQuotaDelta = toNumber(credit.quota_delta);
|
||||||
|
if (storedQuotaDelta !== quotaDelta) {
|
||||||
|
if (storedQuotaDelta !== input.points) throw new Error("订单已存在不一致的业务入账记录");
|
||||||
|
const correction = quotaDelta - storedQuotaDelta;
|
||||||
|
const repaired = await client.query<{ quota: unknown }>(
|
||||||
|
`UPDATE users SET quota = COALESCE(quota, 0) + $2::bigint
|
||||||
|
WHERE id::text = $1 RETURNING quota`, [input.userId, correction]);
|
||||||
|
if (!repaired.rows[0]) throw new Error("业务用户不存在,历史积分映射未修复");
|
||||||
|
await client.query(
|
||||||
|
"UPDATE multipay_recharge_credits SET quota_delta=$2::bigint WHERE order_id=$1",
|
||||||
|
[input.orderId, quotaDelta]);
|
||||||
|
await client.query("COMMIT");
|
||||||
|
return { credited: true, quota: toNumber(repaired.rows[0].quota) };
|
||||||
|
}
|
||||||
const user = await client.query<{ quota: unknown }>(
|
const user = await client.query<{ quota: unknown }>(
|
||||||
"SELECT quota FROM users WHERE id::text = $1 LIMIT 1", [input.userId]);
|
"SELECT quota FROM users WHERE id::text = $1 LIMIT 1", [input.userId]);
|
||||||
if (!user.rows[0]) throw new Error("业务用户不存在");
|
if (!user.rows[0]) throw new Error("业务用户不存在");
|
||||||
@@ -147,7 +169,7 @@ export async function creditExternalUserQuota(input: ExternalQuotaCredit): Promi
|
|||||||
|
|
||||||
const updated = await client.query<{ quota: unknown }>(
|
const updated = await client.query<{ quota: unknown }>(
|
||||||
`UPDATE users SET quota = COALESCE(quota, 0) + $2::bigint
|
`UPDATE users SET quota = COALESCE(quota, 0) + $2::bigint
|
||||||
WHERE id::text = $1 RETURNING quota`, [input.userId, input.points]);
|
WHERE id::text = $1 RETURNING quota`, [input.userId, quotaDelta]);
|
||||||
if (!updated.rows[0]) throw new Error("业务用户不存在,积分未入账");
|
if (!updated.rows[0]) throw new Error("业务用户不存在,积分未入账");
|
||||||
await client.query("COMMIT");
|
await client.query("COMMIT");
|
||||||
return { credited: true, quota: toNumber(updated.rows[0].quota) };
|
return { credited: true, quota: toNumber(updated.rows[0].quota) };
|
||||||
@@ -162,6 +184,7 @@ export async function creditExternalUserQuota(input: ExternalQuotaCredit): Promi
|
|||||||
export async function refundExternalUserQuota(input: ExternalQuotaRefund): Promise<ExternalQuotaCreditResult> {
|
export async function refundExternalUserQuota(input: ExternalQuotaRefund): Promise<ExternalQuotaCreditResult> {
|
||||||
if (!Number.isSafeInteger(input.points) || input.points < 0) throw new Error("回退积分必须是非负整数");
|
if (!Number.isSafeInteger(input.points) || input.points < 0) throw new Error("回退积分必须是非负整数");
|
||||||
if (!input.orderId || !input.providerRefundNo) throw new Error("积分回退缺少退款标识");
|
if (!input.orderId || !input.providerRefundNo) throw new Error("积分回退缺少退款标识");
|
||||||
|
const quotaDelta = pointsToQuota(input.points);
|
||||||
await ensureRefundTable();
|
await ensureRefundTable();
|
||||||
const client = await pool.connect();
|
const client = await pool.connect();
|
||||||
try {
|
try {
|
||||||
@@ -170,15 +193,29 @@ export async function refundExternalUserQuota(input: ExternalQuotaRefund): Promi
|
|||||||
`INSERT INTO multipay_refund_debits (order_id, user_id, quota_delta, provider_refund_no)
|
`INSERT INTO multipay_refund_debits (order_id, user_id, quota_delta, provider_refund_no)
|
||||||
VALUES ($1, $2, $3::bigint, $4) ON CONFLICT (order_id) DO NOTHING
|
VALUES ($1, $2, $3::bigint, $4) ON CONFLICT (order_id) DO NOTHING
|
||||||
RETURNING user_id, quota_delta, provider_refund_no`,
|
RETURNING user_id, quota_delta, provider_refund_no`,
|
||||||
[input.orderId, input.userId, input.points, input.providerRefundNo]);
|
[input.orderId, input.userId, quotaDelta, input.providerRefundNo]);
|
||||||
if (!inserted.rowCount) {
|
if (!inserted.rowCount) {
|
||||||
const existing = await client.query<{ user_id: string; quota_delta: unknown; provider_refund_no: string }>(
|
const existing = await client.query<{ user_id: string; quota_delta: unknown; provider_refund_no: string }>(
|
||||||
`SELECT user_id, quota_delta, provider_refund_no FROM multipay_refund_debits WHERE order_id=$1`, [input.orderId]);
|
`SELECT user_id, quota_delta, provider_refund_no FROM multipay_refund_debits WHERE order_id=$1`, [input.orderId]);
|
||||||
const debit = existing.rows[0];
|
const debit = existing.rows[0];
|
||||||
if (!debit || debit.user_id !== input.userId || toNumber(debit.quota_delta) !== input.points
|
if (!debit || debit.user_id !== input.userId
|
||||||
|| debit.provider_refund_no !== input.providerRefundNo) {
|
|| debit.provider_refund_no !== input.providerRefundNo) {
|
||||||
throw new Error("订单已存在不一致的积分回退记录");
|
throw new Error("订单已存在不一致的积分回退记录");
|
||||||
}
|
}
|
||||||
|
const storedQuotaDelta = toNumber(debit.quota_delta);
|
||||||
|
if (storedQuotaDelta !== quotaDelta) {
|
||||||
|
if (storedQuotaDelta !== input.points) throw new Error("订单已存在不一致的积分回退记录");
|
||||||
|
const correction = quotaDelta - storedQuotaDelta;
|
||||||
|
const repaired = await client.query<{ quota: unknown }>(
|
||||||
|
`UPDATE users SET quota=COALESCE(quota,0)-$2::bigint
|
||||||
|
WHERE id::text=$1 RETURNING quota`, [input.userId, correction]);
|
||||||
|
if (!repaired.rows[0]) throw new Error("业务用户不存在,历史积分回退映射未修复");
|
||||||
|
await client.query(
|
||||||
|
"UPDATE multipay_refund_debits SET quota_delta=$2::bigint WHERE order_id=$1",
|
||||||
|
[input.orderId, quotaDelta]);
|
||||||
|
await client.query("COMMIT");
|
||||||
|
return { credited: true, quota: toNumber(repaired.rows[0].quota) };
|
||||||
|
}
|
||||||
const user = await client.query<{ quota: unknown }>("SELECT quota FROM users WHERE id::text=$1 LIMIT 1", [input.userId]);
|
const user = await client.query<{ quota: unknown }>("SELECT quota FROM users WHERE id::text=$1 LIMIT 1", [input.userId]);
|
||||||
if (!user.rows[0]) throw new Error("业务用户不存在");
|
if (!user.rows[0]) throw new Error("业务用户不存在");
|
||||||
await client.query("COMMIT");
|
await client.query("COMMIT");
|
||||||
@@ -186,7 +223,7 @@ export async function refundExternalUserQuota(input: ExternalQuotaRefund): Promi
|
|||||||
}
|
}
|
||||||
const updated = await client.query<{ quota: unknown }>(
|
const updated = await client.query<{ quota: unknown }>(
|
||||||
`UPDATE users SET quota=COALESCE(quota,0)-$2::bigint WHERE id::text=$1 RETURNING quota`,
|
`UPDATE users SET quota=COALESCE(quota,0)-$2::bigint WHERE id::text=$1 RETURNING quota`,
|
||||||
[input.userId, input.points]);
|
[input.userId, quotaDelta]);
|
||||||
if (!updated.rows[0]) throw new Error("业务用户不存在,积分未回退");
|
if (!updated.rows[0]) throw new Error("业务用户不存在,积分未回退");
|
||||||
await client.query("COMMIT");
|
await client.query("COMMIT");
|
||||||
return { credited: true, quota: toNumber(updated.rows[0].quota) };
|
return { credited: true, quota: toNumber(updated.rows[0].quota) };
|
||||||
@@ -198,6 +235,69 @@ export async function refundExternalUserQuota(input: ExternalQuotaRefund): Promi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function repairLegacyQuotaMappings(orders: LegacyQuotaRepairOrder[]) {
|
||||||
|
if (!orders.length) return { creditsRepaired: 0, refundsRepaired: 0 };
|
||||||
|
await Promise.all([ensureCreditTable(), ensureRefundTable()]);
|
||||||
|
const client = await pool.connect();
|
||||||
|
let creditsRepaired = 0;
|
||||||
|
let refundsRepaired = 0;
|
||||||
|
try {
|
||||||
|
await client.query("BEGIN");
|
||||||
|
for (const order of orders) {
|
||||||
|
const expectedCredit = pointsToQuota(order.points);
|
||||||
|
const creditResult = await client.query<{ user_id: string; quota_delta: unknown }>(
|
||||||
|
"SELECT user_id, quota_delta FROM multipay_recharge_credits WHERE order_id=$1",
|
||||||
|
[order.orderId]);
|
||||||
|
const credit = creditResult.rows[0];
|
||||||
|
if (credit) {
|
||||||
|
if (credit.user_id !== order.userId) throw new Error(`订单 ${order.orderId} 的入账用户不一致`);
|
||||||
|
const storedCredit = toNumber(credit.quota_delta);
|
||||||
|
if (storedCredit !== expectedCredit) {
|
||||||
|
if (storedCredit !== order.points) throw new Error(`订单 ${order.orderId} 的入账额度不是可识别的旧格式`);
|
||||||
|
const correction = expectedCredit - storedCredit;
|
||||||
|
const updated = await client.query(
|
||||||
|
"UPDATE users SET quota=COALESCE(quota,0)+$2::bigint WHERE id::text=$1",
|
||||||
|
[order.userId, correction]);
|
||||||
|
if (!updated.rowCount) throw new Error(`订单 ${order.orderId} 对应的业务用户不存在`);
|
||||||
|
await client.query(
|
||||||
|
"UPDATE multipay_recharge_credits SET quota_delta=$2::bigint WHERE order_id=$1",
|
||||||
|
[order.orderId, expectedCredit]);
|
||||||
|
creditsRepaired += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (order.refundPoints <= 0) continue;
|
||||||
|
const expectedRefund = pointsToQuota(order.refundPoints);
|
||||||
|
const refundResult = await client.query<{ user_id: string; quota_delta: unknown }>(
|
||||||
|
"SELECT user_id, quota_delta FROM multipay_refund_debits WHERE order_id=$1",
|
||||||
|
[order.orderId]);
|
||||||
|
const refund = refundResult.rows[0];
|
||||||
|
if (!refund) continue;
|
||||||
|
if (refund.user_id !== order.userId) throw new Error(`订单 ${order.orderId} 的退款用户不一致`);
|
||||||
|
const storedRefund = toNumber(refund.quota_delta);
|
||||||
|
if (storedRefund !== expectedRefund) {
|
||||||
|
if (storedRefund !== order.refundPoints) throw new Error(`订单 ${order.orderId} 的退款额度不是可识别的旧格式`);
|
||||||
|
const correction = expectedRefund - storedRefund;
|
||||||
|
const updated = await client.query(
|
||||||
|
"UPDATE users SET quota=COALESCE(quota,0)-$2::bigint WHERE id::text=$1",
|
||||||
|
[order.userId, correction]);
|
||||||
|
if (!updated.rowCount) throw new Error(`订单 ${order.orderId} 对应的业务用户不存在`);
|
||||||
|
await client.query(
|
||||||
|
"UPDATE multipay_refund_debits SET quota_delta=$2::bigint WHERE order_id=$1",
|
||||||
|
[order.orderId, expectedRefund]);
|
||||||
|
refundsRepaired += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await client.query("COMMIT");
|
||||||
|
return { creditsRepaired, refundsRepaired };
|
||||||
|
} catch (error) {
|
||||||
|
await client.query("ROLLBACK").catch(() => {});
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function closeExternalDatabase() {
|
export async function closeExternalDatabase() {
|
||||||
await pool.end();
|
await pool.end();
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
export const QUOTA_PER_POINT = 5000;
|
||||||
|
|
||||||
|
export function pointsToQuota(points: unknown): number {
|
||||||
|
const value = Number(points);
|
||||||
|
if (!Number.isSafeInteger(value) || value < 0) {
|
||||||
|
throw new Error("积分必须是非负安全整数");
|
||||||
|
}
|
||||||
|
const quota = value * QUOTA_PER_POINT;
|
||||||
|
if (!Number.isSafeInteger(quota)) {
|
||||||
|
throw new Error("积分换算后的 quota 超出安全整数范围");
|
||||||
|
}
|
||||||
|
return quota;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function quotaToPoints(quota: unknown): number {
|
||||||
|
const value = Number(quota ?? 0);
|
||||||
|
if (!Number.isFinite(value)) return 0;
|
||||||
|
return Math.ceil(value / QUOTA_PER_POINT);
|
||||||
|
}
|
||||||
+10
-5
@@ -10,6 +10,7 @@ import {
|
|||||||
import { isIP } from "node:net";
|
import { isIP } from "node:net";
|
||||||
import { lookup } from "node:dns/promises";
|
import { lookup } from "node:dns/promises";
|
||||||
import { creditExternalUserQuota, getExternalUser, refundExternalUserQuota, searchExternalUsers, type ExternalUser } from "./external-db";
|
import { creditExternalUserQuota, getExternalUser, refundExternalUserQuota, searchExternalUsers, type ExternalUser } from "./external-db";
|
||||||
|
import { pointsToQuota, quotaToPoints } from "./quota";
|
||||||
|
|
||||||
await initializeDatabase();
|
await initializeDatabase();
|
||||||
|
|
||||||
@@ -78,11 +79,12 @@ function getGateway(id: string): GatewayRecord | null {
|
|||||||
|
|
||||||
function syncExternalUser(user: ExternalUser) {
|
function syncExternalUser(user: ExternalUser) {
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
|
const pointsBalance = quotaToPoints(user.quota);
|
||||||
db.transaction(() => {
|
db.transaction(() => {
|
||||||
db.query(`INSERT INTO users (id, display_name, points_balance, enabled, created_at, updated_at)
|
db.query(`INSERT INTO users (id, display_name, points_balance, enabled, created_at, updated_at)
|
||||||
VALUES (?, ?, 0, 1, ?, ?) ON CONFLICT(id) DO UPDATE SET
|
VALUES (?, ?, ?, 1, ?, ?) ON CONFLICT(id) DO UPDATE SET
|
||||||
display_name=excluded.display_name, updated_at=excluded.updated_at`)
|
display_name=excluded.display_name, points_balance=excluded.points_balance, updated_at=excluded.updated_at`)
|
||||||
.run(user.id, user.username, now, now);
|
.run(user.id, user.username, pointsBalance, now, now);
|
||||||
db.query(`INSERT INTO external_user_links
|
db.query(`INSERT INTO external_user_links
|
||||||
(local_user_id, external_user_id, external_username, last_synced_at)
|
(local_user_id, external_user_id, external_username, last_synced_at)
|
||||||
VALUES (?, ?, ?, ?) ON CONFLICT(local_user_id) DO UPDATE SET
|
VALUES (?, ?, ?, ?) ON CONFLICT(local_user_id) DO UPDATE SET
|
||||||
@@ -397,8 +399,9 @@ const server = Bun.serve({
|
|||||||
id: externalUser.id,
|
id: externalUser.id,
|
||||||
displayName: externalUser.username,
|
displayName: externalUser.username,
|
||||||
username: externalUser.username,
|
username: externalUser.username,
|
||||||
pointsBalance: externalUser.quota,
|
pointsBalance: quotaToPoints(externalUser.quota),
|
||||||
quota: externalUser.quota,
|
quota: externalUser.quota,
|
||||||
|
usedPoints: quotaToPoints(externalUser.usedQuota),
|
||||||
usedQuota: externalUser.usedQuota
|
usedQuota: externalUser.usedQuota
|
||||||
},
|
},
|
||||||
packages,
|
packages,
|
||||||
@@ -661,8 +664,9 @@ const server = Bun.serve({
|
|||||||
id: user.id,
|
id: user.id,
|
||||||
display_name: user.username,
|
display_name: user.username,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
points_balance: user.quota,
|
points_balance: quotaToPoints(user.quota),
|
||||||
quota: user.quota,
|
quota: user.quota,
|
||||||
|
used_points: quotaToPoints(user.usedQuota),
|
||||||
used_quota: user.usedQuota,
|
used_quota: user.usedQuota,
|
||||||
enabled: 1,
|
enabled: 1,
|
||||||
updated_at: link?.last_synced_at || new Date().toISOString(),
|
updated_at: link?.last_synced_at || new Date().toISOString(),
|
||||||
@@ -689,6 +693,7 @@ const server = Bun.serve({
|
|||||||
const name = String(input.name || "充值套餐").trim().slice(0, 60);
|
const name = String(input.name || "充值套餐").trim().slice(0, 60);
|
||||||
const amountCents = moneyToCents(input.amount);
|
const amountCents = moneyToCents(input.amount);
|
||||||
const points = Math.max(0, Math.floor(Number(input.points) || 0));
|
const points = Math.max(0, Math.floor(Number(input.points) || 0));
|
||||||
|
pointsToQuota(points);
|
||||||
const sortOrder = Math.floor(Number(input.sort_order) || 0);
|
const sortOrder = Math.floor(Number(input.sort_order) || 0);
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
const rawId = decodeURIComponent(packageAdminMatch[1]);
|
const rawId = decodeURIComponent(packageAdminMatch[1]);
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { pointsToQuota, quotaToPoints, QUOTA_PER_POINT } from "../src/quota";
|
||||||
|
|
||||||
|
describe("quota mapping", () => {
|
||||||
|
test("uses 5000 quota units for one point", () => {
|
||||||
|
expect(QUOTA_PER_POINT).toBe(5000);
|
||||||
|
expect(pointsToQuota(1)).toBe(5000);
|
||||||
|
expect(pointsToQuota(520)).toBe(2_600_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rounds displayed points upward", () => {
|
||||||
|
expect(quotaToPoints(0)).toBe(0);
|
||||||
|
expect(quotaToPoints(1)).toBe(1);
|
||||||
|
expect(quotaToPoints(5000)).toBe(1);
|
||||||
|
expect(quotaToPoints(5001)).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects invalid point values", () => {
|
||||||
|
expect(() => pointsToQuota(-1)).toThrow();
|
||||||
|
expect(() => pointsToQuota(1.5)).toThrow();
|
||||||
|
expect(() => pointsToQuota(Number.MAX_SAFE_INTEGER)).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user