Skip to content

Commit dc83116

Browse files
committed
Lisätty päivityksen aloitusvuoden valinta admin-näkymään
1 parent 74d66e6 commit dc83116

File tree

4 files changed

+67
-12
lines changed

4 files changed

+67
-12
lines changed

backend/src/app.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { fileURLToPath } from 'url';
88
import { runSetup } from './dbSetup.js';
99
import { getLatestStatusEntry, getAllStatusEntries, clearAllStatusEntries } from './db/models/status.js';
1010
import { addStatusRow, createTables } from './db/db.js';
11+
import { yearFrom, yearTo } from './util/config.js';
1112

1213
const app = express()
1314
const __filename = fileURLToPath(import.meta.url);
@@ -31,14 +32,26 @@ app.get('/api/ping', async (req, res) => {
3132
res.send({ data: 'pong' })
3233
})
3334

35+
// Expose a small config endpoint so frontend can show current START_YEAR
36+
app.get('/api/config', (req, res) => {
37+
try {
38+
res.status(200).json({ startYear: yearFrom(), endYear: yearTo() });
39+
} catch (error) {
40+
console.error('Config endpoint error:', error);
41+
res.status(500).json({ error: 'Failed to get config' });
42+
}
43+
})
44+
3445
app.post('/api/setup', async (req: express.Request, res: express.Response): Promise<void> => {
3546
try {
3647
res.status(200).json({ status: 'started', message: 'Database update started in background' });
3748
setImmediate(async () => {
3849
try {
39-
console.log('[SETUP] Starting database setup...');
40-
await runSetup();
41-
console.log('[SETUP] Setup completed successfully');
50+
console.info('Database setup started');
51+
const body: any = req.body || {}
52+
const startYear = body.startYear !== undefined ? parseInt(body.startYear as any, 10) : undefined
53+
await runSetup(startYear);
54+
console.info('Database setup completed');
4255
} catch (error) {
4356
console.error('[SETUP] Setup failed with error:', error);
4457
const errorMessage = error instanceof Error ? error.message : String(error);

backend/src/db/db.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ async function dbIsReady(): Promise<boolean> {
8585
}
8686
}
8787

88-
async function dbIsUpToDate(): Promise<{upToDate: boolean, statutes: StatuteKey[], judgments: JudgmentKey[]}> {
88+
async function dbIsUpToDate(startYear?: number): Promise<{upToDate: boolean, statutes: StatuteKey[], judgments: JudgmentKey[]}> {
8989
console.log('Checking if database is up to date...');
9090

9191
async function compareStatuteCount(year: number): Promise<boolean> {
@@ -218,7 +218,8 @@ async function dbIsUpToDate(): Promise<{upToDate: boolean, statutes: StatuteKey[
218218
const judgments: JudgmentKey[] = [];
219219
let upToDate = true;
220220
const currentYear = yearTo()
221-
for (let year = yearFrom(); year <= currentYear + 1; year++) {
221+
const start = startYear ?? yearFrom()
222+
for (let year = start; year <= currentYear + 1; year++) {
222223

223224
if (!await compareStatuteCount(year)) {
224225
console.log(`Statutes for year ${year} are not up to date`);

backend/src/dbSetup.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { yearFrom, yearTo } from "./util/config.js";
66

77
setPool(process.env.PG_URI ?? '');
88

9-
async function initDatabase() {
9+
async function initDatabase(startYear?: number) {
1010
try {
1111
console.log('[DB] Checking if database is ready...');
1212
if (!await dbIsReady()) {
@@ -18,9 +18,11 @@ async function initDatabase() {
1818
}
1919

2020
await clearStatusRows();
21-
await addStatusRow({ message: 'updating', from: yearFrom(), to: yearTo() }, true);
21+
const from = startYear ?? yearFrom();
22+
const to = yearTo();
23+
await addStatusRow({ message: 'updating', from, to }, true);
2224
console.log('[DB] Checking if database is up to date...');
23-
const { upToDate, statutes, judgments } = await dbIsUpToDate();
25+
const { upToDate, statutes, judgments } = await dbIsUpToDate(from);
2426

2527
console.log('[DB] Up to date:', upToDate, 'missing statutes:', statutes.length, 'missing judgements:', judgments.length);
2628

@@ -38,7 +40,7 @@ async function initDatabase() {
3840
}
3941
}
4042

41-
export const runSetup = async () => {
43+
export const runSetup = async (startYear?: number) => {
4244
try {
4345
if (process.env.NODE_ENV === 'test') {
4446
console.log('[SETUP] Running in test mode...');
@@ -47,7 +49,7 @@ export const runSetup = async () => {
4749
console.log('[SETUP] Running in production mode...');
4850

4951
console.log('[SETUP] Step 1: Initialize database...');
50-
await initDatabase();
52+
await initDatabase(startYear);
5153

5254
console.log('[SETUP] Step 2: Clear and sync Typesense collections...');
5355
await deleteCollection('statutes', 'fin');
@@ -64,7 +66,9 @@ export const runSetup = async () => {
6466
await syncJudgments('swe');
6567

6668
console.log('[SETUP] Step 5: Write completion status...');
67-
await addStatusRow({ message: 'updated', from: yearFrom(), to: yearTo(), timestamp: new Date().toISOString() }, false);
69+
const from = startYear ?? yearFrom();
70+
const to = yearTo();
71+
await addStatusRow({ message: 'updated', from, to, timestamp: new Date().toISOString() }, false);
6872
}
6973
console.log('[SETUP] Database setup done.');
7074
} catch (error) {

frontend/src/components/AdminPage.tsx

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ const AdminPage = ({ language }: AdminPageProps) => {
1919
const [error, setError] = useState('')
2020
const [latestStatus, setLatestStatus] = useState<StatusEntry | null>(null)
2121
const [hasStartedUpdate, setHasStartedUpdate] = useState(false)
22+
const [startYearInput, setStartYearInput] = useState<string>('')
2223
const intervalRef = useRef<NodeJS.Timeout | null>(null)
24+
const [defaultStartYear, setDefaultStartYear] = useState<number | null>(null)
2325

2426
const pollLatestStatus = async () => {
2527
try {
@@ -51,6 +53,25 @@ const AdminPage = ({ language }: AdminPageProps) => {
5153
}
5254
}, [])
5355

56+
// Fetch backend config (current START_YEAR) and prefill input if empty
57+
useEffect(() => {
58+
let mounted = true
59+
const fetchConfig = async () => {
60+
try {
61+
const resp = await axios.get('/api/config')
62+
const sy = resp.data?.startYear
63+
if (mounted && typeof sy === 'number') {
64+
setDefaultStartYear(sy)
65+
if (startYearInput.trim() === '') setStartYearInput(String(sy))
66+
}
67+
} catch (e) {
68+
// ignore
69+
}
70+
}
71+
fetchConfig()
72+
return () => { mounted = false }
73+
}, [])
74+
5475
const handleUpdate = async () => {
5576
setIsUpdating(true)
5677
setMessage('')
@@ -59,7 +80,12 @@ const AdminPage = ({ language }: AdminPageProps) => {
5980
setHasStartedUpdate(true)
6081

6182
try {
62-
const response = await axios.post('/api/setup')
83+
const payload: Record<string, unknown> = {}
84+
if (startYearInput.trim() !== '') {
85+
const yearNum = parseInt(startYearInput, 10)
86+
if (!Number.isNaN(yearNum)) payload.startYear = yearNum
87+
}
88+
const response = await axios.post('/api/setup', payload)
6389
setMessage(language === 'fin'
6490
? 'Päivitys aloitettu!'
6591
: 'Uppdatering startad!'
@@ -232,6 +258,17 @@ const AdminPage = ({ language }: AdminPageProps) => {
232258
</p>
233259

234260
<div style={{ display: 'flex', justifyContent: 'center', flexWrap: 'wrap' }}>
261+
<div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginRight: '10px' }}>
262+
<label style={{ fontSize: '14px' }}>{language === 'fin' ? 'Aloitusvuosi, oletuksena .env START_YEAR:' : 'Startår:'}</label>
263+
<input
264+
type="number"
265+
value={startYearInput}
266+
onChange={(e) => setStartYearInput(e.target.value)}
267+
placeholder={defaultStartYear !== null ? String(defaultStartYear) : (language === 'fin' ? 'Oletus .env START_YEAR' : 'Default from .env START_YEAR')}
268+
style={{ padding: '8px', borderRadius: '4px', border: '1px solid #ccc', width: '140px' }}
269+
/>
270+
</div>
271+
235272
<button
236273
style={buttonStyle}
237274
onClick={handleUpdate}

0 commit comments

Comments
 (0)