feat: Implement subscription management and article saving features
- Added subscriptionPlan and subscriptionExpiresAt fields to UserProfile model. - Enhanced profile routes to handle subscription state updates and expiration logic. - Introduced email and password validation during user registration. - Implemented link stripping for processed articles in the articles route. - Added save article functionality with appropriate UI feedback in the frontend. - Updated AccountSettings and FeedContent components to reflect subscription state and saved articles. - Improved error handling and local storage management for user preferences.
This commit is contained in:
@@ -4,13 +4,15 @@ type AccountSettingsProps = {
|
||||
username: string
|
||||
email: string
|
||||
subscriptionState: SubscriptionState
|
||||
subscriptionExpiresAt?: string | null
|
||||
onUpgrade: () => void
|
||||
onCancelSubscription: () => void
|
||||
}
|
||||
|
||||
// Sezione account: mostra profilo e gestisce in modo condizionale il piano attivo.
|
||||
function AccountSettings({username, email, subscriptionState, onUpgrade, onCancelSubscription}: AccountSettingsProps) {
|
||||
function AccountSettings({username, email, subscriptionState, subscriptionExpiresAt, onUpgrade, onCancelSubscription}: AccountSettingsProps) {
|
||||
const isProPlan = subscriptionState === 'pro'
|
||||
const expires = subscriptionExpiresAt ? new Date(subscriptionExpiresAt) : null
|
||||
|
||||
return (
|
||||
<section className="settings-stack" aria-label="Profilo">
|
||||
@@ -48,7 +50,7 @@ function AccountSettings({username, email, subscriptionState, onUpgrade, onCance
|
||||
{isProPlan ? 'Piano Pro' : 'Piano Gratuito'}
|
||||
</span>
|
||||
{isProPlan ? (
|
||||
<p>Scade il 12/12/2026</p>
|
||||
<p>{expires ? `Scade il ${expires.toLocaleDateString()}` : 'Piano Pro attivo'}</p>
|
||||
) : (
|
||||
<p>Passa al Pro per sbloccare monitoraggio e analisi avanzate.</p>
|
||||
)}
|
||||
|
||||
@@ -1,20 +1,45 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import MagicCard from './MagicCard'
|
||||
import { fetchPersonalizedFeed } from '../services/feedService'
|
||||
import { sendFeedback } from '../services/feedbackService'
|
||||
import { sendFeedback, saveArticle } from '../services/feedbackService'
|
||||
import type { Article } from '../types/article'
|
||||
|
||||
type FeedContentProps = {
|
||||
sentimentFilter?: string | null
|
||||
topicsFilter?: string | null
|
||||
preferenceFilter?: string | null
|
||||
}
|
||||
|
||||
function FeedContent({ sentimentFilter = null, topicsFilter = null }: FeedContentProps) {
|
||||
function FeedContent({ sentimentFilter = null, topicsFilter = null, preferenceFilter = null }: FeedContentProps) {
|
||||
const [articles, setArticles] = useState<Article[]>([])
|
||||
const [status, setStatus] = useState<'loading' | 'ok' | 'error'>('loading')
|
||||
const [voteByArticle, setVoteByArticle] = useState<Record<string, 1 | -1 | null>>({})
|
||||
const [pendingByArticle, setPendingByArticle] = useState<Record<string, boolean>>({})
|
||||
const [savedByArticle, setSavedByArticle] = useState<Record<string, boolean>>({})
|
||||
const [savePendingByArticle, setSavePendingByArticle] = useState<Record<string, boolean>>({})
|
||||
const [voteError, setVoteError] = useState<string | null>(null)
|
||||
const [saveError, setSaveError] = useState<string | null>(null)
|
||||
|
||||
// Carica articoli salvati e voti da localStorage
|
||||
useEffect(() => {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem('briefai_saved_articles') || '{}')
|
||||
setSavedByArticle(saved)
|
||||
const votes = JSON.parse(localStorage.getItem('briefai_voted_articles') || '{}')
|
||||
setVoteByArticle(votes)
|
||||
} catch (e) {
|
||||
console.warn('Errore caricamento preferenze:', e)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Persisti voti in localStorage quando cambiano
|
||||
useEffect(() => {
|
||||
try {
|
||||
localStorage.setItem('briefai_voted_articles', JSON.stringify(voteByArticle))
|
||||
} catch (e) {
|
||||
console.warn('Errore salvataggio voti:', e)
|
||||
}
|
||||
}, [voteByArticle])
|
||||
|
||||
const sendVoteDelta = async (articleId: string, previousVote: 1 | -1 | null, nextVote: 1 | -1 | null) => {
|
||||
// Without server idempotency, simulate undo by applying compensating vote.
|
||||
@@ -53,6 +78,23 @@ function FeedContent({ sentimentFilter = null, topicsFilter = null }: FeedConten
|
||||
}
|
||||
}
|
||||
|
||||
const handleSaveArticle = async (articleId: string) => {
|
||||
if (savePendingByArticle[articleId]) return
|
||||
|
||||
setSaveError(null)
|
||||
setSavedByArticle((prev) => ({ ...prev, [articleId]: !prev[articleId] }))
|
||||
setSavePendingByArticle((prev) => ({ ...prev, [articleId]: true }))
|
||||
|
||||
try {
|
||||
await saveArticle(articleId)
|
||||
} catch {
|
||||
setSavedByArticle((prev) => ({ ...prev, [articleId]: !prev[articleId] }))
|
||||
setSaveError('Impossibile salvare l\'articolo. Riprova.')
|
||||
} finally {
|
||||
setSavePendingByArticle((prev) => ({ ...prev, [articleId]: false }))
|
||||
}
|
||||
}
|
||||
|
||||
// Prende il fetch del feed personalizzato e popola la variabile di stato con i dati
|
||||
useEffect(() => {fetchPersonalizedFeed().then((data) => {
|
||||
setArticles(data)
|
||||
@@ -72,6 +114,7 @@ function FeedContent({ sentimentFilter = null, topicsFilter = null }: FeedConten
|
||||
{status === 'loading' && <p>Caricamento feed...</p>}
|
||||
{status === 'error' && <p>Errore nel caricamento del feed.</p>}
|
||||
{voteError && <p className="feed-no-results">{voteError}</p>}
|
||||
{saveError && <p className="feed-no-results">{saveError}</p>}
|
||||
{/*Render della lista di articoli se il caricamento è andato a buon fine*/}
|
||||
{status === 'ok' && (
|
||||
<>
|
||||
@@ -79,13 +122,13 @@ function FeedContent({ sentimentFilter = null, topicsFilter = null }: FeedConten
|
||||
{(() => {
|
||||
const matchesTopic = (a: Article) => {
|
||||
if (!topicsFilter || topicsFilter === 'All Topics') return true
|
||||
const topic = topicsFilter.toLowerCase()
|
||||
const catMatch = (a.category || '').toLowerCase() === topic
|
||||
const topic = topicsFilter.toLowerCase().trim()
|
||||
const catMatch = (a.category || '').toLowerCase().trim() === topic
|
||||
const trending = (a.trendingTopics || []).some((t) =>
|
||||
String(t || '').toLowerCase() === topic
|
||||
String(t || '').toLowerCase().trim() === topic
|
||||
)
|
||||
const macroTopicMatch = (a.macroTopics || []).some((t) =>
|
||||
String(t || '').toLowerCase() === topic
|
||||
String(t || '').toLowerCase().trim() === topic
|
||||
)
|
||||
return catMatch || trending || macroTopicMatch
|
||||
}
|
||||
@@ -95,7 +138,18 @@ function FeedContent({ sentimentFilter = null, topicsFilter = null }: FeedConten
|
||||
return a.sentiment === sentimentFilter
|
||||
}
|
||||
|
||||
const filtered = articles.filter((a) => matchesSentiment(a) && matchesTopic(a))
|
||||
const matchesPreference = (a: Article) => {
|
||||
if (!preferenceFilter || preferenceFilter === 'Tutti') return true
|
||||
if (preferenceFilter === 'Like') {
|
||||
return voteByArticle[a.uniqueKey] === 1
|
||||
}
|
||||
if (preferenceFilter === 'Salvati') {
|
||||
return savedByArticle[a.uniqueKey] === true
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const filtered = articles.filter((a) => matchesSentiment(a) && matchesTopic(a) && matchesPreference(a))
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -122,7 +176,10 @@ function FeedContent({ sentimentFilter = null, topicsFilter = null }: FeedConten
|
||||
entities={a.entities || []}
|
||||
voteState={voteByArticle[a.uniqueKey] ?? null}
|
||||
votePending={pendingByArticle[a.uniqueKey] ?? false}
|
||||
isSaved={savedByArticle[a.uniqueKey] ?? false}
|
||||
savePending={savePendingByArticle[a.uniqueKey] ?? false}
|
||||
onVoteChange={handleVoteChange}
|
||||
onSave={handleSaveArticle}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,8 @@ type FeedTopbarProps = {
|
||||
onSentimentChange?: (sentiment: string) => void
|
||||
topicsFilter?: string | null
|
||||
onTopicChange?: (topic: string) => void
|
||||
preferenceFilter?: string | null
|
||||
onPreferenceChange?: (preference: string) => void
|
||||
}
|
||||
|
||||
function FeedTopbar({
|
||||
@@ -12,6 +14,8 @@ function FeedTopbar({
|
||||
onSentimentChange,
|
||||
topicsFilter = null,
|
||||
onTopicChange,
|
||||
preferenceFilter = null,
|
||||
onPreferenceChange,
|
||||
}: FeedTopbarProps) {
|
||||
return (
|
||||
<header
|
||||
@@ -56,6 +60,19 @@ function FeedTopbar({
|
||||
<option>Trasporti & Mobilità</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="feed-filter-control" htmlFor="preference-filter">
|
||||
<span className="feed-filter-label">Preferenza</span>
|
||||
<select
|
||||
id="preference-filter"
|
||||
value={preferenceFilter || 'Tutti'}
|
||||
onChange={(e) => onPreferenceChange?.(e.target.value)}
|
||||
>
|
||||
<option>Tutti</option>
|
||||
<option>Like</option>
|
||||
<option>Salvati</option>
|
||||
</select>
|
||||
</label>
|
||||
</nav>
|
||||
) : null}
|
||||
</header>
|
||||
|
||||
@@ -12,11 +12,14 @@ type MagicCardProps = {
|
||||
entities: string[]
|
||||
voteState: 1 | -1 | null
|
||||
votePending?: boolean
|
||||
isSaved?: boolean
|
||||
savePending?: boolean
|
||||
onVoteChange: (articleId: string, nextVote: 1 | -1 | null) => void
|
||||
onSave?: (articleId: string) => void
|
||||
}
|
||||
|
||||
// Card notizia: mostra fonte, sentiment, testo, tag, entità e azioni rapide.
|
||||
function MagicCard({ articleId, articleUrl, source, timeAgo, sentiment, title, summary, tags, entities, voteState, votePending = false, onVoteChange }: MagicCardProps) {
|
||||
function MagicCard({ articleId, articleUrl, source, timeAgo, sentiment, title, summary, tags, entities, voteState, votePending = false, isSaved = false, savePending = false, onVoteChange, onSave }: MagicCardProps) {
|
||||
const handleVote = (clickedVote: 1 | -1) => {
|
||||
if (!articleId || votePending) return
|
||||
|
||||
@@ -24,6 +27,11 @@ function MagicCard({ articleId, articleUrl, source, timeAgo, sentiment, title, s
|
||||
onVoteChange(articleId, nextVote)
|
||||
}
|
||||
|
||||
const handleSave = () => {
|
||||
if (!articleId || savePending || !onSave) return
|
||||
onSave(articleId)
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="magic-card">
|
||||
{/* Testata card: fonte e badge del sentiment allineati ai lati opposti. */}
|
||||
@@ -78,22 +86,22 @@ function MagicCard({ articleId, articleUrl, source, timeAgo, sentiment, title, s
|
||||
<ActionButton
|
||||
label="Mi piace"
|
||||
tone="like"
|
||||
isActive={voteState === 1}
|
||||
onClick={() => handleVote(1)}
|
||||
disabled={votePending}
|
||||
style={{ opacity: voteState === -1 ? 0.4 : 1 }}
|
||||
>
|
||||
<ThumbUpIcon />
|
||||
</ActionButton>
|
||||
<ActionButton
|
||||
label="Non mi piace"
|
||||
tone="dislike"
|
||||
isActive={voteState === -1}
|
||||
onClick={() => handleVote(-1)}
|
||||
disabled={votePending}
|
||||
style={{ opacity: voteState === 1 ? 0.4 : 1 }}
|
||||
>
|
||||
<ThumbDownIcon />
|
||||
</ActionButton>
|
||||
<ActionButton label="Salva" tone="save">
|
||||
<ActionButton label="Salva" tone="save" isActive={isSaved} onClick={handleSave} disabled={savePending}>
|
||||
<BookmarkIcon />
|
||||
</ActionButton>
|
||||
</footer>
|
||||
@@ -102,11 +110,11 @@ function MagicCard({ articleId, articleUrl, source, timeAgo, sentiment, title, s
|
||||
}
|
||||
|
||||
// Piccolo bottone riutilizzabile per mantenere coerente il footer azioni.
|
||||
function ActionButton({ label, tone, children, onClick, disabled, style }: { label: string; tone: string; children: ReactNode; onClick?: () => void; disabled?: boolean; style?: React.CSSProperties }) {
|
||||
function ActionButton({ label, tone, children, onClick, disabled, isActive, style }: { label: string; tone: string; children: ReactNode; onClick?: () => void; disabled?: boolean; isActive?: boolean; style?: React.CSSProperties }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`action-button ${tone}`}
|
||||
className={`action-button ${tone}${isActive ? ' active' : ''}`}
|
||||
aria-label={label}
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
|
||||
@@ -388,6 +388,24 @@
|
||||
background: #f5f3ff;
|
||||
}
|
||||
|
||||
.action-button.like.active {
|
||||
color: #16a34a;
|
||||
border-color: #86efac;
|
||||
background: #f0fdf4;
|
||||
}
|
||||
|
||||
.action-button.dislike.active {
|
||||
color: #dc2626;
|
||||
border-color: #fca5a5;
|
||||
background: #fef2f2;
|
||||
}
|
||||
|
||||
.action-button.save.active {
|
||||
color: #2563eb;
|
||||
border-color: #93c5fd;
|
||||
background: #eff6ff;
|
||||
}
|
||||
|
||||
.action-button svg {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
@@ -401,14 +419,27 @@
|
||||
}
|
||||
|
||||
.load-more-button {
|
||||
color: #2563eb;
|
||||
background: #fff;
|
||||
border: 1px solid #93c5fd;
|
||||
box-shadow: none;
|
||||
padding: 12px 28px;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
color: #fff;
|
||||
background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3);
|
||||
}
|
||||
|
||||
.load-more-button:hover {
|
||||
background: #dbeafe;
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 16px rgba(37, 99, 235, 0.4);
|
||||
background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
|
||||
}
|
||||
|
||||
.load-more-button:active {
|
||||
transform: translateY(0);
|
||||
box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3);
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import './FeedPage.css'
|
||||
function FeedPage() {
|
||||
const [sentimentFilter, setSentimentFilter] = useState<string | null>(null)
|
||||
const [topicsFilter, setTopicsFilter] = useState<string | null>(null)
|
||||
const [preferenceFilter, setPreferenceFilter] = useState<string | null>(null)
|
||||
|
||||
const handleSentimentChange = (sentiment: string) => {
|
||||
setSentimentFilter(sentiment === 'All Sentiment' ? null : sentiment)
|
||||
@@ -16,6 +17,10 @@ function FeedPage() {
|
||||
setTopicsFilter(topic === 'All Topics' ? null : topic)
|
||||
}
|
||||
|
||||
const handlePreferenceChange = (preference: string) => {
|
||||
setPreferenceFilter(preference === 'Tutti' ? null : preference)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="feed-layout" aria-label="Feed BriefAI">
|
||||
<FeedSidebar activeItem="feed" />
|
||||
@@ -27,8 +32,10 @@ function FeedPage() {
|
||||
onSentimentChange={handleSentimentChange}
|
||||
topicsFilter={topicsFilter}
|
||||
onTopicChange={handleTopicChange}
|
||||
preferenceFilter={preferenceFilter}
|
||||
onPreferenceChange={handlePreferenceChange}
|
||||
/>
|
||||
<FeedContent sentimentFilter={sentimentFilter} topicsFilter={topicsFilter} />
|
||||
<FeedContent sentimentFilter={sentimentFilter} topicsFilter={topicsFilter} preferenceFilter={preferenceFilter} />
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -39,6 +39,13 @@ function RegisterPage({ onRegisterSuccess }: RegisterPageProps) {
|
||||
// ignore parsing errors
|
||||
}
|
||||
|
||||
// Basic email format validation on client
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
if (!emailRegex.test(String(email).toLowerCase())) {
|
||||
setError('Formato email non valido.')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await register({
|
||||
email,
|
||||
|
||||
@@ -121,12 +121,26 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
background: linear-gradient(90deg, #2563eb, #1d4ed8);
|
||||
transition: transform 0.2s ease, opacity 0.2s ease, background 0.2s ease;
|
||||
padding: 10px 16px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
color: #fff;
|
||||
background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3);
|
||||
}
|
||||
|
||||
.settings-save-button:hover {
|
||||
transform: translateY(-1px);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 16px rgba(37, 99, 235, 0.4);
|
||||
background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
|
||||
}
|
||||
|
||||
.settings-save-button:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.settings-save-button svg {
|
||||
@@ -135,6 +149,33 @@
|
||||
fill: currentColor;
|
||||
}
|
||||
|
||||
.keyword-add-button {
|
||||
margin-top: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 16px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
color: #fff;
|
||||
background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3);
|
||||
}
|
||||
|
||||
.keyword-add-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 16px rgba(37, 99, 235, 0.4);
|
||||
background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
|
||||
}
|
||||
|
||||
.keyword-add-button:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.keyword-toolbar {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
@@ -152,19 +193,6 @@
|
||||
box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15);
|
||||
}
|
||||
|
||||
.keyword-add-button {
|
||||
margin-top: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
background: #2563eb;
|
||||
transition: transform 0.2s ease, background 0.2s ease;
|
||||
}
|
||||
|
||||
.keyword-add-button:hover {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.suggestion-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -263,17 +291,50 @@
|
||||
|
||||
.subscription-upgrade-button {
|
||||
margin-top: 0;
|
||||
background: linear-gradient(90deg, #2563eb, #7c3aed);
|
||||
padding: 10px 18px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
color: #fff;
|
||||
background: linear-gradient(135deg, #2563eb 0%, #7c3aed 100%);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
box-shadow: 0 2px 8px rgba(37, 99, 235, 0.3);
|
||||
}
|
||||
|
||||
.subscription-upgrade-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 16px rgba(37, 99, 235, 0.4);
|
||||
background: linear-gradient(135deg, #1d4ed8 0%, #6d28d9 100%);
|
||||
}
|
||||
|
||||
.subscription-upgrade-button:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.subscription-link-button {
|
||||
margin-top: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
padding: 10px 18px;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 10px;
|
||||
color: #64748b;
|
||||
background: #fff;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.subscription-link-button:hover {
|
||||
color: #2563eb;
|
||||
background: transparent;
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
border-color: #2563eb;
|
||||
background: #eff6ff;
|
||||
box-shadow: 0 2px 8px rgba(37, 99, 235, 0.15);
|
||||
}
|
||||
|
||||
.subscription-link-button:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
@media (min-width: 900px) {
|
||||
|
||||
@@ -13,6 +13,7 @@ type SettingsSnapshot = {
|
||||
selectedMacroTopics: string[]
|
||||
keywords: string[]
|
||||
subscriptionState: SubscriptionState
|
||||
subscriptionExpiresAt?: string | null
|
||||
}
|
||||
|
||||
type ProfileIdentity = {
|
||||
@@ -43,6 +44,7 @@ function readInitialSettings(): SettingsSnapshot {
|
||||
storedSnapshot?.selectedMacroTopics ?? onboardingSnapshot?.selectedTopics ?? DEFAULT_MACRO_TOPICS,
|
||||
keywords: storedSnapshot?.keywords ?? onboardingSnapshot?.keywords ?? [],
|
||||
subscriptionState: storedSnapshot?.subscriptionState ?? 'free',
|
||||
subscriptionExpiresAt: storedSnapshot?.subscriptionExpiresAt ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,6 +81,9 @@ function SettingsPage() {
|
||||
const [subscriptionState, setSubscriptionState] = useState<SubscriptionState>(
|
||||
() => readInitialSettings().subscriptionState,
|
||||
)
|
||||
const [subscriptionExpiresAt, setSubscriptionExpiresAt] = useState<string | null>(() =>
|
||||
(readInitialSettings() as any).subscriptionExpiresAt ?? null,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
fetchProfile()
|
||||
@@ -90,6 +95,8 @@ function SettingsPage() {
|
||||
})
|
||||
setSelectedMacroTopics(res.profile.macroTopics || [])
|
||||
setKeywords(res.profile.keywords || [])
|
||||
if (res.profile.subscriptionPlan) setSubscriptionState(res.profile.subscriptionPlan as SubscriptionState)
|
||||
setSubscriptionExpiresAt(res.profile.subscriptionExpiresAt || null)
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
@@ -110,11 +117,11 @@ function SettingsPage() {
|
||||
if (res && res.profile) {
|
||||
setSelectedMacroTopics(res.profile.macroTopics || selectedMacroTopics)
|
||||
}
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState })
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState, subscriptionExpiresAt })
|
||||
})
|
||||
.catch(() => {
|
||||
// fallback local persist
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState })
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState, subscriptionExpiresAt })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -142,23 +149,44 @@ function SettingsPage() {
|
||||
if (res && res.profile) {
|
||||
setKeywords(res.profile.keywords || keywords)
|
||||
}
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState })
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState, subscriptionExpiresAt })
|
||||
})
|
||||
.catch(() => {
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState })
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState, subscriptionExpiresAt })
|
||||
})
|
||||
}
|
||||
|
||||
const handleUpgrade = () => {
|
||||
const nextSubscriptionState: SubscriptionState = 'pro'
|
||||
setSubscriptionState(nextSubscriptionState)
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState: nextSubscriptionState })
|
||||
const handleUpgrade = async () => {
|
||||
try {
|
||||
const res = await updateProfile({ subscriptionState: 'pro' })
|
||||
if (res && res.profile) {
|
||||
setSubscriptionState((res.profile.subscriptionPlan as SubscriptionState) || 'pro')
|
||||
setSubscriptionExpiresAt(res.profile.subscriptionExpiresAt || null)
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState: (res.profile.subscriptionPlan as SubscriptionState) || 'pro', subscriptionExpiresAt: res.profile.subscriptionExpiresAt || null })
|
||||
}
|
||||
} catch (e) {
|
||||
// fallback local only
|
||||
const nextSubscriptionState: SubscriptionState = 'pro'
|
||||
setSubscriptionState(nextSubscriptionState)
|
||||
setSubscriptionExpiresAt(new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString())
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState: nextSubscriptionState, subscriptionExpiresAt })
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancelSubscription = () => {
|
||||
const nextSubscriptionState: SubscriptionState = 'free'
|
||||
setSubscriptionState(nextSubscriptionState)
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState: nextSubscriptionState })
|
||||
const handleCancelSubscription = async () => {
|
||||
try {
|
||||
const res = await updateProfile({ subscriptionState: 'free' })
|
||||
if (res && res.profile) {
|
||||
setSubscriptionState((res.profile.subscriptionPlan as SubscriptionState) || 'free')
|
||||
setSubscriptionExpiresAt(res.profile.subscriptionExpiresAt || null)
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState: (res.profile.subscriptionPlan as SubscriptionState) || 'free', subscriptionExpiresAt: res.profile.subscriptionExpiresAt || null })
|
||||
}
|
||||
} catch (e) {
|
||||
const nextSubscriptionState: SubscriptionState = 'free'
|
||||
setSubscriptionState(nextSubscriptionState)
|
||||
setSubscriptionExpiresAt(null)
|
||||
persistSettings({ selectedMacroTopics, keywords, subscriptionState: nextSubscriptionState, subscriptionExpiresAt })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -198,6 +226,7 @@ function SettingsPage() {
|
||||
username={profileIdentity.username || 'Utente'}
|
||||
email={profileIdentity.email || 'Email non disponibile'}
|
||||
subscriptionState={subscriptionState}
|
||||
subscriptionExpiresAt={subscriptionExpiresAt}
|
||||
onUpgrade={handleUpgrade}
|
||||
onCancelSubscription={handleCancelSubscription}
|
||||
/>
|
||||
|
||||
@@ -9,6 +9,8 @@ export type ProfileResponse = {
|
||||
email?: string
|
||||
macroTopics?: string[]
|
||||
keywords?: string[]
|
||||
subscriptionPlan?: 'free' | 'pro'
|
||||
subscriptionExpiresAt?: string | null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +49,7 @@ export const updateProfile = async (data: {
|
||||
userId?: string
|
||||
macroTopics?: string[]
|
||||
keywords?: string[]
|
||||
subscriptionState?: 'free' | 'pro'
|
||||
}) => {
|
||||
// Sync to backend
|
||||
const backendRes = await authFetch('/api/profile', {
|
||||
@@ -57,7 +60,7 @@ export const updateProfile = async (data: {
|
||||
|
||||
// Opt-in sync to n8n if url is present and userId is known
|
||||
const n8nUrl = import.meta.env.VITE_N8N_URL;
|
||||
if (n8nUrl && data.userId && data.macroTopics) {
|
||||
if (n8nUrl && data.userId) {
|
||||
try {
|
||||
await fetch(`${n8nUrl}/briefai/profile/update`, {
|
||||
method: 'POST',
|
||||
@@ -66,6 +69,7 @@ export const updateProfile = async (data: {
|
||||
userId: data.userId,
|
||||
macroTopics: data.macroTopics,
|
||||
keywords: data.keywords,
|
||||
subscriptionState: data.subscriptionState,
|
||||
})
|
||||
});
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Article } from '../types/article'
|
||||
import { getAuthHeader, decodeToken } from './authService'
|
||||
import { getAuthHeader, decodeToken, getMe } from './authService'
|
||||
|
||||
const N8N = import.meta.env.VITE_N8N_URL
|
||||
|
||||
@@ -9,8 +9,19 @@ export const fetchPersonalizedFeed = async (): Promise<Article[]> => {
|
||||
if (!token) throw new Error('Non autenticato')
|
||||
|
||||
const payload = decodeToken(token)
|
||||
const userId: string = payload?.userId
|
||||
if (!userId) throw new Error('Token non valido')
|
||||
let userId: string = payload?.userId
|
||||
|
||||
// Fallback: if token decoding failed, ask backend who we are
|
||||
if (!userId) {
|
||||
try {
|
||||
const me = await getMe()
|
||||
userId = me?.user?.userId
|
||||
} catch (e) {
|
||||
// ignore and let later check throw
|
||||
}
|
||||
}
|
||||
|
||||
if (!userId) throw new Error('Token non valido o utente non riconosciuto')
|
||||
|
||||
const res = await fetch(`${N8N}/briefai/feed`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -46,3 +46,61 @@ export const sendFeedback = async (
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
}
|
||||
|
||||
export const saveArticle = async (articleId: string): Promise<void> => {
|
||||
const token = localStorage.getItem('briefai_token')
|
||||
if (!token) throw new Error('Token mancante')
|
||||
|
||||
if (!N8N) {
|
||||
// Fallback: salva solo localmente se n8n non è configurato
|
||||
console.warn('N8N_URL non configurato, salvataggio locale')
|
||||
const saved = JSON.parse(localStorage.getItem('briefai_saved_articles') || '{}')
|
||||
saved[articleId] = true
|
||||
localStorage.setItem('briefai_saved_articles', JSON.stringify(saved))
|
||||
return
|
||||
}
|
||||
|
||||
let payload: { userId?: string } | null = null
|
||||
try {
|
||||
payload = JSON.parse(atob(token.split('.')[1]))
|
||||
} catch {
|
||||
throw new Error('Token non valido')
|
||||
}
|
||||
|
||||
if (!payload?.userId) throw new Error('userId non presente nel token')
|
||||
|
||||
const controller = new AbortController()
|
||||
const timeoutId = setTimeout(() => controller.abort(), FEEDBACK_TIMEOUT_MS)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${N8N}/briefai/save-article`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
userId: payload.userId,
|
||||
articleId,
|
||||
}),
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
console.error(`Save article HTTP ${response.status}`, response)
|
||||
// Fallback locale se n8n fallisce
|
||||
const saved = JSON.parse(localStorage.getItem('briefai_saved_articles') || '{}')
|
||||
saved[articleId] = true
|
||||
localStorage.setItem('briefai_saved_articles', JSON.stringify(saved))
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Save article error:', error)
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw new Error('Timeout save article')
|
||||
}
|
||||
// Fallback locale se errore di rete
|
||||
const saved = JSON.parse(localStorage.getItem('briefai_saved_articles') || '{}')
|
||||
saved[articleId] = true
|
||||
localStorage.setItem('briefai_saved_articles', JSON.stringify(saved))
|
||||
} finally {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user