37338-vm/_init_single_instance.php
2026-03-02 19:32:17 +00:00

53 lines
1.8 KiB
PHP

<?php
require_once 'lib/ErrorHandler.php';
register_error_handler();
require_once 'db/config.php';
require_once 'WorkflowEngine.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
header('Content-Type: application/json');
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['error' => ['message' => 'Authentication required.']]);
exit;
}
$userId = $_SESSION['user_id'];
$personId = filter_input(INPUT_POST, 'person_id', FILTER_VALIDATE_INT);
$processDefinitionId = filter_input(INPUT_POST, 'process_id', FILTER_VALIDATE_INT);
$subjectType = filter_input(INPUT_POST, 'subject_type', FILTER_SANITIZE_STRING);
$subjectId = filter_input(INPUT_POST, 'subject_id', FILTER_VALIDATE_INT);
$processCode = filter_input(INPUT_POST, 'process_code', FILTER_SANITIZE_STRING);
$mode = filter_input(INPUT_POST, 'mode', FILTER_SANITIZE_STRING) ?: 'resume_or_create';
if ($personId && !$subjectType) {
$subjectType = 'person';
$subjectId = $personId;
}
$pdo = db();
if ($processDefinitionId && !$processCode) {
$stmt = $pdo->prepare("SELECT code FROM process_definitions WHERE id = ?");
$stmt->execute([$processDefinitionId]);
$processCode = $stmt->fetchColumn();
}
if (!$subjectId || !$subjectType || !$processCode) {
throw new InvalidArgumentException('Invalid or missing subject_type, subject_id, or process_code.');
}
$engine = new WorkflowEngine();
$instance = $engine->getOrCreateInstanceBySubject($subjectType, $subjectId, $processCode, $userId, $mode);
if ($instance && isset($instance['instance_id'])) {
echo json_encode(['success' => true, 'message' => 'Process initialized successfully.', 'instance_id' => $instance['instance_id']]);
} else {
throw new Exception("Failed to initialize process for an unknown reason.");
}