feat(supply-chain): 平台账单改用服务器 Chromium RPA
This commit is contained in:
parent
25b263540b
commit
6b32140aaa
@ -37,6 +37,7 @@ JST_RPA_PROFILE_DIR=
|
||||
JST_RPA_CHROME_EXECUTABLE=
|
||||
JST_RPA_HEADLESS=true
|
||||
JST_RPA_DEBUG_PORT=9222
|
||||
JST_RPA_DOWNLOAD_DIR=
|
||||
JST_RPA_PYTHON=/usr/bin/python3
|
||||
# 聚水潭账号密码登录,仅配置在服务器私有环境文件,禁止提交真实值。
|
||||
JST_RPA_LOGIN_ID=
|
||||
@ -151,8 +152,8 @@ DINGTALK_JD_CONSUMPTION_ORDER_WEBHOOK_SECRET=
|
||||
DINGTALK_JD_CONSUMPTION_ORDER_WEBHOOK_TIMEOUT_MS=10000
|
||||
DINGTALK_JD_CONSUMPTION_ORDER_PUSH_ENABLED=false
|
||||
|
||||
# 人工生成平台账单时调用 Codex CLI;留空时自动查找常见安装路径。
|
||||
PLATFORM_BILL_CODEX_BIN=
|
||||
# 人工生成平台账单时,服务器 Chromium RPA 的异步导出等待上限(毫秒)。
|
||||
PLATFORM_BILL_RPA_TASK_TIMEOUT_MS=21600000
|
||||
|
||||
STORE_ACCOUNT_NOTIFICATION_RETRY_SECRET=
|
||||
|
||||
|
||||
@ -38,6 +38,15 @@
|
||||
`node_modules/.bin/tsx scripts/jst-shop-goods-rpa.ts --action=login`
|
||||
验证登录态,不执行链接导出。
|
||||
|
||||
## 各平台账单人工生成
|
||||
|
||||
- 人工生成按钮不再启动 Codex CLI,直接使用同一套服务器 Chromium / RPA 浏览器。
|
||||
- 运行入口:`scripts/platform-bills-rpa.ts`,由 `scripts/run-platform-bill-generation-job.mjs` 异步启动。
|
||||
- 默认复用 `furniture-jst-rpa-browser.service`;Linux 执行前会自动重启该服务,浏览器地址由 `JST_RPA_BROWSER_URL` 指定。
|
||||
- 下载目录由 `JST_RPA_DOWNLOAD_DIR` 指定,未配置时使用当前用户 `Downloads`;异步导出等待上限由 `PLATFORM_BILL_RPA_TASK_TIMEOUT_MS` 指定。
|
||||
- 账户密码登录态复用 `JST_RPA_LOGIN_ID` / `JST_RPA_LOGIN_PASSWORD`;扫码、验证码或密码错误会明确失败并保留任务日志。
|
||||
- 大文件通过 `NightPlan/GetNightList` 查询异步任务;分片 ZIP 会保存为 `.zip`,再由按月导入器合并。
|
||||
|
||||
## 限价每日快照
|
||||
|
||||
- 生产安装入口:`furniture-3d-system/scripts/install-limit-price-snapshot-systemd-timer.sh`。
|
||||
|
||||
551
furniture-3d-system/scripts/platform-bills-rpa.ts
Normal file
551
furniture-3d-system/scripts/platform-bills-rpa.ts
Normal file
@ -0,0 +1,551 @@
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import {
|
||||
mkdirSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs'
|
||||
import { basename, join, resolve } from 'node:path'
|
||||
import { loadEnvConfig } from '@next/env'
|
||||
import puppeteer, { type Page } from 'puppeteer'
|
||||
import {
|
||||
ensureJstRpaLogin,
|
||||
} from '@/server/services/supply-chain-discontinuation-rpa-login'
|
||||
|
||||
loadEnvConfig(process.cwd())
|
||||
|
||||
const ERP_URL = 'https://www.erp321.com/epaas'
|
||||
const PLATFORM_BILL_URL = 'https://ss.erp321.com/process/platform-bill-new'
|
||||
const BROWSER_URL = process.env.JST_RPA_BROWSER_URL?.trim() || 'http://127.0.0.1:9222'
|
||||
const BROWSER_SERVICE = process.env.JST_RPA_BROWSER_SERVICE?.trim()
|
||||
|| 'furniture-jst-rpa-browser.service'
|
||||
const DOWNLOAD_DIR = process.env.JST_RPA_DOWNLOAD_DIR?.trim()
|
||||
|| join(process.env.HOME ?? '', 'Downloads')
|
||||
const RPA_PROFILE_DIR = process.env.JST_RPA_PROFILE_DIR?.trim()
|
||||
|| join(
|
||||
process.env.HOME ?? '',
|
||||
process.platform === 'darwin'
|
||||
? 'Library/Application Support/Furniture3D/JstRpaProfile'
|
||||
: '.local/share/furniture3d/JstRpaProfile',
|
||||
)
|
||||
const TSX_CLI = resolve('node_modules/tsx/dist/cli.mjs')
|
||||
const DEFAULT_TASK_TIMEOUT_MS = 6 * 60 * 60 * 1_000
|
||||
|
||||
type BillConfig = {
|
||||
key: string
|
||||
platformKey: string
|
||||
platformName: string
|
||||
groupTableKey: string
|
||||
groupKey: string
|
||||
unType: string
|
||||
channel: string
|
||||
dateField: string
|
||||
dateLabel: string
|
||||
groupName: string
|
||||
fileNamePrefix: string
|
||||
}
|
||||
|
||||
const BILLS: readonly BillConfig[] = [
|
||||
{
|
||||
key: 'taoxi-alipay',
|
||||
platformKey: 'alipay',
|
||||
platformName: '淘系',
|
||||
groupTableKey: 'billrecords_ALIPAY',
|
||||
groupKey: 'ALIPAY',
|
||||
unType: 'alipay_ALIPAY',
|
||||
channel: 'alipayCSV',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '发生时间',
|
||||
groupName: '支付宝账单',
|
||||
fileNamePrefix: '支付宝',
|
||||
},
|
||||
{
|
||||
key: 'taoxi-wechat',
|
||||
platformKey: 'alipay',
|
||||
platformName: '淘系',
|
||||
groupTableKey: 'billrecords_WeChatPay',
|
||||
groupKey: 'WeChatPay',
|
||||
unType: 'alipay_WeChatPay',
|
||||
channel: 'WeChatPay',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '入账时间',
|
||||
groupName: '微信账单',
|
||||
fileNamePrefix: '微信',
|
||||
},
|
||||
{
|
||||
key: 'jd-statement',
|
||||
platformKey: 'jos',
|
||||
platformName: '京东商城',
|
||||
groupTableKey: 'billrecords_JOS',
|
||||
groupKey: 'JOS',
|
||||
unType: 'jos_JOS',
|
||||
channel: 'JOS',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '费用结算时间',
|
||||
groupName: '京东日账单',
|
||||
fileNamePrefix: '京东商城京东日账单',
|
||||
},
|
||||
{
|
||||
key: 'jd-flow',
|
||||
platformKey: 'jos',
|
||||
platformName: '京东商城',
|
||||
groupTableKey: 'billrecords_JDWALLET',
|
||||
groupKey: 'JDWALLET',
|
||||
unType: 'jos_JDWALLET',
|
||||
channel: 'JDWALLET',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '费用结算时间',
|
||||
groupName: '京东钱包',
|
||||
fileNamePrefix: '京东商城京东钱包',
|
||||
},
|
||||
{
|
||||
key: 'pinduoduo-bill',
|
||||
platformKey: 'pinduoduoplatform',
|
||||
platformName: '拼多多',
|
||||
groupTableKey: 'billrecords_PinduoduoImport',
|
||||
groupKey: 'PinduoduoImport',
|
||||
unType: 'pinduoduoplatform_PinduoduoImport',
|
||||
channel: 'PinduoduoImport',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '发生时间',
|
||||
groupName: '拼多多货款账单',
|
||||
fileNamePrefix: '拼多多拼多多货款账单',
|
||||
},
|
||||
{
|
||||
key: 'douyin-bill',
|
||||
platformKey: 'toutiaofxg',
|
||||
platformName: '头条放心购',
|
||||
groupTableKey: 'billrecords_TOUTIAOFXGZJ',
|
||||
groupKey: 'TOUTIAOFXGZJ',
|
||||
unType: 'toutiaofxg_TOUTIAOFXGZJ',
|
||||
channel: 'TOUTIAOFXGZJ',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '结算时间',
|
||||
groupName: '头条资金流水',
|
||||
fileNamePrefix: '头条放心购头条资金流水',
|
||||
},
|
||||
{
|
||||
key: 'xiaohongshu-bill',
|
||||
platformKey: 'xiaohs',
|
||||
platformName: '小红书',
|
||||
groupTableKey: 'billrecords_XiaohsTran',
|
||||
groupKey: 'XiaohsTran',
|
||||
unType: 'xiaohs_XiaohsTran',
|
||||
channel: 'XiaohsTran',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '结算时间',
|
||||
groupName: '小红书订单结算明细',
|
||||
fileNamePrefix: '小红书小红书订单结算明细',
|
||||
},
|
||||
{
|
||||
key: 'dewu-bill',
|
||||
platformKey: 'dewu',
|
||||
platformName: '得物',
|
||||
groupTableKey: 'billrecords_Dewu',
|
||||
groupKey: 'Dewu',
|
||||
unType: 'dewu_Dewu',
|
||||
channel: 'DewuJS,Dewuhsmj,Dewu,DewuTK,DewuKJ',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '发货时间/退货时间',
|
||||
groupName: '得物',
|
||||
fileNamePrefix: '得物得物',
|
||||
},
|
||||
{
|
||||
key: 'dewu-deposit',
|
||||
platformKey: 'dewu',
|
||||
platformName: '得物',
|
||||
groupTableKey: 'dewu_deposit_select_template',
|
||||
groupKey: 'Dewubzj',
|
||||
unType: 'dewu_Dewubzj',
|
||||
channel: 'Dewubzj',
|
||||
dateField: 'ab.create_time',
|
||||
dateLabel: '变更时间',
|
||||
groupName: '得物保证金',
|
||||
fileNamePrefix: '得物得物保证金',
|
||||
},
|
||||
] as const
|
||||
|
||||
function log(stage: string, detail = '') {
|
||||
console.log(`[platform-bills-rpa] ${new Date().toISOString()} ${stage}${detail ? ` ${detail}` : ''}`)
|
||||
}
|
||||
|
||||
function argument(name: string) {
|
||||
return process.argv.find((value) => value.startsWith(`--${name}=`))
|
||||
?.slice(name.length + 3)
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms))
|
||||
}
|
||||
|
||||
function periodBounds(periodKey: string) {
|
||||
const [year, month] = periodKey.split('-').map(Number)
|
||||
const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate()
|
||||
return {
|
||||
start: `${periodKey}-01`,
|
||||
end: `${periodKey}-${String(lastDay).padStart(2, '0')}`,
|
||||
}
|
||||
}
|
||||
|
||||
function envelope(data: unknown, pageSize = 25) {
|
||||
return {
|
||||
uid: '',
|
||||
coid: '',
|
||||
ip: '',
|
||||
page: { currentPage: 1, pageSize },
|
||||
data,
|
||||
ssProjectType: 'SS',
|
||||
ssClientType: 'Web',
|
||||
}
|
||||
}
|
||||
|
||||
function billQuery(config: BillConfig, start: string, end: string, isExport = false) {
|
||||
return {
|
||||
isExport,
|
||||
groupTableKey: config.groupTableKey,
|
||||
ygUseItem: false,
|
||||
groupKey: config.groupKey,
|
||||
unType: config.unType,
|
||||
conditions: [
|
||||
{
|
||||
serachFldName: config.dateField,
|
||||
serachColName: config.dateLabel,
|
||||
value: start,
|
||||
operatorSymbol: 'GreaterThanOrEqual',
|
||||
},
|
||||
{
|
||||
serachFldName: config.dateField,
|
||||
serachColName: config.dateLabel,
|
||||
value: end,
|
||||
operatorSymbol: 'LessThan',
|
||||
},
|
||||
{
|
||||
serachFldName: 'ab.channel',
|
||||
serachColName: '渠道',
|
||||
value: config.channel,
|
||||
operatorSymbol: 'In',
|
||||
},
|
||||
],
|
||||
platformKey: config.platformKey,
|
||||
}
|
||||
}
|
||||
|
||||
async function requestJson(
|
||||
page: Page,
|
||||
path: string,
|
||||
body: unknown,
|
||||
) {
|
||||
return page.evaluate(async ({ path, body }) => {
|
||||
const response = await fetch(`https://pf.erp321.com${path}?uvalue=pfcweb_process.platform-bill-new`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'content-type': 'application/json;charset=UTF-8' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
const text = await response.text()
|
||||
let payload: Record<string, unknown> | null = null
|
||||
try {
|
||||
payload = JSON.parse(text)
|
||||
} catch {
|
||||
throw new Error(`聚胜算接口返回非 JSON:HTTP ${response.status}`)
|
||||
}
|
||||
if (!response.ok || payload.code !== 0) {
|
||||
throw new Error(String(payload.msg || `聚胜算接口失败:HTTP ${response.status}`))
|
||||
}
|
||||
return payload
|
||||
}, { path, body })
|
||||
}
|
||||
|
||||
async function ensureRpaBrowser() {
|
||||
const ready = async () => {
|
||||
try {
|
||||
const response = await fetch(`${BROWSER_URL}/json/version`, {
|
||||
signal: AbortSignal.timeout(2_000),
|
||||
})
|
||||
return response.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if (process.platform === 'linux') {
|
||||
const result = spawnSync('systemctl', ['restart', BROWSER_SERVICE], {
|
||||
stdio: 'inherit',
|
||||
})
|
||||
if (result.status !== 0) {
|
||||
console.warn(`[platform-bills-rpa] 重启 RPA 浏览器服务失败:${BROWSER_SERVICE}`)
|
||||
}
|
||||
}
|
||||
if (await ready()) return
|
||||
if (process.platform === 'darwin') {
|
||||
spawnSync('open', [
|
||||
'-na',
|
||||
'Google Chrome',
|
||||
'--args',
|
||||
`--user-data-dir=${RPA_PROFILE_DIR}`,
|
||||
'--profile-directory=Default',
|
||||
`--remote-debugging-port=${new URL(BROWSER_URL).port || '9222'}`,
|
||||
'--no-first-run',
|
||||
'--disable-sync',
|
||||
ERP_URL,
|
||||
], { stdio: 'inherit' })
|
||||
}
|
||||
const deadline = Date.now() + 60_000
|
||||
while (Date.now() < deadline) {
|
||||
if (await ready()) return
|
||||
await sleep(1_000)
|
||||
}
|
||||
throw new Error(
|
||||
`聚胜算 RPA 浏览器不可用:${BROWSER_URL}。请启动 ${BROWSER_SERVICE} 并确认登录态。`,
|
||||
)
|
||||
}
|
||||
|
||||
async function findPlatformPage(browser: Awaited<ReturnType<typeof puppeteer.connect>>) {
|
||||
const existing = (await browser.pages()).find((candidate) => (
|
||||
candidate.url().startsWith(PLATFORM_BILL_URL)
|
||||
))
|
||||
const page = existing ?? await browser.newPage()
|
||||
const ownedPage = !existing
|
||||
if (ownedPage) {
|
||||
await page.goto(ERP_URL, { waitUntil: 'domcontentloaded', timeout: 120_000 })
|
||||
await ensureJstRpaLogin(page, {
|
||||
env: process.env,
|
||||
log: (message) => console.log(message),
|
||||
})
|
||||
await page.goto(PLATFORM_BILL_URL, {
|
||||
waitUntil: 'domcontentloaded',
|
||||
timeout: 120_000,
|
||||
})
|
||||
}
|
||||
const readyDeadline = Date.now() + 120_000
|
||||
while (Date.now() < readyDeadline) {
|
||||
const ready = await page.evaluate(() => (
|
||||
(document.body?.innerText ?? '').includes('平台原始账单')
|
||||
)).catch(() => false)
|
||||
if (ready) return { page, ownedPage }
|
||||
await sleep(500)
|
||||
}
|
||||
throw new Error('聚胜算平台账单页面加载超时')
|
||||
}
|
||||
|
||||
async function queryBill(page: Page, config: BillConfig, periodKey: string) {
|
||||
const { start, end } = periodBounds(periodKey)
|
||||
const response = await requestJson(
|
||||
page,
|
||||
'/WebApi/PF/BillRecords/GetBillRecordsList',
|
||||
envelope(billQuery(config, start, end), 1),
|
||||
)
|
||||
const count = Number((response.page as { count?: number } | undefined)?.count ?? 0)
|
||||
const data = response.data as { fldHeads?: unknown[] } | undefined
|
||||
if (!Number.isFinite(count) || count <= 0) {
|
||||
throw new Error(`${config.key} ${periodKey} 没有可导出的账单数据`)
|
||||
}
|
||||
log('query:ready', `${config.key},rows=${count},columns=${data?.fldHeads?.length ?? 0}`)
|
||||
return { count, start, end }
|
||||
}
|
||||
|
||||
async function createExport(
|
||||
page: Page,
|
||||
config: BillConfig,
|
||||
periodKey: string,
|
||||
lineCount: number,
|
||||
start: string,
|
||||
end: string,
|
||||
) {
|
||||
const query = billQuery(config, start, end, true)
|
||||
const response = await requestJson(
|
||||
page,
|
||||
'/WebApi/PF/AdaptiveExport/ExportBillRecordsList',
|
||||
envelope({
|
||||
exportCondition: JSON.stringify({
|
||||
...query,
|
||||
mainName: `${config.platformName}${config.groupName}`,
|
||||
isNewVersion: true,
|
||||
}),
|
||||
lineCount,
|
||||
}),
|
||||
)
|
||||
const data = response.data as {
|
||||
url?: string | null
|
||||
exportType?: number
|
||||
taskId?: number
|
||||
isSuccess?: boolean
|
||||
msg?: string | null
|
||||
} | undefined
|
||||
if (!data?.isSuccess) {
|
||||
throw new Error(`${config.key} 创建导出任务失败:${data?.msg || '未知原因'}`)
|
||||
}
|
||||
if (data.exportType === 0 && data.url) {
|
||||
log('export:sync-ready', config.key)
|
||||
return { url: data.url }
|
||||
}
|
||||
if (data.exportType === 1 && data.taskId) {
|
||||
log('export:async-created', `${config.key},task=${data.taskId},period=${periodKey}`)
|
||||
return { taskId: data.taskId }
|
||||
}
|
||||
throw new Error(`${config.key} 导出响应缺少下载地址或异步任务号`)
|
||||
}
|
||||
|
||||
async function pollNightTask(page: Page, taskId: number) {
|
||||
const timeoutMs = Number(process.env.PLATFORM_BILL_RPA_TASK_TIMEOUT_MS) > 0
|
||||
? Number(process.env.PLATFORM_BILL_RPA_TASK_TIMEOUT_MS)
|
||||
: DEFAULT_TASK_TIMEOUT_MS
|
||||
const startedAt = Date.now()
|
||||
const body = envelope({
|
||||
versionModel: 1201,
|
||||
cbShopSite: '',
|
||||
useOldTaskTable: false,
|
||||
}, 100)
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
const response = await requestJson(page, '/WebApi/PF/NightPlan/GetNightList', body)
|
||||
const rows = Array.isArray(response.data) ? response.data as Array<Record<string, unknown>> : []
|
||||
const row = rows.find((item) => String(item.tId ?? '') === String(taskId))
|
||||
if (row) {
|
||||
const status = String(row.status ?? '').toLowerCase()
|
||||
const fileUrl = String(row.fileUrl ?? '').trim()
|
||||
if (['success', 'finish', 'finished'].includes(status) && fileUrl) return fileUrl
|
||||
if (['failure', 'failed', 'error', 'cancel', 'timeout'].includes(status)) {
|
||||
throw new Error(`聚胜算异步导出任务 ${taskId} 状态为 ${String(row.status)}`)
|
||||
}
|
||||
log('export:polling', `task=${taskId},status=${String(row.status || 'unknown')}`)
|
||||
}
|
||||
await sleep(5_000)
|
||||
}
|
||||
throw new Error(`聚胜算异步导出任务 ${taskId} 等待超时`)
|
||||
}
|
||||
|
||||
function safeFileName(value: string) {
|
||||
return value.replace(/[\\/:*?"<>|]/g, '_').slice(0, 180)
|
||||
}
|
||||
|
||||
function fileNameFromHeaders(headers: Headers) {
|
||||
const contentDisposition = headers.get('content-disposition')
|
||||
const encoded = contentDisposition?.match(/filename\*=UTF-8''([^;]+)/i)?.[1]
|
||||
if (encoded) {
|
||||
try {
|
||||
return decodeURIComponent(encoded)
|
||||
} catch {
|
||||
// Fall back to the plain filename.
|
||||
}
|
||||
}
|
||||
return contentDisposition?.match(/filename="?([^";]+)"?/i)?.[1] ?? ''
|
||||
}
|
||||
|
||||
async function downloadFile(
|
||||
page: Page,
|
||||
url: string,
|
||||
config: BillConfig,
|
||||
periodKey: string,
|
||||
) {
|
||||
const cookies = (await page.cookies())
|
||||
.filter((cookie) => cookie.domain.endsWith('erp321.com'))
|
||||
.map((cookie) => `${cookie.name}=${cookie.value}`)
|
||||
.join('; ')
|
||||
const response = await fetch(url, {
|
||||
headers: cookies ? { cookie: cookies } : undefined,
|
||||
})
|
||||
if (!response.ok) throw new Error(`${config.key} 下载失败:HTTP ${response.status}`)
|
||||
const buffer = Buffer.from(await response.arrayBuffer())
|
||||
if (buffer.length === 0) throw new Error(`${config.key} 下载文件为空`)
|
||||
const responseName = safeFileName(fileNameFromHeaders(response.headers))
|
||||
const contentType = response.headers.get('content-type')?.toLowerCase() ?? ''
|
||||
const sourceName = responseName || basename(new URL(url).pathname)
|
||||
let extension = sourceName.toLowerCase().match(/\.(xlsx|xls|zip)$/)?.[1] ?? ''
|
||||
const isZipArchive = buffer.subarray(0, 4).equals(Buffer.from('504b0304', 'hex'))
|
||||
const isXlsxWorkbook = isZipArchive
|
||||
&& buffer.includes(Buffer.from('[Content_Types].xml'))
|
||||
&& buffer.includes(Buffer.from('xl/workbook.xml'))
|
||||
if (isXlsxWorkbook) {
|
||||
extension = 'xlsx'
|
||||
} else if (isZipArchive) {
|
||||
extension = 'zip'
|
||||
} else if (!extension) {
|
||||
extension = contentType.includes('zip') ? 'zip' : 'xlsx'
|
||||
}
|
||||
const output = join(
|
||||
DOWNLOAD_DIR,
|
||||
`${safeFileName(config.fileNamePrefix)}-${periodKey}.${extension}`,
|
||||
)
|
||||
writeFileSync(output, buffer)
|
||||
if (statSync(output).size !== buffer.length) throw new Error(`${config.key} 文件写入不完整`)
|
||||
log('download:ready', `${config.key},file=${output},bytes=${buffer.length}`)
|
||||
return output
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const periodKey = argument('period')?.trim() ?? ''
|
||||
if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(periodKey)) {
|
||||
throw new Error('请使用 --period=YYYY-MM 指定账单月份')
|
||||
}
|
||||
const receiptPath = argument('receipt')?.trim() ?? ''
|
||||
const exportOnly = process.argv.includes('--export-only')
|
||||
const queryOnly = process.argv.includes('--query-only')
|
||||
const requestedKeys = argument('only')?.split(',').map((value) => value.trim()).filter(Boolean)
|
||||
const bills = requestedKeys?.length
|
||||
? BILLS.filter((bill) => requestedKeys.includes(bill.key))
|
||||
: BILLS
|
||||
if (!bills.length) throw new Error(`未找到指定的账单:${requestedKeys?.join(',') ?? ''}`)
|
||||
mkdirSync(DOWNLOAD_DIR, { recursive: true })
|
||||
|
||||
await ensureRpaBrowser()
|
||||
const browser = await puppeteer.connect({
|
||||
browserURL: BROWSER_URL,
|
||||
defaultViewport: null,
|
||||
protocolTimeout: Number(process.env.JST_RPA_PROTOCOL_TIMEOUT_MS) || 900_000,
|
||||
})
|
||||
let page: Page | null = null
|
||||
let ownedPage = false
|
||||
try {
|
||||
const target = await findPlatformPage(browser)
|
||||
page = target.page
|
||||
ownedPage = target.ownedPage
|
||||
const files: Record<string, string> = {}
|
||||
const results: Array<Record<string, unknown>> = []
|
||||
for (const bill of bills) {
|
||||
const { count, start, end } = await queryBill(page, bill, periodKey)
|
||||
if (queryOnly) {
|
||||
results.push({ billKey: bill.key, rows: count })
|
||||
continue
|
||||
}
|
||||
const exportResult = await createExport(page, bill, periodKey, count, start, end)
|
||||
const url = 'url' in exportResult
|
||||
? exportResult.url
|
||||
: await pollNightTask(page, exportResult.taskId)
|
||||
const file = await downloadFile(page, url, bill, periodKey)
|
||||
files[bill.key] = file
|
||||
results.push({ billKey: bill.key, rows: count, file })
|
||||
}
|
||||
if (queryOnly) {
|
||||
console.log(JSON.stringify({ periodKey, queryOnly: true, results }, null, 2))
|
||||
return
|
||||
}
|
||||
if (exportOnly) {
|
||||
console.log(JSON.stringify({ periodKey, exportOnly: true, results }, null, 2))
|
||||
return
|
||||
}
|
||||
if (bills.length !== BILLS.length) {
|
||||
throw new Error('完整账单生成必须导出全部 9 个平台账单')
|
||||
}
|
||||
const importerArgs = [
|
||||
'scripts/import-monthly-platform-bills.ts',
|
||||
`--period=${periodKey}`,
|
||||
'--require-all',
|
||||
...(receiptPath ? [`--receipt=${receiptPath}`] : []),
|
||||
...BILLS.flatMap((bill) => [`--${bill.key}=${files[bill.key]}`]),
|
||||
]
|
||||
execFileSync(process.execPath, [TSX_CLI, ...importerArgs], {
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
console.log(JSON.stringify({ periodKey, results }, null, 2))
|
||||
} finally {
|
||||
if (ownedPage) await page?.close().catch(() => undefined)
|
||||
browser.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error) => {
|
||||
console.error(
|
||||
`[platform-bills-rpa] failed: ${error instanceof Error ? error.message : String(error)}`,
|
||||
)
|
||||
process.exitCode = 1
|
||||
})
|
||||
@ -1,6 +1,7 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { createWriteStream } from 'node:fs'
|
||||
import { access, readFile, unlink } from 'node:fs/promises'
|
||||
import { readFile, unlink } from 'node:fs/promises'
|
||||
import { resolve } from 'node:path'
|
||||
import { Client } from 'pg'
|
||||
|
||||
const [jobId, periodKey, logPath] = process.argv.slice(2)
|
||||
@ -11,6 +12,9 @@ if (!jobId || !/^\d{4}-(0[1-9]|1[0-2])$/.test(periodKey ?? '') || !logPath) {
|
||||
const databaseUrl = process.env.DATABASE_URL
|
||||
if (!databaseUrl) throw new Error('DATABASE_URL is required')
|
||||
const receiptPath = logPath.replace(/\.log$/, '.receipt.json')
|
||||
const projectRoot = process.cwd()
|
||||
const tsxCli = resolve(projectRoot, 'node_modules/tsx/dist/cli.mjs')
|
||||
const rpaScript = resolve(projectRoot, 'scripts/platform-bills-rpa.ts')
|
||||
const requiredBillKeys = [
|
||||
'alipay',
|
||||
'wechat',
|
||||
@ -23,18 +27,6 @@ const requiredBillKeys = [
|
||||
'dewu-deposit',
|
||||
]
|
||||
|
||||
async function firstExecutable(paths) {
|
||||
for (const path of paths.filter(Boolean)) {
|
||||
try {
|
||||
await access(path)
|
||||
return path
|
||||
} catch {
|
||||
// Try the next known installation path.
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
const client = new Client({ connectionString: databaseUrl })
|
||||
await client.connect()
|
||||
|
||||
@ -51,46 +43,14 @@ try {
|
||||
)
|
||||
|
||||
const log = createWriteStream(logPath, { flags: 'a' })
|
||||
const configuredCodexPath = process.env.PLATFORM_BILL_CODEX_BIN?.trim()
|
||||
const codexPath = await firstExecutable(configuredCodexPath ? [configuredCodexPath] : [
|
||||
'/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex',
|
||||
'/Applications/Codex.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex',
|
||||
'/usr/local/bin/codex',
|
||||
'/opt/homebrew/bin/codex',
|
||||
])
|
||||
if (!codexPath) {
|
||||
throw new Error(configuredCodexPath
|
||||
? `PLATFORM_BILL_CODEX_BIN 不可用:${configuredCodexPath}`
|
||||
: '未找到 Codex CLI,请配置 PLATFORM_BILL_CODEX_BIN')
|
||||
}
|
||||
const prompt = [
|
||||
'Use $monthly-platform-bills for a manual full re-generation.',
|
||||
`The target period is ${periodKey}.`,
|
||||
'Re-export all required platform bills for that exact month and replace only that month.',
|
||||
'Preserve older months and do not modify other months.',
|
||||
'If login requires a QR scan, report the blocker instead of guessing credentials.',
|
||||
`Wait until all ${requiredBillKeys.length} required files exist before importing.`,
|
||||
`Import with --require-all and --receipt="${receiptPath}".`,
|
||||
'Verify all required files, original headers, and row counts before reporting success.',
|
||||
].join(' ')
|
||||
await access(receiptPath).then(
|
||||
() => unlink(receiptPath),
|
||||
() => undefined,
|
||||
)
|
||||
const child = spawn(codexPath, [
|
||||
'-C',
|
||||
process.cwd(),
|
||||
'-s',
|
||||
'danger-full-access',
|
||||
'-a',
|
||||
'never',
|
||||
'exec',
|
||||
'--ephemeral',
|
||||
'--skip-git-repo-check',
|
||||
'--json',
|
||||
prompt,
|
||||
await unlink(receiptPath).catch(() => undefined)
|
||||
const child = spawn(process.execPath, [
|
||||
tsxCli,
|
||||
rpaScript,
|
||||
`--period=${periodKey}`,
|
||||
`--receipt=${receiptPath}`,
|
||||
], {
|
||||
cwd: process.cwd(),
|
||||
cwd: projectRoot,
|
||||
env: {
|
||||
...process.env,
|
||||
PLATFORM_BILL_JOB_ID: jobId,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user