Add repetition_date support for tasks (v3.3.0)
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 42s
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 42s
- Add repetition_date field to tasks table (migration 018) - Support pattern-based repetition: day of week, day of month, specific date - Add 'Через'/'Каждое' mode selector in task form - Auto-calculate next_show_at from repetition_date on create/complete - Show calculated next date in postpone dialog for repetition_date tasks - Update version to 3.3.0
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "play-life-web",
|
||||
"version": "3.2.0",
|
||||
"version": "3.3.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -12,6 +12,7 @@ function TaskForm({ onNavigate, taskId }) {
|
||||
const [rewardMessage, setRewardMessage] = useState('')
|
||||
const [repetitionPeriodValue, setRepetitionPeriodValue] = useState('')
|
||||
const [repetitionPeriodType, setRepetitionPeriodType] = useState('day')
|
||||
const [repetitionMode, setRepetitionMode] = useState('after') // 'after' = Через, 'each' = Каждое
|
||||
const [rewards, setRewards] = useState([])
|
||||
const [subtasks, setSubtasks] = useState([])
|
||||
const [projects, setProjects] = useState([])
|
||||
@@ -44,6 +45,7 @@ function TaskForm({ onNavigate, taskId }) {
|
||||
setProgressionBase('')
|
||||
setRepetitionPeriodValue('')
|
||||
setRepetitionPeriodType('day')
|
||||
setRepetitionMode('after')
|
||||
setRewards([])
|
||||
setSubtasks([])
|
||||
setError('')
|
||||
@@ -76,8 +78,30 @@ function TaskForm({ onNavigate, taskId }) {
|
||||
setRewardMessage(data.task.reward_message || '')
|
||||
setProgressionBase(data.task.progression_base ? String(data.task.progression_base) : '')
|
||||
|
||||
// Парсим repetition_period если он есть
|
||||
if (data.task.repetition_period) {
|
||||
// Парсим repetition_date если он есть (приоритет над repetition_period)
|
||||
if (data.task.repetition_date) {
|
||||
const dateStr = data.task.repetition_date.trim()
|
||||
console.log('Parsing repetition_date:', dateStr) // Отладка
|
||||
|
||||
// Формат: "N unit" где unit = week, month, year
|
||||
// или "MM-DD year" для конкретной даты в году
|
||||
const match = dateStr.match(/^(\d+(?:-\d+)?)\s+(week|month|year)/i)
|
||||
if (match) {
|
||||
const value = match[1]
|
||||
const unit = match[2].toLowerCase()
|
||||
|
||||
setRepetitionPeriodValue(value)
|
||||
setRepetitionPeriodType(unit)
|
||||
setRepetitionMode('each')
|
||||
} else {
|
||||
console.log('Failed to parse repetition_date:', dateStr)
|
||||
setRepetitionPeriodValue('')
|
||||
setRepetitionPeriodType('week')
|
||||
setRepetitionMode('each')
|
||||
}
|
||||
} else if (data.task.repetition_period) {
|
||||
// Парсим repetition_period если он есть
|
||||
setRepetitionMode('after')
|
||||
const periodStr = data.task.repetition_period.trim()
|
||||
console.log('Parsing repetition_period:', periodStr, 'Full task data:', data.task) // Отладка
|
||||
|
||||
@@ -199,9 +223,10 @@ function TaskForm({ onNavigate, taskId }) {
|
||||
console.log('Successfully parsed repetition_period - value will be set') // Отладка
|
||||
}
|
||||
} else {
|
||||
console.log('No repetition_period in task data') // Отладка
|
||||
console.log('No repetition_period or repetition_date in task data') // Отладка
|
||||
setRepetitionPeriodValue('')
|
||||
setRepetitionPeriodType('day')
|
||||
setRepetitionMode('after')
|
||||
}
|
||||
|
||||
// Загружаем rewards
|
||||
@@ -384,25 +409,37 @@ function TaskForm({ onNavigate, taskId }) {
|
||||
}
|
||||
|
||||
try {
|
||||
// Преобразуем период повторения в строку INTERVAL для PostgreSQL
|
||||
// Преобразуем период повторения в строку INTERVAL для PostgreSQL или repetition_date
|
||||
let repetitionPeriod = null
|
||||
let repetitionDate = null
|
||||
|
||||
if (repetitionPeriodValue && repetitionPeriodValue.trim() !== '') {
|
||||
const value = parseInt(repetitionPeriodValue.trim(), 10)
|
||||
if (!isNaN(value) && value >= 0) {
|
||||
const typeMap = {
|
||||
'minute': 'minute',
|
||||
'hour': 'hour',
|
||||
'day': 'day',
|
||||
'week': 'week',
|
||||
'month': 'month',
|
||||
'year': 'year'
|
||||
const valueStr = repetitionPeriodValue.trim()
|
||||
|
||||
if (repetitionMode === 'each') {
|
||||
// Режим "Каждое" - сохраняем как repetition_date
|
||||
// Формат: "N unit" где unit = week, month, year
|
||||
repetitionDate = `${valueStr} ${repetitionPeriodType}`
|
||||
console.log('Sending repetition_date:', repetitionDate)
|
||||
} else {
|
||||
// Режим "Через" - сохраняем как repetition_period (INTERVAL)
|
||||
const value = parseInt(valueStr, 10)
|
||||
if (!isNaN(value) && value >= 0) {
|
||||
const typeMap = {
|
||||
'minute': 'minute',
|
||||
'hour': 'hour',
|
||||
'day': 'day',
|
||||
'week': 'week',
|
||||
'month': 'month',
|
||||
'year': 'year'
|
||||
}
|
||||
const unit = typeMap[repetitionPeriodType] || 'day'
|
||||
repetitionPeriod = `${value} ${unit}`
|
||||
console.log('Sending repetition_period:', repetitionPeriod, 'from value:', repetitionPeriodValue, 'type:', repetitionPeriodType)
|
||||
}
|
||||
const unit = typeMap[repetitionPeriodType] || 'day'
|
||||
repetitionPeriod = `${value} ${unit}`
|
||||
console.log('Sending repetition_period:', repetitionPeriod, 'from value:', repetitionPeriodValue, 'type:', repetitionPeriodType)
|
||||
}
|
||||
} else {
|
||||
console.log('No repetition_period to send (value:', repetitionPeriodValue, 'type:', repetitionPeriodType, ')')
|
||||
console.log('No repetition to send (value:', repetitionPeriodValue, 'type:', repetitionPeriodType, 'mode:', repetitionMode, ')')
|
||||
}
|
||||
|
||||
const payload = {
|
||||
@@ -410,6 +447,7 @@ function TaskForm({ onNavigate, taskId }) {
|
||||
reward_message: rewardMessage.trim() || null,
|
||||
progression_base: progressionBase ? parseFloat(progressionBase) : null,
|
||||
repetition_period: repetitionPeriod,
|
||||
repetition_date: repetitionDate,
|
||||
rewards: rewards.map(r => ({
|
||||
position: r.position,
|
||||
project_name: r.project_name.trim(),
|
||||
@@ -545,37 +583,83 @@ function TaskForm({ onNavigate, taskId }) {
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label htmlFor="repetition_period">Период повторения</label>
|
||||
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
|
||||
<input
|
||||
id="repetition_period"
|
||||
type="number"
|
||||
min="0"
|
||||
value={repetitionPeriodValue}
|
||||
onChange={(e) => setRepetitionPeriodValue(e.target.value)}
|
||||
placeholder="Число"
|
||||
className="form-input"
|
||||
style={{ flex: '1' }}
|
||||
/>
|
||||
{repetitionPeriodValue && repetitionPeriodValue.trim() !== '' && parseInt(repetitionPeriodValue.trim(), 10) !== 0 && (
|
||||
<select
|
||||
value={repetitionPeriodType}
|
||||
onChange={(e) => setRepetitionPeriodType(e.target.value)}
|
||||
className="form-input"
|
||||
style={{ width: '120px' }}
|
||||
>
|
||||
<option value="minute">Минута</option>
|
||||
<option value="hour">Час</option>
|
||||
<option value="day">День</option>
|
||||
<option value="week">Неделя</option>
|
||||
<option value="month">Месяц</option>
|
||||
<option value="year">Год</option>
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<small style={{ color: '#666', fontSize: '0.9em' }}>
|
||||
Оставьте пустым, если задача не повторяется. Введите 0, если задача никогда не переносится в выполненные.
|
||||
</small>
|
||||
<label htmlFor="repetition_period">Повторения</label>
|
||||
{(() => {
|
||||
const hasValidValue = repetitionPeriodValue && repetitionPeriodValue.trim() !== '' && parseInt(repetitionPeriodValue.trim(), 10) !== 0
|
||||
const isEachMode = hasValidValue && repetitionMode === 'each'
|
||||
const isYearType = isEachMode && repetitionPeriodType === 'year'
|
||||
|
||||
return (
|
||||
<>
|
||||
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
|
||||
{hasValidValue && (
|
||||
<select
|
||||
value={repetitionMode}
|
||||
onChange={(e) => {
|
||||
setRepetitionMode(e.target.value)
|
||||
// При переключении режима устанавливаем подходящий тип
|
||||
if (e.target.value === 'each') {
|
||||
// Для режима "Каждое" только week, month, year
|
||||
if (!['week', 'month', 'year'].includes(repetitionPeriodType)) {
|
||||
setRepetitionPeriodType('week')
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="form-input"
|
||||
style={{ width: '100px' }}
|
||||
>
|
||||
<option value="after">Через</option>
|
||||
<option value="each">Каждое</option>
|
||||
</select>
|
||||
)}
|
||||
<input
|
||||
id="repetition_period"
|
||||
type={isYearType ? 'text' : 'number'}
|
||||
min="0"
|
||||
value={repetitionPeriodValue}
|
||||
onChange={(e) => setRepetitionPeriodValue(e.target.value)}
|
||||
placeholder={isYearType ? 'ММ-ДД' : 'Число'}
|
||||
className="form-input"
|
||||
style={{ flex: '1' }}
|
||||
/>
|
||||
{hasValidValue && (
|
||||
<select
|
||||
value={repetitionPeriodType}
|
||||
onChange={(e) => setRepetitionPeriodType(e.target.value)}
|
||||
className="form-input"
|
||||
style={{ width: '120px' }}
|
||||
>
|
||||
{repetitionMode === 'after' ? (
|
||||
<>
|
||||
<option value="minute">Минута</option>
|
||||
<option value="hour">Час</option>
|
||||
<option value="day">День</option>
|
||||
<option value="week">Неделя</option>
|
||||
<option value="month">Месяц</option>
|
||||
<option value="year">Год</option>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<option value="week">Неделя</option>
|
||||
<option value="month">Месяц</option>
|
||||
<option value="year">Год</option>
|
||||
</>
|
||||
)}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
<small style={{ color: '#666', fontSize: '0.9em' }}>
|
||||
{isEachMode ? (
|
||||
repetitionPeriodType === 'week' ? 'Номер дня недели (1-7, где 1 = понедельник)' :
|
||||
repetitionPeriodType === 'month' ? 'Номер дня месяца (1-31)' :
|
||||
'Дата в формате ММ-ДД (например, 02-01 для 1 февраля)'
|
||||
) : (
|
||||
'Оставьте пустым, если задача не повторяется. Введите 0, если задача никогда не переносится в выполненные.'
|
||||
)}
|
||||
</small>
|
||||
</>
|
||||
)
|
||||
})()}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
|
||||
@@ -90,14 +90,109 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, onRefresh }) {
|
||||
onNavigate?.('task-form', { taskId: undefined })
|
||||
}
|
||||
|
||||
// Функция для вычисления следующей даты по repetition_date
|
||||
const calculateNextDateFromRepetitionDate = (repetitionDateStr) => {
|
||||
if (!repetitionDateStr) return null
|
||||
|
||||
const parts = repetitionDateStr.trim().split(/\s+/)
|
||||
if (parts.length < 2) return null
|
||||
|
||||
const value = parts[0]
|
||||
const unit = parts[1].toLowerCase()
|
||||
const now = new Date()
|
||||
now.setHours(0, 0, 0, 0)
|
||||
|
||||
switch (unit) {
|
||||
case 'week': {
|
||||
// N-й день недели (1=понедельник, 7=воскресенье)
|
||||
const dayOfWeek = parseInt(value, 10)
|
||||
if (isNaN(dayOfWeek) || dayOfWeek < 1 || dayOfWeek > 7) return null
|
||||
// JavaScript: 0=воскресенье, 1=понедельник... 6=суббота
|
||||
// Наш формат: 1=понедельник... 7=воскресенье
|
||||
// Конвертируем: наш 1 (Пн) -> JS 1, наш 7 (Вс) -> JS 0
|
||||
const targetJsDay = dayOfWeek === 7 ? 0 : dayOfWeek
|
||||
const currentJsDay = now.getDay()
|
||||
// Вычисляем дни до следующего вхождения (включая сегодня, если ещё не прошло)
|
||||
let daysUntil = (targetJsDay - currentJsDay + 7) % 7
|
||||
// Если сегодня тот же день, берём следующую неделю
|
||||
if (daysUntil === 0) daysUntil = 7
|
||||
const nextDate = new Date(now)
|
||||
nextDate.setDate(now.getDate() + daysUntil)
|
||||
return nextDate
|
||||
}
|
||||
case 'month': {
|
||||
// N-й день месяца
|
||||
const dayOfMonth = parseInt(value, 10)
|
||||
if (isNaN(dayOfMonth) || dayOfMonth < 1 || dayOfMonth > 31) return null
|
||||
|
||||
// Ищем ближайшую дату с этим днём
|
||||
let searchDate = new Date(now)
|
||||
for (let i = 0; i < 12; i++) {
|
||||
const year = searchDate.getFullYear()
|
||||
const month = searchDate.getMonth()
|
||||
const lastDayOfMonth = new Date(year, month + 1, 0).getDate()
|
||||
const actualDay = Math.min(dayOfMonth, lastDayOfMonth)
|
||||
const candidateDate = new Date(year, month, actualDay)
|
||||
|
||||
if (candidateDate > now) {
|
||||
return candidateDate
|
||||
}
|
||||
// Переходим к следующему месяцу
|
||||
searchDate = new Date(year, month + 1, 1)
|
||||
}
|
||||
return null
|
||||
}
|
||||
case 'year': {
|
||||
// MM-DD формат
|
||||
const dateParts = value.split('-')
|
||||
if (dateParts.length !== 2) return null
|
||||
const monthNum = parseInt(dateParts[0], 10)
|
||||
const day = parseInt(dateParts[1], 10)
|
||||
if (isNaN(monthNum) || isNaN(day) || monthNum < 1 || monthNum > 12 || day < 1 || day > 31) return null
|
||||
|
||||
let year = now.getFullYear()
|
||||
let candidateDate = new Date(year, monthNum - 1, day)
|
||||
|
||||
if (candidateDate <= now) {
|
||||
candidateDate = new Date(year + 1, monthNum - 1, day)
|
||||
}
|
||||
return candidateDate
|
||||
}
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Форматирование даты в YYYY-MM-DD (локальное время, без смещения в UTC)
|
||||
const formatDateToLocal = (date) => {
|
||||
const year = date.getFullYear()
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getDate()).padStart(2, '0')
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
const handlePostponeClick = (task, e) => {
|
||||
e.stopPropagation()
|
||||
setSelectedTaskForPostpone(task)
|
||||
// Устанавливаем дату по умолчанию - завтра
|
||||
const tomorrow = new Date()
|
||||
tomorrow.setDate(tomorrow.getDate() + 1)
|
||||
tomorrow.setHours(0, 0, 0, 0)
|
||||
setPostponeDate(tomorrow.toISOString().split('T')[0])
|
||||
|
||||
// Устанавливаем дату по умолчанию
|
||||
let defaultDate
|
||||
if (task.repetition_date) {
|
||||
// Для задач с repetition_date - вычисляем следующую подходящую дату
|
||||
const nextDate = calculateNextDateFromRepetitionDate(task.repetition_date)
|
||||
if (nextDate) {
|
||||
defaultDate = nextDate
|
||||
}
|
||||
}
|
||||
|
||||
if (!defaultDate) {
|
||||
// Без repetition_date или если не удалось вычислить - завтра
|
||||
defaultDate = new Date()
|
||||
defaultDate.setDate(defaultDate.getDate() + 1)
|
||||
}
|
||||
|
||||
defaultDate.setHours(0, 0, 0, 0)
|
||||
setPostponeDate(formatDateToLocal(defaultDate))
|
||||
}
|
||||
|
||||
const handlePostponeSubmit = async () => {
|
||||
@@ -267,6 +362,7 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, onRefresh }) {
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
// Группируем задачи по проектам
|
||||
const groupedTasks = useMemo(() => {
|
||||
const today = new Date()
|
||||
@@ -287,7 +383,7 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, onRefresh }) {
|
||||
let isInfinite = false
|
||||
|
||||
// Если next_show_at установлен, задача всегда в выполненных (если дата в будущем)
|
||||
// даже если она бесконечная
|
||||
// даже если она бесконечная (next_show_at приоритетнее всего)
|
||||
if (task.next_show_at) {
|
||||
const nextShowDate = new Date(task.next_show_at)
|
||||
nextShowDate.setHours(0, 0, 0, 0)
|
||||
@@ -324,7 +420,7 @@ function TaskList({ onNavigate, data, loading, backgroundLoading, onRefresh }) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Если repetition_period == null, используем старую логику
|
||||
// Если нет ни repetition_period, ни repetition_date, используем старую логику
|
||||
if (task.last_completed_at) {
|
||||
const completedDate = new Date(task.last_completed_at)
|
||||
completedDate.setHours(0, 0, 0, 0)
|
||||
|
||||
Reference in New Issue
Block a user