GroupRatioSettings.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import React, { useEffect, useState, useRef } from 'react';
  2. import { Button, Col, Form, Row, Spin } from '@douyinfe/semi-ui';
  3. import {
  4. compareObjects,
  5. API,
  6. showError,
  7. showSuccess,
  8. showWarning,
  9. verifyJSON,
  10. } from '../../../helpers';
  11. import { useTranslation } from 'react-i18next';
  12. export default function GroupRatioSettings(props) {
  13. const { t } = useTranslation();
  14. const [loading, setLoading] = useState(false);
  15. const [inputs, setInputs] = useState({
  16. GroupRatio: '',
  17. UserUsableGroups: '',
  18. GroupGroupRatio: '',
  19. AutoGroups: '',
  20. DefaultUseAutoGroup: false,
  21. });
  22. const refForm = useRef();
  23. const [inputsRow, setInputsRow] = useState(inputs);
  24. async function onSubmit() {
  25. try {
  26. await refForm.current
  27. .validate()
  28. .then(() => {
  29. const updateArray = compareObjects(inputs, inputsRow);
  30. if (!updateArray.length)
  31. return showWarning(t('你似乎并没有修改什么'));
  32. const requestQueue = updateArray.map((item) => {
  33. const value =
  34. typeof inputs[item.key] === 'boolean'
  35. ? String(inputs[item.key])
  36. : inputs[item.key];
  37. return API.put('/api/option/', { key: item.key, value });
  38. });
  39. setLoading(true);
  40. Promise.all(requestQueue)
  41. .then((res) => {
  42. if (res.includes(undefined)) {
  43. return showError(
  44. requestQueue.length > 1
  45. ? t('部分保存失败,请重试')
  46. : t('保存失败'),
  47. );
  48. }
  49. for (let i = 0; i < res.length; i++) {
  50. if (!res[i].data.success) {
  51. return showError(res[i].data.message);
  52. }
  53. }
  54. showSuccess(t('保存成功'));
  55. props.refresh();
  56. })
  57. .catch((error) => {
  58. console.error('Unexpected error:', error);
  59. showError(t('保存失败,请重试'));
  60. })
  61. .finally(() => {
  62. setLoading(false);
  63. });
  64. })
  65. .catch(() => {
  66. showError(t('请检查输入'));
  67. });
  68. } catch (error) {
  69. showError(t('请检查输入'));
  70. console.error(error);
  71. }
  72. }
  73. useEffect(() => {
  74. const currentInputs = {};
  75. for (let key in props.options) {
  76. if (Object.keys(inputs).includes(key)) {
  77. currentInputs[key] = props.options[key];
  78. }
  79. }
  80. setInputs(currentInputs);
  81. setInputsRow(structuredClone(currentInputs));
  82. refForm.current.setValues(currentInputs);
  83. }, [props.options]);
  84. return (
  85. <Spin spinning={loading}>
  86. <Form
  87. values={inputs}
  88. getFormApi={(formAPI) => (refForm.current = formAPI)}
  89. style={{ marginBottom: 15 }}
  90. >
  91. <Form.Section text={t('分组设置')}>
  92. <Row gutter={16}>
  93. <Col xs={24} sm={16}>
  94. <Form.TextArea
  95. label={t('分组倍率')}
  96. placeholder={t('为一个 JSON 文本,键为分组名称,值为倍率')}
  97. extraText={t(
  98. '分组倍率设置,可以在此处新增分组或修改现有分组的倍率,格式为 JSON 字符串,例如:{"vip": 0.5, "test": 1},表示 vip 分组的倍率为 0.5,test 分组的倍率为 1',
  99. )}
  100. field={'GroupRatio'}
  101. autosize={{ minRows: 6, maxRows: 12 }}
  102. trigger='blur'
  103. stopValidateWithError
  104. rules={[
  105. {
  106. validator: (rule, value) => verifyJSON(value),
  107. message: t('不是合法的 JSON 字符串'),
  108. },
  109. ]}
  110. onChange={(value) =>
  111. setInputs({ ...inputs, GroupRatio: value })
  112. }
  113. />
  114. </Col>
  115. </Row>
  116. <Row gutter={16}>
  117. <Col xs={24} sm={16}>
  118. <Form.TextArea
  119. label={t('用户可选分组')}
  120. placeholder={t('为一个 JSON 文本,键为分组名称,值为分组描述')}
  121. extraText={t(
  122. '用户新建令牌时可选的分组,格式为 JSON 字符串,例如:{"vip": "VIP 用户", "test": "测试"},表示用户可以选择 vip 分组和 test 分组',
  123. )}
  124. field={'UserUsableGroups'}
  125. autosize={{ minRows: 6, maxRows: 12 }}
  126. trigger='blur'
  127. stopValidateWithError
  128. rules={[
  129. {
  130. validator: (rule, value) => verifyJSON(value),
  131. message: t('不是合法的 JSON 字符串'),
  132. },
  133. ]}
  134. onChange={(value) =>
  135. setInputs({ ...inputs, UserUsableGroups: value })
  136. }
  137. />
  138. </Col>
  139. </Row>
  140. <Row gutter={16}>
  141. <Col xs={24} sm={16}>
  142. <Form.TextArea
  143. label={t('分组特殊倍率')}
  144. placeholder={t('为一个 JSON 文本')}
  145. extraText={t(
  146. '键为分组名称,值为另一个 JSON 对象,键为分组名称,值为该分组的用户的特殊分组倍率,例如:{"vip": {"default": 0.5, "test": 1}},表示 vip 分组的用户在使用default分组的令牌时倍率为0.5,使用test分组时倍率为1',
  147. )}
  148. field={'GroupGroupRatio'}
  149. autosize={{ minRows: 6, maxRows: 12 }}
  150. trigger='blur'
  151. stopValidateWithError
  152. rules={[
  153. {
  154. validator: (rule, value) => verifyJSON(value),
  155. message: t('不是合法的 JSON 字符串'),
  156. },
  157. ]}
  158. onChange={(value) =>
  159. setInputs({ ...inputs, GroupGroupRatio: value })
  160. }
  161. />
  162. </Col>
  163. </Row>
  164. <Row gutter={16}>
  165. <Col xs={24} sm={16}>
  166. <Form.TextArea
  167. label={t('自动分组auto,从第一个开始选择')}
  168. placeholder={t('为一个 JSON 文本')}
  169. field={'AutoGroups'}
  170. autosize={{ minRows: 6, maxRows: 12 }}
  171. trigger='blur'
  172. stopValidateWithError
  173. rules={[
  174. {
  175. validator: (rule, value) => {
  176. if (!value || value.trim() === '') {
  177. return true; // Allow empty values
  178. }
  179. // First check if it's valid JSON
  180. try {
  181. const parsed = JSON.parse(value);
  182. // Check if it's an array
  183. if (!Array.isArray(parsed)) {
  184. return false;
  185. }
  186. // Check if every element is a string
  187. return parsed.every(item => typeof item === 'string');
  188. } catch (error) {
  189. return false;
  190. }
  191. },
  192. message: t('必须是有效的 JSON 字符串数组,例如:["g1","g2"]'),
  193. },
  194. ]}
  195. onChange={(value) =>
  196. setInputs({ ...inputs, AutoGroups: value })
  197. }
  198. />
  199. </Col>
  200. </Row>
  201. <Row gutter={16}>
  202. <Col span={16}>
  203. <Form.Switch
  204. label={t(
  205. '创建令牌默认选择auto分组,初始令牌也将设为auto(否则留空,为用户默认分组)',
  206. )}
  207. field={'DefaultUseAutoGroup'}
  208. onChange={(value) =>
  209. setInputs({ ...inputs, DefaultUseAutoGroup: value })
  210. }
  211. />
  212. </Col>
  213. </Row>
  214. </Form.Section>
  215. </Form>
  216. <Button onClick={onSubmit}>{t('保存分组倍率设置')}</Button>
  217. </Spin>
  218. );
  219. }