PointsService.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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. // 其他API:优先从 usage 中读取
  172. $tokens = $resultJson['usage']['total_tokens']
  173. ?? $resultJson['usage']['completion_tokens']
  174. ?? $resultJson['content']['usage']['total_tokens']
  175. ?? 0;
  176. return (int)$tokens;
  177. }
  178. /**
  179. * 从接口返回结果中获取实际视频时长(秒)
  180. *
  181. * 各 API 返回格式不同,按 api_type 分别解析;
  182. * 用于 charge_info 中自动时长(-1/0)的任务在成功扣费时回填实际时长。
  183. *
  184. * @param MpGenerateVideoTask $task
  185. * @return int
  186. */
  187. public function getActualVideoDuration(MpGenerateVideoTask $task): int
  188. {
  189. $resultJson = $task->result_json;
  190. if (is_string($resultJson)) {
  191. $resultJson = json_decode($resultJson, true);
  192. }
  193. if (!is_array($resultJson)) {
  194. return 0;
  195. }
  196. switch ($task->api_type) {
  197. case 'zzengine':
  198. return (int)($resultJson['data']['task']['detail']['duration'] ?? 0);
  199. case 'jimeng':
  200. $data = $resultJson['data'] ?? [];
  201. if (!empty($data['duration'])) {
  202. return (int)$data['duration'];
  203. }
  204. if (isset($data['frames'], $data['framespersecond']) && (int)$data['framespersecond'] > 0) {
  205. return (int)floor((int)$data['frames'] / (int)$data['framespersecond']);
  206. }
  207. return 0;
  208. case 'keling':
  209. $taskData = $resultJson['data'] ?? [];
  210. $video = $taskData['task_result']['videos'][0] ?? [];
  211. if (!empty($video['duration'])) {
  212. return (int)$video['duration'];
  213. }
  214. if (!empty($taskData['duration'])) {
  215. return (int)$taskData['duration'];
  216. }
  217. if (isset($video['frames'], $video['framespersecond']) && (int)$video['framespersecond'] > 0) {
  218. return (int)floor((int)$video['frames'] / (int)$video['framespersecond']);
  219. }
  220. return 0;
  221. case 'seedance':
  222. default:
  223. return (int)($resultJson['duration'] ?? 0);
  224. }
  225. }
  226. /**
  227. * 获取系统当前全部积分规则(公共方法)
  228. *
  229. * - chat:文生文(对话)规则,含全局默认扣分与各文本模型按 model 配置的扣分
  230. * - image_models:图片模型计费规则(mp_image_models)
  231. * - video_models:视频模型计费规则(mp_video_models)
  232. *
  233. * @return array
  234. */
  235. public function getPointsRules(): array
  236. {
  237. $textModels = DB::table('mp_text_models')->orderBy('order', 'desc')->orderBy('id', 'desc')->where('is_enabled', 1)->get();
  238. $imageModels = DB::table('mp_image_models')->orderBy('order', 'desc')->orderBy('id', 'desc')->where('is_enabled', 1)->get();
  239. $videoModels = DB::table('mp_video_models')->orderBy('order', 'desc')->orderBy('id', 'desc')->where('is_enabled', 1)->get();
  240. // $textList = [];
  241. // foreach ($textModels as $row) {
  242. // $item = $this->formatModelRule($row);
  243. // $item['charge_points'] = $this->getChatChargePoints((string)$row->model);
  244. // $textList[] = $item;
  245. // }
  246. $textModel = DB::table('mp_text_models')->where('is_enabled', 1)->whereNotNull('price_json')->first();
  247. if ($textModel) {
  248. $price = $this->getChatChargePoints($textModel->model);
  249. $charge_type = 'per_call';
  250. }else {
  251. $price = self::CHAT_CHARGE_POINTS;
  252. $charge_type = 'per_call';
  253. }
  254. return [
  255. 'chat' => [
  256. 'charge_type' => $charge_type,
  257. 'price_json' => ['price'=>$price],
  258. // 'models' => $textList,
  259. ],
  260. 'image_models' => array_map([$this, 'formatModelRule'], $imageModels->all()),
  261. 'video_models' => array_map([$this, 'formatModelRule'], $videoModels->all()),
  262. ];
  263. }
  264. /**
  265. * 将模型表中的计费配置行整理为前端友好结构
  266. *
  267. * price_json 统一解析为数组返回(空配置返回空对象)。
  268. *
  269. * @param object $row
  270. * @return array
  271. */
  272. private function formatModelRule($row): array
  273. {
  274. $priceJson = getProp($row, 'price_json');
  275. $price = is_string($priceJson) ? json_decode($priceJson, true) : $priceJson;
  276. if (!is_array($price)) {
  277. $price = new \stdClass();
  278. }
  279. return [
  280. // 'id' => (int)getProp($row, 'id', 0),
  281. 'model' => (string)getProp($row, 'model', ''),
  282. 'name' => (string)getProp($row, 'name', ''),
  283. // 'description' => (string)getProp($row, 'description', ''),
  284. // 'is_enabled' => (int)getProp($row, 'is_enabled', 1),
  285. // 'order' => (int)getProp($row, 'order', 0),
  286. 'is_multimodal' => (int)getProp($row, 'is_multimodal', 0),
  287. 'charge_type' => (string)getProp($row, 'charge_type', ''),
  288. 'price_json' => $price,
  289. ];
  290. }
  291. /**
  292. * 更新积分规则(公共方法)
  293. *
  294. * 支持三个区块,均可选传,未传区块不处理:
  295. * - text_rules:文生文(对话)按 model 更新(不传 model 时更新全部模型),charge_type 仅支持 per_call,price_json 为 {"price": 积分}
  296. * - image_rules:图片按 model 更新,charge_type 仅支持 per_image,price_json 为 {"1k": 积分, "2k": 积分, "4k": 积分}
  297. * - video_rules:视频按 model 更新,charge_type 支持 per_second / per_call
  298. * per_second 的 price_json 为 {"场景": {"分辨率": 单价/秒}};per_call 的 price_json 为 {"price": 积分}
  299. *
  300. * 每条规则至少需传 charge_type 或 price_json 之一;未传的字段保留原值。
  301. *
  302. * @param array $params
  303. * @return array 各区块实际更新的 model 列表
  304. */
  305. public function updatePointsRules(array $params): array
  306. {
  307. $updated = ['text' => [], 'image' => [], 'video' => []];
  308. if (isset($params['text_rules']) && is_array($params['text_rules'])) {
  309. foreach ($params['text_rules'] as $rule) {
  310. $updated['text'] = array_merge(
  311. $updated['text'],
  312. $this->updateModelRule('mp_text_models', $rule, ['per_call'], false, true)
  313. );
  314. }
  315. }
  316. if (isset($params['image_rules']) && is_array($params['image_rules'])) {
  317. foreach ($params['image_rules'] as $rule) {
  318. $updated['image'] = array_merge(
  319. $updated['image'],
  320. $this->updateModelRule('mp_image_models', $rule, ['per_image'], false)
  321. );
  322. }
  323. }
  324. if (isset($params['video_rules']) && is_array($params['video_rules'])) {
  325. foreach ($params['video_rules'] as $rule) {
  326. $updated['video'] = array_merge(
  327. $updated['video'],
  328. $this->updateModelRule('mp_video_models', $rule, ['per_second', 'per_call'], true)
  329. );
  330. }
  331. }
  332. return $updated;
  333. }
  334. /**
  335. * 更新单个模型的计费配置
  336. *
  337. * @param string $table 模型表名
  338. * @param array $rule 规则(model / charge_type / price_json)
  339. * @param array $chargeTypes 允许的计费方式
  340. * @param bool $nestedPrice 是否允许嵌套价格结构(视频按场景+分辨率)
  341. * @param bool $allowAll 是否允许不传 model 时更新该表全部模型(仅文生文使用)
  342. * @return array 实际更新的 model 列表
  343. */
  344. private function updateModelRule(string $table, array $rule, array $chargeTypes, bool $nestedPrice, bool $allowAll = false): array
  345. {
  346. $model = trim((string)getProp($rule, 'model', ''));
  347. if ($model === '' && !$allowAll) {
  348. Utils::throwError('1002:规则缺少model参数');
  349. }
  350. $data = [];
  351. if (array_key_exists('charge_type', $rule)) {
  352. $chargeType = (string)getProp($rule, 'charge_type', '');
  353. if (!in_array($chargeType, $chargeTypes, true)) {
  354. Utils::throwError('1002:' . $table . '计费方式不合法:' . $chargeType);
  355. }
  356. $data['charge_type'] = $chargeType;
  357. }
  358. if (array_key_exists('price_json', $rule)) {
  359. $price = getProp($rule, 'price_json', null);
  360. $priceArr = $nestedPrice
  361. ? $this->normalizeNestedPrice($price)
  362. : $this->normalizeFlatPrice($price);
  363. $data['price_json'] = json_encode($priceArr, JSON_UNESCAPED_UNICODE);
  364. }
  365. if (empty($data)) {
  366. Utils::throwError('1002:' . $table . '规则请至少传入charge_type或price_json');
  367. }
  368. if ($model !== '') {
  369. if (!DB::table($table)->where('model', $model)->exists()) {
  370. Utils::throwError('1002:模型不存在:' . $model);
  371. }
  372. DB::table($table)->where('model', $model)->update($data);
  373. return [$model];
  374. }
  375. // 未传 model(仅文生文支持):更新该表全部模型
  376. $allModels = DB::table($table)->pluck('model')->all();
  377. if (empty($allModels)) {
  378. Utils::throwError('1002:' . $table . '没有可更新的模型');
  379. }
  380. DB::table($table)->update($data);
  381. return $allModels;
  382. }
  383. /**
  384. * 校验并归一化一层价格结构(文生文/图片)
  385. *
  386. * 所有 key 对应的值必须为不小于 0 的数字;支持传入对象或 JSON 字符串。
  387. *
  388. * @param mixed $price
  389. * @return array
  390. */
  391. private function normalizeFlatPrice($price): array
  392. {
  393. $priceArr = is_string($price) ? json_decode($price, true) : $price;
  394. if (!is_array($priceArr) || empty($priceArr)) {
  395. Utils::throwError('1002:price格式不正确');
  396. }
  397. $result = [];
  398. foreach ($priceArr as $key => $value) {
  399. if (!is_numeric($value) || (float)$value < 0) {
  400. Utils::throwError('1002:price.' . $key . '必须为不小于0的数字');
  401. }
  402. $result[(string)$key] = (float)$value;
  403. }
  404. return $result;
  405. }
  406. /**
  407. * 校验并归一化嵌套价格结构(视频按场景+分辨率)
  408. *
  409. * 支持如 {"video_generation": {"720p": 10, "1080p": 25}} 或 {"price": 5}。
  410. *
  411. * @param mixed $price
  412. * @return array
  413. */
  414. private function normalizeNestedPrice($price): array
  415. {
  416. $priceArr = is_string($price) ? json_decode($price, true) : $price;
  417. if (!is_array($priceArr) || empty($priceArr)) {
  418. Utils::throwError('1002:price格式不正确');
  419. }
  420. $result = [];
  421. foreach ($priceArr as $key => $value) {
  422. if (is_array($value)) {
  423. $result[(string)$key] = $this->normalizeFlatPrice($value);
  424. } elseif (is_numeric($value) && (float)$value >= 0) {
  425. $result[(string)$key] = (float)$value;
  426. } else {
  427. Utils::throwError('1002:price.' . $key . '必须为不小于0的数字或对象');
  428. }
  429. }
  430. return $result;
  431. }
  432. /**
  433. * 获取用户积分流水
  434. *
  435. * @param array $params uid/type/start_date/end_date/page_size
  436. * @return array
  437. */
  438. public function getUserPointsRecords(array $params = []): array
  439. {
  440. $uid = (int)getProp($params, 'uid', 0);
  441. if (!$uid) {
  442. $uid = (int)Site::getUid();
  443. }
  444. $type = getProp($params, 'type', '');
  445. $startDate = getProp($params, 'start_date', '');
  446. $endDate = getProp($params, 'end_date', '');
  447. $pageSize = (int)getProp($params, 'page_size', 15);
  448. if ($pageSize < 1 || $pageSize > 100) {
  449. $pageSize = 15;
  450. }
  451. $query = MpUserPointsDetail::where('uid', $uid);
  452. if ($type) {
  453. $query->where('type', $type);
  454. }
  455. if ($startDate) {
  456. $query->where('created_at', '>=', $startDate . ' 00:00:00');
  457. }
  458. if ($endDate) {
  459. $query->where('created_at', '<=', $endDate . ' 23:59:59');
  460. }
  461. $records = $query->orderBy('created_at', 'desc')
  462. ->orderBy('id', 'desc')
  463. ->paginate($pageSize);
  464. // 汇总统计:当前积分余额、累计消耗/退回积分、累计消耗token
  465. // 排除带 test_mode 标记的测试记录,保证统计口径与用户表实际余额一致
  466. $excludeTestRecords = function ($query) {
  467. $query->whereNull('charge_info')
  468. ->orWhereNull('charge_info->test_mode')
  469. ->orWhere('charge_info->test_mode', '!=', 'true');
  470. };
  471. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  472. $summary = [
  473. 'points_balance' => (float)getProp($user, 'points', 0),
  474. 'total_points_consumed' => (float)MpUserPointsDetail::where('uid', $uid)
  475. ->where('points_consumed', '>', 0)
  476. ->where($excludeTestRecords)
  477. ->sum('points_consumed'),
  478. 'total_points_refunded' => (float)MpUserPointsDetail::where('uid', $uid)
  479. ->where('points_consumed', '<', 0)
  480. ->whereNotIn('type', [MpUserPointsDetail::TYPE_SYSTEM, MpUserPointsDetail::TYPE_COMPANY])
  481. ->where($excludeTestRecords)
  482. ->sum('points_consumed'),
  483. 'total_points_granted' => (float)abs(MpUserPointsDetail::where('uid', $uid)
  484. ->whereIn('type', [MpUserPointsDetail::TYPE_SYSTEM, MpUserPointsDetail::TYPE_COMPANY])
  485. ->where('points_consumed', '<', 0)
  486. ->where($excludeTestRecords)
  487. ->sum('points_consumed')),
  488. 'total_tokens_consumed' => (int)MpUserPointsDetail::where('uid', $uid)
  489. ->where($excludeTestRecords)
  490. ->sum('tokens_consumed'),
  491. 'total_count' => (int)MpUserPointsDetail::where('uid', $uid)
  492. ->where($excludeTestRecords)
  493. ->count(),
  494. ];
  495. return [
  496. 'summary' => $summary,
  497. 'records' => $records,
  498. ];
  499. }
  500. /**
  501. * 发放积分(公共方法)
  502. *
  503. * 权限规则:
  504. * - superadmin(平台):仅可给 role=admin(组织)发放积分,明细 type=system
  505. * - admin(组织):仅可给同 cpid 的 role=user(组员)发放积分,明细 type=company
  506. * - 其他角色不允许发放
  507. *
  508. * 发放成功后写入 mp_user_points_details(points_consumed 记负值,表示积分流入),
  509. * 并原子累加目标用户余额。
  510. *
  511. * @param array $params uid(目标用户ID)/ points(发放积分数,正数)/ remark(可选文案)
  512. * @return array
  513. */
  514. public function grantPoints(array $params): array
  515. {
  516. $fromUid = (int)Site::getUid();
  517. $fromRole = (string)Site::getRole();
  518. if ($fromUid <= 0) {
  519. Utils::throwError(ErrorConst::NOT_LOGIN);
  520. }
  521. $fromUser = DB::table('mp_manage_users')->where('id', $fromUid)->first();
  522. if (!$fromUser) {
  523. Utils::throwError(ErrorConst::USER_IS_NOT_EXIST);
  524. }
  525. $targetUid = (int)getProp($params, 'uid', 0);
  526. $points = (float)getProp($params, 'points', 0);
  527. $remark = trim((string)getProp($params, 'remark', ''));
  528. if ($targetUid <= 0) {
  529. Utils::throwError('1002:请传入目标用户uid');
  530. }
  531. if ($points <= 0) {
  532. Utils::throwError('1002:发放积分数必须大于0');
  533. }
  534. if (floor($points) != $points) {
  535. Utils::throwError('1002:发放积分数必须为整数');
  536. }
  537. $targetUser = DB::table('mp_manage_users')->where('id', $targetUid)->first();
  538. if (!$targetUser) {
  539. Utils::throwError('20003:目标用户不存在');
  540. }
  541. if ((int)getProp($targetUser, 'is_enabled', 1) === 0) {
  542. Utils::throwError('20003:目标用户已被禁用');
  543. }
  544. $targetRole = (string)getProp($targetUser, 'role', '');
  545. $targetCpid = (int)getProp($targetUser, 'cpid', 0);
  546. // 角色与发放对象校验
  547. if ($fromRole === 'superadmin') {
  548. if ($targetRole !== 'admin') {
  549. Utils::throwError('1005:平台仅可给组织发放积分');
  550. }
  551. $type = MpUserPointsDetail::TYPE_SYSTEM;
  552. $defaultRemark = '平台发放积分';
  553. } elseif ($fromRole === 'admin') {
  554. if ($targetRole !== 'user') {
  555. Utils::throwError('1005:组织仅可给同公司的组员发放积分');
  556. }
  557. if ($targetCpid !== (int)Site::getCpid()) {
  558. Utils::throwError('1005:只能给同一公司的组员发放积分');
  559. }
  560. $type = MpUserPointsDetail::TYPE_COMPANY;
  561. $defaultRemark = '组织发放积分';
  562. } else {
  563. Utils::throwError('1005:当前角色无权发放积分');
  564. }
  565. $finalRemark = $remark !== '' ? $defaultRemark . ':' . $remark : $defaultRemark;
  566. $chargeInfo = [
  567. 'from_uid' => $fromUid,
  568. 'from_role' => $fromRole,
  569. 'target_role' => $targetRole,
  570. 'target_cpid' => $targetCpid,
  571. 'grant_type' => $type,
  572. ];
  573. try {
  574. DB::beginTransaction();
  575. $pointsBefore = (float)getProp($targetUser, 'points', 0);
  576. $pointsAfter = $pointsBefore + $points;
  577. // 原子累加积分余额,避免并发覆盖
  578. DB::table('mp_manage_users')->where('id', $targetUid)->update([
  579. 'points' => DB::raw('points + ' . (float)$points),
  580. 'updated_at' => date('Y-m-d H:i:s'),
  581. ]);
  582. // 发放明细:points_consumed 记负值,表示积分流入
  583. DB::table('mp_user_points_details')->insert([
  584. 'uid' => $targetUid,
  585. 'cpid' => $targetCpid,
  586. 'task_id' => null,
  587. 'type' => $type,
  588. 'api_type' => 'grant',
  589. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  590. 'points_before' => $pointsBefore,
  591. 'points_consumed' => -$points,
  592. 'points_after' => $pointsAfter,
  593. 'tokens_consumed' => 0,
  594. 'remark' => $finalRemark,
  595. 'created_at' => date('Y-m-d H:i:s'),
  596. 'updated_at' => date('Y-m-d H:i:s'),
  597. ]);
  598. DB::commit();
  599. dLog('points')->info('积分发放成功', [
  600. 'from_uid' => $fromUid,
  601. 'from_role' => $fromRole,
  602. 'target_uid' => $targetUid,
  603. 'points' => $points,
  604. 'type' => $type,
  605. ]);
  606. return [
  607. 'granted' => true,
  608. 'type' => $type,
  609. 'uid' => $targetUid,
  610. 'points' => $points,
  611. 'points_before' => $pointsBefore,
  612. 'points_after' => $pointsAfter,
  613. 'remark' => $finalRemark,
  614. ];
  615. } catch (\Exception $e) {
  616. DB::rollBack();
  617. dLog('points')->error('积分发放失败: ' . $e->getMessage(), [
  618. 'from_uid' => $fromUid,
  619. 'target_uid' => $targetUid,
  620. 'points' => $points,
  621. ]);
  622. logDB('points', 'error', '积分发放失败', [
  623. 'from_uid' => $fromUid,
  624. 'target_uid' => $targetUid,
  625. 'points' => $points,
  626. 'error' => $e->getMessage(),
  627. ]);
  628. Utils::throwError('1006:积分发放失败,请稍后重试');
  629. }
  630. }
  631. /**
  632. * 获取可发放积分的用户列表(公共方法)
  633. *
  634. * 同一接口按当前角色返回不同列表:
  635. * - superadmin(平台):所有组织(role=admin)
  636. * - admin(组织):同 cpid 的组员(role=user)
  637. * - 其他角色不允许查看
  638. *
  639. * @return array
  640. */
  641. public function getGrantUserList(): array
  642. {
  643. $role = (string)Site::getRole();
  644. $query = DB::table('mp_manage_users')->where('is_enabled', 1);
  645. if ($role === 'superadmin') {
  646. $query->where('role', 'admin');
  647. } elseif ($role === 'admin') {
  648. $query->where('role', 'user')->where('cpid', (int)Site::getCpid());
  649. } else {
  650. Utils::throwError('1005:当前角色无权查看发放列表');
  651. }
  652. $users = $query->orderBy('cpid', 'asc')->orderBy('id', 'asc')
  653. ->get(['id', 'account', 'nickname', 'role', 'cpid', 'points', 'is_enabled'])
  654. ->map(function ($user) {
  655. return [
  656. 'id' => (int)getProp($user, 'id', 0),
  657. 'account' => (string)getProp($user, 'account', ''),
  658. 'nickname' => (string)getProp($user, 'nickname', ''),
  659. // 'role' => (string)getProp($user, 'role', ''),
  660. // 'cpid' => (int)getProp($user, 'cpid', 0),
  661. 'points' => (float)getProp($user, 'points', 0),
  662. // 'is_enabled' => (int)getProp($user, 'is_enabled', 1),
  663. ];
  664. })->all();
  665. return $users;
  666. }
  667. /**
  668. * 获取用户当前积分余额
  669. *
  670. * @param int $uid 用户ID,缺省取当前登录用户
  671. * @return float
  672. */
  673. public function getUserPointsBalance(int $uid = 0): float
  674. {
  675. if (!$uid) {
  676. $uid = (int)Site::getUid();
  677. }
  678. if (!$uid) {
  679. Utils::throwError(ErrorConst::NOT_LOGIN);
  680. }
  681. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  682. if (!$user) {
  683. Utils::throwError(ErrorConst::USER_IS_NOT_EXIST);
  684. }
  685. return (float)getProp($user, 'points', 0);
  686. }
  687. /**
  688. * 余额预检(公共方法)
  689. *
  690. * 计算视频/其他业务所需积分数后,在创建任务前调用;
  691. * 积分不足时直接抛错(20009:积分不足),业务方无需自行处理。
  692. *
  693. * @param float|int $pointsNeeded 需要扣除的积分数
  694. * @param int $uid 用户ID,缺省取当前登录用户
  695. * @return void
  696. */
  697. public function checkUserPointsEnough($pointsNeeded, int $uid = 0): void
  698. {
  699. $pointsNeeded = (float)$pointsNeeded;
  700. if ($pointsNeeded <= 0) {
  701. return;
  702. }
  703. // 测试用户(TEST_CPID / TEST_UID 白名单)跳过余额预检:只记录明细,不实际扣费
  704. if ($this->isTestUser($uid)) {
  705. return;
  706. }
  707. $balance = $this->getUserPointsBalance($uid);
  708. if ($balance < $pointsNeeded) {
  709. Utils::throwError(ErrorConst::POINTS_NOT_ENOUGH);
  710. }
  711. }
  712. /**
  713. * 判断是否为测试用户(TEST_CPID / TEST_UID 白名单)
  714. *
  715. * TEST_CPID / TEST_UID 在 .env 中为英文逗号分隔的纯字符串(如 "1"、"142857,142858"),
  716. * 读取后先转换为数组再判断。uid 命中 TEST_UID 或 cpid 命中 TEST_CPID(任一命中)即视为测试用户:
  717. * 预检不再校验余额,扣费只记录明细、不实际扣减积分。
  718. *
  719. * @param int $uid 用户ID,缺省取当前登录用户
  720. * @param int $cpid 公司ID,缺省取当前上下文公司ID
  721. * @return bool
  722. */
  723. public function isTestUser(int $uid = 0, int $cpid = 0): bool
  724. {
  725. if (!$uid) {
  726. $uid = (int)Site::getUid();
  727. }
  728. if (!$cpid) {
  729. $cpid = (int)Site::getCpid();
  730. }
  731. $testUids = $this->parseEnvList(env('TEST_UID'));
  732. $testCpids = $this->parseEnvList(env('TEST_CPID'));
  733. if (!empty($testUids) && in_array((string)$uid, $testUids, true)) {
  734. return true;
  735. }
  736. if (!empty($testCpids) && in_array((string)$cpid, $testCpids, true)) {
  737. return true;
  738. }
  739. return false;
  740. }
  741. /**
  742. * 将 env 中英文逗号分隔的字符串转换为数组
  743. *
  744. * @param mixed $value
  745. * @return array
  746. */
  747. private function parseEnvList($value): array
  748. {
  749. if ($value === null || $value === '') {
  750. return [];
  751. }
  752. $items = array_map('trim', explode(',', (string)$value));
  753. return array_values(array_filter($items, function ($item) {
  754. return $item !== '';
  755. }));
  756. }
  757. /**
  758. * 视频生成成功后记录计费明细并扣减用户积分
  759. *
  760. * 幂等处理:同一任务只允许计费一次(type + task_id 唯一索引兜底)。
  761. *
  762. * @param MpGenerateVideoTask $task
  763. * @return array
  764. */
  765. public function recordVideoTaskCharge(MpGenerateVideoTask $task): array
  766. {
  767. // 重复计费保护
  768. $exists = DB::table('mp_user_points_details')
  769. ->where('type', MpUserPointsDetail::TYPE_VIDEO)
  770. ->where('task_id', $task->id)
  771. ->exists();
  772. if ($exists) {
  773. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $task->id];
  774. }
  775. $chargeInfo = $task->charge_info;
  776. if (is_string($chargeInfo)) {
  777. $chargeInfo = json_decode($chargeInfo, true);
  778. }
  779. if (!is_array($chargeInfo) || empty($chargeInfo['user_id'])) {
  780. dLog('points')->warning('视频任务缺少计费信息,跳过扣费', ['task_id' => $task->id]);
  781. return ['charged' => false, 'reason' => 'no_charge_info', 'task_id' => $task->id];
  782. }
  783. // 自动时长(-1/0)时,用接口返回的实际时长回填计费信息
  784. $requestedDuration = (int)($chargeInfo['video_duration'] ?? -1);
  785. $actualDuration = $this->getActualVideoDuration($task);
  786. $durationBackfilled = $requestedDuration <= 0 && $actualDuration > 0;
  787. if ($durationBackfilled) {
  788. $chargeInfo['video_duration'] = $actualDuration;
  789. }
  790. $uid = (int)$chargeInfo['user_id'];
  791. $points = (float)$this->getVideoChargePoints($chargeInfo);
  792. $tokens = $this->getVideoTokensConsumed($task);
  793. $result = $this->deductAndRecord(
  794. $uid,
  795. $task->id,
  796. MpUserPointsDetail::TYPE_VIDEO,
  797. (string)getProp($task, 'api_type', ''),
  798. $points,
  799. $tokens,
  800. $chargeInfo,
  801. ''
  802. );
  803. // 自动时长被实际时长覆盖时,计费成功后同步回填任务表的 charge_info
  804. if ($durationBackfilled && !empty($result['charged'])) {
  805. $task->update(['charge_info' => $chargeInfo]);
  806. }
  807. return $result;
  808. }
  809. /**
  810. * 获取图片生成单张应扣积分数
  811. *
  812. * 从 mp_image_models 表读取(charge_type=per_image),按分辨率档位(1k/2k/4k)取单张积分。
  813. *
  814. * @param array $chargeInfo 计费信息(model、resolution、width、height 等)
  815. * @return int
  816. */
  817. public function getImageChargePoints(array $chargeInfo = []): int
  818. {
  819. $model = (string)getProp($chargeInfo, 'model', '');
  820. $resolution = strtolower((string)getProp($chargeInfo, 'resolution', '2k'));
  821. $modelRow = DB::table('mp_image_models')->where('model', $model)->first();
  822. if (!$modelRow || ($modelRow->charge_type ?? '') !== 'per_image') {
  823. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  824. }
  825. $priceJson = $modelRow->price_json;
  826. $prices = is_string($priceJson) ? json_decode($priceJson, true) : $priceJson;
  827. if (!is_array($prices) || empty($prices)) {
  828. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  829. }
  830. $price = $prices[$resolution] ?? null;
  831. if ($price === null || (float)$price <= 0) {
  832. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  833. }
  834. return (int)max(1, round((float)$price));
  835. }
  836. /**
  837. * 根据图片宽高归一化分辨率档位(1k/2k/4k)
  838. *
  839. * 按宽高乘积(面积)分档更准确:各档面积几乎成平方关系——
  840. * 1k≈1MP(1024x1024)、2k≈4MP(2048x2048、1600x2848)、3k≈9MP(3072x3072、4096x2304)、4k≈16MP(4096x4096)。
  841. * 目前没有 3k 计费档,3k 尺寸直接按 4k 计费。
  842. *
  843. * @param int $width
  844. * @param int $height
  845. * @return string
  846. */
  847. public function normalizeImageResolutionKey(int $width, int $height): string
  848. {
  849. if ($width <= 0 || $height <= 0) {
  850. return '2k';
  851. }
  852. // 面积分档:<2MP 视为 1k;2MP~6MP 视为 2k;≥6MP(含3k/4k尺寸)按 4k 计费
  853. $area = $width * $height;
  854. if ($area < 2048 * 1024) {
  855. return '1k';
  856. }
  857. if ($area < 2048 * 3072) {
  858. return '2k';
  859. }
  860. return '4k';
  861. }
  862. /**
  863. * 获取图片生成任务实际消耗的 token 量
  864. *
  865. * 图片接口返回格式:result_json.usage.total_tokens / output_tokens
  866. *
  867. * @param MpGeneratePicTask $task
  868. * @return int
  869. */
  870. public function getImageTokensConsumed(MpGeneratePicTask $task): int
  871. {
  872. $resultJson = $task->result_json;
  873. if (is_string($resultJson)) {
  874. $resultJson = json_decode($resultJson, true);
  875. }
  876. if (!is_array($resultJson)) {
  877. return 0;
  878. }
  879. $tokens = $resultJson['usage']['total_tokens'] ?? $resultJson['usage']['output_tokens'] ?? 0;
  880. return (int)$tokens;
  881. }
  882. /**
  883. * 从 AI 对话接口返回的 usage 中提取消耗的 token 数
  884. *
  885. * DeepSeek/OpenAI 格式:usage.total_tokens / usage.completion_tokens
  886. * Gemini 格式:usageMetadata.totalTokenCount(含思考 token),缺省时按 prompt + candidates 合计
  887. *
  888. * @param mixed $usage
  889. * @return int
  890. */
  891. public function getTokensFromUsage($usage): int
  892. {
  893. if (is_string($usage)) {
  894. $usage = json_decode($usage, true);
  895. }
  896. if (!is_array($usage)) {
  897. return 0;
  898. }
  899. $tokens = $usage['total_tokens']
  900. ?? $usage['completion_tokens']
  901. ?? $usage['totalTokenCount']
  902. ?? (
  903. isset($usage['promptTokenCount']) || isset($usage['candidatesTokenCount'])
  904. ? (int)($usage['promptTokenCount'] ?? 0)
  905. + (int)($usage['candidatesTokenCount'] ?? 0)
  906. + (int)($usage['thoughtsTokenCount'] ?? 0)
  907. : 0
  908. );
  909. return (int)$tokens;
  910. }
  911. /**
  912. * AI对话调用成功后记录计费明细并扣减用户积分
  913. *
  914. * 无对应任务表,task_id 为 NULL((type, task_id) 唯一索引下多个 NULL 互不冲突)。
  915. *
  916. * @param int $uid
  917. * @param int $points
  918. * @param int $tokens
  919. * @param array $chargeInfo
  920. * @param string $remark 特殊备注(默认空,测试用户由内部追加[测试]仅记账不扣费)
  921. * @param string $apiType
  922. * @return array
  923. */
  924. public function recordChatCharge(int $uid, int $points, int $tokens, array $chargeInfo = [], string $remark = '', string $apiType = 'deepseek'): array
  925. {
  926. return $this->deductAndRecord(
  927. $uid,
  928. null,
  929. MpUserPointsDetail::TYPE_CHAT,
  930. $apiType,
  931. (float)$points,
  932. $tokens,
  933. $chargeInfo,
  934. $remark
  935. );
  936. }
  937. /**
  938. * 仅记录 token 使用明细,不扣减积分、不写积分消耗
  939. *
  940. * 用于不按积分计费的文生文接口(免费/不扣积分场景),复用 mp_user_points_details 表:
  941. * points_consumed=0,仅填写 tokens_consumed,保证累计 token 统计口径一致。
  942. * uid<=0(无登录上下文)或 tokens<=0 时不落库。
  943. *
  944. * @param int $uid 用户ID
  945. * @param int $tokens 消耗 token 数
  946. * @param array $chargeInfo 计费/来源信息(model、source 等)
  947. * @param string $type 明细类型(默认 chat)
  948. * @param string $apiType API 类型/模型标识
  949. * @param string $remark 备注
  950. * @return bool 是否落库成功
  951. */
  952. public function recordTokenOnlyDetail(int $uid, int $tokens, array $chargeInfo = [], string $type = MpUserPointsDetail::TYPE_CHAT, string $apiType = '', string $remark = ''): bool
  953. {
  954. if ($uid <= 0 || $tokens <= 0) {
  955. return false;
  956. }
  957. try {
  958. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  959. $cpid = (int)getProp($user, 'cpid', 0);
  960. $pointsBalance = (float)getProp($user, 'points', 0);
  961. // 测试用户标记:保证统计排除口径与扣费明细一致
  962. $isTestUser = $this->isTestUser($uid, $cpid);
  963. if ($isTestUser) {
  964. $chargeInfo['test_mode'] = true;
  965. $remark = trim(($remark ? $remark . ';' : '') . '[测试]仅记账不扣费');
  966. }
  967. DB::table('mp_user_points_details')->insert([
  968. 'uid' => $uid,
  969. 'cpid' => $cpid,
  970. 'task_id' => null,
  971. 'type' => $type,
  972. 'api_type' => $apiType,
  973. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  974. 'points_consumed' => 0,
  975. 'points_before' => $pointsBalance,
  976. 'points_after' => $pointsBalance,
  977. 'tokens_consumed' => $tokens,
  978. 'remark' => $remark,
  979. 'created_at' => date('Y-m-d H:i:s'),
  980. 'updated_at' => date('Y-m-d H:i:s')
  981. ]);
  982. dLog('points')->info('token明细记录成功', [
  983. 'uid' => $uid,
  984. 'tokens_consumed' => $tokens,
  985. 'source' => $chargeInfo['source'] ?? '',
  986. 'test_mode' => $isTestUser
  987. ]);
  988. return true;
  989. } catch (\Exception $e) {
  990. dLog('points')->error('token明细记录失败: ' . $e->getMessage(), ['uid' => $uid]);
  991. logDB('points', 'error', 'token明细记录失败', [
  992. 'uid' => $uid,
  993. 'tokens_consumed' => $tokens,
  994. 'error' => $e->getMessage()
  995. ]);
  996. return false;
  997. }
  998. }
  999. /**
  1000. * 图片生成成功后记录计费明细并扣减用户积分
  1001. *
  1002. * 幂等处理:同一任务只允许计费一次(type + task_id 唯一索引兜底)。
  1003. *
  1004. * @param MpGeneratePicTask $task
  1005. * @return array
  1006. */
  1007. public function recordImageTaskCharge(MpGeneratePicTask $task): array
  1008. {
  1009. // 重复计费保护
  1010. $exists = DB::table('mp_user_points_details')
  1011. ->where('type', MpUserPointsDetail::TYPE_IMAGE)
  1012. ->where('task_id', $task->id)
  1013. ->exists();
  1014. if ($exists) {
  1015. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $task->id];
  1016. }
  1017. $chargeInfo = $task->charge_info;
  1018. if (is_string($chargeInfo)) {
  1019. $chargeInfo = json_decode($chargeInfo, true);
  1020. }
  1021. if (!is_array($chargeInfo) || empty($chargeInfo['user_id'])) {
  1022. dLog('points')->warning('图片任务缺少计费信息,跳过扣费', ['task_id' => $task->id]);
  1023. return ['charged' => false, 'reason' => 'no_charge_info', 'task_id' => $task->id];
  1024. }
  1025. $uid = (int)$chargeInfo['user_id'];
  1026. // 积分 = 单张价格 × 实际生成图片数
  1027. $pointsPerImage = (float)$this->getImageChargePoints($chargeInfo);
  1028. $imageCount = is_array($task->result_url) ? count($task->result_url) : 0;
  1029. if ($imageCount <= 0) {
  1030. $imageCount = (int)($chargeInfo['image_num'] ?? 1);
  1031. }
  1032. if ($imageCount <= 0) {
  1033. $imageCount = 1;
  1034. }
  1035. // 单张价格 × 实际生成图片数(未配置价格时为0,仍记录明细与token)
  1036. $points = (float)round($pointsPerImage * $imageCount);
  1037. $tokens = $this->getImageTokensConsumed($task);
  1038. return $this->deductAndRecord(
  1039. $uid,
  1040. $task->id,
  1041. MpUserPointsDetail::TYPE_IMAGE,
  1042. (string)getProp($task, 'model', ''),
  1043. $points,
  1044. $tokens,
  1045. $chargeInfo,
  1046. ''
  1047. );
  1048. }
  1049. /**
  1050. * 扣减积分并记录积分使用明细(视频/图片共用)
  1051. *
  1052. * @param int $uid
  1053. * @param int $taskId
  1054. * @param string $type
  1055. * @param string $apiType
  1056. * @param float $points
  1057. * @param int $tokens
  1058. * @param array $chargeInfo
  1059. * @param string $remark
  1060. * @return array
  1061. */
  1062. private function deductAndRecord(int $uid, ?int $taskId, string $type, string $apiType, float $points, int $tokens, array $chargeInfo, string $remark): array
  1063. {
  1064. try {
  1065. DB::beginTransaction();
  1066. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  1067. if (!$user) {
  1068. DB::rollBack();
  1069. dLog('points')->error('扣费失败:用户不存在', ['task_id' => $taskId, 'uid' => $uid]);
  1070. return ['charged' => false, 'reason' => 'user_not_found', 'task_id' => $taskId];
  1071. }
  1072. $pointsBefore = (float)getProp($user, 'points', 0);
  1073. // 测试用户(TEST_CPID / TEST_UID 白名单):只记录明细,不实际扣减积分余额
  1074. $isTestUser = $this->isTestUser($uid, (int)getProp($user, 'cpid', 0));
  1075. $pointsAfter = $isTestUser ? $pointsBefore : $pointsBefore - $points;
  1076. // 测试标记落库:charge_info 写入 test_mode,remark 追加 [测试],便于统计排除与历史排查
  1077. if ($isTestUser) {
  1078. $chargeInfo['test_mode'] = true;
  1079. $remark = trim(($remark ? $remark . ';' : '') . '[测试]仅记账不扣费');
  1080. }
  1081. if (!$isTestUser && $pointsBefore < $points) {
  1082. dLog('points')->warning('用户积分不足,扣费后积分为负数', [
  1083. 'task_id' => $taskId,
  1084. 'uid' => $uid,
  1085. 'points_before' => $pointsBefore,
  1086. 'points_consumed' => $points
  1087. ]);
  1088. }
  1089. if (!$isTestUser) {
  1090. // 原子扣减积分:基于数据库当前值执行(points = points - X),
  1091. // 避免并发处理不同任务时基于旧快照覆盖写入导致丢失更新(少扣)
  1092. DB::table('mp_manage_users')->where('id', $uid)->update([
  1093. 'points' => DB::raw('points - ' . (float)$points),
  1094. 'updated_at' => date('Y-m-d H:i:s')
  1095. ]);
  1096. }
  1097. // 记录积分使用明细
  1098. DB::table('mp_user_points_details')->insert([
  1099. 'uid' => $uid,
  1100. 'cpid' => (int)getProp($user, 'cpid', 0),
  1101. 'task_id' => $taskId,
  1102. 'type' => $type,
  1103. 'api_type' => $apiType,
  1104. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  1105. 'points_consumed' => $points,
  1106. 'points_before' => $pointsBefore,
  1107. 'points_after' => $pointsAfter,
  1108. 'tokens_consumed' => $tokens,
  1109. 'remark' => $remark,
  1110. 'created_at' => date('Y-m-d H:i:s'),
  1111. 'updated_at' => date('Y-m-d H:i:s')
  1112. ]);
  1113. DB::commit();
  1114. dLog('points')->info($type . '计费成功', [
  1115. 'task_id' => $taskId,
  1116. 'uid' => $uid,
  1117. 'points_consumed' => $points,
  1118. 'points_after' => $pointsAfter,
  1119. 'tokens_consumed' => $tokens,
  1120. 'test_mode' => $isTestUser
  1121. ]);
  1122. return [
  1123. 'charged' => true,
  1124. 'task_id' => $taskId,
  1125. 'uid' => $uid,
  1126. 'points_consumed' => $points,
  1127. 'points_before' => $pointsBefore,
  1128. 'points_after' => $pointsAfter,
  1129. 'tokens_consumed' => $tokens,
  1130. 'test_mode' => $isTestUser
  1131. ];
  1132. } catch (\Exception $e) {
  1133. DB::rollBack();
  1134. // 唯一索引冲突:同一任务已被其他请求计费,视为已计费(并发验重兜底,避免误报计费失败)
  1135. if ($this->isDuplicateCharge($e)) {
  1136. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $taskId];
  1137. }
  1138. dLog('points')->error($type . '计费失败: ' . $e->getMessage(), ['task_id' => $taskId]);
  1139. logDB('points', 'error', $type . '计费失败', [
  1140. 'task_id' => $taskId,
  1141. 'error' => $e->getMessage()
  1142. ]);
  1143. return ['charged' => false, 'reason' => 'exception: ' . $e->getMessage(), 'task_id' => $taskId];
  1144. }
  1145. }
  1146. /**
  1147. * 判断异常是否为数据库唯一键冲突(重复计费)
  1148. *
  1149. * @param \Exception $e
  1150. * @return bool
  1151. */
  1152. private function isDuplicateCharge(\Exception $e): bool
  1153. {
  1154. // MySQL 重复键:SQLSTATE 23000 / 错误码 1062(Duplicate entry)
  1155. $code = $e->getCode();
  1156. if ($code === 23000 || $code === '23000' || $code === 1062 || $code === '1062') {
  1157. return true;
  1158. }
  1159. return mb_strpos($e->getMessage(), 'Duplicate entry') !== false;
  1160. }
  1161. }