PointsService.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  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' => (int)getProp($user, 'points', 0),
  474. 'total_points_consumed' => (int)MpUserPointsDetail::where('uid', $uid)
  475. ->where('points_consumed', '>', 0)
  476. ->where($excludeTestRecords)
  477. ->sum('points_consumed'),
  478. 'total_points_refunded' => (int)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' => (int)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. * action=grant(发放,默认):目标用户积分增加,points_consumed 记负值(积分流入)
  509. * action=revoke(回收):目标用户积分减少,需校验目标积分充足(只针对组织/组员角色),points_consumed 记正值(积分流出)
  510. *
  511. * @param array $params uid(目标用户ID,支持多个ID用英文逗号隔开,如 "142857,142858")/ points(积分数,正整数)/ action(grant|revoke,默认 grant)/ remark(可选文案)
  512. * @return array
  513. */
  514. public function grantPoints(array $params): array
  515. {
  516. $uidRaw = trim((string)getProp($params, 'uid', ''));
  517. $points = (float)getProp($params, 'points', 0);
  518. $action = (string)getProp($params, 'action', 'grant');
  519. $remark = trim((string)getProp($params, 'remark', ''));
  520. // 解析 uid:单个ID或多个ID(英文逗号隔开),自动去重、忽略空白
  521. $uids = array_values(array_unique(array_filter(array_map(function ($v) {
  522. return (int)trim((string)$v);
  523. }, explode(',', $uidRaw)), function ($v) {
  524. return $v > 0;
  525. })));
  526. if (empty($uids)) {
  527. Utils::throwError('1002:请传入目标用户uid');
  528. }
  529. $this->validatePoints($points);
  530. $this->validateAction($action);
  531. // 单用户:保持原有返回结构
  532. if (count($uids) === 1) {
  533. try {
  534. DB::beginTransaction();
  535. $result = $this->applyPointsChange($uids[0], $points, $action, $remark);
  536. DB::commit();
  537. return $result;
  538. } catch (\Exception $e) {
  539. DB::rollBack();
  540. throw $e;
  541. }
  542. }
  543. // 多用户:先对全部目标校验(只读,不写库),任一失败整体拒绝;再单事务统一写库,保证原子性
  544. foreach ($uids as $uid) {
  545. $this->buildGrantContext($uid, $action, $points);
  546. }
  547. try {
  548. DB::beginTransaction();
  549. $results = [];
  550. foreach ($uids as $uid) {
  551. $results[] = $this->applyPointsChange($uid, $points, $action, $remark);
  552. }
  553. DB::commit();
  554. } catch (\Exception $e) {
  555. DB::rollBack();
  556. throw $e;
  557. }
  558. dLog('points')->info('积分批量操作成功', [
  559. 'action' => $action,
  560. 'count' => count($uids),
  561. 'points' => $points,
  562. ]);
  563. return [
  564. 'action' => $action,
  565. 'points' => $points,
  566. 'success_count' => count($results),
  567. 'results' => $results,
  568. ];
  569. }
  570. /**
  571. * 校验积分数(正整数)
  572. *
  573. * @param float $points
  574. * @return void
  575. */
  576. private function validatePoints(float $points): void
  577. {
  578. if ($points <= 0) {
  579. Utils::throwError('1002:积分数必须大于0');
  580. }
  581. if (floor($points) != $points) {
  582. Utils::throwError('1002:积分数必须为整数');
  583. }
  584. }
  585. /**
  586. * 校验操作类型
  587. *
  588. * @param string $action
  589. * @return void
  590. */
  591. private function validateAction(string $action): void
  592. {
  593. if (!in_array($action, ['grant', 'revoke'], true)) {
  594. Utils::throwError('1002:action仅支持grant(发放)或revoke(回收)');
  595. }
  596. }
  597. /**
  598. * 校验并构建单用户积分操作上下文(只读)
  599. *
  600. * 校验当前操作者角色、目标用户存在/启用、目标角色与公司归属;
  601. * 回收时额外校验目标用户积分充足;管理员发放时额外校验管理员自身可用积分充足。
  602. *
  603. * @param int $targetUid
  604. * @param string $action
  605. * @param float $points
  606. * @return array
  607. */
  608. private function buildGrantContext(int $targetUid, string $action, float $points): array
  609. {
  610. $fromUid = (int)Site::getUid();
  611. if ($fromUid <= 0) {
  612. Utils::throwError(ErrorConst::NOT_LOGIN);
  613. }
  614. $fromRole = (string)Site::getRole();
  615. $fromUser = DB::table('mp_manage_users')->where('id', $fromUid)->first();
  616. if (!$fromUser) {
  617. Utils::throwError(ErrorConst::USER_IS_NOT_EXIST);
  618. }
  619. $targetUser = DB::table('mp_manage_users')->where('id', $targetUid)->first();
  620. if (!$targetUser) {
  621. Utils::throwError('20003:目标用户不存在');
  622. }
  623. if ((int)getProp($targetUser, 'is_enabled', 1) === 0) {
  624. Utils::throwError('20003:目标用户已被禁用');
  625. }
  626. $targetRole = (string)getProp($targetUser, 'role', '');
  627. $targetCpid = (int)getProp($targetUser, 'cpid', 0);
  628. $verb = $action === 'revoke' ? '回收' : '发放';
  629. // 角色与操作对象校验
  630. if ($fromRole === 'superadmin') {
  631. if ($targetRole !== 'admin') {
  632. Utils::throwError('1005:平台仅可给组织' . $verb . '积分');
  633. }
  634. $type = MpUserPointsDetail::TYPE_SYSTEM;
  635. $defaultRemark = $action === 'revoke' ? '平台回收积分' : '平台发放积分';
  636. } elseif ($fromRole === 'admin') {
  637. if ($targetRole !== 'user') {
  638. Utils::throwError('1005:组织仅可给同公司的组员' . $verb . '积分');
  639. }
  640. if ($targetCpid !== (int)Site::getCpid()) {
  641. Utils::throwError('1005:只能给同一公司的组员' . $verb . '积分');
  642. }
  643. $type = MpUserPointsDetail::TYPE_COMPANY;
  644. $defaultRemark = $action === 'revoke' ? '组织回收积分' : '组织发放积分';
  645. } else {
  646. Utils::throwError('1005:当前角色无权操作积分');
  647. }
  648. // 回收时校验目标积分充足(目标只能是组织/组员角色,超管不在操作范围内,无需判断)
  649. if ($action === 'revoke') {
  650. $balance = (float)getProp($targetUser, 'points', 0);
  651. if ($balance < $points) {
  652. Utils::throwError('1002:目标用户积分不足,无法回收');
  653. }
  654. }
  655. // 管理员发放:积分从管理员自身扣减转移给组员,需校验管理员可用积分充足(平台发放不校验)
  656. if ($fromRole === 'admin' && $action === 'grant') {
  657. $operatorBalance = (float)getProp($fromUser, 'points', 0);
  658. if ($operatorBalance < $points) {
  659. Utils::throwError('1002:可用积分不足,无法发放');
  660. }
  661. }
  662. return [
  663. 'from_uid' => $fromUid,
  664. 'from_role' => $fromRole,
  665. 'from_cpid' => (int)getProp($fromUser, 'cpid', 0),
  666. 'from_user' => $fromUser,
  667. 'target_user' => $targetUser,
  668. 'target_role' => $targetRole,
  669. 'target_cpid' => $targetCpid,
  670. 'target_uid' => $targetUid,
  671. 'type' => $type,
  672. 'default_remark' => $defaultRemark,
  673. ];
  674. }
  675. /**
  676. * 对单个用户执行积分变动并写入明细(须在事务内调用)
  677. *
  678. * @param int $targetUid
  679. * @param float $points
  680. * @param string $action grant|revoke
  681. * @param string $remark
  682. * @return array
  683. */
  684. private function applyPointsChange(int $targetUid, float $points, string $action, string $remark): array
  685. {
  686. $ctx = $this->buildGrantContext($targetUid, $action, $points);
  687. $finalRemark = $remark !== '' ? $ctx['default_remark'] . ':' . $remark : $ctx['default_remark'];
  688. $chargeInfo = [
  689. 'from_uid' => $ctx['from_uid'],
  690. 'from_role' => $ctx['from_role'],
  691. 'target_uid' => $targetUid,
  692. 'target_role' => $ctx['target_role'],
  693. 'target_cpid' => $ctx['target_cpid'],
  694. 'grant_type' => $ctx['type'],
  695. 'action' => $action,
  696. ];
  697. $pointsBefore = (float)getProp($ctx['target_user'], 'points', 0);
  698. $delta = $action === 'revoke' ? -$points : $points;
  699. $pointsAfter = $pointsBefore + $delta;
  700. $now = date('Y-m-d H:i:s');
  701. $operatorAfter = null;
  702. // 原子更新余额,避免并发覆盖;COALESCE 处理余额为 NULL 的用户(NULL ± X 在 MySQL 中仍为 NULL)
  703. if ($ctx['from_role'] === 'admin') {
  704. // 转移模式:积分在管理员与组员之间流转,整体数额不变
  705. $operatorBefore = (float)getProp($ctx['from_user'], 'points', 0);
  706. if ($action === 'revoke') {
  707. // 组员扣减(带余额条件),管理员增加
  708. $affected = DB::table('mp_manage_users')
  709. ->where('id', $targetUid)
  710. ->whereRaw('COALESCE(points, 0) >= ?', [(float)$points])
  711. ->update([
  712. 'points' => DB::raw('COALESCE(points, 0) - ' . (float)$points),
  713. 'updated_at' => $now,
  714. ]);
  715. if ($affected === 0) {
  716. Utils::throwError('1002:目标用户积分不足,无法回收');
  717. }
  718. DB::table('mp_manage_users')->where('id', $ctx['from_uid'])->update([
  719. 'points' => DB::raw('COALESCE(points, 0) + ' . (float)$points),
  720. 'updated_at' => $now,
  721. ]);
  722. $operatorDelta = $points;
  723. } else {
  724. // 管理员扣减(带余额条件,防止并发超发),组员增加
  725. $affected = DB::table('mp_manage_users')
  726. ->where('id', $ctx['from_uid'])
  727. ->whereRaw('COALESCE(points, 0) >= ?', [(float)$points])
  728. ->update([
  729. 'points' => DB::raw('COALESCE(points, 0) - ' . (float)$points),
  730. 'updated_at' => $now,
  731. ]);
  732. if ($affected === 0) {
  733. Utils::throwError('1002:可用积分不足,无法发放');
  734. }
  735. DB::table('mp_manage_users')->where('id', $targetUid)->update([
  736. 'points' => DB::raw('COALESCE(points, 0) + ' . (float)$points),
  737. 'updated_at' => $now,
  738. ]);
  739. $operatorDelta = -$points;
  740. }
  741. $operatorAfter = $operatorBefore + $operatorDelta;
  742. // 管理员侧明细(方向与组员相反):发放记支出(正),回收记收入(负)
  743. DB::table('mp_user_points_details')->insert([
  744. 'uid' => $ctx['from_uid'],
  745. 'cpid' => $ctx['from_cpid'],
  746. 'task_id' => null,
  747. 'type' => $ctx['type'],
  748. 'api_type' => $action === 'revoke' ? 'revoke' : 'grant',
  749. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  750. 'points_before' => $operatorBefore,
  751. 'points_consumed' => -$operatorDelta,
  752. 'points_after' => $operatorAfter,
  753. 'tokens_consumed' => 0,
  754. 'remark' => $finalRemark,
  755. 'created_at' => $now,
  756. 'updated_at' => $now,
  757. ]);
  758. } elseif ($action === 'revoke') {
  759. // 平台回收:目标(组织)扣减,带余额条件
  760. $affected = DB::table('mp_manage_users')
  761. ->where('id', $targetUid)
  762. ->whereRaw('COALESCE(points, 0) >= ?', [(float)$points])
  763. ->update([
  764. 'points' => DB::raw('COALESCE(points, 0) - ' . (float)$points),
  765. 'updated_at' => $now,
  766. ]);
  767. if ($affected === 0) {
  768. Utils::throwError('1002:目标用户积分不足,无法回收');
  769. }
  770. } else {
  771. // 平台发放:目标(组织)增加(平台为积分源头,不校验平台余额)
  772. DB::table('mp_manage_users')->where('id', $targetUid)->update([
  773. 'points' => DB::raw('COALESCE(points, 0) + ' . (float)$points),
  774. 'updated_at' => $now,
  775. ]);
  776. }
  777. // 目标侧明细:发放 points_consumed 记负值(流入),回收记正值(流出)
  778. DB::table('mp_user_points_details')->insert([
  779. 'uid' => $targetUid,
  780. 'cpid' => $ctx['target_cpid'],
  781. 'task_id' => null,
  782. 'type' => $ctx['type'],
  783. 'api_type' => $action === 'revoke' ? 'revoke' : 'grant',
  784. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  785. 'points_before' => $pointsBefore,
  786. 'points_consumed' => -$delta,
  787. 'points_after' => $pointsAfter,
  788. 'tokens_consumed' => 0,
  789. 'remark' => $finalRemark,
  790. 'created_at' => $now,
  791. 'updated_at' => $now,
  792. ]);
  793. $result = [
  794. 'uid' => $targetUid,
  795. 'success' => true,
  796. 'action' => $action,
  797. 'type' => $ctx['type'],
  798. 'points' => $points,
  799. 'points_before' => $pointsBefore,
  800. 'points_after' => $pointsAfter,
  801. 'remark' => $finalRemark,
  802. ];
  803. if ($operatorAfter !== null) {
  804. $result['operator_uid'] = $ctx['from_uid'];
  805. $result['operator_points_before'] = $operatorBefore;
  806. $result['operator_points_after'] = $operatorAfter;
  807. }
  808. return $result;
  809. }
  810. /**
  811. * 获取可发放积分的用户列表(公共方法)
  812. *
  813. * 同一接口按当前角色返回不同列表:
  814. * - superadmin(平台):所有组织(role=admin)
  815. * - admin(组织):同 cpid 的组员(role=user)
  816. * - 其他角色不允许查看
  817. *
  818. * @return array
  819. */
  820. public function getGrantUserList(): array
  821. {
  822. $role = (string)Site::getRole();
  823. $query = DB::table('mp_manage_users')->where('is_enabled', 1);
  824. if ($role === 'superadmin') {
  825. $query->where('role', 'admin');
  826. } elseif ($role === 'admin') {
  827. $query->where('role', 'user')->where('cpid', (int)Site::getCpid());
  828. } else {
  829. Utils::throwError('1005:当前角色无权查看发放列表');
  830. }
  831. $users = $query->orderBy('cpid', 'asc')->orderBy('id', 'asc')
  832. ->get(['id', 'account', 'nickname', 'role', 'cpid', 'points', 'is_enabled'])
  833. ->map(function ($user) {
  834. return [
  835. 'id' => (int)getProp($user, 'id', 0),
  836. 'account' => (string)getProp($user, 'account', ''),
  837. 'nickname' => (string)getProp($user, 'nickname', ''),
  838. // 'role' => (string)getProp($user, 'role', ''),
  839. // 'cpid' => (int)getProp($user, 'cpid', 0),
  840. 'points' => (float)getProp($user, 'points', 0),
  841. // 'is_enabled' => (int)getProp($user, 'is_enabled', 1),
  842. ];
  843. })->all();
  844. return $users;
  845. }
  846. /**
  847. * 获取用户当前积分余额
  848. *
  849. * @param int $uid 用户ID,缺省取当前登录用户
  850. * @return float
  851. */
  852. public function getUserPointsBalance(int $uid = 0): float
  853. {
  854. if (!$uid) {
  855. $uid = (int)Site::getUid();
  856. }
  857. if (!$uid) {
  858. Utils::throwError(ErrorConst::NOT_LOGIN);
  859. }
  860. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  861. if (!$user) {
  862. Utils::throwError(ErrorConst::USER_IS_NOT_EXIST);
  863. }
  864. return (float)getProp($user, 'points', 0);
  865. }
  866. /**
  867. * 余额预检(公共方法)
  868. *
  869. * 计算视频/其他业务所需积分数后,在创建任务前调用;
  870. * 积分不足时直接抛错(20009:积分不足),业务方无需自行处理。
  871. *
  872. * @param float|int $pointsNeeded 需要扣除的积分数
  873. * @param int $uid 用户ID,缺省取当前登录用户
  874. * @return void
  875. */
  876. public function checkUserPointsEnough($pointsNeeded, int $uid = 0): void
  877. {
  878. $pointsNeeded = (float)$pointsNeeded;
  879. if ($pointsNeeded <= 0) {
  880. return;
  881. }
  882. // 测试用户(TEST_CPID / TEST_UID 白名单)跳过余额预检:只记录明细,不实际扣费
  883. if ($this->isTestUser($uid)) {
  884. return;
  885. }
  886. $balance = $this->getUserPointsBalance($uid);
  887. if ($balance < $pointsNeeded) {
  888. Utils::throwError(ErrorConst::POINTS_NOT_ENOUGH);
  889. }
  890. }
  891. /**
  892. * 判断是否为测试用户(TEST_CPID / TEST_UID 白名单)
  893. *
  894. * TEST_CPID / TEST_UID 在 .env 中为英文逗号分隔的纯字符串(如 "1"、"142857,142858"),
  895. * 读取后先转换为数组再判断。uid 命中 TEST_UID 或 cpid 命中 TEST_CPID(任一命中)即视为测试用户:
  896. * 预检不再校验余额,扣费只记录明细、不实际扣减积分。
  897. *
  898. * @param int $uid 用户ID,缺省取当前登录用户
  899. * @param int $cpid 公司ID,缺省取当前上下文公司ID
  900. * @return bool
  901. */
  902. public function isTestUser(int $uid = 0, int $cpid = 0): bool
  903. {
  904. if (!$uid) {
  905. $uid = (int)Site::getUid();
  906. }
  907. if (!$cpid) {
  908. $cpid = (int)Site::getCpid();
  909. }
  910. $testUids = $this->parseEnvList(env('TEST_UID'));
  911. $testCpids = $this->parseEnvList(env('TEST_CPID'));
  912. if (!empty($testUids) && in_array((string)$uid, $testUids, true)) {
  913. return true;
  914. }
  915. if (!empty($testCpids) && in_array((string)$cpid, $testCpids, true)) {
  916. return true;
  917. }
  918. return false;
  919. }
  920. /**
  921. * 将 env 中英文逗号分隔的字符串转换为数组
  922. *
  923. * @param mixed $value
  924. * @return array
  925. */
  926. private function parseEnvList($value): array
  927. {
  928. if ($value === null || $value === '') {
  929. return [];
  930. }
  931. $items = array_map('trim', explode(',', (string)$value));
  932. return array_values(array_filter($items, function ($item) {
  933. return $item !== '';
  934. }));
  935. }
  936. /**
  937. * 视频生成成功后记录计费明细并扣减用户积分
  938. *
  939. * 幂等处理:同一任务只允许计费一次(type + task_id 唯一索引兜底)。
  940. *
  941. * @param MpGenerateVideoTask $task
  942. * @return array
  943. */
  944. public function recordVideoTaskCharge(MpGenerateVideoTask $task): array
  945. {
  946. // 重复计费保护
  947. $exists = DB::table('mp_user_points_details')
  948. ->where('type', MpUserPointsDetail::TYPE_VIDEO)
  949. ->where('task_id', $task->id)
  950. ->exists();
  951. if ($exists) {
  952. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $task->id];
  953. }
  954. $chargeInfo = $task->charge_info;
  955. if (is_string($chargeInfo)) {
  956. $chargeInfo = json_decode($chargeInfo, true);
  957. }
  958. if (!is_array($chargeInfo) || empty($chargeInfo['user_id'])) {
  959. dLog('points')->warning('视频任务缺少计费信息,跳过扣费', ['task_id' => $task->id]);
  960. return ['charged' => false, 'reason' => 'no_charge_info', 'task_id' => $task->id];
  961. }
  962. // 自动时长(-1/0)时,用接口返回的实际时长回填计费信息
  963. $requestedDuration = (int)($chargeInfo['video_duration'] ?? -1);
  964. $actualDuration = $this->getActualVideoDuration($task);
  965. $durationBackfilled = $requestedDuration <= 0 && $actualDuration > 0;
  966. if ($durationBackfilled) {
  967. $chargeInfo['video_duration'] = $actualDuration;
  968. }
  969. $uid = (int)$chargeInfo['user_id'];
  970. $points = (float)$this->getVideoChargePoints($chargeInfo);
  971. $tokens = $this->getVideoTokensConsumed($task);
  972. $result = $this->deductAndRecord(
  973. $uid,
  974. $task->id,
  975. MpUserPointsDetail::TYPE_VIDEO,
  976. (string)getProp($task, 'api_type', ''),
  977. $points,
  978. $tokens,
  979. $chargeInfo,
  980. ''
  981. );
  982. // 自动时长被实际时长覆盖时,计费成功后同步回填任务表的 charge_info
  983. if ($durationBackfilled && !empty($result['charged'])) {
  984. $task->update(['charge_info' => $chargeInfo]);
  985. }
  986. return $result;
  987. }
  988. /**
  989. * 获取图片生成单张应扣积分数
  990. *
  991. * 从 mp_image_models 表读取(charge_type=per_image),按分辨率档位(1k/2k/4k)取单张积分。
  992. *
  993. * @param array $chargeInfo 计费信息(model、resolution、width、height 等)
  994. * @return int
  995. */
  996. public function getImageChargePoints(array $chargeInfo = []): int
  997. {
  998. $model = (string)getProp($chargeInfo, 'model', '');
  999. $resolution = strtolower((string)getProp($chargeInfo, 'resolution', '2k'));
  1000. $modelRow = DB::table('mp_image_models')->where('model', $model)->first();
  1001. if (!$modelRow || ($modelRow->charge_type ?? '') !== 'per_image') {
  1002. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  1003. }
  1004. $priceJson = $modelRow->price_json;
  1005. $prices = is_string($priceJson) ? json_decode($priceJson, true) : $priceJson;
  1006. if (!is_array($prices) || empty($prices)) {
  1007. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  1008. }
  1009. $price = $prices[$resolution] ?? null;
  1010. if ($price === null || (float)$price <= 0) {
  1011. return self::DEFAULT_VIDEO_CHARGE_POINTS;
  1012. }
  1013. return (int)max(1, round((float)$price));
  1014. }
  1015. /**
  1016. * 根据图片宽高归一化分辨率档位(1k/2k/4k)
  1017. *
  1018. * 按宽高乘积(面积)分档更准确:各档面积几乎成平方关系——
  1019. * 1k≈1MP(1024x1024)、2k≈4MP(2048x2048、1600x2848)、3k≈9MP(3072x3072、4096x2304)、4k≈16MP(4096x4096)。
  1020. * 目前没有 3k 计费档,3k 尺寸直接按 4k 计费。
  1021. *
  1022. * @param int $width
  1023. * @param int $height
  1024. * @return string
  1025. */
  1026. public function normalizeImageResolutionKey(int $width, int $height): string
  1027. {
  1028. if ($width <= 0 || $height <= 0) {
  1029. return '2k';
  1030. }
  1031. // 面积分档:<2MP 视为 1k;2MP~6MP 视为 2k;≥6MP(含3k/4k尺寸)按 4k 计费
  1032. $area = $width * $height;
  1033. if ($area < 2048 * 1024) {
  1034. return '1k';
  1035. }
  1036. if ($area < 2048 * 3072) {
  1037. return '2k';
  1038. }
  1039. return '4k';
  1040. }
  1041. /**
  1042. * 获取图片生成任务实际消耗的 token 量
  1043. *
  1044. * 图片接口返回格式:result_json.usage.total_tokens / output_tokens
  1045. *
  1046. * @param MpGeneratePicTask $task
  1047. * @return int
  1048. */
  1049. public function getImageTokensConsumed(MpGeneratePicTask $task): int
  1050. {
  1051. $resultJson = $task->result_json;
  1052. if (is_string($resultJson)) {
  1053. $resultJson = json_decode($resultJson, true);
  1054. }
  1055. if (!is_array($resultJson)) {
  1056. return 0;
  1057. }
  1058. $tokens = $resultJson['usage']['total_tokens'] ?? $resultJson['usage']['output_tokens'] ?? 0;
  1059. return (int)$tokens;
  1060. }
  1061. /**
  1062. * 从 AI 对话接口返回的 usage 中提取消耗的 token 数
  1063. *
  1064. * DeepSeek/OpenAI 格式:usage.total_tokens / usage.completion_tokens
  1065. * Gemini 格式:usageMetadata.totalTokenCount(含思考 token),缺省时按 prompt + candidates 合计
  1066. *
  1067. * @param mixed $usage
  1068. * @return int
  1069. */
  1070. public function getTokensFromUsage($usage): int
  1071. {
  1072. if (is_string($usage)) {
  1073. $usage = json_decode($usage, true);
  1074. }
  1075. if (!is_array($usage)) {
  1076. return 0;
  1077. }
  1078. $tokens = $usage['total_tokens']
  1079. ?? $usage['completion_tokens']
  1080. ?? $usage['totalTokenCount']
  1081. ?? (
  1082. isset($usage['promptTokenCount']) || isset($usage['candidatesTokenCount'])
  1083. ? (int)($usage['promptTokenCount'] ?? 0)
  1084. + (int)($usage['candidatesTokenCount'] ?? 0)
  1085. + (int)($usage['thoughtsTokenCount'] ?? 0)
  1086. : 0
  1087. );
  1088. return (int)$tokens;
  1089. }
  1090. /**
  1091. * AI对话调用成功后记录计费明细并扣减用户积分
  1092. *
  1093. * 无对应任务表,task_id 为 NULL((type, task_id) 唯一索引下多个 NULL 互不冲突)。
  1094. *
  1095. * @param int $uid
  1096. * @param int $points
  1097. * @param int $tokens
  1098. * @param array $chargeInfo
  1099. * @param string $remark 特殊备注(默认空,测试用户由内部追加[测试]仅记账不扣费)
  1100. * @param string $apiType
  1101. * @return array
  1102. */
  1103. public function recordChatCharge(int $uid, int $points, int $tokens, array $chargeInfo = [], string $remark = '', string $apiType = 'deepseek'): array
  1104. {
  1105. return $this->deductAndRecord(
  1106. $uid,
  1107. null,
  1108. MpUserPointsDetail::TYPE_CHAT,
  1109. $apiType,
  1110. (float)$points,
  1111. $tokens,
  1112. $chargeInfo,
  1113. $remark
  1114. );
  1115. }
  1116. /**
  1117. * 仅记录 token 使用明细,不扣减积分、不写积分消耗
  1118. *
  1119. * 用于不按积分计费的文生文接口(免费/不扣积分场景),复用 mp_user_points_details 表:
  1120. * points_consumed=0,仅填写 tokens_consumed,保证累计 token 统计口径一致。
  1121. * uid<=0(无登录上下文)或 tokens<=0 时不落库。
  1122. *
  1123. * @param int $uid 用户ID
  1124. * @param int $tokens 消耗 token 数
  1125. * @param array $chargeInfo 计费/来源信息(model、source 等)
  1126. * @param string $type 明细类型(默认 chat)
  1127. * @param string $apiType API 类型/模型标识
  1128. * @param string $remark 备注
  1129. * @return bool 是否落库成功
  1130. */
  1131. public function recordTokenOnlyDetail(int $uid, int $tokens, array $chargeInfo = [], string $type = MpUserPointsDetail::TYPE_CHAT, string $apiType = '', string $remark = ''): bool
  1132. {
  1133. if ($uid <= 0 || $tokens <= 0) {
  1134. return false;
  1135. }
  1136. try {
  1137. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  1138. $cpid = (int)getProp($user, 'cpid', 0);
  1139. $pointsBalance = (float)getProp($user, 'points', 0);
  1140. // 测试用户标记:保证统计排除口径与扣费明细一致
  1141. $isTestUser = $this->isTestUser($uid, $cpid);
  1142. if ($isTestUser) {
  1143. $chargeInfo['test_mode'] = true;
  1144. $remark = trim(($remark ? $remark . ';' : '') . '[测试]仅记账不扣费');
  1145. }
  1146. DB::table('mp_user_points_details')->insert([
  1147. 'uid' => $uid,
  1148. 'cpid' => $cpid,
  1149. 'task_id' => null,
  1150. 'type' => $type,
  1151. 'api_type' => $apiType,
  1152. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  1153. 'points_consumed' => 0,
  1154. 'points_before' => $pointsBalance,
  1155. 'points_after' => $pointsBalance,
  1156. 'tokens_consumed' => $tokens,
  1157. 'remark' => $remark,
  1158. 'created_at' => date('Y-m-d H:i:s'),
  1159. 'updated_at' => date('Y-m-d H:i:s')
  1160. ]);
  1161. dLog('points')->info('token明细记录成功', [
  1162. 'uid' => $uid,
  1163. 'tokens_consumed' => $tokens,
  1164. 'source' => $chargeInfo['source'] ?? '',
  1165. 'test_mode' => $isTestUser
  1166. ]);
  1167. return true;
  1168. } catch (\Exception $e) {
  1169. dLog('points')->error('token明细记录失败: ' . $e->getMessage(), ['uid' => $uid]);
  1170. logDB('points', 'error', 'token明细记录失败', [
  1171. 'uid' => $uid,
  1172. 'tokens_consumed' => $tokens,
  1173. 'error' => $e->getMessage()
  1174. ]);
  1175. return false;
  1176. }
  1177. }
  1178. /**
  1179. * 图片生成成功后记录计费明细并扣减用户积分
  1180. *
  1181. * 幂等处理:同一任务只允许计费一次(type + task_id 唯一索引兜底)。
  1182. *
  1183. * @param MpGeneratePicTask $task
  1184. * @return array
  1185. */
  1186. public function recordImageTaskCharge(MpGeneratePicTask $task): array
  1187. {
  1188. // 重复计费保护
  1189. $exists = DB::table('mp_user_points_details')
  1190. ->where('type', MpUserPointsDetail::TYPE_IMAGE)
  1191. ->where('task_id', $task->id)
  1192. ->exists();
  1193. if ($exists) {
  1194. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $task->id];
  1195. }
  1196. $chargeInfo = $task->charge_info;
  1197. if (is_string($chargeInfo)) {
  1198. $chargeInfo = json_decode($chargeInfo, true);
  1199. }
  1200. if (!is_array($chargeInfo) || empty($chargeInfo['user_id'])) {
  1201. dLog('points')->warning('图片任务缺少计费信息,跳过扣费', ['task_id' => $task->id]);
  1202. return ['charged' => false, 'reason' => 'no_charge_info', 'task_id' => $task->id];
  1203. }
  1204. $uid = (int)$chargeInfo['user_id'];
  1205. // 积分 = 单张价格 × 实际生成图片数
  1206. $pointsPerImage = (float)$this->getImageChargePoints($chargeInfo);
  1207. $imageCount = is_array($task->result_url) ? count($task->result_url) : 0;
  1208. if ($imageCount <= 0) {
  1209. $imageCount = (int)($chargeInfo['image_num'] ?? 1);
  1210. }
  1211. if ($imageCount <= 0) {
  1212. $imageCount = 1;
  1213. }
  1214. // 单张价格 × 实际生成图片数(未配置价格时为0,仍记录明细与token)
  1215. $points = (float)round($pointsPerImage * $imageCount);
  1216. $tokens = $this->getImageTokensConsumed($task);
  1217. return $this->deductAndRecord(
  1218. $uid,
  1219. $task->id,
  1220. MpUserPointsDetail::TYPE_IMAGE,
  1221. (string)getProp($task, 'model', ''),
  1222. $points,
  1223. $tokens,
  1224. $chargeInfo,
  1225. ''
  1226. );
  1227. }
  1228. /**
  1229. * 扣减积分并记录积分使用明细(视频/图片共用)
  1230. *
  1231. * @param int $uid
  1232. * @param int $taskId
  1233. * @param string $type
  1234. * @param string $apiType
  1235. * @param float $points
  1236. * @param int $tokens
  1237. * @param array $chargeInfo
  1238. * @param string $remark
  1239. * @return array
  1240. */
  1241. private function deductAndRecord(int $uid, ?int $taskId, string $type, string $apiType, float $points, int $tokens, array $chargeInfo, string $remark): array
  1242. {
  1243. try {
  1244. DB::beginTransaction();
  1245. $user = DB::table('mp_manage_users')->where('id', $uid)->first();
  1246. if (!$user) {
  1247. DB::rollBack();
  1248. dLog('points')->error('扣费失败:用户不存在', ['task_id' => $taskId, 'uid' => $uid]);
  1249. return ['charged' => false, 'reason' => 'user_not_found', 'task_id' => $taskId];
  1250. }
  1251. $pointsBefore = (float)getProp($user, 'points', 0);
  1252. // 测试用户(TEST_CPID / TEST_UID 白名单):只记录明细,不实际扣减积分余额
  1253. $isTestUser = $this->isTestUser($uid, (int)getProp($user, 'cpid', 0));
  1254. $pointsAfter = $isTestUser ? $pointsBefore : $pointsBefore - $points;
  1255. // 测试标记落库:charge_info 写入 test_mode,remark 追加 [测试],便于统计排除与历史排查
  1256. if ($isTestUser) {
  1257. $chargeInfo['test_mode'] = true;
  1258. $remark = trim(($remark ? $remark . ';' : '') . '[测试]仅记账不扣费');
  1259. }
  1260. if (!$isTestUser && $pointsBefore < $points) {
  1261. dLog('points')->warning('用户积分不足,扣费后积分为负数', [
  1262. 'task_id' => $taskId,
  1263. 'uid' => $uid,
  1264. 'points_before' => $pointsBefore,
  1265. 'points_consumed' => $points
  1266. ]);
  1267. }
  1268. if (!$isTestUser) {
  1269. // 原子扣减积分:基于数据库当前值执行(points = points - X),
  1270. // 避免并发处理不同任务时基于旧快照覆盖写入导致丢失更新(少扣);
  1271. // COALESCE 处理余额为 NULL 的用户(NULL - X 在 MySQL 中仍为 NULL)
  1272. DB::table('mp_manage_users')->where('id', $uid)->update([
  1273. 'points' => DB::raw('COALESCE(points, 0) - ' . (float)$points),
  1274. 'updated_at' => date('Y-m-d H:i:s')
  1275. ]);
  1276. }
  1277. // 记录积分使用明细
  1278. DB::table('mp_user_points_details')->insert([
  1279. 'uid' => $uid,
  1280. 'cpid' => (int)getProp($user, 'cpid', 0),
  1281. 'task_id' => $taskId,
  1282. 'type' => $type,
  1283. 'api_type' => $apiType,
  1284. 'charge_info' => json_encode($chargeInfo, JSON_UNESCAPED_UNICODE),
  1285. 'points_consumed' => $points,
  1286. 'points_before' => $pointsBefore,
  1287. 'points_after' => $pointsAfter,
  1288. 'tokens_consumed' => $tokens,
  1289. 'remark' => $remark,
  1290. 'created_at' => date('Y-m-d H:i:s'),
  1291. 'updated_at' => date('Y-m-d H:i:s')
  1292. ]);
  1293. DB::commit();
  1294. dLog('points')->info($type . '计费成功', [
  1295. 'task_id' => $taskId,
  1296. 'uid' => $uid,
  1297. 'points_consumed' => $points,
  1298. 'points_after' => $pointsAfter,
  1299. 'tokens_consumed' => $tokens,
  1300. 'test_mode' => $isTestUser
  1301. ]);
  1302. return [
  1303. 'charged' => true,
  1304. 'task_id' => $taskId,
  1305. 'uid' => $uid,
  1306. 'points_consumed' => $points,
  1307. 'points_before' => $pointsBefore,
  1308. 'points_after' => $pointsAfter,
  1309. 'tokens_consumed' => $tokens,
  1310. 'test_mode' => $isTestUser
  1311. ];
  1312. } catch (\Exception $e) {
  1313. DB::rollBack();
  1314. // 唯一索引冲突:同一任务已被其他请求计费,视为已计费(并发验重兜底,避免误报计费失败)
  1315. if ($this->isDuplicateCharge($e)) {
  1316. return ['charged' => false, 'reason' => 'already_charged', 'task_id' => $taskId];
  1317. }
  1318. dLog('points')->error($type . '计费失败: ' . $e->getMessage(), ['task_id' => $taskId]);
  1319. logDB('points', 'error', $type . '计费失败', [
  1320. 'task_id' => $taskId,
  1321. 'error' => $e->getMessage()
  1322. ]);
  1323. return ['charged' => false, 'reason' => 'exception: ' . $e->getMessage(), 'task_id' => $taskId];
  1324. }
  1325. }
  1326. /**
  1327. * 判断异常是否为数据库唯一键冲突(重复计费)
  1328. *
  1329. * @param \Exception $e
  1330. * @return bool
  1331. */
  1332. private function isDuplicateCharge(\Exception $e): bool
  1333. {
  1334. // MySQL 重复键:SQLSTATE 23000 / 错误码 1062(Duplicate entry)
  1335. $code = $e->getCode();
  1336. if ($code === 23000 || $code === '23000' || $code === 1062 || $code === '1062') {
  1337. return true;
  1338. }
  1339. return mb_strpos($e->getMessage(), 'Duplicate entry') !== false;
  1340. }
  1341. }