ChannelsTable.js 14 KB

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