พอร์ต UI จาก web-at-transit-mock เข้า Next.js + data sync เข้า Postgres/SeaweedFS

- 8 หน้า (home/stops/routes/stop/check/blog/about/credits) แปลง partials → React component ตรง mock
- ตรรกะพอร์ตเป็น src/lib/ui/*.ts (mount()) + runtime/PageRuntime
- CSS: base + pages/*.css import ต่อ route (คงลำดับ cascade ของ mock)
- asset/content: public/{image,resource/data,content,locales,vendor}
- แก้ path รูปไทล์พาร์ทเนอร์ (.image → /image) + fallback absolute
- ลบ UI เดิมที่ไม่ตรง mock (expanded/stops details/old components/globals.css)
- script/sync_data_to_postgres.mjs + sync_images_to_storage.mjs (dry-run/--apply, backup)
- docs/UI-PORT.md + DESIGN.md + README
This commit is contained in:
itmeadmin committed 2026-10-23 15:50:00 +07:00
1 parent 24187fc3b7
commit 138a3d15d8
300 files changed
+20213 -1978

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""อัปโหลดรูปชุด template (frontend/public/image) เข้า SeaweedFS ผ่าน backend API.
รูปจะถูกเก็บใน core_management storage (SeaweedFS) แล้ว frontend อ่านผ่าน `/files/...`
ค่าเริ่มต้นเป็น dry-run — ต้องใส่ --apply ถึงจะอัปโหลดจริง
ตัวอย่าง:
python script/import_assets_to_storage.py --api http://localhost:8080/api --dry-run
python script/import_assets_to_storage.py --api http://localhost:8080/api --apply
รูปแบบโฟลเดอร์ -> entity:
image/stations/<station_id>.jpg -> entity_type=station, entity_id=<station_id>
image/routes/<route_id>/<file> -> entity_type=route, entity_id=<route_id>
image/stops/<code>.jpg -> entity_type=stop, entity_id=<code>
image/qrcode/<route_id>.png -> entity_type=route, entity_id=<route_id> (kind=qr)
image/{icons,partners,network,landmarks,extras}/... -> ข้าม (เป็น asset ของเว็บ ไม่ใช่รูป entity)
"""
from __future__ import annotations
import argparse
import json
import mimetypes
import os
import sys
import urllib.error
import urllib.request
import uuid
from pathlib import Path
SKIP_DIRS = {"icons", "partners", "network", "landmarks", "extras"}
IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp"}
# โฟลเดอร์ -> (entity_type, kind)
AREA_MAP = {
"stations": ("station", "photo"),
"routes": ("route", "photo"),
"stops": ("stop", "photo"),
"qrcode": ("route", "qr"),
}
def iter_assets(root: Path):
for area_dir in sorted(p for p in root.iterdir() if p.is_dir()):
area = area_dir.name
if area in SKIP_DIRS or area not in AREA_MAP:
continue
entity_type, kind = AREA_MAP[area]
for path in sorted(area_dir.rglob("*")):
if not path.is_file() or path.suffix.lower() not in IMAGE_EXTS:
continue
rel = path.relative_to(area_dir)
if area == "routes" and len(rel.parts) > 1:
entity_id = rel.parts[0]
else:
entity_id = path.stem
yield path, entity_type, entity_id, kind
def post_multipart(api: str, path: Path, entity_type: str, entity_id: str, kind: str) -> dict:
boundary = f"----atroute{uuid.uuid4().hex}"
mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
parts: list[bytes] = []
def field(name: str, value: str) -> None:
parts.append(
f"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n".encode()
)
field("entity_type", entity_type)
field("entity_id", entity_id)
field("kind", kind)
field("display_order", "0")
parts.append(
(
f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{path.name}\"\r\n"
f"Content-Type: {mime}\r\n\r\n"
).encode()
)
parts.append(path.read_bytes())
parts.append(f"\r\n--{boundary}--\r\n".encode())
body = b"".join(parts)
req = urllib.request.Request(
f"{api.rstrip('/')}/images",
data=body,
method="POST",
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
)
with urllib.request.urlopen(req, timeout=120) as res:
return json.loads(res.read().decode("utf-8") or "{}")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--api", default=os.environ.get("API_BASE", "http://localhost:8080/api"))
ap.add_argument("--dir", default="frontend/public/image")
ap.add_argument("--apply", action="store_true", help="อัปโหลดจริง (default = dry-run)")
ap.add_argument("--limit", type=int, default=0)
args = ap.parse_args()
root = Path(args.dir)
if not root.is_dir():
print(f"ไม่พบโฟลเดอร์: {root}", file=sys.stderr)
return 2
items = list(iter_assets(root))
if args.limit:
items = items[: args.limit]
ok = fail = 0
for path, entity_type, entity_id, kind in items:
label = f"{entity_type}/{entity_id}/{path.name} [{kind}]"
if not args.apply:
print(f"[dry-run] {label}")
continue
try:
res = post_multipart(args.api, path, entity_type, entity_id, kind)
print(f"[ok] {label} -> {res.get('url_path') or res.get('id') or 'uploaded'}")
ok += 1
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", "replace")[:200]
print(f"[fail] {label} HTTP {exc.code} {body}", file=sys.stderr)
fail += 1
except Exception as exc: # noqa: BLE001 - CLI
print(f"[fail] {label} {exc}", file=sys.stderr)
fail += 1
total = len(items)
print(f"\nทั้งหมด {total} ไฟล์ · สำเร็จ {ok} · ล้มเหลว {fail}" + (" (dry-run)" if not args.apply else ""))
return 0 if fail == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env node
/**
* sync_data_to_postgres.mjs — อัปเดตข้อมูลจาก mock (เครื่องนี้) เข้า Postgres บน VPS
*
* ที่มา: D:\Git\workspace\web-at-transit-mock\resource\data
* - provinces.json, route_groups.json, stations.json, routes.json
* - scheduleslist/schedules<route_id>.json
* - affiliates.json → sponsors
*
* หลักการ: upsert อย่างเดียว + แทน schedules ต่อสาย (delete→insert) ใน transaction เดียว
* มี --dry-run (default) และ --backup <dir> ก่อนเขียนจริง
*
* ต้องมีไดรเวอร์ pg:
* npm i pg (ในโฟลเดอร์ที่มี node_modules)
* NODE_PATH=<ที่เก็บ node_modules> node script/sync_data_to_postgres.mjs --apply
*
* env: PGHOST PGPORT PGUSER PGPASSWORD PGDATABASE
*/
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
const require = createRequire(process.cwd() + "/package.json");
const { Client } = require("pg");
const DATA = process.env.DATA_DIR || "D:/Git/workspace/web-at-transit-mock/resource/data";
const args = process.argv.slice(2);
const APPLY = args.includes("--apply");
const BACKUP_DIR = (() => {
const i = args.indexOf("--backup");
return i > -1 ? args[i + 1] : "C:/Users/BANK/AppData/Local/hermes/cache/scratch/db-backup";
})();
const readJSON = (name) => JSON.parse(fs.readFileSync(path.join(DATA, name), "utf8"));
function hhmm(t) {
const s = String(t || "").trim();
if (!s) return null;
return /^\d{2}:\d{2}$/.test(s) ? `${s}:00` : s;
}
function scheduleRows(file) {
const d = JSON.parse(fs.readFileSync(file, "utf8"));
const routeId = String(d.route_id || "");
if (!routeId) return [];
const rows = [];
// schema 3: { weekday: {label, directions: {ชื่อทิศ: {from_station_id, departures[]}}}, holiday: {...} }
for (const [dayKey, group] of Object.entries(d)) {
if (!group || typeof group !== "object" || Array.isArray(group) || !group.directions) continue;
if (Array.isArray(group.directions)) continue;
for (const [dirName, dir] of Object.entries(group.directions)) {
const stationId = Number(dir.from_station_id);
const times = (dir.departures || []).map(hhmm).filter(Boolean);
if (!stationId || !times.length) continue;
rows.push({
route_id: routeId,
station_id: stationId,
direction_note: dirName,
departure_times: times,
variants: { day: dayKey, label: group.label || "" },
schedule_note: null,
});
}
}
// schema 2: { directions: [{direction_id, direction_label, stops:[{station_id, times[]}]}] }
if (Array.isArray(d.directions)) {
for (const dir of d.directions) {
const label = dir.direction_label || dir.direction_id || "";
for (const stop of dir.stops || []) {
const times = (stop.times || []).map(hhmm).filter(Boolean);
if (!stop.station_id || !times.length) continue;
rows.push({
route_id: routeId,
station_id: Number(stop.station_id),
direction_note: label,
departure_times: times,
variants: { day: d.day || "weekday", label: dir.direction_label || "" },
schedule_note: null,
});
}
}
}
return rows;
}
/** enum station_kind ไม่มี local_terminal — DB เดิมเก็บเป็น main_terminal */
const STATION_TYPE = {
main_terminal: "main_terminal",
van_terminal: "van_terminal",
local_terminal: "main_terminal",
local_stop: "local_stop",
market: "market",
landmark: "landmark",
private_stop: "private_stop",
other: "other",
};
const stationType = (v) => STATION_TYPE[v] || "other";
async function main() {
const provinces = readJSON("provinces.json").provinces || [];
const groups = readJSON("route_groups.json").route_groups || [];
const stations = readJSON("stations.json").stations || [];
const routes = readJSON("routes.json").routes || [];
const affiliates = readJSON("affiliates.json").partners || [];
const schedDir = path.join(DATA, "scheduleslist");
const schedFiles = fs.existsSync(schedDir)
? fs.readdirSync(schedDir).filter((f) => /^schedules.+\.json$/.test(f))
: [];
const schedules = schedFiles.flatMap((f) => scheduleRows(path.join(schedDir, f)));
console.log(
`source: provinces=${provinces.length} groups=${groups.length} stations=${stations.length} ` +
`routes=${routes.length} schedules=${schedules.length} (files=${schedFiles.length}) partners=${affiliates.length}`,
);
const client = new Client({
host: process.env.PGHOST,
port: Number(process.env.PGPORT || 5432),
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
database: process.env.PGDATABASE,
connectionTimeoutMillis: 8000,
});
await client.connect();
// ---- backup ของเดิมก่อนเขียน ----
if (APPLY) {
fs.mkdirSync(BACKUP_DIR, { recursive: true });
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
for (const t of ["routes", "stations", "schedules", "route_stops", "route_provinces", "sponsors", "provinces", "route_groups"]) {
const { rows } = await client.query(`select * from public.${t}`);
fs.writeFileSync(path.join(BACKUP_DIR, `${t}-${stamp}.json`), JSON.stringify(rows, null, 1), "utf8");
}
console.log(`backup → ${BACKUP_DIR}`);
}
const stats = { routes: 0, stations: 0, schedules: 0, sponsors: 0 };
await client.query("begin");
try {
for (const p of provinces) {
await client.query(
`insert into public.provinces (id, name_th) values ($1,$2)
on conflict (id) do update set name_th = excluded.name_th`,
[p.province_id, p.province_name_th],
);
}
for (const g of groups) {
await client.query(
`insert into public.route_groups (id, code, label_th, display_order, is_active)
values ($1,$2,$3,$4,$5)
on conflict (id) do update set code=excluded.code, label_th=excluded.label_th,
display_order=excluded.display_order, is_active=excluded.is_active`,
[g.route_group_id, g.route_group, g.route_group_label, g.display_order ?? 0, g.is_active !== false],
);
}
for (const s of stations) {
await client.query(
`insert into public.stations (id, code, name_th, city_th, province_th, station_type, lat, lng, attributes, metadata)
values ($1,$2,$3,$4,$5,$6,$7,$8,'{}'::jsonb,'{}'::jsonb)
on conflict (id) do update set code=excluded.code, name_th=excluded.name_th,
city_th=excluded.city_th, province_th=excluded.province_th,
station_type=excluded.station_type, lat=excluded.lat, lng=excluded.lng`,
[s.station_id, s.station_code, s.station_name_th, s.city_th || null, s.province_th || null,
stationType(s.station_type), s.latitude ?? null, s.longitude ?? null],
);
stats.stations++;
}
for (const r of routes) {
const phones = (r.phone || []).map((n) => ({ label: "", number: String(n) }));
const webUrl = Array.isArray(r.web_url) ? r.web_url[1] : (r.web_url || null);
const contact = { phones, web_url: webUrl || null };
await client.query(
`insert into public.routes (route_id, name_th, vehicle_type, route_group_id, contact, metadata)
values ($1,$2,$3,$4,$5::jsonb,'{}'::jsonb)
on conflict (route_id) do update set name_th=excluded.name_th,
vehicle_type=excluded.vehicle_type, route_group_id=excluded.route_group_id,
contact=excluded.contact`,
[String(r.route_id), r.route_name_th, r.vehicle_type || "bus", r.route_group_id, JSON.stringify(contact)],
);
await client.query("delete from public.route_provinces where route_id=$1", [String(r.route_id)]);
for (const pid of r.province_ids || []) {
await client.query(
"insert into public.route_provinces (route_id, province_id) values ($1,$2) on conflict do nothing",
[String(r.route_id), pid],
);
}
await client.query("delete from public.route_stops where route_id=$1", [String(r.route_id)]);
let seq = 0;
for (const sid of r.station_ids || []) {
await client.query(
"insert into public.route_stops (route_id, station_id, stop_sequence) values ($1,$2,$3) on conflict do nothing",
[String(r.route_id), sid, ++seq],
);
}
stats.routes++;
}
const routeIds = [...new Set(schedules.map((s) => s.route_id))];
for (const rid of routeIds) {
await client.query("delete from public.schedules where route_id=$1", [rid]);
}
// schedules.id ไม่มี default (schema เดิมสร้างด้วย serial ที่หลุด) → จ่ายค่าเอง
const maxRow = await client.query("select coalesce(max(id), 0)::int as max_id from public.schedules");
let nextScheduleId = Number(maxRow.rows[0].max_id) + 1;
for (const s of schedules) {
await client.query(
`insert into public.schedules (id, route_id, station_id, direction_note, departure_times, variants, schedule_note)
values ($1,$2,$3,$4,$5::time[],$6::jsonb,$7)`,
[nextScheduleId++, s.route_id, s.station_id, s.direction_note, s.departure_times, JSON.stringify(s.variants), s.schedule_note],
);
stats.schedules++;
}
let order = 0;
for (const p of affiliates) {
await client.query(
`insert into public.sponsors (slug, name_th, website_url, display_order, is_active, meta)
values ($1,$2,$3,$4,$5,$6::jsonb)
on conflict (slug) do update set name_th=excluded.name_th, website_url=excluded.website_url,
display_order=excluded.display_order, is_active=excluded.is_active, meta=excluded.meta`,
[
p.id, p.brand_th || p.brand || p.id, p.affiliate_link || p.program_url || null, order++,
p.in_footer_marquee !== false,
JSON.stringify({ brand: p.brand || null, tile_image: p.tile_image || null, program_url: p.program_url || null, status: p.status || null }),
],
);
stats.sponsors++;
}
if (!APPLY) {
await client.query("rollback");
console.log("DRY-RUN (rollback) — ใช้ --apply เพื่อเขียนจริง");
} else {
await client.query("commit");
console.log("COMMITTED");
}
console.log(JSON.stringify(stats));
} catch (err) {
await client.query("rollback").catch(() => {});
throw err;
} finally {
await client.end();
}
}
main().catch((e) => {
console.error("FAILED:", e.code || "", e.message);
process.exit(1);
});
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/env node
/**
* sync_images_to_storage.mjs — อัปโหลดรูปจากเครื่องนี้เข้า SeaweedFS (core_management)
* แล้วบันทึกแถวในตาราง public.images
*
* ที่มา: frontend/public/image/{stations,routes,stops,qrcode}
* - stations/<id>.<ext> → entity_type=station, entity_id=<id>, kind=photo
* - routes/<route_id>/<file> → entity_type=route, entity_id=<route_id> (qr ถ้าชื่อมี qr)
* - stops/<code>.<ext> → entity_type=stop, entity_id=<code>
* - qrcode/<route_id>.<ext> → entity_type=route, entity_id=<route_id>, kind=qr
*
* ปลายทาง: PUT <STORAGE_URL>/buckets/transit/<type>/<id>/<file>
* url_path = /<type>/<id>/<file> (backend เสิร์ฟผ่าน /files/<url_path>)
*
* ใช้: node script/sync_images_to_storage.mjs [--apply] [--limit N]
* env: STORAGE_URL (default http://103.107.52.82:3103), PGHOST/PGPORT/PGUSER/PGPASSWORD/PGDATABASE
*/
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { createRequire } from "node:module";
const require = createRequire(process.cwd() + "/package.json");
const { Client } = require("pg");
const ROOT = process.env.IMAGE_DIR || "D:/Git/workspace/web-at-transit/frontend/public/image";
const STORAGE = (process.env.STORAGE_URL || "http://103.107.52.82:3103").replace(/\/$/, "");
const BUCKET = "/buckets/transit";
const args = process.argv.slice(2);
const APPLY = args.includes("--apply");
const LIMIT = (() => {
const i = args.indexOf("--limit");
return i > -1 ? Number(args[i + 1]) : 0;
})();
const EXT_OK = new Set([".jpg", ".jpeg", ".png", ".webp"]);
const SKIP_DIRS = new Set(["icons", "partners", "network", "landmarks", "extras", "_original"]);
const MIME = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp" };
function collect() {
const out = [];
for (const area of fs.readdirSync(ROOT)) {
if (SKIP_DIRS.has(area)) continue;
const areaDir = path.join(ROOT, area);
if (!fs.statSync(areaDir).isDirectory()) continue;
for (const entry of fs.readdirSync(areaDir)) {
const full = path.join(areaDir, entry);
const stat = fs.statSync(full);
let files = [];
let entityId;
let type;
if (stat.isDirectory()) {
if (area !== "routes") continue;
type = "route";
entityId = entry;
files = fs.readdirSync(full).map((f) => path.join(full, f));
} else {
if (area === "stations") type = "station";
// schema ไม่รองรับ entity_type=stop (CHECK อนุญาต route/station/sponsor/province/bus/misc)
else if (area === "stops") continue;
else if (area === "qrcode") type = "route";
else continue;
entityId = path.basename(entry, path.extname(entry));
files = [full];
}
for (const f of files) {
const ext = path.extname(f).toLowerCase();
if (!EXT_OK.has(ext)) continue;
const name = path.basename(f);
// kind ที่ CHECK ยอมรับ: photo | logo | icon | map | hero
const kind = "photo";
out.push({ file: f, ext, type, entityId, kind, name });
}
}
}
return out;
}
async function main() {
let items = collect();
if (LIMIT) items = items.slice(0, LIMIT);
console.log(`images: ${items.length} ไฟล์ (apply=${APPLY}) storage=${STORAGE}`);
const client = new Client({
host: process.env.PGHOST,
port: Number(process.env.PGPORT || 5432),
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
database: process.env.PGDATABASE,
connectionTimeoutMillis: 8000,
});
await client.connect();
let uploaded = 0;
let skipped = 0;
let failed = 0;
for (const it of items) {
const urlPath = `/${it.type}/${it.entityId}/${it.name}`;
const fid = `${BUCKET}${urlPath}`;
const exists = await client.query("select 1 from public.images where url_path = $1 limit 1", [urlPath]);
if (exists.rowCount) {
skipped++;
continue;
}
if (!APPLY) {
console.log(`[dry-run] ${it.type}/${it.entityId} ${it.name} (${it.kind})`);
continue;
}
const buf = fs.readFileSync(it.file);
try {
const res = await fetch(`${STORAGE}${fid}`, {
method: "PUT",
headers: { "Content-Type": MIME[it.ext] || "application/octet-stream" },
body: buf,
});
if (!res.ok) throw new Error(`storage ${res.status}`);
const sha = crypto.createHash("sha256").update(buf).digest("hex");
await client.query(
`insert into public.images (id, entity_type, entity_id, kind, fid, url_path, display_order, meta)
values ($1,$2,$3,$4,$5,$6,0,$7::jsonb)`,
[
crypto.randomUUID(),
it.type,
String(it.entityId),
it.kind,
fid,
urlPath,
JSON.stringify({ mime: MIME[it.ext], size_bytes: buf.length, sha256: sha }),
],
);
uploaded++;
console.log(`[ok] ${urlPath}`);
} catch (e) {
failed++;
console.error(`[fail] ${urlPath}: ${e.message}`);
}
}
console.log(JSON.stringify({ uploaded, skipped, failed, total: items.length }));
await client.end();
}
main().catch((e) => {
console.error("FAILED:", e.code || "", e.message);
process.exit(1);
});