PointsService.php 57 KB

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