Schedules — กติกา "จุดนี้ = เวลาจุดอ้างอิง ± n นาที"
- ฟิลด์ derive { from_station_id, offset_min } คำนวณที่ ui/partials/schedules.js (ท่อเดียว) รองรับอ้างจุดข้ามทิศ
- จุดย่อยของ "8 other_stop" ใช้ offsets_min จับคู่ตามลำดับ (เช่น ตลาดสามโก้ = ตลาดท่าช้าง +45 นาที)
- เครื่องมือ resource/tools/derive-times.py + ตาราง resource/data/derive-times.csv (--check / --audit ชี้จุดที่ควรตั้งกฎ)
- แยกตารางเป็นรายสาย: scheduleslist/schedules<route_id>.json และ schedules.json เป็นสารบัญ (โหลดแบบ lazy + cache)
- ตรวจจับวันทำงาน/วันหยุด + schema 3 (weekday/holiday → directions) · ไฟล์ข้อมูลเป็น CRLF ทั้งชุด
- ล้างค่าที่ไม่ใช่ HH:MM ที่ฝังใน times (ทำให้ KPI เพี้ยน) + กันค่าหลอกในตัวสรุปเวลา
UI
- หน้ารายละเอียดป้าย/ตารางเวลา ขับเคลื่อนด้วย JSON (stopDetail.init.js) · จุดขึ้นรถประจำทางอื่นๆ รองรับหลายจุดต่อสาย
- #/stops: แสดง 6 ป้ายแรก + ปุ่ม "แสดงป้ายทั้งหมด" (โหลดรูปเฉพาะที่แสดง) · ชิปสาย → #/routes/<route_id>
- หน้าแรก: ตัดตัวเลือก "ทุกสถานีในจังหวัดนี้" · ตัวกรองจังหวัด/สถานี + ปุ่มแชร์ (share URL)
- การ์ดติดต่อ: ไอคอน/ชื่อ/สีเปลี่ยนตามชนิด URL (Facebook / LINE / เว็บไซต์) + ปุ่มเปิดลิงก์จาก web_url
- รูปรองรับหลายนามสกุล (.jpg → .jpeg → .webp → .png) · ป้าย "ประมาณ" + หมายเหตุสำหรับตารางที่คำนวณ
- หน้าเครดิตเหลือ 3 หมวด · แก้ข้อความหมวดแผนที่ให้ตรงกับข้อมูลจริง
- แผนที่ Leaflet (vendor ในโปรเจกต์ ไม่ใช้ CDN): เส้นทาง + หมุด + ป๊อปอัป · แก้ CSS ที่ทำให้ SVG ยุบ 0x0
เครื่องมือและเอกสาร
- qgis-to-web.py อ่าน .shp ตรง → geojson-web (สร้างใหม่ 10 ไฟล์) + audit-geojson.py ตรวจ 3 ส่วน
- stop-km.py วัดระยะ กม. ตามเส้นจริง → stop-km.json · schedules-editor.html (แก้ทีละไฟล์ · มุมมองตารางแบบ Excel)
- AGENTS.md: กติกา derive · offsets_min · นามสกุลรูป · ชิปสาย · หน้ารายละเอียดป้ายมาจากไหน
619 lines
39 KiB
JavaScript
619 lines
39 KiB
JavaScript
/* ============================================================
|
|
schedules.js — ตัวอ่านข้อมูลตารางเวลา (ใช้ร่วมทุกหน้า)
|
|
|
|
***APIs นี้ไม่เปลี่ยนชื่อ/รูปเดิม*** — หน้า check/busDetail/home/stopDetail เรียกเหมือนเดิม
|
|
ที่เพิ่มเข้ามาคือ "สมองเรื่องวันทำงาน/วันหยุด" ซึ่งทำงานอยู่ในไฟล์นี้ที่เดียว
|
|
|
|
รองรับ schedules.json 2 รูปแบบ:
|
|
schema 1 (เดิม): { "schedules": [ { route_id, station_id, direction_note, departure_times[], schedule_note } ] }
|
|
schema 2 (ใหม่): { "schema": 2, "routes": [ { route_id, station_order[], directions: [
|
|
{ dir_id, dir_label, service?, stops: [ { station_id, times[], dir_note?, note?, groups? } ] } ] } ] }
|
|
|
|
── เรื่องวันทำงาน / วันหยุด (ไม่ต้องแก้โค้ดหน้าไหนเลย) ────────────────
|
|
เพิ่มฟิลด์ "ไม่บังคับ" 2 ระดับ:
|
|
1) ระดับทิศทาง: "service": "all" | "weekday" | "holiday"
|
|
- ทั้งทิศทางใช้เฉพาะวันนั้น (เช่น ทิศ 'ตารางวันหยุด' → service: "holiday")
|
|
- ไม่ใส่ = "all" (ทุกวัน) → ไฟล์เดิมไม่ต้องแก้อะไร พฤติกรรมเหมือนเดิมเป๊ะ
|
|
2) ระดับจุดจอด: "groups": [ { "label": "วันหยุด", "dayType": "holiday", "times": ["10:00"] } ]
|
|
- เวลาที่ "เพิ่มเข้ามาเฉพาะบางวัน" (ตรงกับโน้ตเดิม เช่น "10:00 มีเฉพาะวันหยุด")
|
|
- times[] ยังเป็นตารางพื้นฐานที่ใช้ทุกวัน
|
|
|
|
ค่าเริ่มต้น: ตรวจจากวันที่ของเครื่องเอง (เสาร์–อาทิตย์ = วันหยุด + วันนักขัตฤกษ์จาก holidays.json)
|
|
ความปลอดภัย: ถ้ากรองตามวันแล้วไม่เหลือทิศทางใดเลย → ถอยไปใช้ทั้งหมด + ติดธง fallback (หน้าเว็บไม่ว่าง)
|
|
|
|
API:
|
|
Schedules.records(doc, opts) → record แบน (schema เดิม) สำหรับโค้ดเดิม
|
|
Schedules.route(doc, routeId, opts) → { route_id, station_order[], directions[], entries[] }
|
|
Schedules.directions(doc, routeId, opts) → [{ dir_id, dir_label, service, dayType, fallback, stops[] }]
|
|
Schedules.times(doc, routeId, opts) → เวลาทั้งหมดของสาย (เรียงแล้ว)
|
|
Schedules.countTrips(doc, routeId, opts) → จำนวนเที่ยวของสาย
|
|
Schedules.todayType() → 'weekday' | 'holiday'
|
|
Schedules.dayInfo(date) → { dayType, label_th, date }
|
|
Schedules.ready → promise (โหลด holidays.json เสร็จ)
|
|
opts ที่รับได้: { dayType: 'all' | 'weekday' | 'holiday' } (ไม่ส่ง = ตรวจจากวันนี้)
|
|
============================================================ */
|
|
(function () {
|
|
'use strict';
|
|
|
|
var DATA_URL = '../resource/data/';
|
|
var HOLIDAYS = [];
|
|
var ALIAS = { weekend: 'holiday', 'sat-sun': 'holiday', saturday: 'holiday', sunday: 'holiday', workday: 'weekday', weekday: 'weekday', holiday: 'holiday', all: 'all' };
|
|
|
|
/* ความเร็วเฉลี่ยตั้งต้นสำหรับคำนวณเวลาจุดที่ไม่มีตาราง (ปรับต่อทิศได้ด้วย "speedKmh") */
|
|
var DEFAULT_SPEED_KMH = 40;
|
|
|
|
function pad2(n) { return (n < 10 ? '0' : '') + n; }
|
|
function toMin(hhmm) {
|
|
var a = String(hhmm).split(':');
|
|
var h = parseInt(a[0], 10), m = parseInt(a[1], 10);
|
|
return (isNaN(h) ? 0 : h) * 60 + (isNaN(m) ? 0 : m);
|
|
}
|
|
|
|
/* คำนวณเวลาของจุดที่ไม่มีตาราง จากจุดที่มีเวลาแล้วซึ่งอยู่ใกล้ที่สุดตามระยะทาง (กม.)
|
|
คืน null เมื่อคำนวณไม่ได้ (ไม่มี กม. หรือไม่มีจุดอ้างอิง) */
|
|
function computeTimes(stop, siblings, opts) {
|
|
var o = (typeof opts === 'number') ? { speedKmh: opts } : (opts || {});
|
|
var speed = Number(o.speedKmh) > 0 ? Number(o.speedKmh) : DEFAULT_SPEED_KMH;
|
|
if (!stop || typeof stop.km !== 'number') return null;
|
|
var cands = siblings.filter(function (s) {
|
|
return s !== stop && typeof s.km === 'number' && (s.times || []).length;
|
|
});
|
|
if (!cands.length) return null;
|
|
var base = null;
|
|
if (o.baseSid != null) { /* ผู้ใช้เลือกจุดอ้างอิงเอง (จากเครื่องมือแก้ไข) */
|
|
base = cands.filter(function (s) { return String(s.station_id) === String(o.baseSid); })[0] || null;
|
|
}
|
|
if (!base && o.baseEnd === 'first') { /* ใช้เวลาจริงจากจุดต้นทาง (กม. น้อยสุด) */
|
|
base = cands.reduce(function (a, b) { return a.km <= b.km ? a : b; });
|
|
} else if (!base && o.baseEnd === 'last') { /* ใช้เวลาจริงจากจุดปลายทาง (กม. มากสุด) */
|
|
base = cands.reduce(function (a, b) { return a.km >= b.km ? a : b; });
|
|
} else if (!base) { /* อัตโนมัติ: จุดที่มีเวลาซึ่งใกล้ที่สุด */
|
|
base = cands.reduce(function (a, b) { return Math.abs(b.km - stop.km) < Math.abs(a.km - stop.km) ? b : a; });
|
|
}
|
|
var delta = (stop.km - base.km) / speed * 60; /* นาที (+ ไปข้างหน้า, - ย้อนหลัง) */
|
|
return base.times.map(function (t) {
|
|
var tot = Math.round(toMin(t) + delta);
|
|
tot = ((tot % 1440) + 1440) % 1440;
|
|
return pad2(Math.floor(tot / 60)) + ':' + pad2(tot % 60);
|
|
});
|
|
}
|
|
|
|
/* ความเร็วที่ใช้จริงของทิศหนึ่ง ๆ: มาจาก travelMin (เวลาเดินทางทั้งเส้น) ถ้ามี ไม่งั้นใช้ speedKmh/ค่าตั้งต้น */
|
|
function speedOf(dir) {
|
|
if (Number(dir.travelMin) > 0) {
|
|
var kms = (dir.stops || []).map(function (s) { return s.km; }).filter(function (x) { return typeof x === 'number'; });
|
|
if (kms.length > 1) {
|
|
var span = Math.max.apply(null, kms) - Math.min.apply(null, kms);
|
|
if (span > 0) return { kmh: span / Number(dir.travelMin) * 60, span: span, source: 'travelMin' };
|
|
}
|
|
}
|
|
return { kmh: Number(dir.speedKmh) > 0 ? Number(dir.speedKmh) : DEFAULT_SPEED_KMH, span: null, source: 'speedKmh' };
|
|
}
|
|
|
|
function hasSchema2(doc) {
|
|
return !!(doc && doc.schema === 2 && Array.isArray(doc.routes));
|
|
}
|
|
function normSub(doc) { /* เตรียมไฟล์ย่อยให้อยู่ในรูป { routes: [...] } */
|
|
if (!doc) return null;
|
|
if (doc.route_id != null && !Array.isArray(doc.routes)) {
|
|
var dirs = isSchema3(doc) ? directionsFromSchema3(doc) : (doc.directions || []);
|
|
return { schema: 2, routes: [{ route_id: doc.route_id, station_order: doc.station_order || [], directions: dirs }] };
|
|
}
|
|
return doc;
|
|
}
|
|
|
|
/* ---------- schema 3: { weekday:{directions:{...}}, holiday:{directions:{...}} } ----------
|
|
โครงอ่านง่ายสำหรับเจ้าของข้อมูล (กลุ่มวัน → ทิศทาง) · แปลงเป็นทิศภายในให้ทุกหน้าใช้ต่อได้เหมือนเดิม
|
|
กติกา: จุดที่ระบุเวลามา = จุดตั้งต้นของทิศนั้น · จุดอื่นใน station_order คำนวณจาก กม.+ความเร็ว (ถ้าเปิด autoTimes) */
|
|
var DAYGROUP = { weekday: 'weekday', holiday: 'holiday' };
|
|
function isSchema3(doc) { return !!(doc && doc.schema === 3 && (doc.weekday || doc.holiday)); }
|
|
function directionsFromSchema3(doc) {
|
|
var out = [];
|
|
['weekday', 'holiday'].forEach(function (kind) {
|
|
var grp = doc[kind];
|
|
if (!grp || !grp.directions) return;
|
|
Object.keys(grp.directions).forEach(function (name) {
|
|
var src = grp.directions[name] || {};
|
|
var times = (src.departures || src.times || []).slice();
|
|
var from = (src.from_station_id != null) ? Number(src.from_station_id) : null;
|
|
var stops = [];
|
|
if (from != null && times.length) {
|
|
stops.push({ station_id: from, times: times, dir_note: grp.label || null });
|
|
} else if (from != null) {
|
|
stops.push({ station_id: from, times: [], dir_note: grp.label || null });
|
|
}
|
|
out.push({
|
|
dir_id: kind + ':' + name,
|
|
dir_label: name,
|
|
service: { day: kind, from: 'schema 3', matches: kind === todayType() },
|
|
station_order: doc.station_order || [],
|
|
stops: stops,
|
|
/* จุดตั้งต้นมีเวลาแล้ว → ให้จุดอื่นคำนวณต่อจาก กม. เฉพาะเมื่อเปิด autoTimes */
|
|
autoTimes: !!doc.autoTimes
|
|
});
|
|
});
|
|
});
|
|
return out;
|
|
}
|
|
|
|
/* ---------- ชื่อจุดจอด (สำหรับข้อความ "คำนวณจาก ...") ----------
|
|
โหลดเบื้องหลังครั้งเดียว — ถ้ายังไม่ทัน ก็ถอยไปใช้รหัสจุดในข้อความ (ไม่พัง) */
|
|
var STATION_NAMES = {};
|
|
var namesWarmed = false;
|
|
function warmStations() {
|
|
if (namesWarmed) return;
|
|
namesWarmed = true;
|
|
fetch(DATA_URL + 'stations.json', { cache: 'no-store' })
|
|
.then(function (r) { return r.ok ? r.json() : null; })
|
|
.then(function (d) {
|
|
((d && d.stations) || []).forEach(function (st) { STATION_NAMES[String(st.station_id)] = st.station_name_th; });
|
|
})
|
|
.catch(function () {});
|
|
}
|
|
function stationNameOf(id) { return STATION_NAMES[String(id)] || null; }
|
|
/* หน้าเว็บที่โหลด stations.json อยู่แล้วส่งชื่อเข้ามาได้ → ข้อความหมายเหตุมีชื่อทันที (ไม่ต้องรอ fetch) */
|
|
function setStationNames(list) {
|
|
((list && list.stations) || list || []).forEach(function (st) {
|
|
if (st && st.station_id != null) STATION_NAMES[String(st.station_id)] = st.station_name_th;
|
|
});
|
|
}
|
|
/* เรียกทันทีตอนไฟล์ถูกโหลด — จะทันรอบเรนเดอร์แรก (ชื่อจุดอ้างอิงในข้อความ "คำนวณจาก ...") */
|
|
warmStations();
|
|
|
|
/* ---------- เลื่อนเวลาเป็นนาที (กฎ derive: จุดนี้ = เวลาจุดอ้างอิง ± offset) ----------
|
|
คืน HH:MM เรียงใหม่ · เกินเที่ยงคืน = วนกลับ (ไม่พัง) */
|
|
function shiftTimes(times, offsetMin) {
|
|
var off = Number(offsetMin) || 0;
|
|
return (times || []).map(function (t) {
|
|
var a = String(t).split(':');
|
|
var m = (parseInt(a[0], 10) || 0) * 60 + (parseInt(a[1], 10) || 0) + off;
|
|
m = ((m % 1440) + 1440) % 1440;
|
|
var hh = Math.floor(m / 60), mm = m % 60;
|
|
return (hh < 10 ? '0' : '') + hh + ':' + (mm < 10 ? '0' : '') + mm;
|
|
}).sort();
|
|
}
|
|
/* ป้ายผลต่างเวลา เช่น +30 / −15 (ใช้ในข้อความหมายเหตุ) */
|
|
function offsetLabel(min) {
|
|
var n = Number(min) || 0;
|
|
var sign = n < 0 ? '\u2212' : '+';
|
|
return sign + Math.abs(n);
|
|
}
|
|
|
|
/* ---------- เครื่องยนต์ตรวจวัน (จันทร์–อาทิตย์) ----------
|
|
ทำงานที่ท่อกลางนี้ที่เดียว → ทุกหน้าได้ผลเหมือนกัน ไม่ต้องแก้โค้ดหน้าไหน
|
|
ลำดับการตัดสิน:
|
|
1) ถ้าทิศมี "days" ระบุตรง ๆ (อา จ อ พ พฤ ศ ส) → ใช้ตามนั้น (แม่นสุด)
|
|
2) ถ้ามี service = weekday/holiday → เทียบกับวันนี้
|
|
3) ถ้าไม่มีอะไรระบุ → อ่านคำใน dir_label / dir_note / note ของสายนั้น (ตรวจคำอัตโนมัติ)
|
|
4) ตัดสินไม่ได้ → แสดงทุกวัน (ไม่ซ่อนข้อมูล) พร้อมป้ายว่า "ยังไม่ระบุวัน" */
|
|
var DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; /* ตรงกับ Date.getDay() */
|
|
var DAY_TH = { sun: 'อาทิตย์', mon: 'จันทร์', tue: 'อังคาร', wed: 'พุธ', thu: 'พฤหัสบดี', fri: 'ศุกร์', sat: 'เสาร์' };
|
|
var DAY_ABBR = { sun: 'อา', mon: 'จ', tue: 'อ', wed: 'พ', thu: 'พฤ', fri: 'ศ', sat: 'ส' };
|
|
var DAY_ALIAS = { /* รับได้หลายชื่อ */
|
|
weekday: 'weekday', workday: 'weekday', 'วันทำงาน': 'weekday', 'จ-ศ': 'weekday', 'จ–ศ': 'weekday',
|
|
holiday: 'holiday', weekend: 'holiday', 'วันหยุด': 'holiday', 'ส-อา': 'holiday', 'ส–อา': 'holiday', 'เสาร์-อาทิตย์': 'holiday',
|
|
all: 'all', ทุกวัน: 'all', daily: 'all'
|
|
};
|
|
var DAY_WORDS_HOLIDAY = ['วันหยุด', 'นักขัตฤกษ์', 'เสาร์-อาทิตย์', 'เสาร์–อาทิตย์', 'ส-อา', 'ส–อา', 'weekend', 'holiday'];
|
|
var DAY_WORDS_WEEKDAY = ['วันทำงาน', 'วันธรรมดา', 'จ-ศ', 'จ–ศ', 'จันทร์ถึงศุกร์', 'weekday', 'workday'];
|
|
|
|
function ymd(d) {
|
|
var m = d.getMonth() + 1, day = d.getDate();
|
|
return d.getFullYear() + '-' + (m < 10 ? '0' : '') + m + '-' + (day < 10 ? '0' : '') + day;
|
|
}
|
|
function dayKey(date) { return DAYS[(date || new Date()).getDay()]; }
|
|
function isHolidayDate(date, list) {
|
|
var list_ = list || HOLIDAYS;
|
|
if (list_.indexOf(ymd(date)) !== -1) return true; /* นักขัตฤกษ์ */
|
|
var wd = (date.getDay() + 6) % 7; /* 0 = จันทร์ */
|
|
return wd >= 5; /* เสาร์–อาทิตย์ = วันหยุด */
|
|
}
|
|
function dayTypeOf(date, list) { return isHolidayDate(date || new Date(), list) ? 'holiday' : 'weekday'; }
|
|
function todayType(date) { return dayTypeOf(date); }
|
|
function dayInfo(date) {
|
|
var d = date || new Date();
|
|
var t = dayTypeOf(d);
|
|
return { dayType: t, weekday: DAYS[d.getDay()], weekday_th: DAY_TH[DAYS[d.getDay()]], date: ymd(d),
|
|
label_th: t === 'holiday' ? 'วันหยุด (ส–อา/นักขัตฤกษ์)' : 'วันทำงาน (จ–ศ)' };
|
|
}
|
|
/* ตรวจคำในข้อความ (dir_label / dir_note / note) ว่าหมายถึงวันไหน */
|
|
function detectDay(text) {
|
|
var t = String(text == null ? '' : text).trim();
|
|
if (!t) return null;
|
|
var low = t.toLowerCase();
|
|
var hitH = DAY_WORDS_HOLIDAY.filter(function (w) { return low.indexOf(w.toLowerCase()) !== -1; })[0];
|
|
var hitW = DAY_WORDS_WEEKDAY.filter(function (w) { return low.indexOf(w.toLowerCase()) !== -1; })[0];
|
|
if (hitH && !hitW) return { day: 'holiday', from: 'คำ', text: t };
|
|
if (hitW && !hitH) return { day: 'weekday', from: 'คำ', text: t };
|
|
return null; /* เจอทั้งคู่/ไม่เจอ = ไม่เดา */
|
|
}
|
|
/* รวบข้อความทั้งหมดของทิศ (label + โน้ตของทุกจุด) แล้วตรวจหา "วัน" ให้สอดคล้องกันทั้งทิศ
|
|
คืน { day, from, text } หรือ null (ยังไม่ระบุ) */
|
|
function detectDayOfDir(d) {
|
|
var texts = [];
|
|
if (d && d.dir_label) texts.push(d.dir_label);
|
|
((d && d.stops) || []).forEach(function (s) {
|
|
if (s.dir_note) texts.push(s.dir_note);
|
|
if (s.note) texts.push(s.note);
|
|
});
|
|
var verdicts = [], conflicts = false, hasHol = false, hasWk = false, sample = null;
|
|
texts.forEach(function (t) {
|
|
var v = detectDay(t);
|
|
if (!v) { return; }
|
|
if (v.day === 'holiday') { hasHol = true; } else { hasWk = true; }
|
|
verdicts.push(v); if (!sample) sample = v;
|
|
});
|
|
if (!verdicts.length) return null;
|
|
if (hasHol && hasWk) { /* ทิศเดียวมีทั้งสองวัน */
|
|
return { day: 'all', from: 'ปนกัน', text: sample.text, conflict: true };
|
|
}
|
|
return { day: verdicts[0].day, from: 'คำในโน้ต', text: sample.text };
|
|
}
|
|
/* วันนี้ตรงกับทิศนี้ไหม + บอกเหตุผล (ใช้แสดงบนหน้าเว็บได้) */
|
|
function serviceOf(obj, dirForDetect) {
|
|
if (obj && obj.days && obj.days.length) { /* ระบุวันตรง ๆ มาก่อน */
|
|
return { day: 'custom', days: obj.days.map(String), from: 'ระบุตรง', matches: obj.days.map(String).indexOf(dayKey()) !== -1 };
|
|
}
|
|
var s = (obj && obj.service) ? String(obj.service).toLowerCase() : '';
|
|
var alias = DAY_ALIAS[s] || (DAY_ALIAS[String(obj && obj.service)] || '');
|
|
if (alias === 'weekday' || alias === 'holiday') {
|
|
return { day: alias, from: 'service', matches: alias === todayType() };
|
|
}
|
|
if (alias === 'all') return { day: 'all', from: 'service', matches: true };
|
|
var det = detectDayOfDir(dirForDetect || obj); /* ไม่ระบุ → ตรวจจากคำ */
|
|
if (det) {
|
|
if (det.day === 'all') return { day: 'all', from: det.from + ' (ปนกัน)', text: det.text, conflict: true, matches: true };
|
|
return { day: det.day, from: det.from, text: det.text, matches: det.day === todayType() };
|
|
}
|
|
return { day: 'all', from: 'ไม่ระบุ', unknown: true, matches: true }; /* ไม่รู้ = แสดง (ไม่ซ่อนข้อมูล) */
|
|
}
|
|
function normDay(opts) {
|
|
if (opts && opts.dayType) return DAY_ALIAS[String(opts.dayType).toLowerCase()] || 'all';
|
|
return todayType();
|
|
}
|
|
|
|
/* ตัดสินว่าทิศนี้ใช้กับวันที่กำลังดูอยู่ไหม
|
|
service = ผลจาก serviceOf() → { day, matches, conflict?, unknown? } */
|
|
function applies(info, day) {
|
|
if (!day || day === 'all') return true; /* ไม่ระบุวัน = ดูทุกวัน */
|
|
if (!info || typeof info !== 'object') return true;
|
|
if (info.unknown) return true; /* ยังไม่ระบุวัน → แสดง (ไม่ซ่อนข้อมูล) */
|
|
if (info.conflict) return true; /* ทิศเดียวมีทั้ง 2 ตาราง → ซ่อนไม่ได้ (จะหายข้อมูล) */
|
|
if (info.day === 'custom') { /* ระบุวันตรง ๆ (days[]) */
|
|
return !info.days || info.days.indexOf(dayKey(dayDate(day))) !== -1;
|
|
}
|
|
return info.day === 'all' || info.day === day; /* เทียบกับวันที่กำลังดู ไม่ใช่ค่าของวันนี้ */
|
|
}
|
|
/* 'weekday' / 'holiday' → วันที่สมมติขึ้นมา (ใช้ตรวจ days[] ให้ตรงกับวันที่ขอ) */
|
|
function dayDate(day) {
|
|
var d = new Date();
|
|
if (day === 'weekday') { var wd = (d.getDay() + 6) % 7; d.setDate(d.getDate() - wd); }
|
|
else if (day === 'holiday') { var wd2 = (d.getDay() + 6) % 7; d.setDate(d.getDate() + (5 - wd2)); }
|
|
return d;
|
|
}
|
|
function normDay(opts) {
|
|
if (opts && opts.dayType) return ALIAS[String(opts.dayType).toLowerCase()] || 'all';
|
|
return todayType(); /* ค่าเริ่มต้น: ตรวจจากวันนี้ */
|
|
}
|
|
|
|
/* เวลาของจุดจอด ณ วันหนึ่ง ๆ = times พื้นฐาน + groups ที่ตรงกับวันนั้น */
|
|
/* timesFor(stop, day) — day ที่ส่งมา (weekday/holiday) = "วันเป้าหมาย" ที่ต้องการดู
|
|
ทิศที่ผ่านการกรองวันมาแล้วจะส่ง day='all' → คืน times ตรง ๆ · ส่วนที่ยังไม่แยกวันใช้ groups แยกเอง */
|
|
function timesFor(stop, day) {
|
|
var groups = (stop && stop.groups) || [];
|
|
if (!groups.length) return (stop && stop.times ? stop.times : []).slice();
|
|
var out = ((stop && stop.times) || []).slice(); /* เวลาที่ไม่ผูกวัน = ใช้ทุกวัน */
|
|
groups.forEach(function (g) {
|
|
var gt = g.dayType ? (ALIAS[String(g.dayType).toLowerCase()] || 'all') : 'all';
|
|
if (gt !== 'all' && day && day !== 'all' && gt !== day) return;
|
|
out = out.concat(g.times || []);
|
|
});
|
|
return out;
|
|
}
|
|
|
|
/* ---------- โหลดข้อมูล: schedules.json เป็นได้ทั้ง "ไฟล์รวม" และ "สารบัญ" ----------
|
|
- สารบัญ (index: true): routes[] มี { route_id, file } → โหลดเฉพาะไฟล์ของสายที่ขอ (lazy + cache)
|
|
- ไฟล์รวม (schema 2 เดิม): มี routes[] พร้อม directions ในตัว → ใช้ได้เหมือนเดิมไม่ต้องแก้โค้ดเก่า
|
|
- schema 1 เดิม: { schedules: [...] } → ใช้ได้เหมือนเดิม */
|
|
var SUBS = {}; /* cache ไฟล์ย่อยต่อสาย */
|
|
var subsReady = null;
|
|
function loadSubs() {
|
|
if (subsReady) return subsReady;
|
|
subsReady = fetch(DATA_URL + 'schedules.json', { cache: 'no-store' })
|
|
.then(function (r) { return r.ok ? r.json() : null; })
|
|
.then(function (d) {
|
|
if (!d || !d.index) return d; /* ไฟล์รวม → คืนทั้งไฟล์ */
|
|
var rows = d.routes || [];
|
|
return Promise.all(rows.map(function (row) {
|
|
var file = row.file || ('schedules' + row.route_id + '.json');
|
|
return fetch(DATA_URL + 'scheduleslist/' + file, { cache: 'no-store' })
|
|
.then(function (x) { return x.ok ? x.json() : null; })
|
|
.then(function (sub) {
|
|
if (!sub) return null;
|
|
var dirs = isSchema3(sub) ? directionsFromSchema3(sub) : (sub.directions || []);
|
|
SUBS[String(sub.route_id)] = { route_id: sub.route_id, station_order: sub.station_order || [],
|
|
directions: dirs, schema3: isSchema3(sub) };
|
|
return SUBS[String(sub.route_id)];
|
|
}).catch(function () { return null; });
|
|
})).then(function (list) {
|
|
var routes = list.filter(Boolean);
|
|
return { schema: 2, index: true, routes: routes };
|
|
});
|
|
})
|
|
.catch(function () { return null; });
|
|
return subsReady;
|
|
}
|
|
/* โหลดสายเดียว (เร็ว — ใช้ตอนเปิดหน้า check/routes ของสายนั้น) */
|
|
function loadRoute(rid) {
|
|
var key = String(rid);
|
|
if (SUBS[key]) return Promise.resolve({ schema: 2, routes: [SUBS[key]] });
|
|
if (!subsReady) return loadSubs().then(function () { return SUBS[key] ? { schema: 2, routes: [SUBS[key]] } : null; });
|
|
return Promise.resolve(SUBS[key] ? { schema: 2, routes: [SUBS[key]] } : null);
|
|
}
|
|
|
|
/* ---------- ระยะทาง กม. (ไฟล์แยก resource/data/stop-km.json — สร้างโดย resource/tools/stop-km.py) ----------
|
|
แยกไฟล์เพราะ schedules.json เป็นไฟล์ที่คนแก้มือ ถ้าเอาค่าคำนวณไปฝังไว้ พอบันทึกทับจากสำเนาเก่าจะหายทั้งชุด */
|
|
var KM = {};
|
|
var kmReady = null;
|
|
function loadKm() {
|
|
if (kmReady) return kmReady;
|
|
kmReady = fetch(DATA_URL + 'stop-km.json', { cache: 'no-store' })
|
|
.then(function (r) { return r.ok ? r.json() : null; })
|
|
.then(function (d) {
|
|
KM = (d && typeof d === 'object') ? d : {};
|
|
try { window.dispatchEvent(new CustomEvent('schedules:km', { detail: { routes: Object.keys(KM).length } })); } catch (e) { }
|
|
return KM;
|
|
})
|
|
.catch(function () { KM = {}; return KM; });
|
|
return kmReady;
|
|
}
|
|
function absKm(rid, sid) {
|
|
var r = KM[String(rid)];
|
|
if (!r) return null;
|
|
var v = r[String(sid)];
|
|
return (typeof v === 'number') ? v : null;
|
|
}
|
|
/* km ของจุดในทิศนั้น — พลิกให้ "เพิ่มขึ้นตามทางที่รถวิ่ง" เพื่อให้ผลต่างมีเครื่องหมายถูกต้องเอง
|
|
(ลำดับจุดในทิศ + กม.จริงบนเส้น เป็นตัวบอกทิศ) */
|
|
function relKms(rid, stops) {
|
|
var abs = (stops || []).map(function (s, i) {
|
|
var k = (s && typeof s.km === 'number') ? s.km : (s ? absKm(rid, s.station_id) : null);
|
|
return (typeof k === 'number') ? { i: i, k: k } : null;
|
|
});
|
|
var known = abs.filter(Boolean);
|
|
if (known.length < 2) {
|
|
return (stops || []).map(function (s) {
|
|
if (s && typeof s.km === 'number') return s.km;
|
|
return s ? absKm(rid, s.station_id) : null;
|
|
});
|
|
}
|
|
var forward = known[known.length - 1].k >= known[0].k; /* ทิศนี้วิ่งจาก กม. น้อย → มาก ใช่ไหม */
|
|
var max = known.reduce(function (a, b) { return b.k > a ? b.k : a; }, known[0].k);
|
|
return abs.map(function (x) { if (!x) return null; return forward ? x.k : (max - x.k); });
|
|
}
|
|
|
|
/* โหลด holidays.json ครั้งเดียว (ถ้าไม่มีไฟล์ → ใช้กฎเสาร์–อาทิตย์) */
|
|
var ready = null;
|
|
function loadHolidays() {
|
|
if (ready) return ready;
|
|
ready = fetch(DATA_URL + 'holidays.json', { cache: 'no-store' })
|
|
.then(function (r) { return r.ok ? r.json() : null; })
|
|
.then(function (d) {
|
|
HOLIDAYS = (d && Array.isArray(d.holidays)) ? d.holidays.slice() : [];
|
|
try { window.dispatchEvent(new CustomEvent('schedules:ready', { detail: { holidays: HOLIDAYS.length } })); } catch (e) { }
|
|
return HOLIDAYS;
|
|
})
|
|
.catch(function () { HOLIDAYS = []; return HOLIDAYS; });
|
|
return ready;
|
|
}
|
|
|
|
/* ---------- ทิศทางของสาย (กรองตามวัน + ถอยกลับถ้าว่าง) ---------- */
|
|
function directions(doc, routeId, opts) {
|
|
var rid = String(routeId);
|
|
var list = [];
|
|
if (hasSchema2(doc)) {
|
|
var r = (doc.routes || []).filter(function (x) { return String(x.route_id) === rid; })[0];
|
|
if (!r) return [];
|
|
list = (r.directions || []).map(function (d) {
|
|
return {
|
|
dir_id: d.dir_id,
|
|
dir_label: d.dir_label,
|
|
days: Array.isArray(d.days) ? d.days.map(String) : null, /* ระบุวันตรง ๆ (อา จ อ พ พฤ ศ ส) */
|
|
service: serviceOf(d, d), /* ตรวจวัน + เหตุผล (จากคำ/service/days) */
|
|
autoTimes: !!d.autoTimes, /* true = คำนวณจุดที่ไม่มีตารางให้ */
|
|
autoFor: Array.isArray(d.autoFor) ? d.autoFor.slice() : null, /* จำกัดเฉพาะจุดเหล่านี้ (ไม่ใส่ = ทุกจุดที่ว่าง) */
|
|
travelMin: Number(d.travelMin) > 0 ? Number(d.travelMin) : null, /* เวลาเดินทางทั้งเส้น (นาที) */
|
|
baseEnd: (d.baseEnd === 'first' || d.baseEnd === 'last') ? d.baseEnd : null, /* มีเวลาจริงที่ปลายไหน */
|
|
baseSid: (d.baseSid != null ? d.baseSid : null), /* หรือระบุจุดอ้างอิงตรง ๆ */
|
|
speedKmh: Number(d.speedKmh) > 0 ? Number(d.speedKmh) : DEFAULT_SPEED_KMH,
|
|
stops: (d.stops || []).map(function (s) {
|
|
return {
|
|
station_id: s.station_id,
|
|
times: s.times || [],
|
|
km: (typeof s.km === 'number') ? s.km : null, /* กม. จากต้นทาง (วัดโดย resource/tools/stop-km.py) */
|
|
dir_note: s.dir_note || null,
|
|
note: s.note || null,
|
|
groups: s.groups || null,
|
|
derive: s.derive || null /* กฎ "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" */
|
|
};
|
|
})
|
|
};
|
|
});
|
|
} else {
|
|
/* schema 1 → ยังใช้ได้เหมือนเดิม (ไม่แยกวัน) */
|
|
list = [{ dir_id: 'all', dir_label: null, service: 'all', stops: (doc && doc.schedules ? doc.schedules : []).filter(function (r) {
|
|
return String(r.route_id) === rid;
|
|
}).map(function (r) {
|
|
return { station_id: r.station_id, times: r.departure_times || [], dir_note: r.direction_note || null, note: r.schedule_note || null, groups: null };
|
|
}) }];
|
|
}
|
|
|
|
var day = normDay(opts);
|
|
var kept = list.filter(function (d) { return applies(d.service, day); }); /* service = ผลตรวจวันของทิศนั้น */
|
|
var fallback = false;
|
|
if (!kept.length && list.length) { kept = list.slice(); fallback = true; } /* ห้ามปล่อยว่าง */
|
|
|
|
warmStations(); /* เพื่อให้ข้อความ "คำนวณจาก ..." มีชื่อจุด */
|
|
/* เวลาจริงรายจุดของ "ทั้งสาย" — กฎ derive อ้างจุดข้ามทิศได้ (เช่น 902: จุด 15 ← จุด 6 คนละทิศ) */
|
|
var realByStation = {};
|
|
(kept.length ? kept : list).forEach(function (d) {
|
|
(d.stops || []).forEach(function (s) {
|
|
var t0 = timesFor(s, day === 'all' ? 'all' : day);
|
|
if (t0.length && !realByStation[String(s.station_id)]) realByStation[String(s.station_id)] = t0;
|
|
});
|
|
});
|
|
|
|
return kept.map(function (d) {
|
|
var kms = relKms(rid, d.stops); /* km ตามทางที่รถวิ่ง (จากไฟล์ stop-km.json) */
|
|
/* ใส่ km ให้ "ทุกจุด" ก่อน — ต้องมีครบทั้งชุด ระบบหาจุดอ้างอิง/คำนวณความเร็วถึงจะทำงานได้ */
|
|
var withKm = d.stops.map(function (s, si) {
|
|
var c = {};
|
|
for (var k in s) c[k] = s[k];
|
|
if (typeof c.km !== 'number' && typeof kms[si] === 'number') c.km = kms[si];
|
|
return c;
|
|
});
|
|
var speed = speedOf({ travelMin: d.travelMin, speedKmh: d.speedKmh, stops: withKm });
|
|
var stops = withKm.map(function (s) {
|
|
var t = timesFor(s, day === 'all' ? 'all' : day);
|
|
var est = false;
|
|
var estFrom = null; /* ถ้าเป็นเวลาที่คำนวณ → ข้อมูลจุดอ้างอิง */
|
|
/* ★ กฎของเจ้าของข้อมูล: "จุดนี้ = เวลาจุดอ้างอิง ± n นาที" (เขียนครั้งเดียวในไฟล์สาย) */
|
|
if (s.derive && s.derive.from_station_id != null) {
|
|
var src = realByStation[String(s.derive.from_station_id)];
|
|
if (src && src.length) {
|
|
t = shiftTimes(src, s.derive.offset_min);
|
|
est = true;
|
|
estFrom = { station_id: Number(s.derive.from_station_id),
|
|
name: stationNameOf(s.derive.from_station_id),
|
|
offsetMin: Number(s.derive.offset_min) || 0,
|
|
overrode: (timesFor(s, 'all').length > 0) };
|
|
}
|
|
}
|
|
if (!est && d.autoTimes && !t.length) { /* ไม่มีตารางจริง → คำนวณจากจุดที่มีเวลา + กม. */
|
|
var only = d.autoFor && d.autoFor.length
|
|
? d.autoFor.map(String).indexOf(String(s.station_id)) !== -1
|
|
: true; /* ไม่ระบุ autoFor = ทุกจุดที่ว่าง */
|
|
if (only) {
|
|
var calc = computeTimes(s, withKm, { speedKmh: speed.kmh, baseEnd: d.baseEnd, baseSid: d.baseSid });
|
|
if (calc && calc.length) { t = calc; est = true; }
|
|
}
|
|
}
|
|
return { station_id: s.station_id, times: t, km: s.km, dir_note: s.dir_note, note: s.note,
|
|
groups: s.groups, estimated: est, estimateFrom: estFrom, derive: s.derive || null };
|
|
});
|
|
return { dir_id: d.dir_id, dir_label: d.dir_label, service: d.service, days: d.days, autoTimes: d.autoTimes,
|
|
travelMin: d.travelMin, baseEnd: d.baseEnd, baseSid: d.baseSid, autoFor: d.autoFor,
|
|
speedKmh: Math.round(speed.kmh * 10) / 10,
|
|
speedFrom: speed.source, dayType: day, fallback: fallback, stops: stops };
|
|
});
|
|
}
|
|
|
|
/* ---------- schema 2 → record แบน (คง API เดิม) ---------- */
|
|
function records(doc, opts) {
|
|
if (!doc) return [];
|
|
if (!hasSchema2(doc)) return doc.schedules || (Array.isArray(doc) ? doc : []);
|
|
var out = [];
|
|
(doc.routes || []).forEach(function (r) {
|
|
directions(doc, r.route_id, opts).forEach(function (d) {
|
|
(d.stops || []).forEach(function (s) {
|
|
out.push({
|
|
route_id: r.route_id,
|
|
station_id: s.station_id,
|
|
direction_note: s.dir_note || null,
|
|
dir_label: d.dir_label || null, /* ชื่อทิศ (ป่าโมกไปอยุธยา ฯลฯ) — ใช้เป็นหัวแถว */
|
|
departure_times: s.times || [],
|
|
schedule_note: s.note || null,
|
|
estimated: !!s.estimated, /* true = เวลาคำนวณ ไม่ใช่ตารางจริง */
|
|
estimateFrom: s.estimateFrom || null, /* { station_id, name, offsetMin } เมื่อคำนวณ */
|
|
km: s.km,
|
|
dir_id: d.dir_id,
|
|
service: d.service,
|
|
days: d.days,
|
|
dayType: d.dayType,
|
|
fallback: d.fallback
|
|
});
|
|
});
|
|
});
|
|
});
|
|
return out;
|
|
}
|
|
|
|
/* ---------- ข้อมูลของสายเดียว ---------- */
|
|
function route(doc, routeId, opts) {
|
|
var rid = String(routeId);
|
|
var entries = records(doc, opts).filter(function (r) { return String(r.route_id) === rid; });
|
|
var dirs = directions(doc, rid, opts);
|
|
var order = [];
|
|
if (hasSchema2(doc)) {
|
|
var r = (doc.routes || []).filter(function (x) { return String(x.route_id) === rid; })[0];
|
|
if (r && r.station_order) order = r.station_order.slice();
|
|
}
|
|
if (!order.length) {
|
|
entries.forEach(function (r) { if (order.indexOf(r.station_id) === -1) order.push(r.station_id); });
|
|
order.sort(function (a, b) { return a - b; });
|
|
}
|
|
return { route_id: rid, station_order: order, directions: dirs, entries: entries };
|
|
}
|
|
|
|
/* ---------- เวลาทั้งหมดของสาย (ไม่ซ้ำ + เรียง) ---------- */
|
|
function times(doc, routeId, opts) {
|
|
var seen = {};
|
|
records(doc, opts).forEach(function (r) {
|
|
if (String(r.route_id) !== String(routeId)) return;
|
|
(r.departure_times || []).forEach(function (t) { seen[t] = true; });
|
|
});
|
|
return Object.keys(seen).sort();
|
|
}
|
|
|
|
/* ---------- จำนวนเที่ยวของสาย ---------- */
|
|
function countTrips(doc, routeId, opts) {
|
|
var n = 0;
|
|
records(doc, opts).forEach(function (r) {
|
|
if (String(r.route_id) === String(routeId)) n += (r.departure_times || []).length;
|
|
});
|
|
return n;
|
|
}
|
|
|
|
loadHolidays(); /* เริ่มโหลดทันที (ไม่บล็อกการอ่าน) */
|
|
loadKm();
|
|
|
|
window.Schedules = {
|
|
hasSchema2: hasSchema2,
|
|
load: loadSubs, /* โหลดทุกสาย (จากสารบัญหรือไฟล์รวม) */
|
|
loadRoute: loadRoute, /* โหลดสายเดียว + ไฟล์ย่อยที่ยังไม่เคยโหลด */
|
|
normSub: normSub,
|
|
get subs() { return SUBS; },
|
|
records: records,
|
|
route: route,
|
|
directions: directions,
|
|
times: times,
|
|
countTrips: countTrips,
|
|
/* ส่วนของวันทำงาน/วันหยุด */
|
|
todayType: todayType,
|
|
dayTypeOf: dayTypeOf,
|
|
dayInfo: dayInfo,
|
|
dayKey: dayKey,
|
|
DAYS: DAYS,
|
|
DAY_TH: DAY_TH,
|
|
DAY_ABBR: DAY_ABBR,
|
|
detectDay: detectDay,
|
|
detectDayOfDir: detectDayOfDir,
|
|
offsetLabel: offsetLabel,
|
|
stationNameOf: stationNameOf,
|
|
setStationNames: setStationNames,
|
|
shiftTimes: shiftTimes,
|
|
serviceOf: serviceOf,
|
|
timesFor: timesFor,
|
|
computeTimes: computeTimes,
|
|
speedOf: speedOf,
|
|
absKm: absKm,
|
|
relKms: relKms,
|
|
loadKm: loadKm,
|
|
get km() { return KM; },
|
|
DEFAULT_SPEED_KMH: DEFAULT_SPEED_KMH,
|
|
loadHolidays: loadHolidays,
|
|
get holidays() { return HOLIDAYS.slice(); },
|
|
ready: ready
|
|
};
|
|
})();
|