|
|
|
@@ -10,8 +10,13 @@ interface ProfitOptions {
|
|
|
|
|
since: string;
|
|
|
|
|
targetId: string;
|
|
|
|
|
json: boolean;
|
|
|
|
|
accounts: boolean;
|
|
|
|
|
missingCosts: boolean;
|
|
|
|
|
pageToken: string | null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const PROFIT_ACCOUNT_PAGE_SIZE = 8;
|
|
|
|
|
|
|
|
|
|
export async function codexPoolProfit(config: UniDeskConfig, args: string[]): Promise<Record<string, unknown> | RenderedCliResult> {
|
|
|
|
|
const pool = readCodexPoolConfig();
|
|
|
|
|
if (args.includes("--help")) return renderProfitHelp(pool.profit.defaultWindow);
|
|
|
|
@@ -21,6 +26,9 @@ export async function codexPoolProfit(config: UniDeskConfig, args: string[]): Pr
|
|
|
|
|
const remote = await runRemoteCodexPoolScript(config, "profit", profitScript(payload, pool, target), target);
|
|
|
|
|
const report = parseJsonOutput(remote.stdout);
|
|
|
|
|
const ok = remote.exitCode === 0 && boolField(report, "ok", false);
|
|
|
|
|
const projectedReport = projectProfitReport(report, options);
|
|
|
|
|
const baseCommand = `bun scripts/cli.ts platform-infra sub2api codex-pool profit --target ${target.id} --since ${options.since}`;
|
|
|
|
|
const accountPage = record(record(projectedReport).accountPage);
|
|
|
|
|
const response = {
|
|
|
|
|
ok,
|
|
|
|
|
action: "platform-infra-sub2api-codex-pool-profit",
|
|
|
|
@@ -30,7 +38,16 @@ export async function codexPoolProfit(config: UniDeskConfig, args: string[]): Pr
|
|
|
|
|
mutation: false,
|
|
|
|
|
configPath: "config/platform-infra/sub2api-codex-pool.yaml#profit",
|
|
|
|
|
},
|
|
|
|
|
report,
|
|
|
|
|
report: projectedReport,
|
|
|
|
|
disclosure: {
|
|
|
|
|
accountsIncluded: options.accounts,
|
|
|
|
|
missingCostsIncluded: options.missingCosts,
|
|
|
|
|
accountCount: arrayOfRecords(record(report).accounts).length,
|
|
|
|
|
accounts: `${baseCommand} --accounts`,
|
|
|
|
|
accountsNext: accountPage.nextPageToken ? `${baseCommand} --accounts --page-token ${text(accountPage.nextPageToken)}` : null,
|
|
|
|
|
missingCosts: `${baseCommand} --missing-costs`,
|
|
|
|
|
json: `${baseCommand} --json`,
|
|
|
|
|
},
|
|
|
|
|
remote: compactCapture(remote, { full: !ok || report === null }),
|
|
|
|
|
valuesPrinted: false,
|
|
|
|
|
};
|
|
|
|
@@ -41,6 +58,9 @@ function parseProfitOptions(args: string[], defaultWindow: string): ProfitOption
|
|
|
|
|
let since = defaultWindow;
|
|
|
|
|
let targetId = defaultCodexPoolRuntimeTargetId();
|
|
|
|
|
let json = false;
|
|
|
|
|
let accounts = false;
|
|
|
|
|
let missingCosts = false;
|
|
|
|
|
let pageToken: string | null = null;
|
|
|
|
|
const readValue = (index: number, option: string): [string, number] => {
|
|
|
|
|
const value = args[index + 1];
|
|
|
|
|
if (value === undefined || value.startsWith("--")) throw new Error(`${option} requires a value`);
|
|
|
|
@@ -49,6 +69,11 @@ function parseProfitOptions(args: string[], defaultWindow: string): ProfitOption
|
|
|
|
|
for (let index = 0; index < args.length; index += 1) {
|
|
|
|
|
const arg = args[index]!;
|
|
|
|
|
if (arg === "--json") json = true;
|
|
|
|
|
else if (arg === "--accounts") accounts = true;
|
|
|
|
|
else if (arg === "--missing-costs") missingCosts = true;
|
|
|
|
|
else if (arg === "--page-token") {
|
|
|
|
|
[pageToken, index] = readValue(index, "--page-token");
|
|
|
|
|
} else if (arg.startsWith("--page-token=")) pageToken = arg.slice("--page-token=".length).trim();
|
|
|
|
|
else if (arg === "--since") {
|
|
|
|
|
[since, index] = readValue(index, "--since");
|
|
|
|
|
} else if (arg.startsWith("--since=")) since = arg.slice("--since=".length).trim();
|
|
|
|
@@ -59,7 +84,10 @@ function parseProfitOptions(args: string[], defaultWindow: string): ProfitOption
|
|
|
|
|
}
|
|
|
|
|
if (!/^[1-9][0-9]*(?:s|m|h|d)$/u.test(since)) throw new Error("--since must be a duration such as 24h, 90m, or 7d");
|
|
|
|
|
if (!targetId || /[\r\n\0]/u.test(targetId)) throw new Error("--target has an unsupported format");
|
|
|
|
|
return { since, targetId, json };
|
|
|
|
|
if (accounts && missingCosts) throw new Error("--accounts and --missing-costs are separate semantic disclosures");
|
|
|
|
|
if (pageToken !== null && !accounts) throw new Error("--page-token requires --accounts");
|
|
|
|
|
if (pageToken !== null && (!pageToken || /[\r\n\0\s]/u.test(pageToken))) throw new Error("--page-token has an unsupported format");
|
|
|
|
|
return { since, targetId, json, accounts, missingCosts, pageToken };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderProfitHelp(defaultWindow: string): RenderedCliResult {
|
|
|
|
@@ -69,13 +97,16 @@ function renderProfitHelp(defaultWindow: string): RenderedCliResult {
|
|
|
|
|
renderedText: [
|
|
|
|
|
"SUB2API CODEX-POOL PROFIT",
|
|
|
|
|
"Usage:",
|
|
|
|
|
" bun scripts/cli.ts platform-infra sub2api codex-pool profit [--since 24h] [--target PK01] [--json]",
|
|
|
|
|
" bun scripts/cli.ts platform-infra sub2api codex-pool profit [--since 24h] [--target PK01] [--accounts [--page-token <token>]|--missing-costs] [--json]",
|
|
|
|
|
"Options:",
|
|
|
|
|
` --since <duration> Native usage window; YAML default is ${defaultWindow}.`,
|
|
|
|
|
" --target <id>",
|
|
|
|
|
" --accounts Include one fixed-size account page with complete names and IDs.",
|
|
|
|
|
" --page-token <token> Continue from the opaque token returned by the previous account page.",
|
|
|
|
|
" --missing-costs Include the missing-cost account list and API USD bases.",
|
|
|
|
|
" --json Emit exact structured values.",
|
|
|
|
|
"Notes:",
|
|
|
|
|
" Default output is a Kubernetes-style account list plus both profit scopes.",
|
|
|
|
|
" Default output is a compact summary; use --accounts or --missing-costs for semantic disclosure.",
|
|
|
|
|
" This command is read-only and does not change Sub2API runtime state.",
|
|
|
|
|
].join("\n"),
|
|
|
|
|
contentType: "text/plain",
|
|
|
|
@@ -88,37 +119,57 @@ function renderProfit(response: Record<string, unknown>): RenderedCliResult {
|
|
|
|
|
const policy = record(report.policy);
|
|
|
|
|
const summary = record(report.summary);
|
|
|
|
|
const completeness = record(report.completeness);
|
|
|
|
|
const confirmedCosts = record(summary.confirmedCostsCny);
|
|
|
|
|
const profitBeforeUnknownCosts = record(summary.profitBeforeUnknownCostsCny);
|
|
|
|
|
const unknownBasis = record(summary.unknownCostBasisApiUsd);
|
|
|
|
|
const formulas = record(summary.profitFormula);
|
|
|
|
|
const disclosure = record(response.disclosure);
|
|
|
|
|
const lines = [
|
|
|
|
|
`SUB2API PROFIT status=${text(report.status)} target=${text(record(response.target).id)} window=${text(window.since)}`,
|
|
|
|
|
`WINDOW ${text(window.startAt)} -> ${text(window.endAt)} SOURCE native-admin-usage/${text(record(report.source).usageCostField)}`,
|
|
|
|
|
`POLICY sale-rate=${text(policy.saleRateCnyPerApiUsd)}CNY/API_USD account-cost=${text(policy.accountCostSource)}`,
|
|
|
|
|
"",
|
|
|
|
|
"ACCOUNTS",
|
|
|
|
|
"SUMMARY",
|
|
|
|
|
];
|
|
|
|
|
const accounts = arrayOfRecords(report.accounts);
|
|
|
|
|
lines.push(table(
|
|
|
|
|
["GROUP", "CLASS", "ACCOUNT", "ID", "REQ", "TOKENS", "API_USD", "COST_CNY/USD", "REVENUE_CNY", "UPSTREAM_CNY", "PROFIT_CNY", "STATUS"],
|
|
|
|
|
accounts.map((row) => [
|
|
|
|
|
text(row.groupName), text(row.class), text(row.accountName), text(row.accountId), text(row.requestCount), compactTokens(row.tokenCount),
|
|
|
|
|
apiUsd(row.apiAmountUsd), text(row.costRateCnyPerApiUsd), cny(row.revenueCny), cny(row.upstreamCostCny), cny(row.profitContributionCny), text(row.completeness),
|
|
|
|
|
]),
|
|
|
|
|
));
|
|
|
|
|
lines.push("", "PROFIT");
|
|
|
|
|
lines.push(table(
|
|
|
|
|
["SCOPE", "STATUS", "REVENUE_CNY", "PROFIT_POOL_CNY", "SELF_USE_CNY", "PROFIT_CNY"],
|
|
|
|
|
["SCOPE", "STATUS", "REVENUE_CNY", "PROFIT_POOL_COST_CNY", "SELF_USE_COST_CNY", "PROFIT_BEFORE_UNKNOWN_COSTS_CNY", "UNKNOWN_API_USD"],
|
|
|
|
|
[
|
|
|
|
|
["不扣自用", text(record(summary.withoutSelfUse).status), cny(summary.revenueCny), cny(summary.profitPoolCostCny), "-", cny(record(summary.withoutSelfUse).profitCny)],
|
|
|
|
|
["扣除自用", text(record(summary.withSelfUse).status), cny(summary.revenueCny), cny(summary.profitPoolCostCny), cny(summary.selfUseCostCny), cny(record(summary.withSelfUse).profitCny)],
|
|
|
|
|
["不扣自用", text(record(summary.withoutSelfUse).status), cny(summary.revenueCny), cny(confirmedCosts.profitPool), "-", cny(profitBeforeUnknownCosts.withoutSelfUse), apiUsd(unknownBasis.profitPool)],
|
|
|
|
|
["扣除自用", text(record(summary.withSelfUse).status), cny(summary.revenueCny), cny(confirmedCosts.profitPool), cny(confirmedCosts.selfUse), cny(profitBeforeUnknownCosts.withSelfUse), apiUsd(unknownBasis.total)],
|
|
|
|
|
],
|
|
|
|
|
));
|
|
|
|
|
lines.push("", "FORMULA");
|
|
|
|
|
lines.push(`- 不扣自用: ${text(formulas.withoutSelfUse)}`);
|
|
|
|
|
lines.push(`- 扣除自用: ${text(formulas.withSelfUse)}`);
|
|
|
|
|
lines.push("", `COMPLETENESS status=${text(report.status)} missing-cost=${text(completeness.missingCostAccountCount)} unclassified=${text(completeness.unclassifiedTrafficCount)} missing-groups=${text(completeness.configuredGroupMissingCount)}`);
|
|
|
|
|
lines.push(`NEXT accounts: ${text(disclosure.accounts)}`);
|
|
|
|
|
lines.push(`NEXT missing-costs: ${text(disclosure.missingCosts)}`);
|
|
|
|
|
const accounts = arrayOfRecords(report.accounts);
|
|
|
|
|
if (accounts.length > 0) {
|
|
|
|
|
lines.push("", "ACCOUNTS");
|
|
|
|
|
lines.push(table(
|
|
|
|
|
["GROUP", "CLASS", "ACCOUNT", "ID", "REQ", "TOKENS", "API_USD", "COST_CNY/USD", "REVENUE_CNY", "UPSTREAM_CNY", "PROFIT_CNY", "STATUS"],
|
|
|
|
|
accounts.map((row) => [
|
|
|
|
|
text(row.groupName), text(row.class), text(row.accountName), text(row.accountId), text(row.requestCount), compactTokens(row.tokenCount),
|
|
|
|
|
apiUsd(row.apiAmountUsd), text(row.costRateCnyPerApiUsd), cny(row.revenueCny), cny(row.upstreamCostCny), cny(row.profitContributionCny), text(row.completeness),
|
|
|
|
|
]),
|
|
|
|
|
));
|
|
|
|
|
const accountPage = record(report.accountPage);
|
|
|
|
|
if (accountPage.nextPageToken) lines.push(`NEXT account-page: ${text(disclosure.accountsNext)}`);
|
|
|
|
|
}
|
|
|
|
|
const missingCosts = arrayOfRecords(completeness.missingCostAccounts);
|
|
|
|
|
const unclassified = arrayOfRecords(completeness.unclassifiedTraffic);
|
|
|
|
|
const missingGroups = Array.isArray(completeness.configuredGroupsMissingAtRuntime) ? completeness.configuredGroupsMissingAtRuntime : [];
|
|
|
|
|
if (missingCosts.length || unclassified.length || missingGroups.length) {
|
|
|
|
|
lines.push("", "COMPLETENESS");
|
|
|
|
|
for (const row of missingCosts) lines.push(`- missing-cost group=${text(row.groupName)} account=${text(row.accountName)} id=${text(row.accountId)}`);
|
|
|
|
|
for (const row of unclassified) lines.push(`- unclassified-traffic group=${text(row.groupName)} account=${text(row.accountName)} requests=${text(row.requestCount)}`);
|
|
|
|
|
for (const group of missingGroups) lines.push(`- configured-group-missing ${text(group)}`);
|
|
|
|
|
if (missingCosts.length > 0) {
|
|
|
|
|
lines.push("", "MISSING COST ACCOUNTS");
|
|
|
|
|
for (const row of missingCosts) lines.push(`- class=${text(row.class)} group=${text(row.groupName)} account=${text(row.accountName)} id=${text(row.accountId)} api-usd=${text(row.apiAmountUsd)}`);
|
|
|
|
|
}
|
|
|
|
|
if (accounts.length > 0 || missingCosts.length > 0) {
|
|
|
|
|
const unclassified = arrayOfRecords(completeness.unclassifiedTraffic);
|
|
|
|
|
const missingGroups = Array.isArray(completeness.configuredGroupsMissingAtRuntime) ? completeness.configuredGroupsMissingAtRuntime : [];
|
|
|
|
|
if (unclassified.length || missingGroups.length) {
|
|
|
|
|
lines.push("", "COMPLETENESS DETAILS");
|
|
|
|
|
for (const row of unclassified) lines.push(`- unclassified-traffic group=${text(row.groupName)} account=${text(row.accountName)} requests=${text(row.requestCount)}`);
|
|
|
|
|
for (const group of missingGroups) lines.push(`- configured-group-missing ${text(group)}`);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return {
|
|
|
|
|
ok: response.ok === true,
|
|
|
|
@@ -129,6 +180,60 @@ function renderProfit(response: Record<string, unknown>): RenderedCliResult {
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function projectProfitReport(report: Record<string, unknown> | null, options: ProfitOptions): Record<string, unknown> | null {
|
|
|
|
|
if (report === null) return null;
|
|
|
|
|
const { accounts: rawAccounts, completeness: rawCompleteness, ...summaryReport } = report;
|
|
|
|
|
const accounts = arrayOfRecords(rawAccounts);
|
|
|
|
|
const completeness = record(rawCompleteness);
|
|
|
|
|
const compactCompleteness = {
|
|
|
|
|
missingCostAccountCount: arrayOfRecords(completeness.missingCostAccounts).length,
|
|
|
|
|
unclassifiedTrafficCount: arrayOfRecords(completeness.unclassifiedTraffic).length,
|
|
|
|
|
configuredGroupMissingCount: Array.isArray(completeness.configuredGroupsMissingAtRuntime) ? completeness.configuredGroupsMissingAtRuntime.length : 0,
|
|
|
|
|
};
|
|
|
|
|
const compactReport = {
|
|
|
|
|
...summaryReport,
|
|
|
|
|
accountCount: accounts.length,
|
|
|
|
|
completeness: compactCompleteness,
|
|
|
|
|
};
|
|
|
|
|
if (options.missingCosts) {
|
|
|
|
|
return {
|
|
|
|
|
...compactReport,
|
|
|
|
|
completeness: {
|
|
|
|
|
...compactCompleteness,
|
|
|
|
|
missingCostAccounts: arrayOfRecords(completeness.missingCostAccounts),
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
if (!options.accounts) return compactReport;
|
|
|
|
|
let startIndex = 0;
|
|
|
|
|
if (options.pageToken !== null) {
|
|
|
|
|
const tokenIndex = accounts.findIndex((row) => encodeProfitAccountPageToken(row) === options.pageToken);
|
|
|
|
|
if (tokenIndex < 0) throw new Error(`profit account page token not found: ${options.pageToken}`);
|
|
|
|
|
startIndex = tokenIndex + 1;
|
|
|
|
|
}
|
|
|
|
|
const pageAccounts = accounts.slice(startIndex, startIndex + PROFIT_ACCOUNT_PAGE_SIZE);
|
|
|
|
|
const hasNext = startIndex + pageAccounts.length < accounts.length;
|
|
|
|
|
const nextPageToken = hasNext && pageAccounts.length > 0 ? encodeProfitAccountPageToken(pageAccounts.at(-1)!) : null;
|
|
|
|
|
return {
|
|
|
|
|
...compactReport,
|
|
|
|
|
accounts: pageAccounts,
|
|
|
|
|
accountPage: {
|
|
|
|
|
pageSize: PROFIT_ACCOUNT_PAGE_SIZE,
|
|
|
|
|
returned: pageAccounts.length,
|
|
|
|
|
nextPageToken,
|
|
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function encodeProfitAccountPageToken(account: Record<string, unknown>): string {
|
|
|
|
|
return Buffer.from(JSON.stringify([
|
|
|
|
|
account.class ?? null,
|
|
|
|
|
account.groupId ?? null,
|
|
|
|
|
account.accountId ?? null,
|
|
|
|
|
account.accountName ?? null,
|
|
|
|
|
]), "utf8").toString("base64url");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function renderProfitJson(response: Record<string, unknown>): RenderedCliResult {
|
|
|
|
|
return {
|
|
|
|
|
ok: response.ok === true,
|
|
|
|
|