feat: Initialize core application structure with item tracking, price history, and notification channel management.

This commit is contained in:
Michael committed 2025-11-23 23:17:52 +01:00
1 parent 40225676fe
commit 9637d77cef
10 files changed
+484 -263

No files matched your search

@@ -0,0 +1,44 @@
"""add notification channels
Revision ID: add_notification_channels
Revises: merge_heads
Create Date: 2025-11-23
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'add_notification_channels'
down_revision = 'merge_heads'
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create notification_channels table
op.create_table('notification_channels',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('type', sa.String(), nullable=False),
sa.Column('configuration', sa.Text(), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_notification_channels_id'), 'notification_channels', ['id'], unique=False)
# Add notification_channel_id to items table
op.add_column('items', sa.Column('notification_channel_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'items', 'notification_channels', ['notification_channel_id'], ['id'])
def downgrade() -> None:
# Remove foreign key and column from items table
op.drop_constraint(None, 'items', type_='foreignkey')
op.drop_column('items', 'notification_channel_id')
# Drop notification_channels table
op.drop_index(op.f('ix_notification_channels_id'), table_name='notification_channels')
op.drop_table('notification_channels')
+2 -2
View File
@@ -13,7 +13,7 @@ from sqlalchemy import text
from app.database import SessionLocal, engine
from app.limiter import limiter
from app.routers import auth, items, jobs, openrouter, search, search_sites, settings
from app.routers import auth, items, jobs, notifications, openrouter, search, search_sites, settings
from app.services.scheduler_service import scheduled_refresh, scheduler
from app.services import auth_service, search_service
@@ -163,7 +163,7 @@ os.makedirs("screenshots", exist_ok=True)
app.mount("/screenshots", StaticFiles(directory="screenshots"), name="screenshots")
# Routers
for router in [items.router, settings.router, jobs.router, openrouter.router]:
for router in [notifications.router, items.router, settings.router, jobs.router, openrouter.router]:
app.include_router(router, prefix="/api")
# Search routers (already have /api prefix)
+16
View File
@@ -51,6 +51,9 @@ class Item(Base):
price_history = relationship("PriceHistory", back_populates="item", cascade="all, delete-orphan")
notification_channel_id: int | None = Column(Integer, ForeignKey("notification_channels.id"), nullable=True) # type: ignore
notification_channel = relationship("NotificationChannel", back_populates="items")
class PriceHistory(Base):
__tablename__ = "price_history"
@@ -96,3 +99,16 @@ class SearchSite(Base):
product_link_selector: str | None = Column(String, nullable=True) # type: ignore # Sélecteur CSS pour les liens produits
created_at: datetime = Column(DateTime, default=lambda: datetime.now(UTC)) # type: ignore
updated_at: datetime = Column(DateTime, default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC)) # type: ignore
class NotificationChannel(Base):
__tablename__ = "notification_channels"
id: int = Column(Integer, primary_key=True, index=True) # type: ignore
name: str = Column(String, nullable=False) # type: ignore
type: str = Column(String, nullable=False) # type: ignore # "email", "discord", "mattermost"
configuration: str = Column(Text, nullable=False) # type: ignore # JSON or encrypted string
is_active: bool = Column(Boolean, default=True) # type: ignore
created_at: datetime = Column(DateTime, default=lambda: datetime.now(UTC)) # type: ignore
items = relationship("Item", back_populates="notification_channel")
+55
View File
@@ -0,0 +1,55 @@
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
from sqlalchemy.orm import Session
from app import database, models, schemas
from app.services.notification_service import NotificationService
router = APIRouter(
prefix="/notifications",
tags=["notifications"],
)
@router.get("/channels", response_model=list[schemas.NotificationChannelResponse])
def get_channels(db: Session = Depends(database.get_db)):
return db.query(models.NotificationChannel).all()
@router.post("/channels", response_model=schemas.NotificationChannelResponse)
def create_channel(channel: schemas.NotificationChannelCreate, db: Session = Depends(database.get_db)):
db_channel = models.NotificationChannel(**channel.model_dump())
db.add(db_channel)
db.commit()
db.refresh(db_channel)
return db_channel
@router.put("/channels/{channel_id}", response_model=schemas.NotificationChannelResponse)
def update_channel(channel_id: int, channel_update: schemas.NotificationChannelUpdate, db: Session = Depends(database.get_db)):
db_channel = db.query(models.NotificationChannel).filter(models.NotificationChannel.id == channel_id).first()
if not db_channel:
raise HTTPException(status_code=404, detail="Channel not found")
for key, value in channel_update.model_dump(exclude_unset=True).items():
setattr(db_channel, key, value)
db.commit()
db.refresh(db_channel)
return db_channel
@router.delete("/channels/{channel_id}")
def delete_channel(channel_id: int, db: Session = Depends(database.get_db)):
db_channel = db.query(models.NotificationChannel).filter(models.NotificationChannel.id == channel_id).first()
if not db_channel:
raise HTTPException(status_code=404, detail="Channel not found")
db.delete(db_channel)
db.commit()
return {"ok": True}
@router.post("/channels/{channel_id}/test")
async def test_channel(channel_id: int, background_tasks: BackgroundTasks, db: Session = Depends(database.get_db)):
db_channel = db.query(models.NotificationChannel).filter(models.NotificationChannel.id == channel_id).first()
if not db_channel:
raise HTTPException(status_code=404, detail="Channel not found")
# Send test notification in background
background_tasks.add_task(NotificationService.send_test_notification, db_channel)
return {"message": "Test notification queued"}
+24
View File
@@ -12,6 +12,7 @@ class ItemCreate(BaseModel):
category: str | None = None
tags: str | None = None
description: str | None = None
notification_channel_id: int | None = None
class ItemResponse(ItemCreate):
@@ -116,4 +117,27 @@ class SearchProgress(BaseModel):
completed: int
current_site: str | None = None
results: list[SearchResultItem] = []
results: list[SearchResultItem] = []
message: str | None = None
# === Notification Schemas ===
class NotificationChannelCreate(BaseModel):
name: str
type: str # "email", "discord", "mattermost"
configuration: str # JSON string for now
is_active: bool = True
class NotificationChannelUpdate(BaseModel):
name: str | None = None
type: str | None = None
configuration: str | None = None
is_active: bool | None = None
class NotificationChannelResponse(NotificationChannelCreate):
id: int
created_at: datetime
model_config = ConfigDict(from_attributes=True)
+2
View File
@@ -80,6 +80,7 @@ class ItemService:
return None, None
settings = {s.key: s.value for s in db.query(models.Settings).all()}
channel = item.notification_channel
item_data = {
"id": item.id,
@@ -89,6 +90,7 @@ class ItemService:
"current_price": item.current_price,
"in_stock": item.in_stock,
"target_price": item.target_price,
"notification_channel": channel,
}
config = {
+83
View File
@@ -0,0 +1,83 @@
import logging
import json
import apprise
from app import models
logger = logging.getLogger(__name__)
class NotificationService:
@staticmethod
async def send_notification(channel: models.NotificationChannel, title: str, body: str):
"""Send a notification via the specified channel using Apprise."""
if not channel.is_active:
logger.info(f"Channel {channel.name} is inactive, skipping notification.")
return False
apobj = apprise.Apprise()
# Construct Apprise URL based on channel type and configuration
config_url = NotificationService._get_config_url(channel)
if not config_url:
logger.error(f"Failed to construct Apprise URL for channel {channel.name}")
return False
apobj.add(config_url)
try:
await apobj.async_notify(
body=body,
title=title,
)
logger.info(f"Notification sent to {channel.name}")
return True
except Exception as e:
logger.error(f"Failed to send notification to {channel.name}: {e}")
return False
@staticmethod
def _get_config_url(channel: models.NotificationChannel) -> str | None:
"""Construct Apprise URL from channel configuration."""
try:
# If configuration is already a URL (e.g. for simple webhooks), use it
if channel.configuration.startswith("http") or "://" in channel.configuration:
return channel.configuration
# If it's JSON, parse it
config = json.loads(channel.configuration)
if channel.type == "email":
# mailto://user:password@smtp.example.com:2525
user = config.get("user", "")
password = config.get("password", "")
host = config.get("host", "")
port = config.get("port", "")
auth = f"{user}:{password}@" if user and password else ""
port_str = f":{port}" if port else ""
return f"mailto://{auth}{host}{port_str}"
elif channel.type == "discord":
# discord://webhook_id/webhook_token
# Or just the full webhook URL which Apprise supports
return config.get("webhook_url")
elif channel.type == "mattermost":
# mattermost://hostname/token
# Or the full webhook URL
return config.get("webhook_url")
return None
except Exception as e:
logger.error(f"Error parsing configuration for channel {channel.name}: {e}")
return None
@staticmethod
async def send_test_notification(channel: models.NotificationChannel):
return await NotificationService.send_notification(
channel,
title="Test Priceflow",
body="Ceci est une notification de test de Priceflow ! 🚀"
)
+27
View File
@@ -8,6 +8,7 @@ from app import database, models
from app.ai_schema import AIExtractionMetadata, AIExtractionResponse
from app.services.ai_service import AIService
from app.services.item_service import ItemService
from app.services.notification_service import NotificationService
from app.services.scraper_service import ScraperService
logger = logging.getLogger(__name__)
@@ -133,6 +134,32 @@ async def process_item_check(item_id: int):
None, _update_db_result, item_id, extraction, metadata, thresholds, screenshot_path
)
# Check for notifications
if item_data["notification_channel"] and extraction.price:
channel = item_data["notification_channel"]
# 1. Target Price Reached
if item_data["target_price"] and extraction.price <= item_data["target_price"]:
# Only notify if we haven't already notified for this price (or if price dropped further)
# For simplicity, we notify if current price <= target.
# Ideally we should check if we already notified recently, but let's keep it simple.
if not old_price or old_price > item_data["target_price"]:
await NotificationService.send_notification(
channel,
title=f"🎯 Prix cible atteint : {item_data['name']}",
body=f"Le prix de {item_data['name']} est passé à {extraction.price}€ (Cible: {item_data['target_price']}€)\n{item_data['url']}"
)
# 2. Price Drop
elif old_price and extraction.price < old_price:
drop_percent = (old_price - extraction.price) / old_price * 100
if drop_percent >= 5: # Notify only for significant drops (> 5%)
await NotificationService.send_notification(
channel,
title=f"📉 Baisse de prix : {item_data['name']}",
body=f"Le prix de {item_data['name']} a baissé de {drop_percent:.1f}% !\nNouveau prix : {extraction.price}€ (Ancien: {old_price}€)\n{item_data['url']}"
)
except Exception as e:
@@ -17,8 +17,24 @@ export function ItemModal({ item, onClose, onSaved, open }) {
name: '',
target_price: '',
tags: '',
description: ''
description: '',
notification_channel_id: 'none'
});
const [channels, setChannels] = useState([]);
useEffect(() => {
const fetchChannels = async () => {
try {
const response = await axios.get(`${API_URL}/notifications/channels`);
setChannels(response.data.filter(c => c.is_active));
} catch (error) {
console.error('Error fetching channels:', error);
}
};
if (open) {
fetchChannels();
}
}, [open]);
useEffect(() => {
@@ -28,7 +44,8 @@ export function ItemModal({ item, onClose, onSaved, open }) {
name: item.name || '',
target_price: item.target_price || '',
tags: item.tags || '',
description: item.description || ''
description: item.description || '',
notification_channel_id: item.notification_channel_id ? item.notification_channel_id.toString() : 'none'
});
} else {
setFormData({
@@ -36,7 +53,8 @@ export function ItemModal({ item, onClose, onSaved, open }) {
name: '',
target_price: '',
tags: '',
description: ''
description: '',
notification_channel_id: 'none'
});
}
}, [item, open]);
@@ -48,7 +66,8 @@ export function ItemModal({ item, onClose, onSaved, open }) {
try {
const payload = {
...formData,
target_price: formData.target_price ? parseFloat(formData.target_price) : null
target_price: formData.target_price ? parseFloat(formData.target_price) : null,
notification_channel_id: formData.notification_channel_id === 'none' ? null : parseInt(formData.notification_channel_id)
};
if (item) {
@@ -106,6 +125,26 @@ export function ItemModal({ item, onClose, onSaved, open }) {
/>
</div>
<div className="space-y-2">
<Label htmlFor="channel">Notification Channel</Label>
<Select
value={formData.notification_channel_id}
onValueChange={(val) => setFormData({ ...formData, notification_channel_id: val })}
>
<SelectTrigger>
<SelectValue placeholder="Select a channel" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">None</SelectItem>
{channels.map(channel => (
<SelectItem key={channel.id} value={channel.id.toString()}>
{channel.name} ({channel.type})
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="tags">{t('itemModal.tags')}</Label>
<Input
+188 -257
View File
@@ -23,7 +23,7 @@ const categoryIcons = {
};
export default function Settings() {
const [profiles, setProfiles] = useState([]);
const [channels, setChannels] = useState([]);
const [jobConfig, setJobConfig] = useState({ refresh_interval_minutes: 60, next_run: null, running: false });
const [config, setConfig] = useState({
ai_provider: 'ollama',
@@ -41,21 +41,21 @@ export default function Settings() {
text_context_length: 5000,
scraper_timeout: 90000
});
const [newProfile, setNewProfile] = useState({
const [newChannel, setNewChannel] = useState({
name: '',
apprise_url: '',
provider: 'custom',
type: 'email',
configuration: '',
// Helper fields for UI
email_user: '',
email_pass: '',
email_host: '',
email_port: '',
discord_webhook: '',
telegram_token: '',
telegram_chat_id: '',
check_interval_minutes: 60,
notify_on_price_drop: true,
notify_on_target_price: true,
price_drop_threshold_percent: 10,
notify_on_stock_change: true
mattermost_webhook: '',
is_active: true
});
const [editingProfileId, setEditingProfileId] = useState(null);
const [editingChannelId, setEditingChannelId] = useState(null);
const [showAdvancedAI, setShowAdvancedAI] = useState(false);
// Search Sites state
@@ -116,14 +116,14 @@ export default function Settings() {
const fetchAll = async () => {
try {
const [profilesRes, settingsRes, jobRes, sitesRes] = await Promise.all([
axios.get(`${API_URL}/notification-profiles`),
const [channelsRes, settingsRes, jobRes, sitesRes] = await Promise.all([
axios.get(`${API_URL}/notifications/channels`),
axios.get(`${API_URL}/settings`),
axios.get(`${API_URL}/jobs/config`),
axios.get(`${API_URL}/search-sites`)
]);
setProfiles(profilesRes.data);
setChannels(channelsRes.data);
setJobConfig(jobRes.data);
setSearchSites(sitesRes.data);
@@ -174,128 +174,131 @@ export default function Settings() {
}
};
const handleProfileSubmit = async (e) => {
const handleChannelSubmit = async (e) => {
e.preventDefault();
try {
let finalAppriseUrl = newProfile.apprise_url;
let configuration = newChannel.configuration;
// Construct Apprise URL based on provider
if (newProfile.provider === 'discord' && newProfile.discord_webhook) {
// Parse Discord Webhook: https://discord.com/api/webhooks/{id}/{token} -> discord://{id}/{token}
const match = newProfile.discord_webhook.match(/webhooks\/(\d+)\/(.+)/);
if (match) {
finalAppriseUrl = `discord://${match[1]}/${match[2]}`;
} else {
toast.error('Invalid Discord Webhook URL');
return;
}
} else if (newProfile.provider === 'telegram' && newProfile.telegram_token && newProfile.telegram_chat_id) {
// Construct Telegram URL: tgram://{token}/{chat_id}
finalAppriseUrl = `tgram://${newProfile.telegram_token}/${newProfile.telegram_chat_id}`;
// Construct configuration based on type
if (newChannel.type === 'email') {
configuration = JSON.stringify({
user: newChannel.email_user,
password: newChannel.email_pass,
host: newChannel.email_host,
port: newChannel.email_port
});
} else if (newChannel.type === 'discord') {
configuration = JSON.stringify({
webhook_url: newChannel.discord_webhook
});
} else if (newChannel.type === 'mattermost') {
configuration = JSON.stringify({
webhook_url: newChannel.mattermost_webhook
});
}
const profileData = {
...newProfile,
apprise_url: finalAppriseUrl
const channelData = {
name: newChannel.name,
type: newChannel.type,
configuration: configuration,
is_active: newChannel.is_active
};
if (editingProfileId) {
await axios.put(`${API_URL}/notification-profiles/${editingProfileId}`, profileData);
toast.success('Profile updated');
if (editingChannelId) {
await axios.put(`${API_URL}/notifications/channels/${editingChannelId}`, channelData);
toast.success('Channel updated');
} else {
await axios.post(`${API_URL}/notification-profiles`, profileData);
toast.success('Profile created');
await axios.post(`${API_URL}/notifications/channels`, channelData);
toast.success('Channel created');
}
setNewProfile({
name: '',
apprise_url: '',
discord_webhook: '',
telegram_token: '',
telegram_chat_id: '',
provider: 'custom',
check_interval_minutes: 60,
notify_on_price_drop: true,
notify_on_target_price: true,
price_drop_threshold_percent: 10,
notify_on_stock_change: true
});
setEditingProfileId(null);
resetChannelForm();
fetchAll();
} catch (error) {
toast.error(editingProfileId ? 'Failed to update profile' : 'Failed to create profile');
toast.error(editingChannelId ? 'Failed to update channel' : 'Failed to create channel');
}
};
const editProfile = (profile) => {
let provider = 'custom';
let discord_webhook = '';
let telegram_token = '';
let telegram_chat_id = '';
const resetChannelForm = () => {
setNewChannel({
name: '',
type: 'email',
configuration: '',
email_user: '',
email_pass: '',
email_host: '',
email_port: '',
discord_webhook: '',
mattermost_webhook: '',
is_active: true
});
setEditingChannelId(null);
};
// Deconstruct Apprise URL
if (profile.apprise_url.startsWith('discord://')) {
provider = 'discord';
// discord://{id}/{token} -> https://discord.com/api/webhooks/{id}/{token}
const parts = profile.apprise_url.replace('discord://', '').split('/');
if (parts.length >= 2) {
discord_webhook = `https://discord.com/api/webhooks/${parts[0]}/${parts[1]}`;
}
} else if (profile.apprise_url.startsWith('tgram://')) {
provider = 'telegram';
// tgram://{token}/{chat_id}
const parts = profile.apprise_url.replace('tgram://', '').split('/');
if (parts.length >= 2) {
telegram_token = parts[0];
telegram_chat_id = parts[1];
const editChannel = (channel) => {
let email_user = '';
let email_pass = '';
let email_host = '';
let email_port = '';
let discord_webhook = '';
let mattermost_webhook = '';
try {
const config = JSON.parse(channel.configuration);
if (channel.type === 'email') {
email_user = config.user || '';
email_pass = config.password || '';
email_host = config.host || '';
email_port = config.port || '';
} else if (channel.type === 'discord') {
discord_webhook = config.webhook_url || '';
} else if (channel.type === 'mattermost') {
mattermost_webhook = config.webhook_url || '';
}
} catch (e) {
// If config is not JSON, maybe it's a raw URL
}
setNewProfile({
name: profile.name,
apprise_url: profile.apprise_url,
provider,
setNewChannel({
name: channel.name,
type: channel.type,
configuration: channel.configuration,
email_user,
email_pass,
email_host,
email_port,
discord_webhook,
telegram_token,
telegram_chat_id,
check_interval_minutes: profile.check_interval_minutes,
notify_on_price_drop: profile.notify_on_price_drop,
notify_on_target_price: profile.notify_on_target_price,
price_drop_threshold_percent: profile.price_drop_threshold_percent,
notify_on_stock_change: profile.notify_on_stock_change
mattermost_webhook,
is_active: channel.is_active
});
setEditingProfileId(profile.id);
setEditingChannelId(channel.id);
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
};
const cancelEdit = () => {
setNewProfile({
name: '',
apprise_url: '',
check_interval_minutes: 60,
notify_on_price_drop: true,
notify_on_target_price: true,
price_drop_threshold_percent: 10,
notify_on_stock_change: true
});
setEditingProfileId(null);
};
const deleteProfile = async (id) => {
if (confirm('Are you sure you want to delete this profile?')) {
const deleteChannel = async (id) => {
if (confirm('Are you sure you want to delete this channel?')) {
try {
await axios.delete(`${API_URL}/notification-profiles/${id}`);
toast.success('Profile deleted');
if (editingProfileId === id) {
cancelEdit();
await axios.delete(`${API_URL}/notifications/channels/${id}`);
toast.success('Channel deleted');
if (editingChannelId === id) {
resetChannelForm();
}
fetchAll();
} catch (error) {
toast.error('Failed to delete profile');
toast.error('Failed to delete channel');
}
}
};
const testChannel = async (id) => {
try {
await axios.post(`${API_URL}/notifications/channels/${id}/test`);
toast.success('Test notification queued');
} catch (error) {
toast.error('Failed to send test notification');
}
};
// Search Sites functions
const toggleSiteActive = async (site) => {
try {
@@ -678,192 +681,120 @@ export default function Settings() {
</Card>
{/* Notification Profiles */}
{/* Notification Channels */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2"><Bell className="h-5 w-5" />TEST 2025 - Notification Profiles</CardTitle>
<CardDescription>Manage notification settings for different groups of items.</CardDescription>
<CardTitle className="flex items-center gap-2"><Bell className="h-5 w-5" />Notification Channels</CardTitle>
<CardDescription>Configure where you want to receive alerts (Email, Discord, Mattermost).</CardDescription>
</CardHeader>
<CardContent className="space-y-8">
<form onSubmit={handleProfileSubmit} className="space-y-4 border-b pb-8">
<form onSubmit={handleChannelSubmit} className="space-y-4 border-b pb-8">
<div className="flex items-center justify-between">
<h4 className="text-sm font-medium">{editingProfileId ? 'Edit Profile' : 'Create New Profile'}</h4>
{editingProfileId && (
<Button type="button" variant="ghost" size="sm" onClick={cancelEdit}>Cancel Edit</Button>
<h4 className="text-sm font-medium">{editingChannelId ? 'Edit Channel' : 'Create New Channel'}</h4>
{editingChannelId && (
<Button type="button" variant="ghost" size="sm" onClick={resetChannelForm}>Cancel Edit</Button>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Name</Label>
<Input required value={newProfile.name} onChange={(e) => setNewProfile({ ...newProfile, name: e.target.value })} placeholder="e.g., Email Alerts" />
<Input required value={newChannel.name} onChange={(e) => setNewChannel({ ...newChannel, name: e.target.value })} placeholder="e.g., My Discord" />
</div>
<div className="space-y-4 md:col-span-2 border p-4 rounded-lg bg-muted/20">
<div className="space-y-2">
<Label>Notification Provider</Label>
<Select
value={newProfile.provider || 'custom'}
onValueChange={(val) => {
setNewProfile(prev => ({
...prev,
provider: val,
// Reset fields when switching provider
discord_webhook: '',
telegram_token: '',
telegram_chat_id: '',
apprise_url: val === 'custom' ? prev.apprise_url : ''
}));
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="custom">Custom (Apprise URL)</SelectItem>
<SelectItem value="discord">Discord</SelectItem>
<SelectItem value="telegram">Telegram</SelectItem>
</SelectContent>
</Select>
<div className="space-y-2">
<Label>Type</Label>
<Select
value={newChannel.type}
onValueChange={(val) => setNewChannel({ ...newChannel, type: val })}
>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="email">Email</SelectItem>
<SelectItem value="discord">Discord</SelectItem>
<SelectItem value="mattermost">Mattermost</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{/* Configuration Fields based on Type */}
<div className="space-y-4 border p-4 rounded-lg bg-muted/20">
{newChannel.type === 'email' && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>SMTP User</Label>
<Input value={newChannel.email_user} onChange={(e) => setNewChannel({ ...newChannel, email_user: e.target.value })} placeholder="user@example.com" />
</div>
<div className="space-y-2">
<Label>SMTP Password</Label>
<Input type="password" value={newChannel.email_pass} onChange={(e) => setNewChannel({ ...newChannel, email_pass: e.target.value })} />
</div>
<div className="space-y-2">
<Label>SMTP Host</Label>
<Input value={newChannel.email_host} onChange={(e) => setNewChannel({ ...newChannel, email_host: e.target.value })} placeholder="smtp.gmail.com" />
</div>
<div className="space-y-2">
<Label>SMTP Port</Label>
<Input value={newChannel.email_port} onChange={(e) => setNewChannel({ ...newChannel, email_port: e.target.value })} placeholder="587" />
</div>
</div>
)}
{(!newProfile.provider || newProfile.provider === 'custom') && (
<div className="space-y-2">
<Label>Apprise URL</Label>
<Input
required
value={newProfile.apprise_url}
onChange={(e) => setNewProfile({ ...newProfile, apprise_url: e.target.value })}
placeholder="mailto://user:pass@gmail.com"
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
See <a href="https://github.com/caronc/apprise/wiki" target="_blank" rel="noopener noreferrer" className="text-primary hover:underline">Apprise documentation</a> for supported services.
</p>
</div>
)}
{newChannel.type === 'discord' && (
<div className="space-y-2">
<Label>Webhook URL</Label>
<Input value={newChannel.discord_webhook} onChange={(e) => setNewChannel({ ...newChannel, discord_webhook: e.target.value })} placeholder="https://discord.com/api/webhooks/..." />
</div>
)}
{newProfile.provider === 'discord' && (
<div className="space-y-2">
<Label>Discord Webhook URL</Label>
<Input
value={newProfile.discord_webhook}
onChange={(e) => setNewProfile({ ...newProfile, discord_webhook: e.target.value })}
placeholder="https://discord.com/api/webhooks/..."
className="font-mono text-sm"
/>
<p className="text-xs text-muted-foreground">
Paste the full Webhook URL from Discord Server Settings &gt; Integrations &gt; Webhooks.
</p>
</div>
)}
{newChannel.type === 'mattermost' && (
<div className="space-y-2">
<Label>Webhook URL</Label>
<Input value={newChannel.mattermost_webhook} onChange={(e) => setNewChannel({ ...newChannel, mattermost_webhook: e.target.value })} placeholder="https://mattermost.example.com/hooks/..." />
</div>
)}
</div>
{newProfile.provider === 'telegram' && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Bot Token</Label>
<Input
value={newProfile.telegram_token}
onChange={(e) => setNewProfile({ ...newProfile, telegram_token: e.target.value })}
placeholder="123456789:ABCdef..."
className="font-mono text-sm"
/>
</div>
<div className="space-y-2">
<Label>Chat ID</Label>
<Input
value={newProfile.telegram_chat_id}
onChange={(e) => setNewProfile({ ...newProfile, telegram_chat_id: e.target.value })}
placeholder="-100123456789"
className="font-mono text-sm"
/>
</div>
</div>
)}
</div>
<div className="flex items-center space-x-2">
<Switch checked={newChannel.is_active} onCheckedChange={(checked) => setNewChannel({ ...newChannel, is_active: checked })} />
<Label>Active</Label>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Check Interval (Minutes)</Label>
<Input type="number" min="1" value={newProfile.check_interval_minutes} onChange={(e) => setNewProfile({ ...newProfile, check_interval_minutes: parseInt(e.target.value) })} />
</div>
<div className="space-y-2">
<Label>Price Drop Threshold (%)</Label>
<Input type="number" min="1" max="100" value={newProfile.price_drop_threshold_percent} onChange={(e) => setNewProfile({ ...newProfile, price_drop_threshold_percent: parseFloat(e.target.value) })} />
</div>
</div>
<div className="flex flex-wrap gap-4">
<div className="flex items-center space-x-2">
<Switch checked={newProfile.notify_on_price_drop} onCheckedChange={(checked) => setNewProfile({ ...newProfile, notify_on_price_drop: checked })} />
<Label>Notify on Drop</Label>
</div>
<div className="flex items-center space-x-2">
<Switch checked={newProfile.notify_on_target_price} onCheckedChange={(checked) => setNewProfile({ ...newProfile, notify_on_target_price: checked })} />
<Label>Notify on Target</Label>
</div>
<div className="flex items-center space-x-2">
<Switch checked={newProfile.notify_on_stock_change} onCheckedChange={(checked) => setNewProfile({ ...newProfile, notify_on_stock_change: checked })} />
<Label>Notify on Stock Change</Label>
</div>
</div>
<Button type="submit">{editingProfileId ? 'Update Profile' : 'Create Profile'}</Button>
<Button type="submit">{editingChannelId ? 'Update Channel' : 'Create Channel'}</Button>
</form>
<div className="space-y-4">
<h4 className="text-sm font-medium">Existing Profiles</h4>
{profiles.length === 0 ? (
<p className="text-sm text-muted-foreground">No profiles created yet.</p>
<h4 className="text-sm font-medium">Existing Channels</h4>
{channels.length === 0 ? (
<p className="text-sm text-muted-foreground">No channels created yet.</p>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{profiles.map(profile => (
<div key={profile.id} className={cn(
{channels.map(channel => (
<div key={channel.id} className={cn(
"relative group overflow-hidden rounded-xl border bg-card text-card-foreground shadow transition-all hover:shadow-md",
editingProfileId === profile.id && "ring-2 ring-primary"
editingChannelId === channel.id && "ring-2 ring-primary",
!channel.is_active && "opacity-60"
)}>
<div className="p-6 space-y-4">
<div className="flex items-start justify-between">
<div>
<h3 className="font-semibold leading-none tracking-tight">{profile.name}</h3>
<p className="text-sm text-muted-foreground mt-1 truncate max-w-[200px]" title={profile.apprise_url}>{profile.apprise_url}</p>
<h3 className="font-semibold leading-none tracking-tight flex items-center gap-2">
{channel.name}
{!channel.is_active && <span className="text-xs font-normal text-muted-foreground">(Inactive)</span>}
</h3>
<p className="text-sm text-muted-foreground mt-1 capitalize">{channel.type}</p>
</div>
<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => editProfile(profile)}>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => testChannel(channel.id)} title="Send Test Notification">
<Bell className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => editChannel(channel)}>
<Edit2 className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive" onClick={() => deleteProfile(profile.id)}>
<Button variant="ghost" size="icon" className="h-8 w-8 text-destructive hover:text-destructive" onClick={() => deleteChannel(channel.id)}>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
<div className="grid grid-cols-2 gap-4 text-sm">
<div className="flex items-center gap-2">
<Clock className="h-4 w-4 text-muted-foreground" />
<span>{profile.check_interval_minutes}m interval</span>
</div>
<div className="flex items-center gap-2">
<TrendingDown className="h-4 w-4 text-muted-foreground" />
<span>{profile.price_drop_threshold_percent}% drop</span>
</div>
</div>
<div className="flex flex-wrap gap-2 pt-2">
{profile.notify_on_price_drop && (
<span className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80">
<DollarSign className="mr-1 h-3 w-3" /> Price Drop
</span>
)}
{profile.notify_on_target_price && (
<span className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80">
<CheckCircle2 className="mr-1 h-3 w-3" /> Target Hit
</span>
)}
{profile.notify_on_stock_change && (
<span className="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80">
<Package className="mr-1 h-3 w-3" /> Stock Change
</span>
)}
</div>
</div>
<div className="absolute top-0 right-0 p-6 opacity-5 pointer-events-none">
<Bell className="h-24 w-24" />
</div>
</div>
))}