ChannelsTable.js 36 KB

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