File size: 10,248 Bytes
daa8246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
Copyright (C) 2025 QuantumNous

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact support@quantumnous.com
*/

import { useRef, useState } from 'react';
import { API, showError, showInfo, showSuccess } from '../../helpers';
import { normalizeModelList } from './upstreamUpdateUtils';

const getManualIgnoredModelCountFromSettings = (settings) => {
  let parsed = null;
  if (settings && typeof settings === 'object') {
    parsed = settings;
  } else if (typeof settings === 'string') {
    try {
      parsed = JSON.parse(settings);
    } catch (error) {
      parsed = null;
    }
  }
  if (!parsed || typeof parsed !== 'object') {
    return 0;
  }
  return normalizeModelList(parsed.upstream_model_update_ignored_models).length;
};

export const useChannelUpstreamUpdates = ({ t, refresh }) => {
  const [showUpstreamUpdateModal, setShowUpstreamUpdateModal] = useState(false);
  const [upstreamUpdateChannel, setUpstreamUpdateChannel] = useState(null);
  const [upstreamUpdateAddModels, setUpstreamUpdateAddModels] = useState([]);
  const [upstreamUpdateRemoveModels, setUpstreamUpdateRemoveModels] = useState(
    [],
  );
  const [upstreamUpdatePreferredTab, setUpstreamUpdatePreferredTab] =
    useState('add');
  const [upstreamApplyLoading, setUpstreamApplyLoading] = useState(false);
  const [detectAllUpstreamUpdatesLoading, setDetectAllUpstreamUpdatesLoading] =
    useState(false);
  const [applyAllUpstreamUpdatesLoading, setApplyAllUpstreamUpdatesLoading] =
    useState(false);

  const applyUpstreamUpdatesInFlightRef = useRef(false);
  const detectChannelUpstreamUpdatesInFlightRef = useRef(false);
  const detectAllUpstreamUpdatesInFlightRef = useRef(false);
  const applyAllUpstreamUpdatesInFlightRef = useRef(false);

  const openUpstreamUpdateModal = (
    record,
    pendingAddModels = [],
    pendingRemoveModels = [],
    preferredTab = 'add',
  ) => {
    const normalizedAddModels = normalizeModelList(pendingAddModels);
    const normalizedRemoveModels = normalizeModelList(pendingRemoveModels);
    if (
      !record?.id ||
      (normalizedAddModels.length === 0 && normalizedRemoveModels.length === 0)
    ) {
      showInfo(t('该渠道暂无可处理的上游模型更新'));
      return;
    }
    setUpstreamUpdateChannel(record);
    setUpstreamUpdateAddModels(normalizedAddModels);
    setUpstreamUpdateRemoveModels(normalizedRemoveModels);
    const normalizedPreferredTab = preferredTab === 'remove' ? 'remove' : 'add';
    setUpstreamUpdatePreferredTab(normalizedPreferredTab);
    setShowUpstreamUpdateModal(true);
  };

  const closeUpstreamUpdateModal = () => {
    setShowUpstreamUpdateModal(false);
    setUpstreamUpdateChannel(null);
    setUpstreamUpdateAddModels([]);
    setUpstreamUpdateRemoveModels([]);
    setUpstreamUpdatePreferredTab('add');
  };

  const applyUpstreamUpdates = async ({
    addModels: selectedAddModels = [],
    removeModels: selectedRemoveModels = [],
  } = {}) => {
    if (applyUpstreamUpdatesInFlightRef.current) {
      showInfo(t('正在处理,请稍候'));
      return;
    }
    if (!upstreamUpdateChannel?.id) {
      closeUpstreamUpdateModal();
      return;
    }
    applyUpstreamUpdatesInFlightRef.current = true;
    setUpstreamApplyLoading(true);

    try {
      const normalizedSelectedAddModels = normalizeModelList(selectedAddModels);
      const normalizedSelectedRemoveModels =
        normalizeModelList(selectedRemoveModels);
      const selectedAddSet = new Set(normalizedSelectedAddModels);
      const ignoreModels = upstreamUpdateAddModels.filter(
        (model) => !selectedAddSet.has(model),
      );

      const res = await API.post(
        '/api/channel/upstream_updates/apply',
        {
          id: upstreamUpdateChannel.id,
          add_models: normalizedSelectedAddModels,
          ignore_models: ignoreModels,
          remove_models: normalizedSelectedRemoveModels,
        },
        { skipErrorHandler: true },
      );
      const { success, message, data } = res.data || {};
      if (!success) {
        showError(message || t('操作失败'));
        return;
      }

      const addedCount = data?.added_models?.length || 0;
      const removedCount = data?.removed_models?.length || 0;
      const totalIgnoredCount = getManualIgnoredModelCountFromSettings(
        data?.settings,
      );
      const ignoredCount = normalizeModelList(ignoreModels).length;
      showSuccess(
        t(
          '已处理上游模型更新:加入 {{added}} 个,删除 {{removed}} 个,本次忽略 {{ignored}} 个,当前已忽略模型 {{totalIgnored}} 个',
          {
            added: addedCount,
            removed: removedCount,
            ignored: ignoredCount,
            totalIgnored: totalIgnoredCount,
          },
        ),
      );
      closeUpstreamUpdateModal();
      await refresh();
    } catch (error) {
      showError(
        error?.response?.data?.message || error?.message || t('操作失败'),
      );
    } finally {
      applyUpstreamUpdatesInFlightRef.current = false;
      setUpstreamApplyLoading(false);
    }
  };

  const applyAllUpstreamUpdates = async () => {
    if (applyAllUpstreamUpdatesInFlightRef.current) {
      showInfo(t('正在批量处理,请稍候'));
      return;
    }
    applyAllUpstreamUpdatesInFlightRef.current = true;
    setApplyAllUpstreamUpdatesLoading(true);
    try {
      const res = await API.post(
        '/api/channel/upstream_updates/apply_all',
        {},
        { skipErrorHandler: true },
      );
      const { success, message, data } = res.data || {};
      if (!success) {
        showError(message || t('批量处理失败'));
        return;
      }

      const channelCount = data?.processed_channels || 0;
      const addedCount = data?.added_models || 0;
      const removedCount = data?.removed_models || 0;
      const failedCount = (data?.failed_channel_ids || []).length;
      showSuccess(
        t(
          '已批量处理上游模型更新:渠道 {{channels}} 个,加入 {{added}} 个,删除 {{removed}} 个,失败 {{fails}} 个',
          {
            channels: channelCount,
            added: addedCount,
            removed: removedCount,
            fails: failedCount,
          },
        ),
      );
      await refresh();
    } catch (error) {
      showError(
        error?.response?.data?.message || error?.message || t('批量处理失败'),
      );
    } finally {
      applyAllUpstreamUpdatesInFlightRef.current = false;
      setApplyAllUpstreamUpdatesLoading(false);
    }
  };

  const detectChannelUpstreamUpdates = async (channel) => {
    if (detectChannelUpstreamUpdatesInFlightRef.current) {
      showInfo(t('正在检测,请稍候'));
      return;
    }
    if (!channel?.id) {
      return;
    }
    detectChannelUpstreamUpdatesInFlightRef.current = true;
    try {
      const res = await API.post(
        '/api/channel/upstream_updates/detect',
        {
          id: channel.id,
        },
        { skipErrorHandler: true },
      );
      const { success, message, data } = res.data || {};
      if (!success) {
        showError(message || t('检测失败'));
        return;
      }

      const addCount = data?.add_models?.length || 0;
      const removeCount = data?.remove_models?.length || 0;
      showSuccess(
        t('检测完成:新增 {{add}} 个,删除 {{remove}} 个', {
          add: addCount,
          remove: removeCount,
        }),
      );
      await refresh();
    } catch (error) {
      showError(
        error?.response?.data?.message || error?.message || t('检测失败'),
      );
    } finally {
      detectChannelUpstreamUpdatesInFlightRef.current = false;
    }
  };

  const detectAllUpstreamUpdates = async () => {
    if (detectAllUpstreamUpdatesInFlightRef.current) {
      showInfo(t('正在批量检测,请稍候'));
      return;
    }
    detectAllUpstreamUpdatesInFlightRef.current = true;
    setDetectAllUpstreamUpdatesLoading(true);
    try {
      const res = await API.post(
        '/api/channel/upstream_updates/detect_all',
        {},
        { skipErrorHandler: true },
      );
      const { success, message, data } = res.data || {};
      if (!success) {
        showError(message || t('批量检测失败'));
        return;
      }

      const channelCount = data?.processed_channels || 0;
      const addCount = data?.detected_add_models || 0;
      const removeCount = data?.detected_remove_models || 0;
      const failedCount = (data?.failed_channel_ids || []).length;
      showSuccess(
        t(
          '批量检测完成:渠道 {{channels}} 个,新增 {{add}} 个,删除 {{remove}} 个,失败 {{fails}} 个',
          {
            channels: channelCount,
            add: addCount,
            remove: removeCount,
            fails: failedCount,
          },
        ),
      );
      await refresh();
    } catch (error) {
      showError(
        error?.response?.data?.message || error?.message || t('批量检测失败'),
      );
    } finally {
      detectAllUpstreamUpdatesInFlightRef.current = false;
      setDetectAllUpstreamUpdatesLoading(false);
    }
  };

  return {
    showUpstreamUpdateModal,
    setShowUpstreamUpdateModal,
    upstreamUpdateChannel,
    upstreamUpdateAddModels,
    upstreamUpdateRemoveModels,
    upstreamUpdatePreferredTab,
    upstreamApplyLoading,
    detectAllUpstreamUpdatesLoading,
    applyAllUpstreamUpdatesLoading,
    openUpstreamUpdateModal,
    closeUpstreamUpdateModal,
    applyUpstreamUpdates,
    applyAllUpstreamUpdates,
    detectChannelUpstreamUpdates,
    detectAllUpstreamUpdates,
  };
};