File size: 12,979 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 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | /*
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 React, { useState, useEffect, useMemo } from 'react';
import {
Card,
Calendar,
Button,
Typography,
Avatar,
Spin,
Tooltip,
Collapsible,
Modal,
} from '@douyinfe/semi-ui';
import {
CalendarCheck,
Gift,
Check,
ChevronDown,
ChevronUp,
} from 'lucide-react';
import Turnstile from 'react-turnstile';
import { API, showError, showSuccess, renderQuota } from '../../../../helpers';
const CheckinCalendar = ({ t, status, turnstileEnabled, turnstileSiteKey }) => {
const [loading, setLoading] = useState(false);
const [checkinLoading, setCheckinLoading] = useState(false);
const [turnstileModalVisible, setTurnstileModalVisible] = useState(false);
const [turnstileWidgetKey, setTurnstileWidgetKey] = useState(0);
const [checkinData, setCheckinData] = useState({
enabled: false,
stats: {
checked_in_today: false,
total_checkins: 0,
total_quota: 0,
checkin_count: 0,
records: [],
},
});
const [currentMonth, setCurrentMonth] = useState(
new Date().toISOString().slice(0, 7),
);
// 初始加载状态,用于避免折叠状态闪烁
const [initialLoaded, setInitialLoaded] = useState(false);
// 折叠状态:null 表示未确定(等待首次加载)
const [isCollapsed, setIsCollapsed] = useState(null);
// 创建日期到额度的映射,方便快速查找
const checkinRecordsMap = useMemo(() => {
const map = {};
const records = checkinData.stats?.records || [];
records.forEach((record) => {
map[record.checkin_date] = record.quota_awarded;
});
return map;
}, [checkinData.stats?.records]);
// 计算本月获得的额度
const monthlyQuota = useMemo(() => {
const records = checkinData.stats?.records || [];
return records.reduce(
(sum, record) => sum + (record.quota_awarded || 0),
0,
);
}, [checkinData.stats?.records]);
// 获取签到状态
const fetchCheckinStatus = async (month) => {
const isFirstLoad = !initialLoaded;
setLoading(true);
try {
const res = await API.get(`/api/user/checkin?month=${month}`);
const { success, data, message } = res.data;
if (success) {
setCheckinData(data);
// 首次加载时,根据签到状态设置折叠状态
if (isFirstLoad) {
setIsCollapsed(data.stats?.checked_in_today ?? false);
setInitialLoaded(true);
}
} else {
showError(message || t('获取签到状态失败'));
if (isFirstLoad) {
setIsCollapsed(false);
setInitialLoaded(true);
}
}
} catch (error) {
showError(t('获取签到状态失败'));
if (isFirstLoad) {
setIsCollapsed(false);
setInitialLoaded(true);
}
} finally {
setLoading(false);
}
};
const postCheckin = async (token) => {
const url = token
? `/api/user/checkin?turnstile=${encodeURIComponent(token)}`
: '/api/user/checkin';
return API.post(url);
};
const shouldTriggerTurnstile = (message) => {
if (!turnstileEnabled) return false;
if (typeof message !== 'string') return true;
return message.includes('Turnstile');
};
const doCheckin = async (token) => {
setCheckinLoading(true);
try {
const res = await postCheckin(token);
const { success, data, message } = res.data;
if (success) {
showSuccess(
t('签到成功!获得') + ' ' + renderQuota(data.quota_awarded),
);
// 刷新签到状态
fetchCheckinStatus(currentMonth);
setTurnstileModalVisible(false);
} else {
if (!token && shouldTriggerTurnstile(message)) {
if (!turnstileSiteKey) {
showError('Turnstile is enabled but site key is empty.');
return;
}
setTurnstileModalVisible(true);
return;
}
if (token && shouldTriggerTurnstile(message)) {
setTurnstileWidgetKey((v) => v + 1);
}
showError(message || t('签到失败'));
}
} catch (error) {
showError(t('签到失败'));
} finally {
setCheckinLoading(false);
}
};
useEffect(() => {
if (status?.checkin_enabled) {
fetchCheckinStatus(currentMonth);
}
}, [status?.checkin_enabled, currentMonth]);
// 如果签到功能未启用,不显示组件
if (!status?.checkin_enabled) {
return null;
}
// 日期渲染函数 - 显示签到状态和获得的额度
const dateRender = (dateString) => {
// Semi Calendar 传入的 dateString 是 Date.toString() 格式
// 需要转换为 YYYY-MM-DD 格式来匹配后端数据
const date = new Date(dateString);
if (isNaN(date.getTime())) {
return null;
}
// 使用本地时间格式化,避免时区问题
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`; // YYYY-MM-DD
const quotaAwarded = checkinRecordsMap[formattedDate];
const isCheckedIn = quotaAwarded !== undefined;
if (isCheckedIn) {
return (
<Tooltip
content={`${t('获得')} ${renderQuota(quotaAwarded)}`}
position='top'
>
<div className='absolute inset-0 flex flex-col items-center justify-center cursor-pointer'>
<div className='w-6 h-6 rounded-full bg-green-500 flex items-center justify-center mb-0.5 shadow-sm'>
<Check size={14} className='text-white' strokeWidth={3} />
</div>
<div className='text-[10px] font-medium text-green-600 dark:text-green-400 leading-none'>
{renderQuota(quotaAwarded)}
</div>
</div>
</Tooltip>
);
}
return null;
};
// 处理月份变化
const handleMonthChange = (date) => {
const month = date.toISOString().slice(0, 7);
setCurrentMonth(month);
};
return (
<Card className='!rounded-2xl'>
<Modal
title='Security Check'
visible={turnstileModalVisible}
footer={null}
centered
onCancel={() => {
setTurnstileModalVisible(false);
setTurnstileWidgetKey((v) => v + 1);
}}
>
<div className='flex justify-center py-2'>
<Turnstile
key={turnstileWidgetKey}
sitekey={turnstileSiteKey}
onVerify={(token) => {
doCheckin(token);
}}
onExpire={() => {
setTurnstileWidgetKey((v) => v + 1);
}}
/>
</div>
</Modal>
{/* 卡片头部 */}
<div className='flex items-center justify-between'>
<div
className='flex items-center flex-1 cursor-pointer'
onClick={() => setIsCollapsed(!isCollapsed)}
>
<Avatar size='small' color='green' className='mr-3 shadow-md'>
<CalendarCheck size={16} />
</Avatar>
<div className='flex-1'>
<div className='flex items-center gap-2'>
<Typography.Text className='text-lg font-medium'>
{t('每日签到')}
</Typography.Text>
{isCollapsed ? (
<ChevronDown size={16} className='text-gray-400' />
) : (
<ChevronUp size={16} className='text-gray-400' />
)}
</div>
<div className='text-xs text-gray-500 dark:text-gray-400'>
{!initialLoaded
? t('正在加载签到状态...')
: checkinData.stats?.checked_in_today
? t('今日已签到,累计签到') +
` ${checkinData.stats?.total_checkins || 0} ` +
t('天')
: t('每日签到可获得随机额度奖励')}
</div>
</div>
</div>
<Button
type='primary'
theme='solid'
icon={<Gift size={16} />}
onClick={() => doCheckin()}
loading={checkinLoading || !initialLoaded}
disabled={!initialLoaded || checkinData.stats?.checked_in_today}
className='!bg-green-600 hover:!bg-green-700'
>
{!initialLoaded
? t('加载中...')
: checkinData.stats?.checked_in_today
? t('今日已签到')
: t('立即签到')}
</Button>
</div>
{/* 可折叠内容 */}
<Collapsible isOpen={isCollapsed === false} keepDOM>
{/* 签到统计 */}
<div className='grid grid-cols-3 gap-3 mb-4 mt-4'>
<div className='text-center p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg'>
<div className='text-xl font-bold text-green-600'>
{checkinData.stats?.total_checkins || 0}
</div>
<div className='text-xs text-gray-500'>{t('累计签到')}</div>
</div>
<div className='text-center p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg'>
<div className='text-xl font-bold text-orange-600'>
{renderQuota(monthlyQuota, 6)}
</div>
<div className='text-xs text-gray-500'>{t('本月获得')}</div>
</div>
<div className='text-center p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg'>
<div className='text-xl font-bold text-blue-600'>
{renderQuota(checkinData.stats?.total_quota || 0, 6)}
</div>
<div className='text-xs text-gray-500'>{t('累计获得')}</div>
</div>
</div>
{/* 签到日历 - 使用更紧凑的样式 */}
<Spin spinning={loading}>
<div className='border rounded-lg overflow-hidden checkin-calendar'>
<style>{`
.checkin-calendar .semi-calendar {
font-size: 13px;
}
.checkin-calendar .semi-calendar-month-header {
padding: 8px 12px;
}
.checkin-calendar .semi-calendar-month-week-row {
height: 28px;
}
.checkin-calendar .semi-calendar-month-week-row th {
font-size: 12px;
padding: 4px 0;
}
.checkin-calendar .semi-calendar-month-grid-row {
height: auto;
}
.checkin-calendar .semi-calendar-month-grid-row td {
height: 56px;
padding: 2px;
}
.checkin-calendar .semi-calendar-month-grid-row-cell {
position: relative;
height: 100%;
}
.checkin-calendar .semi-calendar-month-grid-row-cell-day {
position: absolute;
top: 4px;
left: 50%;
transform: translateX(-50%);
font-size: 12px;
z-index: 1;
}
.checkin-calendar .semi-calendar-month-same {
background: transparent;
}
.checkin-calendar .semi-calendar-month-today .semi-calendar-month-grid-row-cell-day {
background: var(--semi-color-primary);
color: white;border-radius: 50%;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;}
`}</style>
<Calendar
mode='month'
onChange={handleMonthChange}
dateGridRender={(dateString, date) => dateRender(dateString)}
/>
</div>
</Spin>
{/* 签到说明 */}
<div className='mt-3 p-2.5 bg-slate-50 dark:bg-slate-800 rounded-lg'>
<Typography.Text type='tertiary' className='text-xs'>
<ul className='list-disc list-inside space-y-0.5'>
<li>{t('每日签到可获得随机额度奖励')}</li>
<li>{t('签到奖励将直接添加到您的账户余额')}</li>
<li>{t('每日仅可签到一次,请勿重复签到')}</li>
</ul>
</Typography.Text>
</div>
</Collapsible>
</Card>
);
};
export default CheckinCalendar;
|