PointsService.php 66 KB

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