Initial commit

This commit is contained in:
Porawit Dongwang
2026-09-16 23:20:08 +07:00
commit 0041668dbb
32577 changed files with 3687927 additions and 0 deletions
@@ -0,0 +1,53 @@
# Hospital & Public Health Internal PR & Document Announcement System
### ระบบบริหารจัดการข่าวสาร บันทึกข้อความ คำสั่ง และแนวทางเวชปฏิบัติ (CPG) สำหรับโรงพยาบาลและหน่วยงานสังกัดกระทรวงสาธารณสุข
---
## 📌 ภาพรวมระบบ (System Overview)
ระบบข่าวประชาสัมพันธ์และหนังสือเวียนภายในองค์กร พัฒนาขึ้นด้วยรูปแบบ **Document-Centric Single-Page Application (SPA)** ขับเคลื่อนด้วย **PHP & PDO Database Engine** เน้นการใช้งานที่เป็นทางการ มีความน่าเชื่อถือ สง่างาม ด้วยอัตลักษณ์สีประจำกระทรวงสาธารณสุข (`#056839`) พร้อมศูนย์ควบคุมผู้ดูแลระบบกลาง (Super Admin Control Panel) และรองรับการใช้งานบนทุกอุปกรณ์ (Full Responsive Web Application)
---
## 🛠️ โครงสร้างเทคโนโลยี (Technical Stack)
| ส่วนประกอบ | เทคโนโลยีที่ใช้ | รายละเอียด |
| :--- | :--- | :--- |
| **Frontend Framework** | Vanilla JavaScript (ES6+) | พัฒนาสคริปต์ควบคุมการทำงานแบบ Single-Page Application |
| **Styling Framework** | Tailwind CSS (v3 via CDN) | ออกแบบอินเทอร์เฟซและระบบตอบสนอง (Responsive UI) |
| **Typography** | Google Fonts (Sarabun) | แบบอักษรมาตรฐานหนังสือราชการภาครัฐ 100% |
| **Accessibility Controls** | Font Resizer (ก- ก ก+) | ชุดปุ่มปรับขนาดตัวอักษรมาตรฐานภาครัฐ |
| **Icons** | FontAwesome 6 | ชุดไอคอนสัญลักษณ์มาตรฐาน |
| **Backend Engine** | PHP 8.1+ (PDO) | RESTful API & Database Data Access Object |
| **Database Engine** | MySQL 8.0+ / SQLite Fallback | ระบบจัดการฐานข้อมูลเชิงสัมพันธ์ PDO |
---
## 📁 โครงสร้างไฟล์ในโครงการ (Project Files Structure)
- `index.php` - หน้าหลัก Single-Page Application (PHP Engine) สำหรับแสดงผล ค้นหา ออกหนังสือเวียน ตั้งค่าระบบ และศูนย์ควบคุมผู้ดูแลระบบกลาง
- `config/db.php` - ระบบเชื่อมต่อฐานข้อมูล PDO MySQL พร้อมระบบ Auto-Migration & SQLite Fallback
- `schema.sql` - คำสั่ง SQL สร้างฐานข้อมูล `moph_hospital_news` พร้อมตาราง 5 ตาราง และ 25 ข้อมูลตัวอย่าง
- `api/get_news.php` - RESTful API สำหรับดึงข้อมูลข่าวสาร, กลุ่มงาน, เอกสารแนบ และการตั้งค่าระบบ
- `api/save_news.php` - RESTful API สำหรับบันทึก/แก้ไขหนังสือเวียนและไฟล์แนบ
- `api/delete_news.php` - RESTful API สำหรับลบหนังสือเวียน
- `api/reset_data.php` - RESTful API สำหรับรีเซ็ตฐานข้อมูลเป็นชุดข้อมูลตัวอย่าง
- `api/admin_settings.php` - RESTful API สำหรับศูนย์ควบคุม Super Admin (สร้างหน่วยงาน, เปลี่ยนรหัสผ่าน, ตั้งค่าระบบ)
- `README.md` - เอกสารคำแนะนำการตั้งค่าและเปิดใช้งาน
---
## 🚀 ขั้นตอนการติดตั้งและใช้งาน (Installation & Setup Guide)
### 1. เปิดใช้งาน PHP Dev Server ทันที
```bash
php -S localhost:8000
```
- เข้าใช้งานผ่านเว็บเบราว์เซอร์ที่: **`http://localhost:8000/index.php`**
- ระบบจะสร้างฐานข้อมูลพร้อมข้อมูลตัวอย่าง 25 รายการให้โดยอัตโนมัติ
- **รหัสผ่านทดสอบเข้าสู่ระบบ:** `1234` (ทั้งสิทธิ์กลุ่มงานและสิทธิ์ Super Admin)
### 2. นำเข้า MySQL ฐานข้อมูลจริง (Production Setup)
1. เปิด phpMyAdmin หรือ MySQL CLI
2. นำเข้าไฟล์ `schema.sql` เพื่อสร้างฐานข้อมูล `moph_hospital_news`
3. ตั้งค่า `mysqlUser` และ `mysqlPass` ใน `config/db.php` ให้ตรงกับ MySQL Server ของคุณ
@@ -0,0 +1,141 @@
<?php
// api/admin_settings.php - Super Admin Management API for Agencies, Passwords, and System Settings
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.php';
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'GET') {
// Fetch all agencies including password
$agenciesStmt = $pdo->query("SELECT id, name, code, COALESCE(admin_password, '1234') AS admin_password FROM agencies ORDER BY id ASC");
$agencies = $agenciesStmt->fetchAll();
// Fetch all system settings
$settingsStmt = $pdo->query("SELECT setting_key, setting_value FROM system_settings");
$rawSettings = $settingsStmt->fetchAll();
$settings = [];
foreach ($rawSettings as $row) {
$settings[$row['setting_key']] = $row['setting_value'];
}
echo json_encode([
'status' => 'success',
'agencies' => $agencies,
'settings' => $settings
], JSON_UNESCAPED_UNICODE);
exit;
}
if ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$action = $input['action'] ?? '';
if ($action === 'save_agency') {
$id = strtoupper(trim($input['id'] ?? ''));
$name = trim($input['name'] ?? '');
$code = strtoupper(trim($input['code'] ?? ''));
$password = trim($input['password'] ?? '1234');
$isEdit = !empty($input['is_edit']);
if (empty($id) || empty($name) || empty($code)) {
echo json_encode(['status' => 'error', 'message' => 'กรุณากรอกรหัสหน่วยงาน ชื่อกลุ่มงาน และอักษรย่อให้ครบถ้วน']);
exit;
}
if ($isEdit) {
$stmt = $pdo->prepare("UPDATE agencies SET name = ?, code = ?, admin_password = ? WHERE id = ?");
$stmt->execute([$name, $code, $password, $id]);
$msg = 'บันทึกการแก้ไขหน่วยงานเรียบร้อยแล้ว';
} else {
// Check if duplicate ID
$chk = $pdo->prepare("SELECT COUNT(*) AS cnt FROM agencies WHERE id = ?");
$chk->execute([$id]);
if ($chk->fetch()['cnt'] > 0) {
echo json_encode(['status' => 'error', 'message' => "รหัสหน่วยงาน '{$id}' มีอยู่ในระบบแล้ว"]);
exit;
}
$stmt = $pdo->prepare("INSERT INTO agencies (id, name, code, admin_password) VALUES (?, ?, ?, ?)");
$stmt->execute([$id, $name, $code, $password]);
$msg = 'สร้างหน่วยงานใหม่เรียบร้อยแล้ว';
}
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'SAVE_AGENCY', ['agency_id' => $id, 'name' => $name, 'code' => $code, 'is_edit' => $isEdit]);
echo json_encode(['status' => 'success', 'message' => $msg], JSON_UNESCAPED_UNICODE);
exit;
}
if ($action === 'delete_agency') {
$id = trim($input['id'] ?? '');
if (empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'ไม่พบรหัสหน่วยงาน']);
exit;
}
// Check if news exist for this agency
$chk = $pdo->prepare("SELECT COUNT(*) AS cnt FROM news WHERE agency_id = ?");
$chk->execute([$id]);
if ($chk->fetch()['cnt'] > 0) {
echo json_encode(['status' => 'error', 'message' => 'ไม่สามารถลบหน่วยงานนี้ได้เนื่องจากมีหนังสือเวียนของหน่วยงานนี้อยู่ในระบบ']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM agencies WHERE id = ?");
$stmt->execute([$id]);
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'DELETE_AGENCY', ['agency_id' => $id]);
echo json_encode(['status' => 'success', 'message' => 'ลบหน่วยงานออกจากระบบเรียบร้อยแล้ว'], JSON_UNESCAPED_UNICODE);
exit;
}
if ($action === 'save_settings') {
$validKeys = [
'hospital_name',
'system_title',
'hospital_logo_url',
'ticker_text',
'super_admin_password',
'gdrive_gas_url',
'footer_text'
];
$sql = "REPLACE INTO system_settings (setting_key, setting_value) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
foreach ($validKeys as $key) {
if (isset($input[$key])) {
$stmt->execute([$key, trim($input[$key])]);
}
}
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'SAVE_SETTINGS', ['updated_keys' => array_keys($input)]);
echo json_encode(['status' => 'success', 'message' => 'บันทึกการตั้งค่าระบบเรียบร้อยแล้ว'], JSON_UNESCAPED_UNICODE);
exit;
}
}
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
@@ -0,0 +1,117 @@
<?php
// api/agency_actions.php - Handle CRUD for agencies
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$action = $input['action'] ?? '';
if (empty($action)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'add_agency') {
$id = strtoupper(trim($input['id'] ?? ''));
$name = trim($input['name'] ?? '');
$code = strtoupper(trim($input['code'] ?? ''));
$password = trim($input['password'] ?? '1234');
$gdriveFolderId = trim($input['gdriveFolderId'] ?? '');
if(empty($id) || empty($name) || empty($code)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
// Check if ID exists
$checkStmt = $pdo->prepare("SELECT id FROM agencies WHERE id = ?");
$checkStmt->execute([$id]);
if ($checkStmt->fetch()) {
echo json_encode(['status' => 'error', 'message' => 'รหัสหน่วยงานนี้มีอยู่ในระบบแล้ว']);
exit;
}
$stmt = $pdo->prepare("INSERT INTO agencies (id, name, code, admin_password, gdrive_folder_id) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([$id, $name, $code, $password, $gdriveFolderId ?: null]);
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'ADD_AGENCY', ['agency_id' => $id, 'name' => $name, 'code' => $code]);
echo json_encode(['status' => 'success', 'message' => 'เพิ่มหน่วยงานเรียบร้อยแล้ว']);
}
elseif ($action === 'edit_agency') {
$id = strtoupper(trim($input['id'] ?? ''));
$name = trim($input['name'] ?? '');
$code = strtoupper(trim($input['code'] ?? ''));
$password = trim($input['password'] ?? '');
$gdriveFolderId = trim($input['gdriveFolderId'] ?? '');
if(empty($id) || empty($name) || empty($code)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
if (empty($password)) {
$stmt = $pdo->prepare("UPDATE agencies SET name = ?, code = ?, gdrive_folder_id = ? WHERE id = ?");
$stmt->execute([$name, $code, $gdriveFolderId ?: null, $id]);
} else {
$stmt = $pdo->prepare("UPDATE agencies SET name = ?, code = ?, admin_password = ?, gdrive_folder_id = ? WHERE id = ?");
$stmt->execute([$name, $code, $password, $gdriveFolderId ?: null, $id]);
}
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'EDIT_AGENCY', ['agency_id' => $id, 'name' => $name, 'code' => $code]);
echo json_encode(['status' => 'success', 'message' => 'แก้ไขข้อมูลหน่วยงานเรียบร้อยแล้ว']);
}
elseif ($action === 'delete_agency') {
$id = strtoupper(trim($input['id'] ?? ''));
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing agency ID']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM agencies WHERE id = ?");
$stmt->execute([$id]);
$actionUserId = $input['action_user_id'] ?? 'SUPER_ADMIN';
$actionUserName = $input['action_user_name'] ?? 'ผู้ดูแลระบบ';
logActivity($pdo, $actionUserId, $actionUserName, 'DELETE_AGENCY', ['agency_id' => $id]);
echo json_encode(['status' => 'success', 'message' => 'ลบหน่วยงานเรียบร้อยแล้ว']);
}
elseif ($action === 'reset_password') {
$id = strtoupper(trim($input['id'] ?? ''));
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing agency ID']);
exit;
}
$stmt = $pdo->prepare("UPDATE agencies SET admin_password = '1234' WHERE id = ?");
$stmt->execute([$id]);
echo json_encode(['status' => 'success', 'message' => 'รีเซ็ตรหัสผ่านเป็น 1234 เรียบร้อยแล้ว']);
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,87 @@
<?php
// api/category_actions.php - Handle CRUD for categories
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$action = $input['action'] ?? '';
if (empty($action)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'add_category') {
$id = $input['id'] ?? '';
$name = $input['name'] ?? '';
$agencyId = $input['agencyId'] ?? 'SUPER_ADMIN';
if(empty($id) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing category ID or name']);
exit;
}
$stmt = $pdo->prepare("INSERT INTO categories (id, name, agency_id) VALUES (?, ?, ?)");
$stmt->execute([$id, $name, $agencyId]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'ADD_CATEGORY', ['category_id' => $id, 'name' => $name]);
echo json_encode(['status' => 'success', 'message' => 'เพิ่มหมวดหมู่เรียบร้อยแล้ว']);
}
elseif ($action === 'edit_category') {
$id = $input['id'] ?? '';
$name = $input['name'] ?? '';
if(empty($id) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing category ID or name']);
exit;
}
$stmt = $pdo->prepare("UPDATE categories SET name = ? WHERE id = ?");
$stmt->execute([$name, $id]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'EDIT_CATEGORY', ['category_id' => $id, 'name' => $name]);
echo json_encode(['status' => 'success', 'message' => 'แก้ไขหมวดหมู่เรียบร้อยแล้ว']);
}
elseif ($action === 'delete_category') {
$id = $input['id'] ?? '';
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing category ID']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
$stmt->execute([$id]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'DELETE_CATEGORY', ['category_id' => $id]);
echo json_encode(['status' => 'success', 'message' => 'ลบหมวดหมู่เรียบร้อยแล้ว']);
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,83 @@
<?php
// api/delete_file.php - Delete file from Google Drive via Apps Script Web App
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$url = $input['url'] ?? '';
if (empty($url)) {
echo json_encode(['status' => 'error', 'message' => 'Missing Google Drive File URL']);
exit;
}
// Extract file ID from Google Drive URL
// Typically: https://drive.google.com/file/d/1XyZ.../view?usp=drivesdk
preg_match('/\/d\/([a-zA-Z0-9_-]+)/', $url, $matches);
if (empty($matches[1])) {
echo json_encode(['status' => 'error', 'message' => 'Invalid Google Drive URL format']);
exit;
}
$fileId = $matches[1];
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
// Get GAS URL from system settings
$settingsStmt = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'gdrive_gas_url'");
$gasUrlRow = $settingsStmt->fetch();
$gasUrl = $gasUrlRow ? $gasUrlRow['setting_value'] : '';
if (empty($gasUrl)) {
echo json_encode(['status' => 'error', 'message' => 'Super Admin ยังไม่ได้ตั้งค่า Google Apps Script Web App URL']);
exit;
}
$payload = json_encode([
'action' => 'delete',
'fileId' => $fileId
]);
// Send to GAS via cURL
$ch = curl_init($gasUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // GAS requires follow location for redirects
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Fix HTTP/2 PROTOCOL_ERROR
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch)) {
throw new \Exception(curl_error($ch));
}
curl_close($ch);
$resData = json_decode($response, true);
if (!$resData) {
throw new \Exception("Invalid JSON response from GAS: " . $response);
}
echo json_encode($resData);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
exit;
}
@@ -0,0 +1,50 @@
<?php
// api/get_logs.php - Fetch Activity Logs for Super Admin
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/db.php';
try {
$agencyId = $_GET['agency_id'] ?? '';
if ($agencyId !== 'SUPER_ADMIN') {
echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
exit;
}
$startDate = $_GET['start_date'] ?? '';
$endDate = $_GET['end_date'] ?? '';
$search = $_GET['search'] ?? '';
$db = getDbConnection();
$pdo = $db['pdo'];
$query = "SELECT * FROM activity_logs WHERE 1=1";
$params = [];
if ($startDate) {
$query .= " AND created_at >= ?";
$params[] = $startDate . ' 00:00:00';
}
if ($endDate) {
$query .= " AND created_at <= ?";
$params[] = $endDate . ' 23:59:59';
}
if ($search) {
$query .= " AND (user_name LIKE ? OR action LIKE ? OR details LIKE ?)";
$searchParam = "%$search%";
$params[] = $searchParam;
$params[] = $searchParam;
$params[] = $searchParam;
}
$query .= " ORDER BY created_at DESC LIMIT 500"; // Limit to prevent massive payload
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['status' => 'success', 'data' => $logs]);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
@@ -0,0 +1,76 @@
<?php
// api/get_news.php - PHP REST Endpoint to fetch news, agencies, and system settings from database
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
// Increment view count if ID specified
if (isset($_GET['view_id']) && !empty($_GET['view_id'])) {
$viewStmt = $pdo->prepare("UPDATE news SET views = views + 1 WHERE id = ?");
$viewStmt->execute([$_GET['view_id']]);
}
// Query news list with agency and category names
$stmt = $pdo->query("
SELECT n.*, a.name AS agency_name, a.code AS agency_code, c.name AS category_name
FROM news n
JOIN agencies a ON n.agency_id = a.id
JOIN categories c ON n.category_id = c.id
ORDER BY n.publish_date DESC, n.created_at DESC
");
$newsList = $stmt->fetchAll();
// Query attachments for each news document
foreach ($newsList as &$news) {
$attachStmt = $pdo->prepare("SELECT file_name AS name, file_type AS type, file_size AS size, file_url AS url FROM attachments WHERE news_id = ?");
$attachStmt->execute([$news['id']]);
$news['attachments'] = $attachStmt->fetchAll();
$news['isPinned'] = (bool)$news['is_pinned'];
$news['isUrgent'] = (bool)$news['is_urgent'];
$news['isHidden'] = (bool)($news['is_hidden'] ?? 0);
$news['docNum'] = $news['doc_num'];
$news['agencyId'] = $news['agency_id'];
$news['categoryId'] = $news['category_id'];
$news['date'] = $news['publish_date'];
$news['views'] = (int)$news['views'];
}
// Query active agencies list
$agenciesStmt = $pdo->query("SELECT id, name, code, COALESCE(admin_password, '1234') AS admin_password, gdrive_folder_id FROM agencies ORDER BY id ASC");
$agenciesList = $agenciesStmt->fetchAll();
// Query categories list
$categoriesStmt = $pdo->query("SELECT id, name, agency_id FROM categories ORDER BY id ASC");
$categoriesList = $categoriesStmt->fetchAll();
// Query system settings
$settingsStmt = $pdo->query("SELECT setting_key, setting_value FROM system_settings");
$rawSettings = $settingsStmt->fetchAll();
$settings = [];
foreach ($rawSettings as $row) {
$settings[$row['setting_key']] = $row['setting_value'];
}
// Query templates list
$templatesStmt = $pdo->query("SELECT id, agency_id, name, category_id, doc_num_format, title, content FROM templates ORDER BY created_at ASC");
$templatesList = $templatesStmt->fetchAll();
echo json_encode([
'status' => 'success',
'driver' => $dbInfo['driver'],
'data' => $newsList,
'agencies' => $agenciesList,
'categories' => $categoriesList,
'templates' => $templatesList,
'settings' => $settings
], JSON_UNESCAPED_UNICODE);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
@@ -0,0 +1,25 @@
<?php
// api/log_auth.php - Logs Authentication Events (Login)
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/db.php';
require_once 'logger.php';
try {
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (!$data || !isset($data['user_id']) || !isset($data['user_name']) || !isset($data['action'])) {
echo json_encode(['status' => 'error', 'message' => 'Invalid data']);
exit;
}
$db = getDbConnection();
$pdo = $db['pdo'];
logActivity($pdo, $data['user_id'], $data['user_name'], $data['action'], $data['details'] ?? '');
echo json_encode(['status' => 'success']);
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
@@ -0,0 +1,12 @@
<?php
// api/logger.php - Activity Logger Helper
function logActivity($pdo, $userId, $userName, $action, $details) {
try {
$stmt = $pdo->prepare("INSERT INTO activity_logs (user_id, user_name, action, details) VALUES (?, ?, ?, ?)");
$detailsStr = is_array($details) || is_object($details) ? json_encode($details, JSON_UNESCAPED_UNICODE) : $details;
$stmt->execute([$userId, $userName, $action, $detailsStr]);
} catch (\Exception $e) {
error_log("Failed to log activity: " . $e->getMessage());
}
}
@@ -0,0 +1,105 @@
<?php
// api/news_actions.php - Handle hide and delete news actions
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$action = $input['action'] ?? '';
$id = $input['id'] ?? '';
if (empty($action) || empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action or id']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'delete_news') {
// Fetch attachments first to delete them from Google Drive
$stmt = $pdo->prepare("SELECT file_url FROM attachments WHERE news_id = ?");
$stmt->execute([$id]);
$attachments = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($attachments)) {
// Get GAS URL
$settingsStmt = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'gdrive_gas_url'");
$gasUrlRow = $settingsStmt->fetch();
$gasUrl = $gasUrlRow ? $gasUrlRow['setting_value'] : '';
if (!empty($gasUrl)) {
foreach ($attachments as $att) {
if (!empty($att['file_url'])) {
preg_match('/\/d\/([a-zA-Z0-9_-]+)/', $att['file_url'], $matches);
if (!empty($matches[1])) {
$fileId = $matches[1];
$payload = json_encode(['action' => 'delete', 'fileId' => $fileId]);
$ch = curl_init($gasUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_exec($ch);
curl_close($ch);
}
}
}
}
}
// Delete from attachments table (cascading might handle this, but to be safe)
$stmt = $pdo->prepare("DELETE FROM attachments WHERE news_id = ?");
$stmt->execute([$id]);
$stmt = $pdo->prepare("DELETE FROM news WHERE id = ?");
$stmt->execute([$id]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'DELETE_NEWS', ['news_id' => $id]);
echo json_encode(['status' => 'success', 'message' => 'ลบข้อมูลและไฟล์แนบที่เกี่ยวข้องเรียบร้อยแล้ว']);
}
elseif ($action === 'toggle_hide_news') {
// First get current status
$stmt = $pdo->prepare("SELECT is_hidden FROM news WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
$newStatus = $row['is_hidden'] ? 0 : 1;
$update = $pdo->prepare("UPDATE news SET is_hidden = ? WHERE id = ?");
$update->execute([$newStatus, $id]);
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
logActivity($pdo, $actionUserId, $actionUserName, 'TOGGLE_HIDE_NEWS', ['news_id' => $id, 'is_hidden' => $newStatus]);
echo json_encode(['status' => 'success', 'message' => 'อัปเดตสถานะเรียบร้อยแล้ว', 'is_hidden' => $newStatus]);
} else {
echo json_encode(['status' => 'error', 'message' => 'ไม่พบข้อมูล']);
}
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,104 @@
<?php
// api/save_news.php - PHP REST Endpoint to insert or update news in database
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/logger.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$id = $input['id'] ?? '';
$docNum = trim($input['docNum'] ?? $input['doc_num'] ?? '');
if ($docNum === '') $docNum = '-';
$title = trim($input['title'] ?? '');
$agencyId = $input['agencyId'] ?? $input['agency_id'] ?? '';
$categoryId = $input['categoryId'] ?? $input['category_id'] ?? '';
$date = $input['date'] ?? $input['publish_date'] ?? date('Y-m-d');
$content = trim($input['content'] ?? '');
$isPinned = !empty($input['isPinned']) || !empty($input['is_pinned']) ? 1 : 0;
$isUrgent = !empty($input['isUrgent']) || !empty($input['is_urgent']) ? 1 : 0;
$attachments = $input['attachments'] ?? [];
if (empty($title) || empty($agencyId) || empty($categoryId)) {
echo json_encode(['status' => 'error', 'message' => 'กรุณากรอกข้อมูลที่จำเป็นให้ครบถ้วน']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
$pdo->beginTransaction();
if (!empty($id)) {
// Update existing document
$stmt = $pdo->prepare("
UPDATE news
SET doc_num = ?, title = ?, agency_id = ?, category_id = ?, publish_date = ?, content = ?, is_pinned = ?, is_urgent = ?
WHERE id = ?
");
$stmt->execute([$docNum, $title, $agencyId, $categoryId, $date, $content, $isPinned, $isUrgent, $id]);
// Delete existing attachments to recreate
$delAttach = $pdo->prepare("DELETE FROM attachments WHERE news_id = ?");
$delAttach->execute([$id]);
$newsId = $id;
$message = 'บันทึกการแก้ไขข้อมูลลงในฐานข้อมูลเรียบร้อยแล้ว';
} else {
// Generate new ID
$countStmt = $pdo->query("SELECT COUNT(*) AS total FROM news");
$total = $countStmt->fetch()['total'] + 1;
$newsId = 'DOC-2026-' . str_pad($total, 3, '0', STR_PAD_LEFT);
$stmt = $pdo->prepare("
INSERT INTO news (id, doc_num, title, agency_id, category_id, publish_date, content, is_pinned, is_urgent, views)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
");
$stmt->execute([$newsId, $docNum, $title, $agencyId, $categoryId, $date, $content, $isPinned, $isUrgent]);
$message = 'เผยแพร่บันทึกข้อความลงในฐานข้อมูลเรียบร้อยแล้ว';
}
// Insert attachments
if (is_array($attachments) && count($attachments) > 0) {
$attachStmt = $pdo->prepare("
INSERT INTO attachments (news_id, file_name, file_type, file_size, file_url)
VALUES (?, ?, ?, ?, ?)
");
foreach ($attachments as $att) {
$fileName = trim($att['name'] ?? $att['file_name'] ?? '');
$fileType = $att['type'] ?? $att['file_type'] ?? 'pdf';
$fileSize = $att['size'] ?? $att['file_size'] ?? '1.0 MB';
$fileUrl = $att['url'] ?? $att['file_url'] ?? null;
if (!empty($fileName)) {
$attachStmt->execute([$newsId, $fileName, $fileType, $fileSize, $fileUrl]);
}
}
}
$actionUserId = $input['action_user_id'] ?? 'SYSTEM';
$actionUserName = $input['action_user_name'] ?? 'SYSTEM';
$actionType = $id ? 'UPDATE_NEWS' : 'CREATE_NEWS';
logActivity($pdo, $actionUserId, $actionUserName, $actionType, ['news_id' => $newsId, 'title' => $title]);
$pdo->commit();
echo json_encode(['status' => 'success', 'message' => $message, 'id' => $newsId], JSON_UNESCAPED_UNICODE);
} catch (\Exception $e) {
if (isset($pdo) && $pdo->inTransaction()) {
$pdo->rollBack();
}
echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
@@ -0,0 +1,85 @@
<?php
// api/template_actions.php - Handle CRUD for templates
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
$input = $_POST;
}
$action = $input['action'] ?? '';
if (empty($action)) {
echo json_encode(['status' => 'error', 'message' => 'Missing action']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
if ($action === 'add_template') {
$agencyId = $input['agencyId'] ?? '';
$name = $input['name'] ?? '';
$categoryId = $input['categoryId'] ?? '';
$docNumFormat = $input['docNumFormat'] ?? '';
$title = $input['title'] ?? '';
$content = $input['content'] ?? '';
if(empty($agencyId) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
// Generate unique ID
$id = 'TPL-' . time() . rand(100, 999);
$stmt = $pdo->prepare("INSERT INTO templates (id, agency_id, name, category_id, doc_num_format, title, content) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$id, $agencyId, $name, $categoryId, $docNumFormat, $title, $content]);
echo json_encode(['status' => 'success', 'message' => 'เพิ่มแม่แบบด่วนเรียบร้อยแล้ว', 'id' => $id]);
}
elseif ($action === 'edit_template') {
$id = $input['id'] ?? '';
$agencyId = $input['agencyId'] ?? '';
$name = $input['name'] ?? '';
$categoryId = $input['categoryId'] ?? '';
$docNumFormat = $input['docNumFormat'] ?? '';
$title = $input['title'] ?? '';
$content = $input['content'] ?? '';
if(empty($id) || empty($name)) {
echo json_encode(['status' => 'error', 'message' => 'Missing required fields']);
exit;
}
$stmt = $pdo->prepare("UPDATE templates SET name = ?, category_id = ?, doc_num_format = ?, title = ?, content = ? WHERE id = ? AND (agency_id = ? OR ? = 'SUPER_ADMIN')");
$stmt->execute([$name, $categoryId, $docNumFormat, $title, $content, $id, $agencyId, $agencyId]);
echo json_encode(['status' => 'success', 'message' => 'แก้ไขแม่แบบด่วนเรียบร้อยแล้ว']);
}
elseif ($action === 'delete_template') {
$id = $input['id'] ?? '';
$agencyId = $input['agencyId'] ?? '';
if(empty($id)) {
echo json_encode(['status' => 'error', 'message' => 'Missing template ID']);
exit;
}
$stmt = $pdo->prepare("DELETE FROM templates WHERE id = ? AND (agency_id = ? OR ? = 'SUPER_ADMIN')");
$stmt->execute([$id, $agencyId, $agencyId]);
echo json_encode(['status' => 'success', 'message' => 'ลบแม่แบบด่วนเรียบร้อยแล้ว']);
}
else {
echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Database Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,129 @@
<?php
// api/upload_file.php - Upload file to Google Drive via Apps Script Web App
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
require_once __DIR__ . '/../config/db.php';
// Set higher limits for large file uploads to GAS (70MB+ requires a lot of memory for base64 & JSON)
set_time_limit(600);
ini_set('memory_limit', '1024M');
ini_set('post_max_size', '128M');
ini_set('upload_max_filesize', '128M');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
exit;
}
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
echo json_encode(['status' => 'error', 'message' => 'No file uploaded or upload error']);
exit;
}
$folderId = $_POST['folderId'] ?? '';
if (empty($folderId)) {
echo json_encode(['status' => 'error', 'message' => 'Missing Google Drive Folder ID. ผู้ดูแลระบบยังไม่ได้ตั้งค่า Folder ID ให้กับหน่วยงานนี้']);
exit;
}
try {
$dbInfo = getDbConnection();
$pdo = $dbInfo['pdo'];
// Get GAS URL from system settings
$settingsStmt = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'gdrive_gas_url'");
$gasUrlRow = $settingsStmt->fetch();
$gasUrl = $gasUrlRow ? $gasUrlRow['setting_value'] : '';
if (empty($gasUrl)) {
echo json_encode(['status' => 'error', 'message' => 'Super Admin ยังไม่ได้ตั้งค่า Google Apps Script Web App URL']);
exit;
}
$fileTmpPath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileMimeType = mime_content_type($fileTmpPath);
if (!$fileMimeType) {
$fileMimeType = $_FILES['file']['type'];
}
$fileData = file_get_contents($fileTmpPath);
$base64 = base64_encode($fileData);
$payload = json_encode([
'filename' => $fileName,
'mimeType' => $fileMimeType,
'base64' => $base64,
'folderId' => $folderId
]);
// Send to GAS via cURL
$ch = curl_init($gasUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Handle redirect manually to prevent POST/GET confusion
curl_setopt($ch, CURLOPT_HEADER, true); // Include headers to parse Location
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
if(curl_errno($ch)) {
throw new \Exception(curl_error($ch));
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headerStr = substr($response, 0, $headerSize);
$bodyStr = substr($response, $headerSize);
curl_close($ch);
// If GAS rejects because payload is too large
if ($httpCode === 413) {
echo json_encode(['status' => 'error', 'message' => 'ขนาดไฟล์ใหญ่เกินกว่าที่ Google Drive จะรับได้ (จำกัดการส่งข้อมูลที่ 50MB)']);
exit;
}
// If GAS returns a redirect (e.g. 302, 307)
if ($httpCode >= 300 && $httpCode < 400) {
if (preg_match('/^Location:\s*([^\r\n]+)/im', $headerStr, $matches)) {
$redirectUrl = trim($matches[1]);
// Force a GET request to the redirect URL
$ch2 = curl_init($redirectUrl);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch2, CURLOPT_HTTPGET, true); // Force GET
curl_setopt($ch2, CURLOPT_TIMEOUT, 60);
$bodyStr = curl_exec($ch2);
if(curl_errno($ch2)) {
throw new \Exception(curl_error($ch2));
}
curl_close($ch2);
} else {
throw new \Exception("GAS returned redirect but no Location header found.");
}
}
$resData = json_decode($bodyStr, true);
if ($resData && isset($resData['status']) && $resData['status'] === 'success') {
echo json_encode([
'status' => 'success',
'message' => 'File uploaded to Google Drive',
'fileId' => $resData['fileId'] ?? null,
'url' => $resData['url'] ?? null,
'fileName' => $fileName,
'fileSize' => $_FILES['file']['size']
]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Google Apps Script Error: ' . ($resData['message'] ?? $response)]);
}
} catch (\Exception $e) {
echo json_encode(['status' => 'error', 'message' => 'Upload Error: ' . $e->getMessage()]);
}
?>
@@ -0,0 +1,365 @@
<?php
// config/db.php - Database Connection Handler (PDO MySQL with SQLite Fallback)
function getDbConnection()
{
$mysqlHost = 'localhost';
$mysqlDb = 'hos_dep_news';
$charset = 'utf8mb4';
// List of credentials to try (Local MySQL / XAMPP / Custom Passwords)
$credentials = [
['user' => 'root', 'pass' => '@Samui@10742']
];
// 1. Try Connecting to MySQL Server
foreach ($credentials as $cred) {
try {
$pdoServer = new PDO("mysql:host=$mysqlHost;charset=$charset", $cred['user'], $cred['pass'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_TIMEOUT => 1
]);
$pdoServer->exec("CREATE DATABASE IF NOT EXISTS `$mysqlDb` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
$pdo = new PDO("mysql:host=$mysqlHost;dbname=$mysqlDb;charset=$charset", $cred['user'], $cred['pass'], [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$check = $pdo->query("SHOW TABLES LIKE 'news'");
if ($check->rowCount() === 0) {
seedDatabase($pdo, 'mysql');
} else {
ensureAdminTables($pdo, 'mysql');
}
return ['pdo' => $pdo, 'driver' => 'mysql'];
} catch (\Throwable $e) {
continue; // Try next credential
}
}
// 2. Fallback to SQLite if MySQL is offline or not configured
try {
$sqliteFile = __DIR__ . '/../database.sqlite';
$pdo = new PDO("sqlite:$sqliteFile", null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$pdo->exec("PRAGMA foreign_keys = ON;");
$check = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='news'");
if (!$check->fetch()) {
seedDatabase($pdo, 'sqlite');
} else {
ensureAdminTables($pdo, 'sqlite');
}
return ['pdo' => $pdo, 'driver' => 'sqlite'];
} catch (\Throwable $e) {
throw new \Exception("Database Connection Error: " . $e->getMessage());
}
}
function ensureAdminTables($pdo, $driver = 'mysql')
{
try {
if ($driver === 'sqlite') {
$pdo->exec("
CREATE TABLE IF NOT EXISTS system_settings (
setting_key VARCHAR(100) PRIMARY KEY,
setting_value TEXT NOT NULL
)
");
$pdo->exec("
CREATE TABLE IF NOT EXISTS templates (
id VARCHAR(50) PRIMARY KEY,
agency_id VARCHAR(10) NOT NULL,
name VARCHAR(100) NOT NULL,
category_id VARCHAR(10) NOT NULL,
doc_num_format VARCHAR(100) NOT NULL,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");
// Check if admin_password column exists in agencies
$cols = $pdo->query("PRAGMA table_info(agencies)")->fetchAll();
$hasPass = false;
foreach ($cols as $c) {
if ($c['name'] === 'admin_password') {
$hasPass = true;
break;
}
}
if (!$hasPass) {
$pdo->exec("ALTER TABLE agencies ADD COLUMN admin_password VARCHAR(255) DEFAULT '1234'");
}
// Check if gdrive_folder_id column exists in agencies
$hasGdriveFolder = false;
foreach ($cols as $c) {
if ($c['name'] === 'gdrive_folder_id') {
$hasGdriveFolder = true;
break;
}
}
if (!$hasGdriveFolder) {
$pdo->exec("ALTER TABLE agencies ADD COLUMN gdrive_folder_id VARCHAR(255) DEFAULT NULL");
}
// Check if is_hidden column exists in news
$newsCols = $pdo->query("PRAGMA table_info(news)")->fetchAll();
$hasHidden = false;
foreach ($newsCols as $c) {
if ($c['name'] === 'is_hidden') {
$hasHidden = true;
break;
}
}
if (!$hasHidden) {
$pdo->exec("ALTER TABLE news ADD COLUMN is_hidden INTEGER NOT NULL DEFAULT 0");
}
// Check if file_url column exists in attachments
$attCols = $pdo->query("PRAGMA table_info(attachments)")->fetchAll();
$hasFileUrl = false;
foreach ($attCols as $c) {
if ($c['name'] === 'file_url') {
$hasFileUrl = true;
break;
}
}
if (!$hasFileUrl) {
$pdo->exec("ALTER TABLE attachments ADD COLUMN file_url TEXT DEFAULT NULL");
}
// Check if agency_id column exists in categories
$catCols = $pdo->query("PRAGMA table_info(categories)")->fetchAll();
$hasCatAgency = false;
foreach ($catCols as $c) {
if ($c['name'] === 'agency_id') {
$hasCatAgency = true;
break;
}
}
if (!$hasCatAgency) {
$pdo->exec("ALTER TABLE categories ADD COLUMN agency_id VARCHAR(20) DEFAULT 'SUPER_ADMIN'");
}
// Create activity_logs table
$pdo->exec("
CREATE TABLE IF NOT EXISTS activity_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id VARCHAR(50) NOT NULL,
user_name VARCHAR(100) NOT NULL,
action VARCHAR(100) NOT NULL,
details TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");
} else {
$pdo->exec("
CREATE TABLE IF NOT EXISTS `system_settings` (
`setting_key` VARCHAR(100) NOT NULL,
`setting_value` TEXT NOT NULL,
PRIMARY KEY (`setting_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
$pdo->exec("
CREATE TABLE IF NOT EXISTS `categories` (
`id` VARCHAR(10) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`agency_id` VARCHAR(20) DEFAULT 'SUPER_ADMIN',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
");
$pdo->exec("
CREATE TABLE IF NOT EXISTS `templates` (
`id` VARCHAR(50) NOT NULL,
`agency_id` VARCHAR(10) NOT NULL,
`name` VARCHAR(100) NOT NULL,
`category_id` VARCHAR(10) NOT NULL,
`doc_num_format` VARCHAR(100) NOT NULL,
`title` VARCHAR(255) NOT NULL,
`content` TEXT NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
$cols = $pdo->query("SHOW COLUMNS FROM agencies LIKE 'admin_password'")->fetchAll();
if (count($cols) === 0) {
$pdo->exec("ALTER TABLE agencies ADD COLUMN admin_password VARCHAR(255) DEFAULT '1234'");
}
$colsGdrive = $pdo->query("SHOW COLUMNS FROM agencies LIKE 'gdrive_folder_id'")->fetchAll();
if (count($colsGdrive) === 0) {
$pdo->exec("ALTER TABLE agencies ADD COLUMN gdrive_folder_id VARCHAR(255) DEFAULT NULL");
}
$newsCols = $pdo->query("SHOW COLUMNS FROM news LIKE 'is_hidden'")->fetchAll();
if (count($newsCols) === 0) {
$pdo->exec("ALTER TABLE news ADD COLUMN is_hidden TINYINT(1) NOT NULL DEFAULT 0");
}
$attCols = $pdo->query("SHOW COLUMNS FROM attachments LIKE 'file_url'")->fetchAll();
if (count($attCols) === 0) {
$pdo->exec("ALTER TABLE attachments ADD COLUMN file_url TEXT DEFAULT NULL");
}
$catCols = $pdo->query("SHOW COLUMNS FROM categories LIKE 'agency_id'")->fetchAll();
if (count($catCols) === 0) {
$pdo->exec("ALTER TABLE categories ADD COLUMN agency_id VARCHAR(20) DEFAULT 'SUPER_ADMIN'");
}
// Create activity_logs table
$pdo->exec("
CREATE TABLE IF NOT EXISTS `activity_logs` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`user_id` VARCHAR(50) NOT NULL,
`user_name` VARCHAR(100) NOT NULL,
`action` VARCHAR(100) NOT NULL,
`details` TEXT,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
");
}
// Insert default system settings if empty
$stmt = $pdo->query("SELECT COUNT(*) AS total FROM system_settings");
if ($stmt->fetch()['total'] == 0) {
$initSettings = [
'hospital_name' => 'โรงพยาบาลศูนย์ / โรงพยาบาลทั่วไป กระทรวงสาธารณสุข',
'system_title' => 'ระบบข่าวประชาสัมพันธ์และหนังสือเวียน',
'hospital_logo_url' => 'https://samuihospital.moph.go.th/dashboard/waiting/assets/img/logo.png',
'super_admin_password' => '1234',
'ticker_text' => 'ระบบข่าวสารและหนังสือเวียนภายในองค์กร โรงพยาบาลเปิดให้บริการตามปกติ',
'gdrive_gas_url' => '',
'footer_text' => 'กระทรวงสาธารณสุข - Ministry of Public Health Thailand\nพัฒนาเพื่อการปฏิบัติงานภายในโรงพยาบาลและหน่วยงานในสังกัด | รองรับระบบรักษาความปลอดภัยสารสนเทศ'
];
$ins = $pdo->prepare("INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?)");
foreach ($initSettings as $k => $v) {
$ins->execute([$k, $v]);
}
}
// Check for missing footer_text
$stmtF = $pdo->query("SELECT COUNT(*) AS c FROM system_settings WHERE setting_key = 'footer_text'");
if ($stmtF->fetch()['c'] == 0) {
$pdo->exec("INSERT INTO system_settings (setting_key, setting_value) VALUES ('footer_text', 'กระทรวงสาธารณสุข - Ministry of Public Health Thailand\nพัฒนาเพื่อการปฏิบัติงานภายในโรงพยาบาลและหน่วยงานในสังกัด | รองรับระบบรักษาความปลอดภัยสารสนเทศ')");
}
} catch (\Exception $e) {
error_log("ensureAdminTables Error: " . $e->getMessage());
// Silently continue if table already upgraded
}
}
function seedDatabase($pdo, $driver = 'mysql')
{
if ($driver === 'sqlite') {
$pdo->exec("
CREATE TABLE IF NOT EXISTS agencies (
id VARCHAR(10) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
code VARCHAR(10) NOT NULL,
admin_password VARCHAR(255) DEFAULT '1234',
gdrive_folder_id VARCHAR(255) DEFAULT NULL
);
CREATE TABLE IF NOT EXISTS categories (
id VARCHAR(10) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
agency_id VARCHAR(20) DEFAULT 'SUPER_ADMIN'
);
CREATE TABLE IF NOT EXISTS news (
id VARCHAR(20) PRIMARY KEY,
doc_num VARCHAR(100) NOT NULL,
title VARCHAR(500) NOT NULL,
agency_id VARCHAR(10) NOT NULL,
category_id VARCHAR(10) NOT NULL,
content TEXT NOT NULL,
publish_date DATE NOT NULL,
is_pinned INTEGER NOT NULL DEFAULT 0,
is_urgent INTEGER NOT NULL DEFAULT 0,
views INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (agency_id) REFERENCES agencies(id) ON DELETE CASCADE,
FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS attachments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
news_id VARCHAR(20) NOT NULL,
file_name VARCHAR(255) NOT NULL,
file_type VARCHAR(20) NOT NULL DEFAULT 'pdf',
file_size VARCHAR(50) DEFAULT '1.0 MB',
file_url TEXT DEFAULT NULL,
FOREIGN KEY (news_id) REFERENCES news(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS system_settings (
setting_key VARCHAR(100) PRIMARY KEY,
setting_value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS templates (
id VARCHAR(50) PRIMARY KEY,
agency_id VARCHAR(10) NOT NULL,
name VARCHAR(100) NOT NULL,
category_id VARCHAR(10) NOT NULL,
doc_num_format VARCHAR(100) NOT NULL,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
");
// Seed Default Agencies
$agencies = [
['MED', 'องค์กรแพทย์ / กลุ่มงานการแพทย์', 'MED', '1234'],
['NURSE', 'กลุ่มงานการพยาบาล', 'NRS', '1234'],
['PHARM', 'กลุ่มงานเภสัชกรรมและคลังยา', 'RX', '1234'],
['IT', 'ศูนย์เทคโนโลยีสารสนเทศ (HIS)', 'IT', '1234'],
['ADMIN', 'กลุ่มงานบริหารทั่วไป / สารบรรณ', 'ADM', '1234']
];
$stmt = $pdo->prepare("INSERT INTO agencies (id, name, code, admin_password) VALUES (?, ?, ?, ?)");
foreach ($agencies as $a) {
$stmt->execute($a);
}
// Seed Default Categories
$cats = [
['MEMO', '📜 บันทึกข้อความ / แจ้งเวียน'],
['ORDERS', '⚖️ คำสั่ง / ประกาศโรงพยาบาล'],
['CPG', '🩺 แนวทาง CPG / ระเบียบ SOP'],
['MEETING', '🎓 ข่าวประชุมวิชาการ / ฝึกอบรม'],
['HR', '🎁 สวัสดิการ / ทรัพยากรบุคคล']
];
$stmtCat = $pdo->prepare("INSERT INTO categories (id, name) VALUES (?, ?)");
foreach ($cats as $c) {
$stmtCat->execute($c);
}
// Seed Default Templates
$templates = [
['TPL-001', 'SUPER_ADMIN', 'แนวทาง CPG', 'CPG', 'สธ 0202/ว {random}', 'แนวทางเวชปฏิบัติ (CPG) การดูแลรักษาผู้ป่วย... ฉบับปรับปรุงใหม่', "เรียน คณะแพทย์, พยาบาล และบุคลากรทางการแพทย์ทุกท่าน\n\nกลุ่มงานการแพทย์ขอแจ้งอนุมัติใช้แนวทางเวชปฏิบัติ (CPG) และคู่มือระเบียบปฏิบัติ (SOP) เรื่อง... ประจำปีงบประมาณ 2569\n\nโปรดศึกษารายละเอียดแนวทาง CPG ตามเอกสารแนบเพื่อถือปฏิบัติตามมาตรฐานเดียวกัน"],
['TPL-002', 'SUPER_ADMIN', 'หนังสือเวียนด่วน', 'MEMO', 'สธ 0201/ว {random}', 'บันทึกข้อความแจ้งเวียนด่วน เรื่อง ...', "เรียน หัวหน้ากลุ่มงานและผู้รับผิดชอบงานทุกฝ่าย\n\nตามที่โรงพยาบาลได้กำหนดมาตรการ... จึงขอเรียนแจ้งแนวทางปฏิบัติเพิ่มเติมดังนี้\n1. ...\n2. ...\n\nจึงเรียนมาเพื่อโปรดทราบและถือปฏิบัติต่อไป"],
['TPL-003', 'SUPER_ADMIN', 'คำสั่งโรงพยาบาล', 'ORDERS', 'คำสั่ง รพ. ที่ {random}/2569', 'คำสั่งแต่งตั้งคณะกรรมการ/คณะทำงาน ...', "เพื่อให้การดำเนินงานด้าน... เป็นไปด้วยความเรียบร้อยและมีประสิทธิภาพ\n\nอาศัยอำนาจตามระเบียบบริหารราชการแผ่นดิน จึงแต่งตั้งคณะทำงานโดยมีรายนามตามเอกสารแนบท้ายคำสั่งนี้"]
];
$stmtTpl = $pdo->prepare("INSERT INTO templates (id, agency_id, name, category_id, doc_num_format, title, content) VALUES (?, ?, ?, ?, ?, ?, ?)");
foreach ($templates as $t) {
$stmtTpl->execute($t);
}
ensureAdminTables($pdo, 'sqlite');
} else {
$sql = file_get_contents(__DIR__ . '/../schema.sql');
$pdo->exec($sql);
ensureAdminTables($pdo, 'mysql');
return;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

File diff suppressed because it is too large Load Diff