feat: refactor Todoist integration to single app with OAuth
Some checks failed
Build and Push Docker Image / build-and-push (push) Failing after 32s

- Single webhook URL for all users

- OAuth authorization flow

- Removed individual webhook tokens

- User identification by todoist_user_id

- Added OAuth endpoints: connect, callback, status, disconnect

- Updated frontend with OAuth flow

- DB migration 013: removed webhook_token, added todoist_user_id, todoist_email, access_token

Version: 2.2.0
This commit is contained in:
Play Life Bot
2026-01-02 15:34:01 +03:00
parent 8ba7e8fd45
commit a7128703fe
6 changed files with 1354 additions and 133 deletions

View File

@@ -4,45 +4,80 @@ import './Integrations.css'
function TodoistIntegration({ onBack }) {
const { authFetch } = useAuth()
const [webhookURL, setWebhookURL] = useState('')
const [connected, setConnected] = useState(false)
const [todoistEmail, setTodoistEmail] = useState('')
const [loading, setLoading] = useState(true)
const [copied, setCopied] = useState(false)
const [error, setError] = useState('')
const [message, setMessage] = useState('')
useEffect(() => {
fetchWebhookURL()
checkStatus()
// Проверяем URL параметры для сообщений
const params = new URLSearchParams(window.location.search)
const integration = params.get('integration')
const status = params.get('status')
if (integration === 'todoist') {
if (status === 'connected') {
setMessage('✅ Todoist успешно подключен!')
// Очищаем URL параметры
window.history.replaceState({}, '', window.location.pathname)
} else if (status === 'error') {
const errorMsg = params.get('message') || 'Произошла ошибка'
setError(errorMsg)
window.history.replaceState({}, '', window.location.pathname)
}
}
}, [])
const fetchWebhookURL = async () => {
const checkStatus = async () => {
try {
setLoading(true)
setError('')
const response = await authFetch('/api/integrations/todoist/webhook-url')
const response = await authFetch('/api/integrations/todoist/status')
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(errorData.error || 'Ошибка при загрузке URL webhook')
throw new Error('Ошибка при проверке статуса')
}
const data = await response.json()
if (data.webhook_url) {
setWebhookURL(data.webhook_url)
} else {
throw new Error('Webhook URL не найден в ответе')
setConnected(data.connected || false)
if (data.connected && data.todoist_email) {
setTodoistEmail(data.todoist_email)
}
} catch (error) {
console.error('Error fetching webhook URL:', error)
setError(error.message || 'Не удалось загрузить webhook URL')
console.error('Error checking status:', error)
setError(error.message || 'Не удалось проверить статус')
} finally {
setLoading(false)
}
}
const copyToClipboard = async () => {
const handleConnect = () => {
// Перенаправляем на OAuth endpoint
window.location.href = '/api/integrations/todoist/oauth/connect'
}
const handleDisconnect = async () => {
if (!window.confirm('Вы уверены, что хотите отключить Todoist?')) {
return
}
try {
await navigator.clipboard.writeText(webhookURL)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
setLoading(true)
setError('')
const response = await authFetch('/api/integrations/todoist/disconnect', {
method: 'DELETE',
})
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
throw new Error(errorData.error || 'Ошибка при отключении')
}
setConnected(false)
setTodoistEmail('')
setMessage('Todoist отключен')
} catch (error) {
console.error('Error copying to clipboard:', error)
console.error('Error disconnecting:', error)
setError(error.message || 'Не удалось отключить Todoist')
} finally {
setLoading(false)
}
}
@@ -52,59 +87,89 @@ function TodoistIntegration({ onBack }) {
</button>
<h1 className="text-2xl font-bold mb-6">TODOist интеграция</h1>
<h1 className="text-2xl font-bold mb-6">Todoist интеграция</h1>
<div className="bg-white rounded-lg shadow-md p-6 mb-6">
<h2 className="text-lg font-semibold mb-4">Webhook URL</h2>
{loading ? (
<div className="text-gray-500">Загрузка...</div>
) : error ? (
<div className="text-red-600 mb-4">
<p className="mb-2">{error}</p>
{message && (
<div className="bg-green-50 border border-green-200 rounded-lg p-4 mb-6 text-green-800">
{message}
</div>
)}
{error && (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6 text-red-800">
{error}
</div>
)}
{loading ? (
<div className="text-gray-500">Загрузка...</div>
) : connected ? (
<div>
<div className="bg-white rounded-lg shadow-md p-6 mb-6">
<h2 className="text-lg font-semibold mb-4">Статус подключения</h2>
<div className="space-y-3">
<div className="flex items-center gap-2">
<span className="text-green-600 font-semibold"> Todoist подключен</span>
</div>
{todoistEmail && (
<div>
<span className="text-gray-600">Email: </span>
<span className="font-medium">{todoistEmail}</span>
</div>
)}
</div>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-6 mb-6">
<h3 className="text-lg font-semibold mb-3 text-blue-900">
Как это работает
</h3>
<p className="text-gray-700 mb-2">
Todoist подключен! Закрывайте задачи в Todoist они автоматически
появятся в Play Life.
</p>
<p className="text-gray-600 text-sm">
Никаких дополнительных настроек не требуется. Просто закрывайте задачи
в Todoist, и они будут обработаны автоматически.
</p>
</div>
<button
onClick={handleDisconnect}
className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
>
Отключить Todoist
</button>
</div>
) : (
<div>
<div className="bg-white rounded-lg shadow-md p-6 mb-6">
<h2 className="text-lg font-semibold mb-4">Подключение Todoist</h2>
<p className="text-gray-700 mb-4">
Подключите свой Todoist аккаунт для автоматической обработки закрытых задач.
</p>
<button
onClick={fetchWebhookURL}
className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
onClick={handleConnect}
className="px-6 py-3 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors font-semibold"
>
Попробовать снова
Подключить Todoist
</button>
</div>
) : (
<div className="flex items-center gap-2">
<input
type="text"
value={webhookURL}
readOnly
className="flex-1 px-4 py-2 border border-gray-300 rounded-lg bg-gray-50 text-sm"
/>
<button
onClick={copyToClipboard}
className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors whitespace-nowrap"
>
{copied ? 'Скопировано!' : 'Копировать'}
</button>
</div>
)}
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
<h3 className="text-lg font-semibold mb-3 text-blue-900">
Как использовать в приложении TODOist
</h3>
<ol className="list-decimal list-inside space-y-2 text-gray-700">
<li>Откройте приложение TODOist на вашем устройстве</li>
<li>Перейдите в настройки проекта или задачи</li>
<li>Найдите раздел "Интеграции" или "Webhooks"</li>
<li>Вставьте скопированный URL webhook в соответствующее поле</li>
<li>Сохраните настройки</li>
<li>
Теперь при закрытии задач в TODOist они будут автоматически
обрабатываться системой
</li>
</ol>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
<h3 className="text-lg font-semibold mb-3 text-blue-900">
Что нужно сделать
</h3>
<ol className="list-decimal list-inside space-y-2 text-gray-700">
<li>Нажмите кнопку "Подключить Todoist"</li>
<li>Авторизуйтесь в Todoist</li>
<li>Готово! Закрытые задачи будут автоматически обрабатываться</li>
</ol>
</div>
</div>
)}
</div>
)
}
export default TodoistIntegration