PointsService.php 66 KB

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