feat: add api to fetch hr tickets
This commit is contained in:
84
front/ticket.api.php
Normal file
84
front/ticket.api.php
Normal file
@ -0,0 +1,84 @@
|
||||
<?php
|
||||
require_once '../functionsophalglpi.php';
|
||||
include('../inc/includes.php');
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
header('Access-Control-Allow-Methods: GET');
|
||||
header('Access-Control-Allow-Headers: X-API-Key, Content-Type');
|
||||
|
||||
const ALLOWED_ITIL_CATEGORIES = [12, 15, 16, 36, 38, 72];
|
||||
|
||||
// === SECURITY (simple token auth) ===
|
||||
$headers = getallheaders();
|
||||
$apiKey = $headers['X-API-Key'] ?? '';
|
||||
$validKey = getenv('HR_API_KEY'); // store securely in system env or .env
|
||||
|
||||
if ($apiKey !== $validKey) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['error' => 'Unauthorized'], JSON_PRETTY_PRINT);
|
||||
exit;
|
||||
}
|
||||
|
||||
// === Validate & normalize dates ===
|
||||
function check_param($from_date = null, $itilcategories_id = null) {
|
||||
|
||||
// Validate dates
|
||||
if ($from_date && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $from_date)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['error' => 'Invalid start_date format (YYYY-MM-DD)'], JSON_PRETTY_PRINT);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Validate category if provided
|
||||
if ($itilcategories_id !== null) {
|
||||
|
||||
// It must be numeric
|
||||
if (!ctype_digit((string)$itilcategories_id)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['error' => 'Invalid category id (must be numeric)'], JSON_PRETTY_PRINT);
|
||||
exit;
|
||||
}
|
||||
|
||||
// It must be one of the allowed values
|
||||
if (!in_array((int)$itilcategories_id, ALLOWED_ITIL_CATEGORIES, true)) {
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'error' => 'Invalid category id',
|
||||
], JSON_PRETTY_PRINT);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
|
||||
return [$from_date, $itilcategories_id];
|
||||
}
|
||||
|
||||
// ====== ONLY ONE ROUTE: /tickets ======
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
||||
|
||||
$path = basename(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));
|
||||
|
||||
if ($path !== 'tickets') {
|
||||
http_response_code(404);
|
||||
echo json_encode(['error' => 'Route not found'], JSON_PRETTY_PRINT);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Read GET URL params
|
||||
$from_date = $_GET['from_date'] ?? null;
|
||||
$itilcategories_id = $_GET['itilcategories_id'] ?? null;
|
||||
|
||||
[$from_date, $itilcategories_id] = check_param(
|
||||
$from_date,
|
||||
$itilcategories_id
|
||||
);
|
||||
|
||||
// Fetch GLPI data
|
||||
$tickets = get_hr_tickets($from_date, $itilcategories_id);
|
||||
|
||||
echo json_encode($tickets, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Default
|
||||
http_response_code(404);
|
||||
echo json_encode(['error' => 'Invalid request'], JSON_PRETTY_PRINT);
|
||||
Reference in New Issue
Block a user