PointsService.php 63 KB

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