PointsService.php 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. <?php
  2. namespace App\Services;
  3. use App\Consts\ErrorConst;
  4. use App\Facade\Site;
  5. use App\Libs\Utils;
  6. use App\Models\MpGeneratePicTask;
  7. use App\Models\MpGenerateVideoTask;
  8. use App\Models\MpUserPointsDetail;
  9. use Illuminate\Support\Facades\DB;
  10. /**
  11. * 用户积分服务
  12. *
  13. * 负责视频生成等业务的积分扣费、积分使用明细记录以及用户积分余额更新。
  14. */
  15. class PointsService
  16. {
  17. /**
  18. * 视频生成单次默认扣费积分数
  19. * 视频模型未配置计费规则时的默认扣费积分数(兜底,避免未配置模型免费)
  20. */
  21. const DEFAULT_VIDEO_CHARGE_POINTS = 0;
  22. /**
  23. * AI对话(chatForAce / addChatForAce单剧集 / reGenerateAnimeForAce单剧集 / regenerateSegmentScript剧集模式)单次扣费积分数
  24. *
  25. * 该值为文生文(对话)的默认扣费积分数:
  26. * 各模型可在 mp_text_models.price_json 中按 model 单独配置({"price": 10}),
  27. * 未配置或模型不存在时回退此默认值。
  28. */
  29. const CHAT_CHARGE_POINTS = 10;
  30. /**
  31. * 获取文生文(AI对话)单次应扣积分数(公共方法)
  32. *
  33. * 计费规则从 mp_text_models 表读取(charge_type=per_call,按次计费):
  34. * - 传入 model 且该模型配置了 price_json.price 时,返回配置值(允许 0,即免费)
  35. * - 模型未配置、模型不存在或未传 model 时,返回默认值 10
  36. *
  37. * @param string $model 文本模型 ID(如 deepseek-reasoner / doubao-seed-2-0-mini-260215)
  38. * @return int
  39. */
  40. public function getChatChargePoints(string $model = ''): int
  41. {
  42. if ($model !== '') {
  43. $modelRow = DB::table('mp_text_models')->where('model', $model)->first();
  44. if ($modelRow && ($modelRow->charge_type ?? '') === 'per_call') {
  45. $priceJson = $modelRow->price_json;
  46. $priceRule = is_string($priceJson) ? json_decode($priceJson, true) : $priceJson;
  47. if (is_array($priceRule) && isset($priceRule['price']) && is_numeric($priceRule['price'])) {
  48. return (int)max(0, round((float)$priceRule['price']));
  49. }
  50. }
  51. }
  52. return self::CHAT_CHARGE_POINTS;
  53. }
  54. /**
  55. * 获取视频模型应扣积分数(公共方法)
  56. *
  57. * 计费规则从 mp_video_models 表读取:
  58. * - 按秒计费(per_second):积分 = 单价/秒 × 视频时长(秒)
  59. * - 按次计费(per_call):积分 = 固定单价(如 Gemini 视频理解,暂未接入)
  60. * 分辨率会归一化为计费档位;“超分720p”档对应生成分辨率 480p(任务更新代码会对 480p 直接超分到 720p)。
  61. *
  62. * @param array $chargeInfo 计费信息(model、video_resolution、video_duration、mode 等)
  63. * @return int
  64. */
  65. public function getVideoChargePoints(array $chargeInfo = []): int
  66. {
  67. $model = (string)getProp($chargeInfo, 'model', '');
  68. $resolution = strtolower((string)getProp($chargeInfo, 'video_resolution', '720p'));
  69. $duration = (int)getProp($chargeInfo, 'video_duration', 0);
  70. if ($duration <= 0) {
  71. $duration = 1; // 时长未知时按1秒兜底
  72. }
  73. $mode = (string)getProp($chargeInfo, 'mode', 'video_generation');
  74. // 从 mp_video_models 表读取计费规则
  75. $modelRow = DB::table('mp_video_models')->where('model', $model)->first();
  76. if (!$modelRow || empty($modelRow->charge_type)) {
  77. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  78. }
  79. $priceJson = $modelRow->price_json;
  80. $priceRule = is_string($priceJson) ? json_decode($priceJson, true) : $priceJson;
  81. if (!is_array($priceRule) || empty($priceRule)) {
  82. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  83. }
  84. // 按次计费(如 Gemini 视频理解:每次固定积分)
  85. if ($modelRow->charge_type === 'per_call') {
  86. $price = (float)($priceRule['price'] ?? self::DEFAULT_VIDEO_CHARGE_POINTS);
  87. return (int)max(1, round($price));
  88. }
  89. // 按秒计费:按场景取分辨率价格表(默认视频生成场景)
  90. $prices = $priceRule[$mode] ?? $priceRule['video_generation'] ?? [];
  91. if (!is_array($prices) || empty($prices)) {
  92. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  93. }
  94. $pricePerSecond = $prices[$this->normalizeResolutionKey($resolution)] ?? null;
  95. if ($pricePerSecond === null || (float)$pricePerSecond <= 0) {
  96. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  97. }
  98. return (int)max(1, round((float)$pricePerSecond * $duration));
  99. }
  100. /**
  101. * 将分辨率归一化为计费档位
  102. *
  103. * “超分720p”档对应生成分辨率 480p(任务更新代码会对 480p 直接超分到 720p),
  104. * 因此 480p / sr_720p / 超分720p 均归一化为 480p 档。
  105. *
  106. * @param string $resolution
  107. * @return string
  108. */
  109. private function normalizeResolutionKey(string $resolution): string
  110. {
  111. $resolution = strtolower(trim($resolution));
  112. switch ($resolution) {
  113. case '4k':
  114. case '2160p':
  115. case '4096x2160':
  116. return '4k';
  117. case '1080p':
  118. return '1080p';
  119. case '720p':
  120. return '720p';
  121. case '480p':
  122. return '480p';
  123. case 'sr_720p':
  124. case 'sr720p':
  125. case '超分720p':
  126. return '480p';
  127. case 'sr_1080p':
  128. case 'sr1080p':
  129. case '超分1080p':
  130. return 'sr_1080p';
  131. default:
  132. return $resolution;
  133. }
  134. }
  135. /**
  136. * 获取视频生成任务实际消耗的 token 量
  137. *
  138. * 优先从接口返回的 result_json.usage 中读取;
  139. * 当前视频类接口暂未返回 token 用量,默认返回 0。
  140. *
  141. * @param MpGenerateVideoTask $task
  142. * @return int
  143. */
  144. public function getVideoTokensConsumed(MpGenerateVideoTask $task): int
  145. {
  146. $resultJson = $task->result_json;
  147. if (is_string($resultJson)) {
  148. $resultJson = json_decode($resultJson, true);
  149. }
  150. if (!is_array($resultJson)) {
  151. return 0;
  152. }
  153. // zzengine(智帧/统一API)返回格式:
  154. // data.task.detail.actual_token_total 或 data.task.detail.result.provider_token_total
  155. // 或 data.task.detail.result.billing_snapshot.token_total
  156. if ($task->api_type === 'zzengine') {
  157. $tokens = $resultJson['data']['task']['detail']['actual_token_total']
  158. ?? $resultJson['data']['task']['detail']['result']['provider_token_total']
  159. ?? $resultJson['data']['task']['detail']['result']['billing_snapshot']['token_total']
  160. ?? $resultJson['data']['task']['detail']['result']['billing_snapshot']['token_output']
  161. ?? 0;
  162. return (int)$tokens;
  163. }
  164. // seedance(豆包视频)返回格式:usage.total_tokens / usage.completion_tokens
  165. if ($task->api_type === 'seedance') {
  166. $tokens = $resultJson['usage']['total_tokens']
  167. ?? $resultJson['usage']['completion_tokens']
  168. ?? 0;
  169. return (int)$tokens;
  170. }
  171. // kuaikuai(快快AI)返回格式:data.data.usage.total_tokens / completion_tokens
  172. // result_json 中已保留规范化后的 usage 字段(queryKuaikuaiTaskStatus 同步)
  173. if ($task->api_type === 'kuaikuai') {
  174. $tokens = $resultJson['usage']['total_tokens']
  175. ?? $resultJson['data']['data']['usage']['total_tokens']
  176. ?? $resultJson['usage']['completion_tokens']
  177. ?? $resultJson['data']['data']['usage']['completion_tokens']
  178. ?? 0;
  179. return (int)$tokens;
  180. }
  181. // 其他API:优先从 usage 中读取
  182. $tokens = $resultJson['usage']['total_tokens']
  183. ?? $resultJson['usage']['completion_tokens']
  184. ?? $resultJson['content']['usage']['total_tokens']
  185. ?? 0;
  186. return (int)$tokens;
  187. }
  188. /**
  189. * 从接口返回结果中获取实际视频时长(秒)
  190. *
  191. * 各 API 返回格式不同,按 api_type 分别解析;
  192. * 用于 charge_info 中自动时长(-1/0)的任务在成功扣费时回填实际时长。
  193. *
  194. * @param MpGenerateVideoTask $task
  195. * @return int
  196. */
  197. public function getActualVideoDuration(MpGenerateVideoTask $task): int
  198. {
  199. $resultJson = $task->result_json;
  200. if (is_string($resultJson)) {
  201. $resultJson = json_decode($resultJson, true);
  202. }
  203. if (!is_array($resultJson)) {
  204. return 0;
  205. }
  206. switch ($task->api_type) {
  207. case 'zzengine':
  208. return (int)($resultJson['data']['task']['detail']['duration'] ?? 0);
  209. case 'jimeng':
  210. $data = $resultJson['data'] ?? [];
  211. if (!empty($data['duration'])) {
  212. return (int)$data['duration'];
  213. }
  214. if (isset($data['frames'], $data['framespersecond']) && (int)$data['framespersecond'] > 0) {
  215. return (int)floor((int)$data['frames'] / (int)$data['framespersecond']);
  216. }
  217. return 0;
  218. case 'keling':
  219. $taskData = $resultJson['data'] ?? [];
  220. $video = $taskData['task_result']['videos'][0] ?? [];
  221. if (!empty($video['duration'])) {
  222. return (int)$video['duration'];
  223. }
  224. if (!empty($taskData['duration'])) {
  225. return (int)$taskData['duration'];
  226. }
  227. if (isset($video['frames'], $video['framespersecond']) && (int)$video['framespersecond'] > 0) {
  228. return (int)floor((int)$video['frames'] / (int)$video['framespersecond']);
  229. }
  230. return 0;
  231. case 'seedance':
  232. default:
  233. return (int)($resultJson['duration'] ?? 0);
  234. }
  235. }
  236. /**
  237. * 获取系统当前全部积分规则(公共方法)
  238. *
  239. * - chat:文生文(对话)规则,含全局默认扣分与各文本模型按 model 配置的扣分
  240. * - image_models:图片模型计费规则(mp_image_models)
  241. * - video_models:视频模型计费规则(mp_video_models)
  242. *
  243. * @return array
  244. */
  245. public function getPointsRules(): array
  246. {
  247. $textModels = DB::table('mp_text_models')->orderBy('order', 'desc')->orderBy('id', 'desc')->where('is_enabled', 1)->get();
  248. $imageModels = DB::table('mp_image_models')->orderBy('order', 'desc')->orderBy('id', 'desc')->where('is_enabled', 1)->get();
  249. $videoModels = DB::table('mp_video_models')->orderBy('order', 'desc')->orderBy('id', 'desc')->where('is_enabled', 1)->get();
  250. // $textList = [];
  251. // foreach ($textModels as $row) {
  252. // $item = $this->formatModelRule($row);
  253. // $item['charge_points'] = $this->getChatChargePoints((string)$row->model);
  254. // $textList[] = $item;
  255. // }
  256. $textModel = DB::table('mp_text_models')->where('is_enabled', 1)->whereNotNull('price_json')->first();
  257. if ($textModel) {
  258. $price = $this->getChatChargePoints($textModel->model);
  259. $charge_type = 'per_call';
  260. }else {
  261. $price = self::CHAT_CHARGE_POINTS;
  262. $charge_type = 'per_call';
  263. }
  264. return [
  265. 'chat' => [
  266. 'charge_type' => $charge_type,
  267. 'price_json' => ['price'=>$price],
  268. // 'models' => $textList,
  269. ],
  270. 'image_models' => array_map([$this, 'formatModelRule'], $imageModels->all()),
  271. 'video_models' => array_map([$this, 'formatModelRule'], $videoModels->all()),
  272. ];
  273. }
  274. /**
  275. * 将模型表中的计费配置行整理为前端友好结构
  276. *
  277. * price_json 统一解析为数组返回(空配置返回空对象)。
  278. *
  279. * @param object $row
  280. * @return array
  281. */
  282. private function formatModelRule($row): array
  283. {
  284. $priceJson = getProp($row, 'price_json');
  285. $price = is_string($priceJson) ? json_decode($priceJson, true) : $priceJson;
  286. if (!is_array($price)) {
  287. $price = new \stdClass();
  288. }
  289. return [
  290. // 'id' => (int)getProp($row, 'id', 0),
  291. 'model' => (string)getProp($row, 'model', ''),
  292. 'name' => (string)getProp($row, 'name', ''),
  293. // 'description' => (string)getProp($row, 'description', ''),
  294. // 'is_enabled' => (int)getProp($row, 'is_enabled', 1),
  295. // 'order' => (int)getProp($row, 'order', 0),
  296. 'is_multimodal' => (int)getProp($row, 'is_multimodal', 0),
  297. 'charge_type' => (string)getProp($row, 'charge_type', ''),
  298. 'price_json' => $price,
  299. ];
  300. }
  301. /**
  302. * 更新积分规则(公共方法)
  303. *
  304. * 支持三个区块,均可选传,未传区块不处理:
  305. * - text_rules:文生文(对话)按 model 更新(不传 model 时更新全部模型),charge_type 仅支持 per_call,price_json 为 {"price": 积分}
  306. * - image_rules:图片按 model 更新,charge_type 仅支持 per_image,price_json 为 {"1k": 积分, "2k": 积分, "4k": 积分}
  307. * - video_rules:视频按 model 更新,charge_type 支持 per_second / per_call
  308. * per_second 的 price_json 为 {"场景": {"分辨率": 单价/秒}};per_call 的 price_json 为 {"price": 积分}
  309. *
  310. * 每条规则至少需传 charge_type 或 price_json 之一;未传的字段保留原值。
  311. *
  312. * @param array $params
  313. * @return array 各区块实际更新的 model 列表
  314. */
  315. public function updatePointsRules(array $params): array
  316. {
  317. $updated = ['text' => [], 'image' => [], 'video' => []];
  318. if (isset($params['text_rules']) && is_array($params['text_rules'])) {
  319. foreach ($params['text_rules'] as $rule) {
  320. $updated['text'] = array_merge(
  321. $updated['text'],
  322. $this->updateModelRule('mp_text_models', $rule, ['per_call'], false, true)
  323. );
  324. }
  325. }
  326. if (isset($params['image_rules']) && is_array($params['image_rules'])) {
  327. foreach ($params['image_rules'] as $rule) {
  328. $updated['image'] = array_merge(
  329. $updated['image'],
  330. $this->updateModelRule('mp_image_models', $rule, ['per_image'], false)
  331. );
  332. }
  333. }
  334. if (isset($params['video_rules']) && is_array($params['video_rules'])) {
  335. foreach ($params['video_rules'] as $rule) {
  336. $updated['video'] = array_merge(
  337. $updated['video'],
  338. $this->updateModelRule('mp_video_models', $rule, ['per_second', 'per_call'], true)
  339. );
  340. }
  341. }
  342. return $updated;
  343. }
  344. /**
  345. * 更新单个模型的计费配置
  346. *
  347. * @param string $table 模型表名
  348. * @param array $rule 规则(model / charge_type / price_json)
  349. * @param array $chargeTypes 允许的计费方式
  350. * @param bool $nestedPrice 是否允许嵌套价格结构(视频按场景+分辨率)
  351. * @param bool $allowAll 是否允许不传 model 时更新该表全部模型(仅文生文使用)
  352. * @return array 实际更新的 model 列表
  353. */
  354. private function updateModelRule(string $table, array $rule, array $chargeTypes, bool $nestedPrice, bool $allowAll = false): array
  355. {
  356. $model = trim((string)getProp($rule, 'model', ''));
  357. if ($model === '' && !$allowAll) {
  358. Utils::throwError('1002:规则缺少model参数');
  359. }
  360. $data = [];
  361. if (array_key_exists('charge_type', $rule)) {
  362. $chargeType = (string)getProp($rule, 'charge_type', '');
  363. if (!in_array($chargeType, $chargeTypes, true)) {
  364. Utils::throwError('1002:' . $table . '计费方式不合法:' . $chargeType);
  365. }
  366. $data['charge_type'] = $chargeType;
  367. }
  368. if (array_key_exists('price_json', $rule)) {
  369. $price = getProp($rule, 'price_json', null);
  370. $priceArr = $nestedPrice
  371. ? $this->normalizeNestedPrice($price)
  372. : $this->normalizeFlatPrice($price);
  373. $data['price_json'] = json_encode($priceArr, JSON_UNESCAPED_UNICODE);
  374. }
  375. if (empty($data)) {
  376. Utils::throwError('1002:' . $table . '规则请至少传入charge_type或price_json');
  377. }
  378. if ($model !== '') {
  379. if (!DB::table($table)->where('model', $model)->exists()) {
  380. Utils::throwError('1002:模型不存在:' . $model);
  381. }
  382. DB::table($table)->where('model', $model)->update($data);
  383. return [$model];
  384. }
  385. // 未传 model(仅文生文支持):更新该表全部模型
  386. $allModels = DB::table($table)->pluck('model')->all();
  387. if (empty($allModels)) {
  388. Utils::throwError('1002:' . $table . '没有可更新的模型');
  389. }
  390. DB::table($table)->update($data);
  391. return $allModels;
  392. }
  393. /**
  394. * 校验并归一化一层价格结构(文生文/图片)
  395. *
  396. * 所有 key 对应的值必须为不小于 0 的数字;支持传入对象或 JSON 字符串。
  397. *
  398. * @param mixed $price
  399. * @return array
  400. */
  401. private function normalizeFlatPrice($price): array
  402. {
  403. $priceArr = is_string($price) ? json_decode($price, true) : $price;
  404. if (!is_array($priceArr) || empty($priceArr)) {
  405. Utils::throwError('1002:price格式不正确');
  406. }
  407. $result = [];
  408. foreach ($priceArr as $key => $value) {
  409. if (!is_numeric($value) || (float)$value < 0) {
  410. Utils::throwError('1002:price.' . $key . '必须为不小于0的数字');
  411. }
  412. $result[(string)$key] = (float)$value;
  413. }
  414. return $result;
  415. }
  416. /**
  417. * 校验并归一化嵌套价格结构(视频按场景+分辨率)
  418. *
  419. * 支持如 {"video_generation": {"720p": 10, "1080p": 25}} 或 {"price": 5}。
  420. *
  421. * @param mixed $price
  422. * @return array
  423. */
  424. private function normalizeNestedPrice($price): array
  425. {
  426. $priceArr = is_string($price) ? json_decode($price, true) : $price;
  427. if (!is_array($priceArr) || empty($priceArr)) {
  428. Utils::throwError('1002:price格式不正确');
  429. }
  430. $result = [];
  431. foreach ($priceArr as $key => $value) {
  432. if (is_array($value)) {
  433. $result[(string)$key] = $this->normalizeFlatPrice($value);
  434. } elseif (is_numeric($value) && (float)$value >= 0) {
  435. $result[(string)$key] = (float)$value;
  436. } else {
  437. Utils::throwError('1002:price.' . $key . '必须为不小于0的数字或对象');
  438. }
  439. }
  440. return $result;
  441. }
  442. /**
  443. * 获取用户积分流水
  444. *
  445. * @param array $params uid/type/start_date/end_date/page_size
  446. * @return array
  447. */
  448. public function getUserPointsRecords(array $params = []): array
  449. {
  450. $uid = (int)getProp($params, 'uid', 0);
  451. if (!$uid) {
  452. $uid = (int)Site::getUid();
  453. }
  454. $type = getProp($params, 'type', '');
  455. $startDate = getProp($params, 'start_date', '');
  456. $endDate = getProp($params, 'end_date', '');
  457. $pageSize = (int)getProp($params, 'page_size', 15);
  458. if ($pageSize < 1 || $pageSize > 100) {
  459. $pageSize = 15;
  460. }
  461. $query = MpUserPointsDetail::where('uid', $uid);
  462. if ($type) {
  463. $query->where('type', $type);
  464. }
  465. if ($startDate) {
  466. $query->where('created_at', '>=', $startDate . ' 00:00:00');
  467. }
  468. if ($endDate) {
  469. $query->where('created_at', '<=', $endDate . ' 23:59:59');
  470. }
  471. $records = $query->orderBy('created_at', 'desc')
  472. ->orderBy('id', 'desc')
  473. ->paginate($pageSize);
  474. // 汇总统计:当前积分余额、累计消耗/退回积分、累计消耗token
  475. // 排除带 test_mode 标记的测试记录,保证统计口径与用户表实际余额一致
  476. $excludeTestRecords = function ($query) {
  477. $query->whereNull('charge_info')
  478. ->orWhereNull('charge_info->test_mode')
  479. ->orWhere('charge_info->test_mode', '!=', 'true');
  480. };
  481. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  482. $summary = [
  483. 'points_balance' => (int)getProp($user, 'points', 0),
  484. 'total_points_consumed' => (int)MpUserPointsDetail::where('uid', $uid)
  485. ->where('points_consumed', '>', 0)
  486. ->where($excludeTestRecords)
  487. ->sum('points_consumed'),
  488. 'total_points_refunded' => (int)MpUserPointsDetail::where('uid', $uid)
  489. ->where('points_consumed', '<', 0)
  490. ->whereNotIn('type', [MpUserPointsDetail::TYPE_SYSTEM, MpUserPointsDetail::TYPE_COMPANY])
  491. ->where($excludeTestRecords)
  492. ->sum('points_consumed'),
  493. 'total_points_granted' => (int)abs(MpUserPointsDetail::where('uid', $uid)
  494. ->whereIn('type', [MpUserPointsDetail::TYPE_SYSTEM, MpUserPointsDetail::TYPE_COMPANY])
  495. ->where('points_consumed', '<', 0)
  496. ->where($excludeTestRecords)
  497. ->sum('points_consumed')),
  498. 'total_tokens_consumed' => (int)MpUserPointsDetail::where('uid', $uid)
  499. ->where($excludeTestRecords)
  500. ->sum('tokens_consumed'),
  501. 'total_count' => (int)MpUserPointsDetail::where('uid', $uid)
  502. ->where($excludeTestRecords)
  503. ->count(),
  504. ];
  505. return [
  506. 'summary' => $summary,
  507. 'records' => $records,
  508. ];
  509. }
  510. /**
  511. * 发放/回收积分(公共方法)
  512. *
  513. * 权限规则:
  514. * - superadmin(平台):仅可对 role=admin(组织)操作,明细 type=system
  515. * - admin(组织):仅可对同 cpid 的 role=user(组员)操作,明细 type=company
  516. * - 其他角色不允许操作
  517. *
  518. * action=grant(发放,默认):目标用户积分增加,points_consumed 记负值(积分流入)
  519. * action=revoke(回收):目标用户积分减少,需校验目标积分充足(只针对组织/组员角色),points_consumed 记正值(积分流出)
  520. *
  521. * @param array $params uid(目标用户ID,支持多个ID用英文逗号隔开,如 "142857,142858")/ points(积分数,正整数)/ action(grant|revoke,默认 grant)/ remark(可选文案)
  522. * @return array
  523. */
  524. public function grantPoints(array $params): array
  525. {
  526. $uidRaw = trim((string)getProp($params, 'uid', ''));
  527. $points = (float)getProp($params, 'points', 0);
  528. $action = (string)getProp($params, 'action', 'grant');
  529. $remark = trim((string)getProp($params, 'remark', ''));
  530. // 解析 uid:单个ID或多个ID(英文逗号隔开),自动去重、忽略空白
  531. $uids = array_values(array_unique(array_filter(array_map(function ($v) {
  532. return (int)trim((string)$v);
  533. }, explode(',', $uidRaw)), function ($v) {
  534. return $v > 0;
  535. })));
  536. if (empty($uids)) {
  537. Utils::throwError('1002:请传入目标用户uid');
  538. }
  539. $this->validatePoints($points);
  540. $this->validateAction($action);
  541. // 单用户:保持原有返回结构
  542. if (count($uids) === 1) {
  543. try {
  544. DB::beginTransaction();
  545. $result = $this->applyPointsChange($uids[0], $points, $action, $remark);
  546. DB::commit();
  547. return $result;
  548. } catch (\Exception $e) {
  549. DB::rollBack();
  550. throw $e;
  551. }
  552. }
  553. // 多用户:先对全部目标校验(只读,不写库),任一失败整体拒绝;再单事务统一写库,保证原子性
  554. foreach ($uids as $uid) {
  555. $this->buildGrantContext($uid, $action, $points);
  556. }
  557. try {
  558. DB::beginTransaction();
  559. $results = [];
  560. foreach ($uids as $uid) {
  561. $results[] = $this->applyPointsChange($uid, $points, $action, $remark);
  562. }
  563. DB::commit();
  564. } catch (\Exception $e) {
  565. DB::rollBack();
  566. throw $e;
  567. }
  568. dLog('points')->info('积分批量操作成功', [
  569. 'action' => $action,
  570. 'count' => count($uids),
  571. 'points' => $points,
  572. ]);
  573. return [
  574. 'action' => $action,
  575. 'points' => $points,
  576. 'success_count' => count($results),
  577. 'results' => $results,
  578. ];
  579. }
  580. /**
  581. * 校验积分数(正整数)
  582. *
  583. * @param float $points
  584. * @return void
  585. */
  586. private function validatePoints(float $points): void
  587. {
  588. if ($points <= 0) {
  589. Utils::throwError('1002:积分数必须大于0');
  590. }
  591. if (floor($points) != $points) {
  592. Utils::throwError('1002:积分数必须为整数');
  593. }
  594. }
  595. /**
  596. * 校验操作类型
  597. *
  598. * @param string $action
  599. * @return void
  600. */
  601. private function validateAction(string $action): void
  602. {
  603. if (!in_array($action, ['grant', 'revoke'], true)) {
  604. Utils::throwError('1002:action仅支持grant(发放)或revoke(回收)');
  605. }
  606. }
  607. /**
  608. * 校验并构建单用户积分操作上下文(只读)
  609. *
  610. * 校验当前操作者角色、目标用户存在/启用、目标角色与公司归属;
  611. * 回收时额外校验目标用户积分充足;管理员发放时额外校验管理员自身可用积分充足。
  612. *
  613. * @param int $targetUid
  614. * @param string $action
  615. * @param float $points
  616. * @return array
  617. */
  618. private function buildGrantContext(int $targetUid, string $action, float $points): array
  619. {
  620. $fromUid = (int)Site::getUid();
  621. if ($fromUid <= 0) {
  622. Utils::throwError(ErrorConst::NOT_LOGIN);
  623. }
  624. $fromRole = (string)Site::getRole();
  625. $fromUser = DB::table('mp_manage_users')->where('id', $fromUid)->first();
  626. if (!$fromUser) {
  627. Utils::throwError(ErrorConst::USER_IS_NOT_EXIST);
  628. }
  629. $targetUser = DB::table('mp_manage_users')->where('id', $targetUid)->first();
  630. if (!$targetUser) {
  631. Utils::throwError('20003:目标用户不存在');
  632. }
  633. if ((int)getProp($targetUser, 'is_enabled', 1) === 0) {
  634. Utils::throwError('20003:目标用户已被禁用');
  635. }
  636. $targetRole = (string)getProp($targetUser, 'role', '');
  637. $targetCpid = (int)getProp($targetUser, 'cpid', 0);
  638. $verb = $action === 'revoke' ? '回收' : '发放';
  639. // 角色与操作对象校验
  640. if ($fromRole === 'superadmin') {
  641. if ($targetRole !== 'admin') {
  642. Utils::throwError('1005:平台仅可给组织' . $verb . '积分');
  643. }
  644. $type = MpUserPointsDetail::TYPE_SYSTEM;
  645. $defaultRemark = $action === 'revoke' ? '平台回收积分' : '平台发放积分';
  646. } elseif ($fromRole === 'admin') {
  647. if ($targetRole !== 'user') {
  648. Utils::throwError('1005:组织仅可给同公司的组员' . $verb . '积分');
  649. }
  650. if ($targetCpid !== (int)Site::getCpid()) {
  651. Utils::throwError('1005:只能给同一公司的组员' . $verb . '积分');
  652. }
  653. $type = MpUserPointsDetail::TYPE_COMPANY;
  654. $defaultRemark = $action === 'revoke' ? '组织回收积分' : '组织发放积分';
  655. } else {
  656. Utils::throwError('1005:当前角色无权操作积分');
  657. }
  658. // 回收时校验目标积分充足(目标只能是组织/组员角色,超管不在操作范围内,无需判断)
  659. if ($action === 'revoke') {
  660. $balance = (float)getProp($targetUser, 'points', 0);
  661. if ($balance < $points) {
  662. Utils::throwError('1002:目标用户积分不足,无法回收');
  663. }
  664. }
  665. // 管理员发放:积分从管理员自身扣减转移给组员,需校验管理员可用积分充足(平台发放不校验)
  666. if ($fromRole === 'admin' && $action === 'grant') {
  667. $operatorBalance = (float)getProp($fromUser, 'points', 0);
  668. if ($operatorBalance < $points) {
  669. Utils::throwError('1002:可用积分不足,无法发放');
  670. }
  671. }
  672. return [
  673. 'from_uid' => $fromUid,
  674. 'from_role' => $fromRole,
  675. 'from_cpid' => (int)getProp($fromUser, 'cpid', 0),
  676. 'from_user' => $fromUser,
  677. 'target_user' => $targetUser,
  678. 'target_role' => $targetRole,
  679. 'target_cpid' => $targetCpid,
  680. 'target_uid' => $targetUid,
  681. 'type' => $type,
  682. 'default_remark' => $defaultRemark,
  683. ];
  684. }
  685. /**
  686. * 对单个用户执行积分变动并写入明细(须在事务内调用)
  687. *
  688. * @param int $targetUid
  689. * @param float $points
  690. * @param string $action grant|revoke
  691. * @param string $remark
  692. * @return array
  693. */
  694. private function applyPointsChange(int $targetUid, float $points, string $action, string $remark): array
  695. {
  696. $ctx = $this->buildGrantContext($targetUid, $action, $points);
  697. $finalRemark = $remark !== '' ? $ctx['default_remark'] . ':' . $remark : $ctx['default_remark'];
  698. $chargeInfo = [
  699. 'from_uid' => $ctx['from_uid'],
  700. 'from_role' => $ctx['from_role'],
  701. 'target_uid' => $targetUid,
  702. 'target_role' => $ctx['target_role'],
  703. 'target_cpid' => $ctx['target_cpid'],
  704. 'grant_type' => $ctx['type'],
  705. 'action' => $action,
  706. ];
  707. $pointsBefore = (float)getProp($ctx['target_user'], 'points', 0);
  708. $delta = $action === 'revoke' ? -$points : $points;
  709. $pointsAfter = $pointsBefore + $delta;
  710. $now = date('Y-m-d H:i:s');
  711. $operatorAfter = null;
  712. // 原子更新余额,避免并发覆盖;COALESCE 处理余额为 NULL 的用户(NULL ± X 在 MySQL 中仍为 NULL)
  713. if ($ctx['from_role'] === 'admin') {
  714. // 转移模式:积分在管理员与组员之间流转,整体数额不变
  715. $operatorBefore = (float)getProp($ctx['from_user'], 'points', 0);
  716. if ($action === 'revoke') {
  717. // 组员扣减(带余额条件),管理员增加
  718. $affected = DB::table('mp_manage_users')
  719. ->where('id', $targetUid)
  720. ->whereRaw('COALESCE(points, 0) >= ?', [(float)$points])
  721. ->update([
  722. 'points' => DB::raw('COALESCE(points, 0) - ' . (float)$points),
  723. 'updated_at' => $now,
  724. ]);
  725. if ($affected === 0) {
  726. Utils::throwError('1002:目标用户积分不足,无法回收');
  727. }
  728. DB::table('mp_manage_users')->where('id', $ctx['from_uid'])->update([
  729. 'points' => DB::raw('COALESCE(points, 0) + ' . (float)$points),
  730. 'updated_at' => $now,
  731. ]);
  732. $operatorDelta = $points;
  733. } else {
  734. // 管理员扣减(带余额条件,防止并发超发),组员增加
  735. $affected = DB::table('mp_manage_users')
  736. ->where('id', $ctx['from_uid'])
  737. ->whereRaw('COALESCE(points, 0) >= ?', [(float)$points])
  738. ->update([
  739. 'points' => DB::raw('COALESCE(points, 0) - ' . (float)$points),
  740. 'updated_at' => $now,
  741. ]);
  742. if ($affected === 0) {
  743. Utils::throwError('1002:可用积分不足,无法发放');
  744. }
  745. DB::table('mp_manage_users')->where('id', $targetUid)->update([
  746. 'points' => DB::raw('COALESCE(points, 0) + ' . (float)$points),
  747. 'updated_at' => $now,
  748. ]);
  749. $operatorDelta = -$points;
  750. }
  751. $operatorAfter = $operatorBefore + $operatorDelta;
  752. // 管理员侧明细(方向与组员相反):发放记支出(正),回收记收入(负)
  753. DB::table('mp_user_points_details')->insert([
  754. 'uid' => $ctx['from_uid'],
  755. 'cpid' => $ctx['from_cpid'],
  756. 'task_id' => null,
  757. 'type' => $ctx['type'],
  758. 'api_type' => $action === 'revoke' ? 'revoke' : 'grant',
  759. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  760. 'points_before' => $operatorBefore,
  761. 'points_consumed' => -$operatorDelta,
  762. 'points_after' => $operatorAfter,
  763. 'tokens_consumed' => 0,
  764. 'remark' => $finalRemark,
  765. 'created_at' => $now,
  766. 'updated_at' => $now,
  767. ]);
  768. } elseif ($action === 'revoke') {
  769. // 平台回收:目标(组织)扣减,带余额条件
  770. $affected = DB::table('mp_manage_users')
  771. ->where('id', $targetUid)
  772. ->whereRaw('COALESCE(points, 0) >= ?', [(float)$points])
  773. ->update([
  774. 'points' => DB::raw('COALESCE(points, 0) - ' . (float)$points),
  775. 'updated_at' => $now,
  776. ]);
  777. if ($affected === 0) {
  778. Utils::throwError('1002:目标用户积分不足,无法回收');
  779. }
  780. } else {
  781. // 平台发放:目标(组织)增加(平台为积分源头,不校验平台余额)
  782. DB::table('mp_manage_users')->where('id', $targetUid)->update([
  783. 'points' => DB::raw('COALESCE(points, 0) + ' . (float)$points),
  784. 'updated_at' => $now,
  785. ]);
  786. }
  787. // 目标侧明细:发放 points_consumed 记负值(流入),回收记正值(流出)
  788. DB::table('mp_user_points_details')->insert([
  789. 'uid' => $targetUid,
  790. 'cpid' => $ctx['target_cpid'],
  791. 'task_id' => null,
  792. 'type' => $ctx['type'],
  793. 'api_type' => $action === 'revoke' ? 'revoke' : 'grant',
  794. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  795. 'points_before' => $pointsBefore,
  796. 'points_consumed' => -$delta,
  797. 'points_after' => $pointsAfter,
  798. 'tokens_consumed' => 0,
  799. 'remark' => $finalRemark,
  800. 'created_at' => $now,
  801. 'updated_at' => $now,
  802. ]);
  803. $result = [
  804. 'uid' => $targetUid,
  805. 'success' => true,
  806. 'action' => $action,
  807. 'type' => $ctx['type'],
  808. 'points' => $points,
  809. 'points_before' => $pointsBefore,
  810. 'points_after' => $pointsAfter,
  811. 'remark' => $finalRemark,
  812. ];
  813. if ($operatorAfter !== null) {
  814. $result['operator_uid'] = $ctx['from_uid'];
  815. $result['operator_points_before'] = $operatorBefore;
  816. $result['operator_points_after'] = $operatorAfter;
  817. }
  818. return $result;
  819. }
  820. /**
  821. * 获取可发放积分的用户列表(公共方法)
  822. *
  823. * 同一接口按当前角色返回不同列表:
  824. * - superadmin(平台):所有组织(role=admin)
  825. * - admin(组织):同 cpid 的组员(role=user)
  826. * - 其他角色不允许查看
  827. *
  828. * @return array
  829. */
  830. public function getGrantUserList(): array
  831. {
  832. $role = (string)Site::getRole();
  833. $query = DB::table('mp_manage_users')->where('is_enabled', 1);
  834. if ($role === 'superadmin') {
  835. $query->where('role', 'admin');
  836. } elseif ($role === 'admin') {
  837. $query->where('role', 'user')->where('cpid', (int)Site::getCpid());
  838. } else {
  839. Utils::throwError('1005:当前角色无权查看发放列表');
  840. }
  841. $users = $query->orderBy('cpid', 'asc')->orderBy('id', 'asc')
  842. ->get(['id', 'account', 'nickname', 'role', 'cpid', 'points', 'is_enabled'])
  843. ->map(function ($user) {
  844. return [
  845. 'id' => (int)getProp($user, 'id', 0),
  846. 'account' => (string)getProp($user, 'account', ''),
  847. 'nickname' => (string)getProp($user, 'nickname', ''),
  848. // 'role' => (string)getProp($user, 'role', ''),
  849. // 'cpid' => (int)getProp($user, 'cpid', 0),
  850. 'points' => (float)getProp($user, 'points', 0),
  851. // 'is_enabled' => (int)getProp($user, 'is_enabled', 1),
  852. ];
  853. })->all();
  854. return $users;
  855. }
  856. /**
  857. * 获取用户当前积分余额
  858. *
  859. * @param int $uid 用户ID,缺省取当前登录用户
  860. * @return float
  861. */
  862. public function getUserPointsBalance(int $uid = 0): float
  863. {
  864. if (!$uid) {
  865. $uid = (int)Site::getUid();
  866. }
  867. if (!$uid) {
  868. Utils::throwError(ErrorConst::NOT_LOGIN);
  869. }
  870. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  871. if (!$user) {
  872. Utils::throwError(ErrorConst::USER_IS_NOT_EXIST);
  873. }
  874. return (float)getProp($user, 'points', 0);
  875. }
  876. /**
  877. * 余额预检(公共方法)
  878. *
  879. * 计算视频/其他业务所需积分数后,在创建任务前调用;
  880. * 积分不足时直接抛错(20009:积分不足),业务方无需自行处理。
  881. *
  882. * @param float|int $pointsNeeded 需要扣除的积分数
  883. * @param int $uid 用户ID,缺省取当前登录用户
  884. * @return void
  885. */
  886. public function checkUserPointsEnough($pointsNeeded, int $uid = 0): void
  887. {
  888. $pointsNeeded = (float)$pointsNeeded;
  889. if ($pointsNeeded <= 0) {
  890. return;
  891. }
  892. // 测试用户(TEST_CPID / TEST_UID 白名单)跳过余额预检:只记录明细,不实际扣费
  893. if ($this->isTestUser($uid)) {
  894. return;
  895. }
  896. $balance = $this->getUserPointsBalance($uid);
  897. if ($balance < $pointsNeeded) {
  898. Utils::throwError(ErrorConst::POINTS_NOT_ENOUGH);
  899. }
  900. }
  901. /**
  902. * 判断是否为测试用户(TEST_CPID / TEST_UID 白名单)
  903. *
  904. * TEST_CPID / TEST_UID 在 .env 中为英文逗号分隔的纯字符串(如 "1"、"142857,142858"),
  905. * 读取后先转换为数组再判断。uid 命中 TEST_UID 或 cpid 命中 TEST_CPID(任一命中)即视为测试用户:
  906. * 预检不再校验余额,扣费只记录明细、不实际扣减积分。
  907. *
  908. * @param int $uid 用户ID,缺省取当前登录用户
  909. * @param int $cpid 公司ID,缺省取当前上下文公司ID
  910. * @return bool
  911. */
  912. public function isTestUser(int $uid = 0, int $cpid = 0): bool
  913. {
  914. if (!$uid) {
  915. $uid = (int)Site::getUid();
  916. }
  917. if (!$cpid) {
  918. $cpid = (int)Site::getCpid();
  919. }
  920. $testUids = $this->parseEnvList(env('TEST_UID'));
  921. $testCpids = $this->parseEnvList(env('TEST_CPID'));
  922. if (!empty($testUids) && in_array((string)$uid, $testUids, true)) {
  923. return true;
  924. }
  925. if (!empty($testCpids) && in_array((string)$cpid, $testCpids, true)) {
  926. return true;
  927. }
  928. return false;
  929. }
  930. /**
  931. * 将 env 中英文逗号分隔的字符串转换为数组
  932. *
  933. * @param mixed $value
  934. * @return array
  935. */
  936. private function parseEnvList($value): array
  937. {
  938. if ($value === null || $value === '') {
  939. return [];
  940. }
  941. $items = array_map('trim', explode(',', (string)$value));
  942. return array_values(array_filter($items, function ($item) {
  943. return $item !== '';
  944. }));
  945. }
  946. /**
  947. * 视频生成成功后记录计费明细并扣减用户积分
  948. *
  949. * 幂等处理:同一任务只允许计费一次(type + task_id 唯一索引兜底)。
  950. *
  951. * @param MpGenerateVideoTask $task
  952. * @return array
  953. */
  954. public function recordVideoTaskCharge(MpGenerateVideoTask $task): array
  955. {
  956. // 重复计费保护
  957. $exists = DB::table('mp_user_points_details')
  958. ->where('type', MpUserPointsDetail::TYPE_VIDEO)
  959. ->where('task_id', $task->id)
  960. ->exists();
  961. if ($exists) {
  962. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $task->id];
  963. }
  964. $chargeInfo = $task->charge_info;
  965. if (is_string($chargeInfo)) {
  966. $chargeInfo = json_decode($chargeInfo, true);
  967. }
  968. if (!is_array($chargeInfo) || empty($chargeInfo['user_id'])) {
  969. dLog('points')->warning('视频任务缺少计费信息,跳过扣费', ['task_id' => $task->id]);
  970. return ['charged' => false, 'reason' => 'no_charge_info', 'task_id' => $task->id];
  971. }
  972. // 自动时长(-1/0)时,用接口返回的实际时长回填计费信息
  973. $requestedDuration = (int)($chargeInfo['video_duration'] ?? -1);
  974. $actualDuration = $this->getActualVideoDuration($task);
  975. $durationBackfilled = $requestedDuration <= 0 && $actualDuration > 0;
  976. if ($durationBackfilled) {
  977. $chargeInfo['video_duration'] = $actualDuration;
  978. }
  979. $uid = (int)$chargeInfo['user_id'];
  980. $points = (float)$this->getVideoChargePoints($chargeInfo);
  981. $tokens = $this->getVideoTokensConsumed($task);
  982. $result = $this->deductAndRecord(
  983. $uid,
  984. $task->id,
  985. MpUserPointsDetail::TYPE_VIDEO,
  986. (string)getProp($task, 'api_type', ''),
  987. $points,
  988. $tokens,
  989. $chargeInfo,
  990. ''
  991. );
  992. // 自动时长被实际时长覆盖时,计费成功后同步回填任务表的 charge_info
  993. if ($durationBackfilled && !empty($result['charged'])) {
  994. $task->update(['charge_info' => $chargeInfo]);
  995. }
  996. return $result;
  997. }
  998. /**
  999. * 获取图片生成单张应扣积分数
  1000. *
  1001. * 从 mp_image_models 表读取(charge_type=per_image),按分辨率档位(1k/2k/4k)取单张积分。
  1002. *
  1003. * @param array $chargeInfo 计费信息(model、resolution、width、height 等)
  1004. * @return int
  1005. */
  1006. public function getImageChargePoints(array $chargeInfo = []): int
  1007. {
  1008. $model = (string)getProp($chargeInfo, 'model', '');
  1009. $resolution = strtolower((string)getProp($chargeInfo, 'resolution', '2k'));
  1010. $modelRow = DB::table('mp_image_models')->where('model', $model)->first();
  1011. if (!$modelRow || ($modelRow->charge_type ?? '') !== 'per_image') {
  1012. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  1013. }
  1014. $priceJson = $modelRow->price_json;
  1015. $prices = is_string($priceJson) ? json_decode($priceJson, true) : $priceJson;
  1016. if (!is_array($prices) || empty($prices)) {
  1017. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  1018. }
  1019. $price = $prices[$resolution] ?? null;
  1020. if ($price === null || (float)$price <= 0) {
  1021. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  1022. }
  1023. return (int)max(1, round((float)$price));
  1024. }
  1025. /**
  1026. * 根据图片宽高归一化分辨率档位(1k/2k/4k)
  1027. *
  1028. * 按宽高乘积(面积)分档更准确:各档面积几乎成平方关系——
  1029. * 1k≈1MP(1024x1024)、2k≈4MP(2048x2048、1600x2848)、3k≈9MP(3072x3072、4096x2304)、4k≈16MP(4096x4096)。
  1030. * 目前没有 3k 计费档,3k 尺寸直接按 4k 计费。
  1031. *
  1032. * @param int $width
  1033. * @param int $height
  1034. * @return string
  1035. */
  1036. public function normalizeImageResolutionKey(int $width, int $height): string
  1037. {
  1038. if ($width <= 0 || $height <= 0) {
  1039. return '2k';
  1040. }
  1041. // 面积分档:<2MP 视为 1k;2MP~6MP 视为 2k;≥6MP(含3k/4k尺寸)按 4k 计费
  1042. $area = $width * $height;
  1043. if ($area < 2048 * 1024) {
  1044. return '1k';
  1045. }
  1046. if ($area < 2048 * 3072) {
  1047. return '2k';
  1048. }
  1049. return '4k';
  1050. }
  1051. /**
  1052. * 获取图片生成任务实际消耗的 token 量
  1053. *
  1054. * 图片接口返回格式:result_json.usage.total_tokens / output_tokens
  1055. *
  1056. * @param MpGeneratePicTask $task
  1057. * @return int
  1058. */
  1059. public function getImageTokensConsumed(MpGeneratePicTask $task): int
  1060. {
  1061. $resultJson = $task->result_json;
  1062. if (is_string($resultJson)) {
  1063. $resultJson = json_decode($resultJson, true);
  1064. }
  1065. if (!is_array($resultJson)) {
  1066. return 0;
  1067. }
  1068. $tokens = $resultJson['usage']['total_tokens'] ?? $resultJson['usage']['output_tokens'] ?? 0;
  1069. return (int)$tokens;
  1070. }
  1071. /**
  1072. * 从 AI 对话接口返回的 usage 中提取消耗的 token 数
  1073. *
  1074. * DeepSeek/OpenAI 格式:usage.total_tokens / usage.completion_tokens
  1075. * Gemini 格式:usageMetadata.totalTokenCount(含思考 token),缺省时按 prompt + candidates 合计
  1076. *
  1077. * @param mixed $usage
  1078. * @return int
  1079. */
  1080. public function getTokensFromUsage($usage): int
  1081. {
  1082. if (is_string($usage)) {
  1083. $usage = json_decode($usage, true);
  1084. }
  1085. if (!is_array($usage)) {
  1086. return 0;
  1087. }
  1088. $tokens = $usage['total_tokens']
  1089. ?? $usage['completion_tokens']
  1090. ?? $usage['totalTokenCount']
  1091. ?? (
  1092. isset($usage['promptTokenCount']) || isset($usage['candidatesTokenCount'])
  1093. ? (int)($usage['promptTokenCount'] ?? 0)
  1094. + (int)($usage['candidatesTokenCount'] ?? 0)
  1095. + (int)($usage['thoughtsTokenCount'] ?? 0)
  1096. : 0
  1097. );
  1098. return (int)$tokens;
  1099. }
  1100. /**
  1101. * AI对话调用成功后记录计费明细并扣减用户积分
  1102. *
  1103. * 无对应任务表,task_id 为 NULL((type, task_id) 唯一索引下多个 NULL 互不冲突)。
  1104. *
  1105. * @param int $uid
  1106. * @param int $points
  1107. * @param int $tokens
  1108. * @param array $chargeInfo
  1109. * @param string $remark 特殊备注(默认空,测试用户由内部追加[测试]仅记账不扣费)
  1110. * @param string $apiType
  1111. * @return array
  1112. */
  1113. public function recordChatCharge(int $uid, int $points, int $tokens, array $chargeInfo = [], string $remark = '', string $apiType = 'deepseek'): array
  1114. {
  1115. return $this->deductAndRecord(
  1116. $uid,
  1117. null,
  1118. MpUserPointsDetail::TYPE_CHAT,
  1119. $apiType,
  1120. (float)$points,
  1121. $tokens,
  1122. $chargeInfo,
  1123. $remark
  1124. );
  1125. }
  1126. /**
  1127. * 仅记录 token 使用明细,不扣减积分、不写积分消耗
  1128. *
  1129. * 用于不按积分计费的文生文接口(免费/不扣积分场景),复用 mp_user_points_details 表:
  1130. * points_consumed=0,仅填写 tokens_consumed,保证累计 token 统计口径一致。
  1131. * uid<=0(无登录上下文)或 tokens<=0 时不落库。
  1132. *
  1133. * @param int $uid 用户ID
  1134. * @param int $tokens 消耗 token 数
  1135. * @param array $chargeInfo 计费/来源信息(model、source 等)
  1136. * @param string $type 明细类型(默认 chat)
  1137. * @param string $apiType API 类型/模型标识
  1138. * @param string $remark 备注
  1139. * @return bool 是否落库成功
  1140. */
  1141. public function recordTokenOnlyDetail(int $uid, int $tokens, array $chargeInfo = [], string $type = MpUserPointsDetail::TYPE_CHAT, string $apiType = '', string $remark = ''): bool
  1142. {
  1143. if ($uid <= 0 || $tokens <= 0) {
  1144. return false;
  1145. }
  1146. try {
  1147. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  1148. $cpid = (int)getProp($user, 'cpid', 0);
  1149. $pointsBalance = (float)getProp($user, 'points', 0);
  1150. // 测试用户标记:保证统计排除口径与扣费明细一致
  1151. $isTestUser = $this->isTestUser($uid, $cpid);
  1152. if ($isTestUser) {
  1153. $chargeInfo['test_mode'] = true;
  1154. $remark = trim(($remark ? $remark . ';' : '') . '[测试]仅记账不扣费');
  1155. }
  1156. DB::table('mp_user_points_details')->insert([
  1157. 'uid' => $uid,
  1158. 'cpid' => $cpid,
  1159. 'task_id' => null,
  1160. 'type' => $type,
  1161. 'api_type' => $apiType,
  1162. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  1163. 'points_consumed' => 0,
  1164. 'points_before' => $pointsBalance,
  1165. 'points_after' => $pointsBalance,
  1166. 'tokens_consumed' => $tokens,
  1167. 'remark' => $remark,
  1168. 'created_at' => date('Y-m-d H:i:s'),
  1169. 'updated_at' => date('Y-m-d H:i:s')
  1170. ]);
  1171. dLog('points')->info('token明细记录成功', [
  1172. 'uid' => $uid,
  1173. 'tokens_consumed' => $tokens,
  1174. 'source' => $chargeInfo['source'] ?? '',
  1175. 'test_mode' => $isTestUser
  1176. ]);
  1177. return true;
  1178. } catch (\Exception $e) {
  1179. dLog('points')->error('token明细记录失败: ' . $e->getMessage(), ['uid' => $uid]);
  1180. logDB('points', 'error', 'token明细记录失败', [
  1181. 'uid' => $uid,
  1182. 'tokens_consumed' => $tokens,
  1183. 'error' => $e->getMessage()
  1184. ]);
  1185. return false;
  1186. }
  1187. }
  1188. /**
  1189. * 图片生成成功后记录计费明细并扣减用户积分
  1190. *
  1191. * 幂等处理:同一任务只允许计费一次(type + task_id 唯一索引兜底)。
  1192. *
  1193. * @param MpGeneratePicTask $task
  1194. * @return array
  1195. */
  1196. public function recordImageTaskCharge(MpGeneratePicTask $task): array
  1197. {
  1198. // 重复计费保护
  1199. $exists = DB::table('mp_user_points_details')
  1200. ->where('type', MpUserPointsDetail::TYPE_IMAGE)
  1201. ->where('task_id', $task->id)
  1202. ->exists();
  1203. if ($exists) {
  1204. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $task->id];
  1205. }
  1206. $chargeInfo = $task->charge_info;
  1207. if (is_string($chargeInfo)) {
  1208. $chargeInfo = json_decode($chargeInfo, true);
  1209. }
  1210. if (!is_array($chargeInfo) || empty($chargeInfo['user_id'])) {
  1211. dLog('points')->warning('图片任务缺少计费信息,跳过扣费', ['task_id' => $task->id]);
  1212. return ['charged' => false, 'reason' => 'no_charge_info', 'task_id' => $task->id];
  1213. }
  1214. $uid = (int)$chargeInfo['user_id'];
  1215. // 积分 = 单张价格 × 实际生成图片数
  1216. $pointsPerImage = (float)$this->getImageChargePoints($chargeInfo);
  1217. $imageCount = is_array($task->result_url) ? count($task->result_url) : 0;
  1218. if ($imageCount <= 0) {
  1219. $imageCount = (int)($chargeInfo['image_num'] ?? 1);
  1220. }
  1221. if ($imageCount <= 0) {
  1222. $imageCount = 1;
  1223. }
  1224. // 单张价格 × 实际生成图片数(未配置价格时为0,仍记录明细与token)
  1225. $points = (float)round($pointsPerImage * $imageCount);
  1226. $tokens = $this->getImageTokensConsumed($task);
  1227. return $this->deductAndRecord(
  1228. $uid,
  1229. $task->id,
  1230. MpUserPointsDetail::TYPE_IMAGE,
  1231. (string)getProp($task, 'model', ''),
  1232. $points,
  1233. $tokens,
  1234. $chargeInfo,
  1235. ''
  1236. );
  1237. }
  1238. /**
  1239. * 扣减积分并记录积分使用明细(视频/图片共用)
  1240. *
  1241. * @param int $uid
  1242. * @param int $taskId
  1243. * @param string $type
  1244. * @param string $apiType
  1245. * @param float $points
  1246. * @param int $tokens
  1247. * @param array $chargeInfo
  1248. * @param string $remark
  1249. * @return array
  1250. */
  1251. private function deductAndRecord(int $uid, ?int $taskId, string $type, string $apiType, float $points, int $tokens, array $chargeInfo, string $remark): array
  1252. {
  1253. try {
  1254. DB::beginTransaction();
  1255. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  1256. if (!$user) {
  1257. DB::rollBack();
  1258. dLog('points')->error('扣费失败:用户不存在', ['task_id' => $taskId, 'uid' => $uid]);
  1259. return ['charged' => false, 'reason' => 'user_not_found', 'task_id' => $taskId];
  1260. }
  1261. $pointsBefore = (float)getProp($user, 'points', 0);
  1262. // 测试用户(TEST_CPID / TEST_UID 白名单):只记录明细,不实际扣减积分余额
  1263. $isTestUser = $this->isTestUser($uid, (int)getProp($user, 'cpid', 0));
  1264. $pointsAfter = $isTestUser ? $pointsBefore : $pointsBefore - $points;
  1265. // 测试标记落库:charge_info 写入 test_mode,remark 追加 [测试],便于统计排除与历史排查
  1266. if ($isTestUser) {
  1267. $chargeInfo['test_mode'] = true;
  1268. $remark = trim(($remark ? $remark . ';' : '') . '[测试]仅记账不扣费');
  1269. }
  1270. if (!$isTestUser && $pointsBefore < $points) {
  1271. dLog('points')->warning('用户积分不足,扣费后积分为负数', [
  1272. 'task_id' => $taskId,
  1273. 'uid' => $uid,
  1274. 'points_before' => $pointsBefore,
  1275. 'points_consumed' => $points
  1276. ]);
  1277. }
  1278. if (!$isTestUser) {
  1279. // 原子扣减积分:基于数据库当前值执行(points = points - X),
  1280. // 避免并发处理不同任务时基于旧快照覆盖写入导致丢失更新(少扣);
  1281. // COALESCE 处理余额为 NULL 的用户(NULL - X 在 MySQL 中仍为 NULL)
  1282. DB::table('mp_manage_users')->where('id', $uid)->update([
  1283. 'points' => DB::raw('COALESCE(points, 0) - ' . (float)$points),
  1284. 'updated_at' => date('Y-m-d H:i:s')
  1285. ]);
  1286. }
  1287. // 记录积分使用明细
  1288. DB::table('mp_user_points_details')->insert([
  1289. 'uid' => $uid,
  1290. 'cpid' => (int)getProp($user, 'cpid', 0),
  1291. 'task_id' => $taskId,
  1292. 'type' => $type,
  1293. 'api_type' => $apiType,
  1294. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  1295. 'points_consumed' => $points,
  1296. 'points_before' => $pointsBefore,
  1297. 'points_after' => $pointsAfter,
  1298. 'tokens_consumed' => $tokens,
  1299. 'remark' => $remark,
  1300. 'created_at' => date('Y-m-d H:i:s'),
  1301. 'updated_at' => date('Y-m-d H:i:s')
  1302. ]);
  1303. DB::commit();
  1304. dLog('points')->info($type . '计费成功', [
  1305. 'task_id' => $taskId,
  1306. 'uid' => $uid,
  1307. 'points_consumed' => $points,
  1308. 'points_after' => $pointsAfter,
  1309. 'tokens_consumed' => $tokens,
  1310. 'test_mode' => $isTestUser
  1311. ]);
  1312. return [
  1313. 'charged' => true,
  1314. 'task_id' => $taskId,
  1315. 'uid' => $uid,
  1316. 'points_consumed' => $points,
  1317. 'points_before' => $pointsBefore,
  1318. 'points_after' => $pointsAfter,
  1319. 'tokens_consumed' => $tokens,
  1320. 'test_mode' => $isTestUser
  1321. ];
  1322. } catch (\Exception $e) {
  1323. DB::rollBack();
  1324. // 唯一索引冲突:同一任务已被其他请求计费,视为已计费(并发验重兜底,避免误报计费失败)
  1325. if ($this->isDuplicateCharge($e)) {
  1326. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $taskId];
  1327. }
  1328. dLog('points')->error($type . '计费失败: ' . $e->getMessage(), ['task_id' => $taskId]);
  1329. logDB('points', 'error', $type . '计费失败', [
  1330. 'task_id' => $taskId,
  1331. 'error' => $e->getMessage()
  1332. ]);
  1333. return ['charged' => false, 'reason' => 'exception: ' . $e->getMessage(), 'task_id' => $taskId];
  1334. }
  1335. }
  1336. /**
  1337. * 判断异常是否为数据库唯一键冲突(重复计费)
  1338. *
  1339. * @param \Exception $e
  1340. * @return bool
  1341. */
  1342. private function isDuplicateCharge(\Exception $e): bool
  1343. {
  1344. // MySQL 重复键:SQLSTATE 23000 / 错误码 1062(Duplicate entry)
  1345. $code = $e->getCode();
  1346. if ($code === 23000 || $code === '23000' || $code === 1062 || $code === '1062') {
  1347. return true;
  1348. }
  1349. return mb_strpos($e->getMessage(), 'Duplicate entry') !== false;
  1350. }
  1351. }