Files
2026-09-16 23:20:08 +07:00

73 lines
2.5 KiB
PHP

<?php
// models/DispatchEngine.php
require_once dirname(__DIR__) . '/config/database.php';
require_once __DIR__ . '/User.php';
require_once __DIR__ . '/Job.php';
require_once __DIR__ . '/Setting.php';
require_once __DIR__ . '/Notification.php';
class DispatchEngine {
private $conn;
private $settingModel;
private $userModel;
private $jobModel;
public function __construct() {
$this->conn = Database::getInstance();
$this->settingModel = new Setting();
$this->userModel = new User();
$this->jobModel = new Job();
}
/**
* Run auto-dispatch for a newly created job
* @param int $job_id
* @return bool True if successfully assigned, false if no one available
*/
public function runAutoDispatch($job_id) {
// 1. Check if auto dispatch is enabled
$dispatchSettings = $this->settingModel->getAllFlat();
if (!isset($dispatchSettings['auto_dispatch_enabled']) || $dispatchSettings['auto_dispatch_enabled'] != '1') {
return false;
}
// 2. Find available staff
$staff = $this->userModel->getAvailableStaff();
if (!$staff) {
// No one is available, leave job as pending
return false;
}
$staff_id = $staff['id'];
$staff_name = $staff['full_name'];
// 3. Assign the job
$query = "UPDATE jobs SET status = 'assigned', assigned_to = :staff_id WHERE id = :job_id";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':staff_id', $staff_id);
$stmt->bindParam(':job_id', $job_id);
if ($stmt->execute()) {
// Log timeline
$this->jobModel->logTimeline($job_id, 'assigned', "ระบบจ่ายงานอัตโนมัติไปยัง: " . $staff_name, null);
// Note: Notification will be sent later in the job lifecycle if needed,
// but we can also trigger a specific "Auto Assigned" notification here.
try {
$job = $this->jobModel->getById($job_id);
if ($job) {
$notification = new Notification();
$msg = "🤖 [Auto Dispatch]\nระบบมอบหมายงาน " . $job['job_number'] . "\nให้กับ: " . $staff_name;
$notification->sendToAll($msg);
}
} catch (Exception $e) {
// Ignore
}
return true;
}
return false;
}
}