PointsService.php 72 KB

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