ChannelsTable.js 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  1. import React, { useEffect, useState } from 'react';
  2. import {
  3. API,
  4. isMobile,
  5. shouldShowPrompt,
  6. showError,
  7. showInfo,
  8. showSuccess,
  9. showWarning,
  10. timestamp2string
  11. } from '../helpers';
  12. import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../constants';
  13. import {
  14. getQuotaPerUnit,
  15. renderGroup,
  16. renderNumberWithPoint,
  17. renderQuota, renderQuotaWithPrompt
  18. } from '../helpers/render';
  19. import {
  20. Button, Divider,
  21. Dropdown,
  22. Form, Input,
  23. InputNumber, Modal,
  24. Popconfirm,
  25. Space,
  26. SplitButtonGroup,
  27. Switch,
  28. Table,
  29. Tag,
  30. Tooltip,
  31. Typography
  32. } from '@douyinfe/semi-ui';
  33. import EditChannel from '../pages/Channel/EditChannel';
  34. import { IconList, IconTreeTriangleDown } from '@douyinfe/semi-icons';
  35. import { loadChannelModels } from './utils.js';
  36. import EditTagModal from '../pages/Channel/EditTagModal.js';
  37. import TextNumberInput from './custom/TextNumberInput.js';
  38. import { useTranslation } from 'react-i18next';
  39. function renderTimestamp(timestamp) {
  40. return <>{timestamp2string(timestamp)}</>;
  41. }
  42. const ChannelsTable = () => {
  43. const { t } = useTranslation();
  44. let type2label = undefined;
  45. const renderType = (type) => {
  46. if (!type2label) {
  47. type2label = new Map();
  48. for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
  49. type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
  50. }
  51. type2label[0] = { value: 0, text: t('未知类型'), color: 'grey' };
  52. }
  53. return (
  54. <Tag size="large" color={type2label[type]?.color}>
  55. {type2label[type]?.text}
  56. </Tag>
  57. );
  58. };
  59. const renderTagType = () => {
  60. return (
  61. <Tag
  62. color='light-blue'
  63. prefixIcon={<IconList />}
  64. size='large'
  65. shape='circle'
  66. type='light'
  67. >
  68. {t('标签聚合')}
  69. </Tag>
  70. );
  71. };
  72. const renderStatus = (status) => {
  73. switch (status) {
  74. case 1:
  75. return (
  76. <Tag size="large" color="green">
  77. {t('已启用')}
  78. </Tag>
  79. );
  80. case 2:
  81. return (
  82. <Tag size="large" color="yellow">
  83. {t('已禁用')}
  84. </Tag>
  85. );
  86. case 3:
  87. return (
  88. <Tag size="large" color="yellow">
  89. {t('自动禁用')}
  90. </Tag>
  91. );
  92. default:
  93. return (
  94. <Tag size="large" color="grey">
  95. {t('未知状态')}
  96. </Tag>
  97. );
  98. }
  99. };
  100. const renderResponseTime = (responseTime) => {
  101. let time = responseTime / 1000;
  102. time = time.toFixed(2) + t(' 秒');
  103. if (responseTime === 0) {
  104. return (
  105. <Tag size="large" color="grey">
  106. {t('未测试')}
  107. </Tag>
  108. );
  109. } else if (responseTime <= 1000) {
  110. return (
  111. <Tag size="large" color="green">
  112. {time}
  113. </Tag>
  114. );
  115. } else if (responseTime <= 3000) {
  116. return (
  117. <Tag size="large" color="lime">
  118. {time}
  119. </Tag>
  120. );
  121. } else if (responseTime <= 5000) {
  122. return (
  123. <Tag size="large" color="yellow">
  124. {time}
  125. </Tag>
  126. );
  127. } else {
  128. return (
  129. <Tag size="large" color="red">
  130. {time}
  131. </Tag>
  132. );
  133. }
  134. };
  135. const columns = [
  136. // {
  137. // title: '',
  138. // dataIndex: 'checkbox',
  139. // className: 'checkbox',
  140. // },
  141. {
  142. title: t('ID'),
  143. dataIndex: 'id'
  144. },
  145. {
  146. title: t('名称'),
  147. dataIndex: 'name'
  148. },
  149. {
  150. title: t('分组'),
  151. dataIndex: 'group',
  152. render: (text, record, index) => {
  153. return (
  154. <div>
  155. <Space spacing={2}>
  156. {text?.split(',').map((item, index) => {
  157. return renderGroup(item);
  158. })}
  159. </Space>
  160. </div>
  161. );
  162. }
  163. },
  164. {
  165. title: t('类型'),
  166. dataIndex: 'type',
  167. render: (text, record, index) => {
  168. if (record.children === undefined) {
  169. return <>{renderType(text)}</>;
  170. } else {
  171. return <>{renderTagType()}</>;
  172. }
  173. }
  174. },
  175. {
  176. title: t('状态'),
  177. dataIndex: 'status',
  178. render: (text, record, index) => {
  179. if (text === 3) {
  180. if (record.other_info === '') {
  181. record.other_info = '{}';
  182. }
  183. let otherInfo = JSON.parse(record.other_info);
  184. let reason = otherInfo['status_reason'];
  185. let time = otherInfo['status_time'];
  186. return (
  187. <div>
  188. <Tooltip content={t('原因:') + reason + t(',时间:') + timestamp2string(time)}>
  189. {renderStatus(text)}
  190. </Tooltip>
  191. </div>
  192. );
  193. } else {
  194. return renderStatus(text);
  195. }
  196. }
  197. },
  198. {
  199. title: t('响应时间'),
  200. dataIndex: 'response_time',
  201. render: (text, record, index) => {
  202. return <div>{renderResponseTime(text)}</div>;
  203. }
  204. },
  205. {
  206. title: t('已用/剩余'),
  207. dataIndex: 'expired_time',
  208. render: (text, record, index) => {
  209. if (record.children === undefined) {
  210. return (
  211. <div>
  212. <Space spacing={1}>
  213. <Tooltip content={t('已用额度')}>
  214. <Tag color="white" type="ghost" size="large">
  215. {renderQuota(record.used_quota)}
  216. </Tag>
  217. </Tooltip>
  218. <Tooltip content={t('剩余额度') + record.balance + t(',点击更新')}>
  219. <Tag
  220. color="white"
  221. type="ghost"
  222. size="large"
  223. onClick={() => {
  224. updateChannelBalance(record);
  225. }}
  226. >
  227. ${renderNumberWithPoint(record.balance)}
  228. </Tag>
  229. </Tooltip>
  230. </Space>
  231. </div>
  232. );
  233. } else {
  234. return <Tooltip content={t('已用额度')}>
  235. <Tag color="white" type="ghost" size="large">
  236. {renderQuota(record.used_quota)}
  237. </Tag>
  238. </Tooltip>;
  239. }
  240. }
  241. },
  242. {
  243. title: '优先级',
  244. dataIndex: 'priority',
  245. render: (text, record, index) => {
  246. if (record.children === undefined) {
  247. return (
  248. <div>
  249. <InputNumber
  250. style={{ width: 70 }}
  251. name="priority"
  252. onBlur={(e) => {
  253. manageChannel(record.id, 'priority', record, e.target.value);
  254. }}
  255. keepFocus={true}
  256. innerButtons
  257. defaultValue={record.priority}
  258. min={-999}
  259. />
  260. </div>
  261. );
  262. } else {
  263. return <>
  264. <InputNumber
  265. style={{ width: 70 }}
  266. name="priority"
  267. keepFocus={true}
  268. onBlur={(e) => {
  269. Modal.warning({
  270. title: '修改子渠道优先级',
  271. content: '确定要修改所有子渠道优先级为 ' + e.target.value + ' 吗?',
  272. onOk: () => {
  273. if (e.target.value === '') {
  274. return;
  275. }
  276. submitTagEdit('priority', {
  277. tag: record.key,
  278. priority: e.target.value
  279. })
  280. },
  281. })
  282. }}
  283. innerButtons
  284. defaultValue={record.priority}
  285. min={-999}
  286. />
  287. </>;
  288. }
  289. }
  290. },
  291. {
  292. title: '权重',
  293. dataIndex: 'weight',
  294. render: (text, record, index) => {
  295. if (record.children === undefined) {
  296. return (
  297. <div>
  298. <InputNumber
  299. style={{ width: 70 }}
  300. name="weight"
  301. onBlur={(e) => {
  302. manageChannel(record.id, 'weight', record, e.target.value);
  303. }}
  304. keepFocus={true}
  305. innerButtons
  306. defaultValue={record.weight}
  307. min={0}
  308. />
  309. </div>
  310. );
  311. } else {
  312. return (
  313. <InputNumber
  314. style={{ width: 70 }}
  315. name="weight"
  316. keepFocus={true}
  317. onBlur={(e) => {
  318. Modal.warning({
  319. title: '修改子渠道权重',
  320. content: '确定要修改所有子渠道权重为 ' + e.target.value + ' 吗?',
  321. onOk: () => {
  322. if (e.target.value === '') {
  323. return;
  324. }
  325. submitTagEdit('weight', {
  326. tag: record.key,
  327. weight: e.target.value
  328. })
  329. },
  330. })
  331. }}
  332. innerButtons
  333. defaultValue={record.weight}
  334. min={-999}
  335. />
  336. );
  337. }
  338. }
  339. },
  340. {
  341. title: '',
  342. dataIndex: 'operate',
  343. render: (text, record, index) => {
  344. if (record.children === undefined) {
  345. return (
  346. <div>
  347. <SplitButtonGroup
  348. style={{ marginRight: 1 }}
  349. aria-label={t('测试单个渠道操作项目组')}
  350. >
  351. <Button
  352. theme="light"
  353. onClick={() => {
  354. testChannel(record, '');
  355. }}
  356. >
  357. {t('测试')}
  358. </Button>
  359. <Dropdown
  360. trigger="click"
  361. position="bottomRight"
  362. menu={record.test_models}
  363. >
  364. <Button
  365. style={{ padding: '8px 4px' }}
  366. type="primary"
  367. icon={<IconTreeTriangleDown />}
  368. ></Button>
  369. </Dropdown>
  370. </SplitButtonGroup>
  371. <Popconfirm
  372. title={t('确定是否要删除此渠道?')}
  373. content={t('此修改将不可逆')}
  374. okType={'danger'}
  375. position={'left'}
  376. onConfirm={() => {
  377. manageChannel(record.id, 'delete', record).then(() => {
  378. removeRecord(record);
  379. });
  380. }}
  381. >
  382. <Button theme="light" type="danger" style={{ marginRight: 1 }}>
  383. {t('删除')}
  384. </Button>
  385. </Popconfirm>
  386. {record.status === 1 ? (
  387. <Button
  388. theme="light"
  389. type="warning"
  390. style={{ marginRight: 1 }}
  391. onClick={async () => {
  392. manageChannel(record.id, 'disable', record);
  393. }}
  394. >
  395. {t('禁用')}
  396. </Button>
  397. ) : (
  398. <Button
  399. theme="light"
  400. type="secondary"
  401. style={{ marginRight: 1 }}
  402. onClick={async () => {
  403. manageChannel(record.id, 'enable', record);
  404. }}
  405. >
  406. {t('启用')}
  407. </Button>
  408. )}
  409. <Button
  410. theme="light"
  411. type="tertiary"
  412. style={{ marginRight: 1 }}
  413. onClick={() => {
  414. setEditingChannel(record);
  415. setShowEdit(true);
  416. }}
  417. >
  418. {t('编辑')}
  419. </Button>
  420. <Popconfirm
  421. title={t('确定是否要复制此渠道?')}
  422. content={t('复制渠道的所有信息')}
  423. okType={'danger'}
  424. position={'left'}
  425. onConfirm={async () => {
  426. copySelectedChannel(record);
  427. }}
  428. >
  429. <Button theme="light" type="primary" style={{ marginRight: 1 }}>
  430. {t('复制')}
  431. </Button>
  432. </Popconfirm>
  433. </div>
  434. );
  435. } else {
  436. return (
  437. <>
  438. <Button
  439. theme="light"
  440. type="secondary"
  441. style={{ marginRight: 1 }}
  442. onClick={async () => {
  443. manageTag(record.key, 'enable');
  444. }}
  445. >
  446. {t('启用全部')}
  447. </Button>
  448. <Button
  449. theme="light"
  450. type="warning"
  451. style={{ marginRight: 1 }}
  452. onClick={async () => {
  453. manageTag(record.key, 'disable');
  454. }}
  455. >
  456. {t('禁用全部')}
  457. </Button>
  458. <Button
  459. theme="light"
  460. type="tertiary"
  461. style={{ marginRight: 1 }}
  462. onClick={() => {
  463. setShowEditTag(true);
  464. setEditingTag(record.key);
  465. }}
  466. >
  467. {t('编辑')}
  468. </Button>
  469. </>
  470. );
  471. }
  472. }
  473. }
  474. ];
  475. const [channels, setChannels] = useState([]);
  476. const [loading, setLoading] = useState(true);
  477. const [activePage, setActivePage] = useState(1);
  478. const [idSort, setIdSort] = useState(false);
  479. const [searchKeyword, setSearchKeyword] = useState('');
  480. const [searchGroup, setSearchGroup] = useState('');
  481. const [searchModel, setSearchModel] = useState('');
  482. const [searching, setSearching] = useState(false);
  483. const [updatingBalance, setUpdatingBalance] = useState(false);
  484. const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
  485. const [showPrompt, setShowPrompt] = useState(
  486. shouldShowPrompt('channel-test')
  487. );
  488. const [channelCount, setChannelCount] = useState(pageSize);
  489. const [groupOptions, setGroupOptions] = useState([]);
  490. const [showEdit, setShowEdit] = useState(false);
  491. const [enableBatchDelete, setEnableBatchDelete] = useState(false);
  492. const [editingChannel, setEditingChannel] = useState({
  493. id: undefined
  494. });
  495. const [showEditTag, setShowEditTag] = useState(false);
  496. const [editingTag, setEditingTag] = useState('');
  497. const [selectedChannels, setSelectedChannels] = useState([]);
  498. const [showEditPriority, setShowEditPriority] = useState(false);
  499. const [enableTagMode, setEnableTagMode] = useState(false);
  500. const removeRecord = (record) => {
  501. let newDataSource = [...channels];
  502. if (record.id != null) {
  503. let idx = newDataSource.findIndex((data) => {
  504. if (data.children !== undefined) {
  505. for (let i = 0; i < data.children.length; i++) {
  506. if (data.children[i].id === record.id) {
  507. data.children.splice(i, 1);
  508. return false;
  509. }
  510. }
  511. } else {
  512. return data.id === record.id
  513. }
  514. });
  515. if (idx > -1) {
  516. newDataSource.splice(idx, 1);
  517. setChannels(newDataSource);
  518. }
  519. }
  520. };
  521. const setChannelFormat = (channels, enableTagMode) => {
  522. let channelDates = [];
  523. let channelTags = {};
  524. for (let i = 0; i < channels.length; i++) {
  525. channels[i].key = '' + channels[i].id;
  526. let test_models = [];
  527. channels[i].models.split(',').forEach((item, index) => {
  528. test_models.push({
  529. node: 'item',
  530. name: item,
  531. onClick: () => {
  532. testChannel(channels[i], item);
  533. }
  534. });
  535. });
  536. channels[i].test_models = test_models;
  537. if (!enableTagMode) {
  538. channelDates.push(channels[i]);
  539. } else {
  540. let tag = channels[i].tag?channels[i].tag:"";
  541. // find from channelTags
  542. let tagIndex = channelTags[tag];
  543. let tagChannelDates = undefined;
  544. if (tagIndex === undefined) {
  545. // not found, create a new tag
  546. channelTags[tag] = 1;
  547. tagChannelDates = {
  548. key: tag,
  549. id: tag,
  550. tag: tag,
  551. name: '标签:' + tag,
  552. group: '',
  553. used_quota: 0,
  554. response_time: 0,
  555. priority: -1,
  556. weight: -1,
  557. };
  558. tagChannelDates.children = [];
  559. channelDates.push(tagChannelDates);
  560. } else {
  561. // found, add to the tag
  562. tagChannelDates = channelDates.find((item) => item.key === tag);
  563. }
  564. if (tagChannelDates.priority === -1) {
  565. tagChannelDates.priority = channels[i].priority;
  566. } else {
  567. if (tagChannelDates.priority !== channels[i].priority) {
  568. tagChannelDates.priority = '';
  569. }
  570. }
  571. if (tagChannelDates.weight === -1) {
  572. tagChannelDates.weight = channels[i].weight;
  573. } else {
  574. if (tagChannelDates.weight !== channels[i].weight) {
  575. tagChannelDates.weight = '';
  576. }
  577. }
  578. if (tagChannelDates.group === '') {
  579. tagChannelDates.group = channels[i].group;
  580. } else {
  581. let channelGroupsStr = channels[i].group;
  582. channelGroupsStr.split(',').forEach((item, index) => {
  583. if (tagChannelDates.group.indexOf(item) === -1) {
  584. // join
  585. tagChannelDates.group += ',' + item;
  586. }
  587. });
  588. }
  589. tagChannelDates.children.push(channels[i]);
  590. if (channels[i].status === 1) {
  591. tagChannelDates.status = 1;
  592. }
  593. tagChannelDates.used_quota += channels[i].used_quota;
  594. tagChannelDates.response_time += channels[i].response_time;
  595. tagChannelDates.response_time = tagChannelDates.response_time / 2;
  596. }
  597. }
  598. // data.key = '' + data.id
  599. setChannels(channelDates);
  600. if (channelDates.length >= pageSize) {
  601. setChannelCount(channelDates.length + pageSize);
  602. } else {
  603. setChannelCount(channelDates.length);
  604. }
  605. };
  606. const loadChannels = async (startIdx, pageSize, idSort, enableTagMode) => {
  607. setLoading(true);
  608. const res = await API.get(
  609. `/api/channel/?p=${startIdx}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}`
  610. );
  611. if (res === undefined) {
  612. return;
  613. }
  614. const { success, message, data } = res.data;
  615. if (success) {
  616. if (startIdx === 0) {
  617. setChannelFormat(data, enableTagMode);
  618. } else {
  619. let newChannels = [...channels];
  620. newChannels.splice(startIdx * pageSize, data.length, ...data);
  621. setChannelFormat(newChannels, enableTagMode);
  622. }
  623. } else {
  624. showError(message);
  625. }
  626. setLoading(false);
  627. };
  628. const copySelectedChannel = async (record) => {
  629. const channelToCopy = record
  630. channelToCopy.name += '_复制';
  631. channelToCopy.created_time = null;
  632. channelToCopy.balance = 0;
  633. channelToCopy.used_quota = 0;
  634. if (!channelToCopy) {
  635. showError('渠道未找到,请刷新页面后重试。');
  636. return;
  637. }
  638. try {
  639. const newChannel = { ...channelToCopy, id: undefined };
  640. const response = await API.post('/api/channel/', newChannel);
  641. if (response.data.success) {
  642. showSuccess('渠道复制成功');
  643. await refresh();
  644. } else {
  645. showError(response.data.message);
  646. }
  647. } catch (error) {
  648. showError('渠道复制失败: ' + error.message);
  649. }
  650. };
  651. const refresh = async () => {
  652. await loadChannels(activePage - 1, pageSize, idSort, enableTagMode);
  653. };
  654. useEffect(() => {
  655. // console.log('default effect')
  656. const localIdSort = localStorage.getItem('id-sort') === 'true';
  657. const localPageSize =
  658. parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
  659. setIdSort(localIdSort);
  660. setPageSize(localPageSize);
  661. loadChannels(0, localPageSize, localIdSort, enableTagMode)
  662. .then()
  663. .catch((reason) => {
  664. showError(reason);
  665. });
  666. fetchGroups().then();
  667. loadChannelModels().then();
  668. }, []);
  669. const manageChannel = async (id, action, record, value) => {
  670. let data = { id };
  671. let res;
  672. switch (action) {
  673. case 'delete':
  674. res = await API.delete(`/api/channel/${id}/`);
  675. break;
  676. case 'enable':
  677. data.status = 1;
  678. res = await API.put('/api/channel/', data);
  679. break;
  680. case 'disable':
  681. data.status = 2;
  682. res = await API.put('/api/channel/', data);
  683. break;
  684. case 'priority':
  685. if (value === '') {
  686. return;
  687. }
  688. data.priority = parseInt(value);
  689. res = await API.put('/api/channel/', data);
  690. break;
  691. case 'weight':
  692. if (value === '') {
  693. return;
  694. }
  695. data.weight = parseInt(value);
  696. if (data.weight < 0) {
  697. data.weight = 0;
  698. }
  699. res = await API.put('/api/channel/', data);
  700. break;
  701. }
  702. const { success, message } = res.data;
  703. if (success) {
  704. showSuccess('操作成功完成!');
  705. let channel = res.data.data;
  706. let newChannels = [...channels];
  707. if (action === 'delete') {
  708. } else {
  709. record.status = channel.status;
  710. }
  711. setChannels(newChannels);
  712. } else {
  713. showError(message);
  714. }
  715. };
  716. const manageTag = async (tag, action) => {
  717. console.log(tag, action);
  718. let res;
  719. switch (action) {
  720. case 'enable':
  721. res = await API.post('/api/channel/tag/enabled', {
  722. tag: tag
  723. });
  724. break;
  725. case 'disable':
  726. res = await API.post('/api/channel/tag/disabled', {
  727. tag: tag
  728. });
  729. break;
  730. }
  731. const { success, message } = res.data;
  732. if (success) {
  733. showSuccess('操作成功完成!');
  734. let newChannels = [...channels];
  735. for (let i = 0; i < newChannels.length; i++) {
  736. if (newChannels[i].tag === tag) {
  737. let status = action === 'enable' ? 1 : 2;
  738. newChannels[i]?.children?.forEach((channel) => {
  739. channel.status = status;
  740. });
  741. newChannels[i].status = status;
  742. }
  743. }
  744. setChannels(newChannels);
  745. } else {
  746. showError(message);
  747. }
  748. };
  749. const searchChannels = async (searchKeyword, searchGroup, searchModel, enableTagMode) => {
  750. if (searchKeyword === '' && searchGroup === '' && searchModel === '') {
  751. await loadChannels(0, pageSize, idSort, enableTagMode);
  752. setActivePage(1);
  753. return;
  754. }
  755. setSearching(true);
  756. const res = await API.get(
  757. `/api/channel/search?keyword=${searchKeyword}&group=${searchGroup}&model=${searchModel}&id_sort=${idSort}&tag_mode=${enableTagMode}`
  758. );
  759. const { success, message, data } = res.data;
  760. if (success) {
  761. setChannelFormat(data, enableTagMode);
  762. setActivePage(1);
  763. } else {
  764. showError(message);
  765. }
  766. setSearching(false);
  767. };
  768. const testChannel = async (record, model) => {
  769. const res = await API.get(`/api/channel/test/${record.id}?model=${model}`);
  770. const { success, message, time } = res.data;
  771. if (success) {
  772. record.response_time = time * 1000;
  773. record.test_time = Date.now() / 1000;
  774. showInfo(t('通道 ${name} 测试成功,耗时 ${time.toFixed(2)} 秒。').replace('${name}', record.name).replace('${time.toFixed(2)}', time.toFixed(2)));
  775. } else {
  776. showError(message);
  777. }
  778. };
  779. const testAllChannels = async () => {
  780. const res = await API.get(`/api/channel/test`);
  781. const { success, message } = res.data;
  782. if (success) {
  783. showInfo(t('已成功开始测试所有已启用通道,请刷新页面查看结果。'));
  784. } else {
  785. showError(message);
  786. }
  787. };
  788. const deleteAllDisabledChannels = async () => {
  789. const res = await API.delete(`/api/channel/disabled`);
  790. const { success, message, data } = res.data;
  791. if (success) {
  792. showSuccess(t('已删除所有禁用渠道,共计 ${data} 个').replace('${data}', data));
  793. await refresh();
  794. } else {
  795. showError(message);
  796. }
  797. };
  798. const updateChannelBalance = async (record) => {
  799. const res = await API.get(`/api/channel/update_balance/${record.id}/`);
  800. const { success, message, balance } = res.data;
  801. if (success) {
  802. record.balance = balance;
  803. record.balance_updated_time = Date.now() / 1000;
  804. showInfo(t('通道 ${name} 余额更新成功!').replace('${name}', record.name));
  805. } else {
  806. showError(message);
  807. }
  808. };
  809. const updateAllChannelsBalance = async () => {
  810. setUpdatingBalance(true);
  811. const res = await API.get(`/api/channel/update_balance`);
  812. const { success, message } = res.data;
  813. if (success) {
  814. showInfo(t('已更新完毕所有已启用通道余额!'));
  815. } else {
  816. showError(message);
  817. }
  818. setUpdatingBalance(false);
  819. };
  820. const batchDeleteChannels = async () => {
  821. if (selectedChannels.length === 0) {
  822. showError(t('请先选择要删除的通道!'));
  823. return;
  824. }
  825. setLoading(true);
  826. let ids = [];
  827. selectedChannels.forEach((channel) => {
  828. ids.push(channel.id);
  829. });
  830. const res = await API.post(`/api/channel/batch`, { ids: ids });
  831. const { success, message, data } = res.data;
  832. if (success) {
  833. showSuccess(t('已删除 ${data} 个通道!').replace('${data}', data));
  834. await refresh();
  835. } else {
  836. showError(message);
  837. }
  838. setLoading(false);
  839. };
  840. const fixChannelsAbilities = async () => {
  841. const res = await API.post(`/api/channel/fix`);
  842. const { success, message, data } = res.data;
  843. if (success) {
  844. showSuccess(t('已修复 ${data} 个通道!').replace('${data}', data));
  845. await refresh();
  846. } else {
  847. showError(message);
  848. }
  849. };
  850. let pageData = channels.slice(
  851. (activePage - 1) * pageSize,
  852. activePage * pageSize
  853. );
  854. const handlePageChange = (page) => {
  855. setActivePage(page);
  856. if (page === Math.ceil(channels.length / pageSize) + 1) {
  857. // In this case we have to load more data and then append them.
  858. loadChannels(page - 1, pageSize, idSort, enableTagMode).then((r) => {
  859. });
  860. }
  861. };
  862. const handlePageSizeChange = async (size) => {
  863. localStorage.setItem('page-size', size + '');
  864. setPageSize(size);
  865. setActivePage(1);
  866. loadChannels(0, size, idSort, enableTagMode)
  867. .then()
  868. .catch((reason) => {
  869. showError(reason);
  870. });
  871. };
  872. const fetchGroups = async () => {
  873. try {
  874. let res = await API.get(`/api/group/`);
  875. // add 'all' option
  876. // res.data.data.unshift('all');
  877. if (res === undefined) {
  878. return;
  879. }
  880. setGroupOptions(
  881. res.data.data.map((group) => ({
  882. label: group,
  883. value: group
  884. }))
  885. );
  886. } catch (error) {
  887. showError(error.message);
  888. }
  889. };
  890. const submitTagEdit = async (type, data) => {
  891. switch (type) {
  892. case 'priority':
  893. if (data.priority === undefined || data.priority === '') {
  894. showInfo('优先级必须是整数!');
  895. return;
  896. }
  897. data.priority = parseInt(data.priority);
  898. break;
  899. case 'weight':
  900. if (data.weight === undefined || data.weight < 0 || data.weight === '') {
  901. showInfo('权重必须是非负整数!');
  902. return;
  903. }
  904. data.weight = parseInt(data.weight);
  905. break
  906. }
  907. try {
  908. const res = await API.put('/api/channel/tag', data);
  909. if (res?.data?.success) {
  910. showSuccess('更新成功!');
  911. await refresh();
  912. }
  913. } catch (error) {
  914. showError(error);
  915. }
  916. }
  917. const closeEdit = () => {
  918. setShowEdit(false);
  919. };
  920. const handleRow = (record, index) => {
  921. if (record.status !== 1) {
  922. return {
  923. style: {
  924. background: 'var(--semi-color-disabled-border)'
  925. }
  926. };
  927. } else {
  928. return {};
  929. }
  930. };
  931. return (
  932. <>
  933. <EditTagModal
  934. visible={showEditTag}
  935. tag={editingTag}
  936. handleClose={() => setShowEditTag(false)}
  937. refresh={refresh}
  938. />
  939. <EditChannel
  940. refresh={refresh}
  941. visible={showEdit}
  942. handleClose={closeEdit}
  943. editingChannel={editingChannel}
  944. />
  945. <Form
  946. onSubmit={() => {
  947. searchChannels(searchKeyword, searchGroup, searchModel, enableTagMode);
  948. }}
  949. labelPosition="left"
  950. >
  951. <div style={{ display: 'flex' }}>
  952. <Space>
  953. <Form.Input
  954. field="search_keyword"
  955. label={t('搜索渠道关键词')}
  956. placeholder={t('搜索渠道的 ID,名称和密钥 ...')}
  957. value={searchKeyword}
  958. loading={searching}
  959. onChange={(v) => {
  960. setSearchKeyword(v.trim());
  961. }}
  962. />
  963. <Form.Input
  964. field="search_model"
  965. label={t('模型')}
  966. placeholder={t('模型关键字')}
  967. value={searchModel}
  968. loading={searching}
  969. onChange={(v) => {
  970. setSearchModel(v.trim());
  971. }}
  972. />
  973. <Form.Select
  974. field="group"
  975. label={t('分组')}
  976. optionList={[{ label: t('选择分组'), value: null }, ...groupOptions]}
  977. initValue={null}
  978. onChange={(v) => {
  979. setSearchGroup(v);
  980. searchChannels(searchKeyword, v, searchModel, enableTagMode);
  981. }}
  982. />
  983. <Button
  984. label={t('查询')}
  985. type="primary"
  986. htmlType="submit"
  987. className="btn-margin-right"
  988. style={{ marginRight: 8 }}
  989. >
  990. {t('查询')}
  991. </Button>
  992. </Space>
  993. </div>
  994. </Form>
  995. <Divider style={{ marginBottom: 15 }} />
  996. <div
  997. style={{
  998. display: isMobile() ? '' : 'flex',
  999. marginTop: isMobile() ? 0 : -45,
  1000. zIndex: 999,
  1001. pointerEvents: 'none'
  1002. }}
  1003. >
  1004. <Space
  1005. style={{ pointerEvents: 'auto', marginTop: isMobile() ? 0 : 45 }}
  1006. >
  1007. <Typography.Text strong>{t('使用ID排序')}</Typography.Text>
  1008. <Switch
  1009. checked={idSort}
  1010. label={t('使用ID排序')}
  1011. uncheckedText={t('关')}
  1012. aria-label={t('是否用ID排序')}
  1013. onChange={(v) => {
  1014. localStorage.setItem('id-sort', v + '');
  1015. setIdSort(v);
  1016. loadChannels(0, pageSize, v, enableTagMode)
  1017. .then()
  1018. .catch((reason) => {
  1019. showError(reason);
  1020. });
  1021. }}
  1022. ></Switch>
  1023. <Button
  1024. theme="light"
  1025. type="primary"
  1026. style={{ marginRight: 8 }}
  1027. onClick={() => {
  1028. setEditingChannel({
  1029. id: undefined
  1030. });
  1031. setShowEdit(true);
  1032. }}
  1033. >
  1034. {t('添加渠道')}
  1035. </Button>
  1036. <Popconfirm
  1037. title={t('确定?')}
  1038. okType={'warning'}
  1039. onConfirm={testAllChannels}
  1040. position={isMobile() ? 'top' : 'top'}
  1041. >
  1042. <Button theme="light" type="warning" style={{ marginRight: 8 }}>
  1043. {t('测试所有通道')}
  1044. </Button>
  1045. </Popconfirm>
  1046. <Popconfirm
  1047. title={t('确定?')}
  1048. okType={'secondary'}
  1049. onConfirm={updateAllChannelsBalance}
  1050. >
  1051. <Button theme="light" type="secondary" style={{ marginRight: 8 }}>
  1052. {t('更新所有已启用通道余额')}
  1053. </Button>
  1054. </Popconfirm>
  1055. <Popconfirm
  1056. title={t('确定是否要删除禁用通道?')}
  1057. content={t('此修改将不可逆')}
  1058. okType={'danger'}
  1059. onConfirm={deleteAllDisabledChannels}
  1060. >
  1061. <Button theme="light" type="danger" style={{ marginRight: 8 }}>
  1062. {t('删除禁用通道')}
  1063. </Button>
  1064. </Popconfirm>
  1065. <Button
  1066. theme="light"
  1067. type="primary"
  1068. style={{ marginRight: 8 }}
  1069. onClick={refresh}
  1070. >
  1071. {t('刷新')}
  1072. </Button>
  1073. </Space>
  1074. </div>
  1075. <div style={{ marginTop: 20 }}>
  1076. <Space>
  1077. <Typography.Text strong>{t('开启批量删除')}</Typography.Text>
  1078. <Switch
  1079. label={t('开启批量删除')}
  1080. uncheckedText={t('关')}
  1081. aria-label={t('是否开启批量删除')}
  1082. onChange={(v) => {
  1083. setEnableBatchDelete(v);
  1084. }}
  1085. ></Switch>
  1086. <Popconfirm
  1087. title={t('确定是否要删除所选通道?')}
  1088. content={t('此修改将不可逆')}
  1089. okType={'danger'}
  1090. onConfirm={batchDeleteChannels}
  1091. disabled={!enableBatchDelete}
  1092. position={'top'}
  1093. >
  1094. <Button
  1095. disabled={!enableBatchDelete}
  1096. theme="light"
  1097. type="danger"
  1098. style={{ marginRight: 8 }}
  1099. >
  1100. {t('删除所选通道')}
  1101. </Button>
  1102. </Popconfirm>
  1103. <Popconfirm
  1104. title={t('确定是否要修复数据库一致性?')}
  1105. content={t('进行该操作时,可能导致渠道访问错误,请仅在数据库出现问题时使用')}
  1106. okType={'warning'}
  1107. onConfirm={fixChannelsAbilities}
  1108. position={'top'}
  1109. >
  1110. <Button theme="light" type="secondary" style={{ marginRight: 8 }}>
  1111. {t('修复数据库一致性')}
  1112. </Button>
  1113. </Popconfirm>
  1114. </Space>
  1115. </div>
  1116. <div style={{ marginTop: 20 }}>
  1117. <Space>
  1118. <Typography.Text strong>{t('标签聚合模式')}</Typography.Text>
  1119. <Switch
  1120. checked={enableTagMode}
  1121. label={t('标签聚合模式')}
  1122. uncheckedText={t('关')}
  1123. aria-label={t('是否启用标签聚合')}
  1124. onChange={(v) => {
  1125. setEnableTagMode(v);
  1126. loadChannels(0, pageSize, idSort, v);
  1127. }}
  1128. />
  1129. </Space>
  1130. </div>
  1131. <Table
  1132. className={'channel-table'}
  1133. style={{ marginTop: 15 }}
  1134. columns={columns}
  1135. dataSource={pageData}
  1136. pagination={{
  1137. currentPage: activePage,
  1138. pageSize: pageSize,
  1139. total: channelCount,
  1140. pageSizeOpts: [10, 20, 50, 100],
  1141. showSizeChanger: true,
  1142. formatPageText: (page) => '',
  1143. onPageSizeChange: (size) => {
  1144. handlePageSizeChange(size).then();
  1145. },
  1146. onPageChange: handlePageChange
  1147. }}
  1148. loading={loading}
  1149. onRow={handleRow}
  1150. rowSelection={
  1151. enableBatchDelete
  1152. ? {
  1153. onChange: (selectedRowKeys, selectedRows) => {
  1154. // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  1155. setSelectedChannels(selectedRows);
  1156. }
  1157. }
  1158. : null
  1159. }
  1160. />
  1161. </>
  1162. );
  1163. };
  1164. export default ChannelsTable;