66 lines
2.6 KiB
PHP
66 lines
2.6 KiB
PHP
<?php
|
||
|
||
namespace app\chukebao\controller;
|
||
|
||
use app\cunkebao\service\TokensService;
|
||
use library\ResponseHelper;
|
||
|
||
/**
|
||
* 模块 D · 算力消耗(需求六 §6.3)
|
||
* 触客宝侧 type 枚举 → TokensService action(算力规则真源),按「次/轮」× 规则 cost 扣费。
|
||
*
|
||
* 对齐 SuperAdmin_AI算力计费规则配置_20260529 §十 type→slug 映射。
|
||
*/
|
||
class AiConsumeController extends BaseController
|
||
{
|
||
/** type → TokensService action(统一规则真源) */
|
||
const ACTION_MAP = [
|
||
'ai_reception' => TokensService::ACTION_AI_KEFU, // 13 · AI 客服(按轮)
|
||
'ai_quick_reply' => TokensService::ACTION_AI_REWRITE, // 12 · AI 改写
|
||
'quick_reply_to_kb' => TokensService::ACTION_AI_REWRITE, // 12
|
||
'contact_classify' => TokensService::ACTION_AI_REWRITE, // 12 · 批量打标签
|
||
'rfm_refresh' => 0, // 免费
|
||
'other' => TokensService::ACTION_AI_REWRITE, // 12
|
||
];
|
||
|
||
/**
|
||
* POST /v1/kefu/ai/consume
|
||
* body: { type(string), times?(次/轮, 默认1), refId?, remark? }
|
||
* 兼容旧字段 amount(等价 times)。
|
||
*/
|
||
public function consume()
|
||
{
|
||
$type = (string)$this->request->param('type', 'other');
|
||
// 次数/轮次:优先 times,兼容旧 amount
|
||
$times = (int)$this->request->param('times', 0);
|
||
if ($times <= 0) {
|
||
$times = (int)$this->request->param('amount', 1);
|
||
}
|
||
$times = max(1, $times);
|
||
$refId = (int)$this->request->param('refId', 0);
|
||
$remark = (string)$this->request->param('remark', '');
|
||
|
||
$action = self::ACTION_MAP[$type] ?? self::ACTION_MAP['other'];
|
||
$companyId = (int)$this->getUserInfo('companyId');
|
||
$userId = (int)$this->getUserInfo('id');
|
||
|
||
// 免费行为(如 rfm_refresh)直接返回
|
||
if ($action <= 0) {
|
||
return ResponseHelper::success(['deducted' => 0, 'free' => true], '免费行为,不扣算力');
|
||
}
|
||
|
||
$svc = new TokensService($companyId, $userId);
|
||
if (!$svc->canConsume($action, $times)) {
|
||
return ResponseHelper::error('算力不够啦,去充一点就能继续', 402);
|
||
}
|
||
$res = $svc->consume($action, $remark ?: $type, $times, $refId);
|
||
if (empty($res['ok'])) {
|
||
return ResponseHelper::error($res['msg'] ?? '扣费失败', 402);
|
||
}
|
||
return ResponseHelper::success([
|
||
'deducted' => (int)($res['deducted'] ?? 0),
|
||
'balance' => (int)($res['balance'] ?? 0),
|
||
], '已扣费');
|
||
}
|
||
}
|