feat: add logging functionality for counter updates for incrementing on different dates (for stats)
Build and publish Docker image / build-and-push (release) Successful in 1m9s
Build and publish Docker image / build-and-push (release) Successful in 1m9s
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import db from '@/lib/db';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
type Params = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function POST(request: Request, { params }: Params) {
|
||||
const { id } = await params;
|
||||
const { date, delta } = await request.json();
|
||||
|
||||
if (!date || typeof date !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(date)) {
|
||||
return NextResponse.json({ error: 'Invalid date' }, { status: 400 });
|
||||
}
|
||||
if (delta !== 1 && delta !== -1) {
|
||||
return NextResponse.json({ error: 'Delta must be 1 or -1' }, { status: 400 });
|
||||
}
|
||||
|
||||
const existing = db.prepare('SELECT * FROM counters WHERE id = ? AND archived_at IS NULL').get(Number(id)) as Record<string, unknown> | undefined;
|
||||
if (!existing) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
// Store at noon local server time so SQLite's 'localtime' grouping matches the picked date
|
||||
const createdAt = new Date(`${date}T12:00:00`).getTime();
|
||||
if (isNaN(createdAt)) return NextResponse.json({ error: 'Invalid date' }, { status: 400 });
|
||||
|
||||
const result = db.transaction(() => {
|
||||
const updated = db.prepare(
|
||||
delta === 1
|
||||
? 'UPDATE counters SET value = value + 1 WHERE id = ? RETURNING *'
|
||||
: 'UPDATE counters SET value = value - 1 WHERE id = ? AND value > 0 RETURNING *'
|
||||
).get(Number(id)) as Record<string, unknown> | undefined;
|
||||
if (!updated) return null;
|
||||
db.prepare('INSERT INTO events (counter_id, delta, created_at) VALUES (?, ?, ?)').run(Number(id), delta, createdAt);
|
||||
return updated;
|
||||
})();
|
||||
|
||||
if (!result) return NextResponse.json({ error: 'Counter cannot go below 0' }, { status: 400 });
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ interface Props {
|
||||
counterId: number | null;
|
||||
cache?: Map<number, HistoryData>;
|
||||
onClose: () => void;
|
||||
onLog?: (counter: Counter) => void;
|
||||
}
|
||||
|
||||
function toLocalDateStr(d: Date): string {
|
||||
@@ -47,12 +48,18 @@ function computeLongestStreak(sortedDates: string[]): number {
|
||||
return best;
|
||||
}
|
||||
|
||||
export default function CounterDetailModal({ counterId, cache, onClose }: Props) {
|
||||
export default function CounterDetailModal({ counterId, cache, onClose, onLog }: Props) {
|
||||
const [data, setData] = useState<HistoryData | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [logDate, setLogDate] = useState(() => { const d = new Date(); d.setDate(d.getDate() - 1); return toLocalDateStr(d); });
|
||||
const [logging, setLogging] = useState(false);
|
||||
const [logError, setLogError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!counterId) return;
|
||||
const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1);
|
||||
setLogDate(toLocalDateStr(yesterday));
|
||||
setLogError('');
|
||||
const cached = cache?.get(counterId);
|
||||
if (cached) { setData(cached); setLoading(false); return; }
|
||||
setData(null);
|
||||
@@ -70,6 +77,33 @@ export default function CounterDetailModal({ counterId, cache, onClose }: Props)
|
||||
return () => window.removeEventListener('keydown', handler);
|
||||
}, [counterId, onClose]);
|
||||
|
||||
async function handleLog(delta: number) {
|
||||
if (!counterId || !logDate) return;
|
||||
setLogging(true);
|
||||
setLogError('');
|
||||
try {
|
||||
const res = await fetch(`/api/counters/${counterId}/log`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ date: logDate, delta }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const body = await res.json();
|
||||
setLogError(body.error ?? 'Failed to log entry');
|
||||
return;
|
||||
}
|
||||
const updated: Counter = await res.json();
|
||||
cache?.delete(counterId);
|
||||
const histRes = await fetch(`/api/counters/${counterId}/history`);
|
||||
const d: HistoryData = await histRes.json();
|
||||
cache?.set(counterId, d);
|
||||
setData(d);
|
||||
onLog?.(updated);
|
||||
} finally {
|
||||
setLogging(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!counterId) return null;
|
||||
|
||||
const dateSet = new Set(data?.dailyActivity.map(d => d.date) ?? []);
|
||||
@@ -165,6 +199,42 @@ export default function CounterDetailModal({ counterId, cache, onClose }: Props)
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Log past entry */}
|
||||
<div className="border-t border-ctp-surface1 pt-4">
|
||||
<h3 className="text-sm font-bold text-ctp-text mb-3">Log past entry</h3>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<input
|
||||
type="date"
|
||||
value={logDate}
|
||||
max={toLocalDateStr(new Date())}
|
||||
onChange={e => setLogDate(e.target.value)}
|
||||
className="rounded-lg border border-ctp-surface1 bg-ctp-surface0 text-ctp-text px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ctp-mauve"
|
||||
/>
|
||||
<button
|
||||
onClick={() => handleLog(-1)}
|
||||
disabled={logging || !logDate || (data?.dailyActivity.find(d => d.date === logDate)?.value ?? 0) <= 0}
|
||||
aria-label="Log decrement"
|
||||
className="w-10 h-10 flex items-center justify-center rounded-xl bg-ctp-surface1 text-ctp-red hover:bg-ctp-red/20 active:bg-ctp-red/30 disabled:opacity-40 transition-colors"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
|
||||
<line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleLog(1)}
|
||||
disabled={logging || !logDate}
|
||||
aria-label="Log increment"
|
||||
className="w-10 h-10 flex items-center justify-center rounded-xl bg-ctp-surface1 text-ctp-green hover:bg-ctp-green/20 active:bg-ctp-green/30 disabled:opacity-40 transition-colors"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
|
||||
<line x1="12" y1="5" x2="12" y2="19" />
|
||||
<line x1="5" y1="12" x2="19" y2="12" />
|
||||
</svg>
|
||||
</button>
|
||||
{logError && <p className="text-xs text-ctp-red">{logError}</p>}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -495,6 +495,10 @@ export default function Home() {
|
||||
counterId={historyCounterId}
|
||||
cache={historyCache.current}
|
||||
onClose={() => setHistoryCounterId(null)}
|
||||
onLog={updated => {
|
||||
setCounters(prev => prev.map(c => c.id === updated.id ? { ...c, value: updated.value } : c));
|
||||
setArchivedCounters(prev => prev.map(c => c.id === updated.id ? { ...c, value: updated.value } : c));
|
||||
}}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user