ChannelsTable.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import React, { useEffect, useState } from 'react';
  2. import { Button, Form, Label, Pagination, Popup, Table } from 'semantic-ui-react';
  3. import { Link } from 'react-router-dom';
  4. import { API, showError, showInfo, showSuccess, timestamp2string } from '../helpers';
  5. import { CHANNEL_OPTIONS, ITEMS_PER_PAGE } from '../constants';
  6. import {renderGroup, renderNumber, renderQuota} from '../helpers/render';
  7. function renderTimestamp(timestamp) {
  8. return (
  9. <>
  10. {timestamp2string(timestamp)}
  11. </>
  12. );
  13. }
  14. let type2label = undefined;
  15. function renderType(type) {
  16. if (!type2label) {
  17. type2label = new Map;
  18. for (let i = 0; i < CHANNEL_OPTIONS.length; i++) {
  19. type2label[CHANNEL_OPTIONS[i].value] = CHANNEL_OPTIONS[i];
  20. }
  21. type2label[0] = { value: 0, text: '未知类型', color: 'grey' };
  22. }
  23. return <Label basic color={type2label[type].color}>{type2label[type].text}</Label>;
  24. }
  25. function renderBalance(type, balance) {
  26. switch (type) {
  27. case 1: // OpenAI
  28. return <span>${balance.toFixed(2)}</span>;
  29. case 4: // CloseAI
  30. return <span>¥{balance.toFixed(2)}</span>;
  31. case 8: // 自定义
  32. return <span>${balance.toFixed(2)}</span>;
  33. case 5: // OpenAI-SB
  34. return <span>¥{(balance / 10000).toFixed(2)}</span>;
  35. case 10: // AI Proxy
  36. return <span>{renderNumber(balance)}</span>;
  37. case 12: // API2GPT
  38. return <span>¥{balance.toFixed(2)}</span>;
  39. case 13: // AIGC2D
  40. return <span>{renderNumber(balance)}</span>;
  41. default:
  42. return <span>不支持</span>;
  43. }
  44. }
  45. const ChannelsTable = () => {
  46. const [channels, setChannels] = useState([]);
  47. const [loading, setLoading] = useState(true);
  48. const [activePage, setActivePage] = useState(1);
  49. const [searchKeyword, setSearchKeyword] = useState('');
  50. const [searching, setSearching] = useState(false);
  51. const [updatingBalance, setUpdatingBalance] = useState(false);
  52. const loadChannels = async (startIdx) => {
  53. const res = await API.get(`/api/channel/?p=${startIdx}`);
  54. const { success, message, data } = res.data;
  55. if (success) {
  56. if (startIdx === 0) {
  57. setChannels(data);
  58. } else {
  59. let newChannels = [...channels];
  60. newChannels.splice(startIdx * ITEMS_PER_PAGE, data.length, ...data);
  61. setChannels(newChannels);
  62. }
  63. } else {
  64. showError(message);
  65. }
  66. setLoading(false);
  67. };
  68. const onPaginationChange = (e, { activePage }) => {
  69. (async () => {
  70. if (activePage === Math.ceil(channels.length / ITEMS_PER_PAGE) + 1) {
  71. // In this case we have to load more data and then append them.
  72. await loadChannels(activePage - 1);
  73. }
  74. setActivePage(activePage);
  75. })();
  76. };
  77. const refresh = async () => {
  78. setLoading(true);
  79. await loadChannels(activePage - 1);
  80. };
  81. useEffect(() => {
  82. loadChannels(0)
  83. .then()
  84. .catch((reason) => {
  85. showError(reason);
  86. });
  87. }, []);
  88. const manageChannel = async (id, action, idx) => {
  89. let data = { id };
  90. let res;
  91. switch (action) {
  92. case 'delete':
  93. res = await API.delete(`/api/channel/${id}/`);
  94. break;
  95. case 'enable':
  96. data.status = 1;
  97. res = await API.put('/api/channel/', data);
  98. break;
  99. case 'disable':
  100. data.status = 2;
  101. res = await API.put('/api/channel/', data);
  102. break;
  103. }
  104. const { success, message } = res.data;
  105. if (success) {
  106. showSuccess('操作成功完成!');
  107. let channel = res.data.data;
  108. let newChannels = [...channels];
  109. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  110. if (action === 'delete') {
  111. newChannels[realIdx].deleted = true;
  112. } else {
  113. newChannels[realIdx].status = channel.status;
  114. }
  115. setChannels(newChannels);
  116. } else {
  117. showError(message);
  118. }
  119. };
  120. const renderStatus = (status) => {
  121. switch (status) {
  122. case 1:
  123. return <Label basic color='green'>已启用</Label>;
  124. case 2:
  125. return (
  126. <Label basic color='red'>
  127. 已禁用
  128. </Label>
  129. );
  130. default:
  131. return (
  132. <Label basic color='grey'>
  133. 未知状态
  134. </Label>
  135. );
  136. }
  137. };
  138. const renderResponseTime = (responseTime) => {
  139. let time = responseTime / 1000;
  140. time = time.toFixed(2) + ' 秒';
  141. if (responseTime === 0) {
  142. return <Label basic color='grey'>未测试</Label>;
  143. } else if (responseTime <= 1000) {
  144. return <Label basic color='green'>{time}</Label>;
  145. } else if (responseTime <= 3000) {
  146. return <Label basic color='olive'>{time}</Label>;
  147. } else if (responseTime <= 5000) {
  148. return <Label basic color='yellow'>{time}</Label>;
  149. } else {
  150. return <Label basic color='red'>{time}</Label>;
  151. }
  152. };
  153. const searchChannels = async () => {
  154. if (searchKeyword === '') {
  155. // if keyword is blank, load files instead.
  156. await loadChannels(0);
  157. setActivePage(1);
  158. return;
  159. }
  160. setSearching(true);
  161. const res = await API.get(`/api/channel/search?keyword=${searchKeyword}`);
  162. const { success, message, data } = res.data;
  163. if (success) {
  164. setChannels(data);
  165. setActivePage(1);
  166. } else {
  167. showError(message);
  168. }
  169. setSearching(false);
  170. };
  171. const testChannel = async (id, name, idx) => {
  172. const res = await API.get(`/api/channel/test/${id}/`);
  173. const { success, message, time } = res.data;
  174. if (success) {
  175. let newChannels = [...channels];
  176. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  177. newChannels[realIdx].response_time = time * 1000;
  178. newChannels[realIdx].test_time = Date.now() / 1000;
  179. setChannels(newChannels);
  180. showInfo(`通道 ${name} 测试成功,耗时 ${time.toFixed(2)} 秒。`);
  181. } else {
  182. showError(message);
  183. }
  184. };
  185. const testAllChannels = async () => {
  186. const res = await API.get(`/api/channel/test`);
  187. const { success, message } = res.data;
  188. if (success) {
  189. showInfo('已成功开始测试所有已启用通道,请刷新页面查看结果。');
  190. } else {
  191. showError(message);
  192. }
  193. };
  194. const updateChannelBalance = async (id, name, idx) => {
  195. const res = await API.get(`/api/channel/update_balance/${id}/`);
  196. const { success, message, balance } = res.data;
  197. if (success) {
  198. let newChannels = [...channels];
  199. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  200. newChannels[realIdx].balance = balance;
  201. newChannels[realIdx].balance_updated_time = Date.now() / 1000;
  202. setChannels(newChannels);
  203. showInfo(`通道 ${name} 余额更新成功!`);
  204. } else {
  205. showError(message);
  206. }
  207. };
  208. const updateAllChannelsBalance = async () => {
  209. setUpdatingBalance(true);
  210. const res = await API.get(`/api/channel/update_balance`);
  211. const { success, message } = res.data;
  212. if (success) {
  213. showInfo('已更新完毕所有已启用通道余额!');
  214. } else {
  215. showError(message);
  216. }
  217. setUpdatingBalance(false);
  218. };
  219. const handleKeywordChange = async (e, { value }) => {
  220. setSearchKeyword(value.trim());
  221. };
  222. const sortChannel = (key) => {
  223. if (channels.length === 0) return;
  224. setLoading(true);
  225. let sortedChannels = [...channels];
  226. if (typeof sortedChannels[0][key] === 'string') {
  227. sortedChannels.sort((a, b) => {
  228. return ('' + a[key]).localeCompare(b[key]);
  229. });
  230. } else {
  231. sortedChannels.sort((a, b) => {
  232. if (a[key] === b[key]) return 0;
  233. if (a[key] > b[key]) return -1;
  234. if (a[key] < b[key]) return 1;
  235. });
  236. }
  237. if (sortedChannels[0].id === channels[0].id) {
  238. sortedChannels.reverse();
  239. }
  240. setChannels(sortedChannels);
  241. setLoading(false);
  242. };
  243. return (
  244. <>
  245. <Form onSubmit={searchChannels}>
  246. <Form.Input
  247. icon='search'
  248. fluid
  249. iconPosition='left'
  250. placeholder='搜索渠道的 ID,名称和密钥 ...'
  251. value={searchKeyword}
  252. loading={searching}
  253. onChange={handleKeywordChange}
  254. />
  255. </Form>
  256. <Table basic compact size='small'>
  257. <Table.Header>
  258. <Table.Row>
  259. <Table.HeaderCell
  260. style={{ cursor: 'pointer' }}
  261. onClick={() => {
  262. sortChannel('id');
  263. }}
  264. >
  265. ID
  266. </Table.HeaderCell>
  267. <Table.HeaderCell
  268. style={{ cursor: 'pointer' }}
  269. onClick={() => {
  270. sortChannel('name');
  271. }}
  272. >
  273. 名称
  274. </Table.HeaderCell>
  275. <Table.HeaderCell
  276. style={{ cursor: 'pointer' }}
  277. onClick={() => {
  278. sortChannel('group');
  279. }}
  280. width={1}
  281. >
  282. 分组
  283. </Table.HeaderCell>
  284. <Table.HeaderCell
  285. style={{ cursor: 'pointer' }}
  286. onClick={() => {
  287. sortChannel('type');
  288. }}
  289. width={2}
  290. >
  291. 类型
  292. </Table.HeaderCell>
  293. <Table.HeaderCell
  294. style={{ cursor: 'pointer' }}
  295. onClick={() => {
  296. sortChannel('status');
  297. }}
  298. width={2}
  299. >
  300. 状态
  301. </Table.HeaderCell>
  302. <Table.HeaderCell
  303. style={{ cursor: 'pointer' }}
  304. onClick={() => {
  305. sortChannel('response_time');
  306. }}
  307. >
  308. 响应时间
  309. </Table.HeaderCell>
  310. <Table.HeaderCell
  311. style={{ cursor: 'pointer' }}
  312. onClick={() => {
  313. sortChannel('used_quota');
  314. }}
  315. width={1}
  316. >
  317. 已使用
  318. </Table.HeaderCell>
  319. <Table.HeaderCell
  320. style={{ cursor: 'pointer' }}
  321. onClick={() => {
  322. sortChannel('balance');
  323. }}
  324. >
  325. 余额
  326. </Table.HeaderCell>
  327. <Table.HeaderCell>操作</Table.HeaderCell>
  328. </Table.Row>
  329. </Table.Header>
  330. <Table.Body>
  331. {channels
  332. .slice(
  333. (activePage - 1) * ITEMS_PER_PAGE,
  334. activePage * ITEMS_PER_PAGE
  335. )
  336. .map((channel, idx) => {
  337. if (channel.deleted) return <></>;
  338. return (
  339. <Table.Row key={channel.id}>
  340. <Table.Cell>{channel.id}</Table.Cell>
  341. <Table.Cell>{channel.name ? channel.name : '无'}</Table.Cell>
  342. <Table.Cell>{renderGroup(channel.group)}</Table.Cell>
  343. <Table.Cell>{renderType(channel.type)}</Table.Cell>
  344. <Table.Cell>{renderStatus(channel.status)}</Table.Cell>
  345. <Table.Cell>
  346. <Popup
  347. content={channel.test_time ? renderTimestamp(channel.test_time) : '未测试'}
  348. key={channel.id}
  349. trigger={renderResponseTime(channel.response_time)}
  350. basic
  351. />
  352. </Table.Cell>
  353. <Table.Cell>{renderQuota(channel.used_quota)}</Table.Cell>
  354. <Table.Cell>
  355. <Popup
  356. content={channel.balance_updated_time ? renderTimestamp(channel.balance_updated_time) : '未更新'}
  357. key={channel.id}
  358. trigger={renderBalance(channel.type, channel.balance)}
  359. basic
  360. />
  361. </Table.Cell>
  362. <Table.Cell>
  363. <div>
  364. <Button
  365. size={'small'}
  366. positive
  367. onClick={() => {
  368. testChannel(channel.id, channel.name, idx);
  369. }}
  370. >
  371. 测试
  372. </Button>
  373. <Button
  374. size={'small'}
  375. positive
  376. loading={updatingBalance}
  377. onClick={() => {
  378. updateChannelBalance(channel.id, channel.name, idx);
  379. }}
  380. >
  381. 更新余额
  382. </Button>
  383. <Popup
  384. trigger={
  385. <Button size='small' negative>
  386. 删除
  387. </Button>
  388. }
  389. on='click'
  390. flowing
  391. hoverable
  392. >
  393. <Button
  394. negative
  395. onClick={() => {
  396. manageChannel(channel.id, 'delete', idx);
  397. }}
  398. >
  399. 删除渠道 {channel.name}
  400. </Button>
  401. </Popup>
  402. <Button
  403. size={'small'}
  404. onClick={() => {
  405. manageChannel(
  406. channel.id,
  407. channel.status === 1 ? 'disable' : 'enable',
  408. idx
  409. );
  410. }}
  411. >
  412. {channel.status === 1 ? '禁用' : '启用'}
  413. </Button>
  414. <Button
  415. size={'small'}
  416. as={Link}
  417. to={'/channel/edit/' + channel.id}
  418. >
  419. 编辑
  420. </Button>
  421. </div>
  422. </Table.Cell>
  423. </Table.Row>
  424. );
  425. })}
  426. </Table.Body>
  427. <Table.Footer>
  428. <Table.Row>
  429. <Table.HeaderCell colSpan='8'>
  430. <Button size='small' as={Link} to='/channel/add' loading={loading}>
  431. 添加新的渠道
  432. </Button>
  433. <Button size='small' loading={loading} onClick={testAllChannels}>
  434. 测试所有已启用通道
  435. </Button>
  436. <Button size='small' onClick={updateAllChannelsBalance}
  437. loading={loading || updatingBalance}>更新所有已启用通道余额</Button>
  438. <Pagination
  439. floated='right'
  440. activePage={activePage}
  441. onPageChange={onPaginationChange}
  442. size='small'
  443. siblingRange={1}
  444. totalPages={
  445. Math.ceil(channels.length / ITEMS_PER_PAGE) +
  446. (channels.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
  447. }
  448. />
  449. <Button size='small' onClick={refresh} loading={loading}>刷新</Button>
  450. </Table.HeaderCell>
  451. </Table.Row>
  452. </Table.Footer>
  453. </Table>
  454. </>
  455. );
  456. };
  457. export default ChannelsTable;