1
0

feat(helpdesk): add software updates tracking with BC ticket integration

New Updates page in the Helpdesk module that fetches UPDATE/UPDATE-HF tickets
from Business Central (PBI_LV_Tickets) and allows assigning a domain and Gitea
link via a dialog. Ticket status (from BC) and assignment status (local) are
shown as separate columns with filters for both plus type and free-text search.
Assigned updates also appear on the domain detail page. Includes session-cached
BC fetch with refresh button, admin permissions, migration, and 16 unit tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-16 13:21:40 +02:00
parent 693d33a0c8
commit da0abc824a
23 changed files with 1971 additions and 6 deletions

View File

@@ -24,6 +24,8 @@ class BcODataGateway
public const ENTITY_MEETINGS = 'FS_Debitor_Meetings';
/** @api Used by listContractTypes() */
public const ENTITY_CONTRACT_TYPES = 'FS_Contract_Types';
/** @api Used by handover-domains-data endpoint and domains-data endpoint */
public const ENTITY_CONTRACT_DOMAINS = 'FS_Contract_Domains';
private const CONNECT_TIMEOUT = 10;
private const REQUEST_TIMEOUT = 30;
@@ -687,6 +689,62 @@ class BcODataGateway
return ['tickets' => $allTickets, 'truncated' => $truncated];
}
/**
* Fetch all update/hotfix tickets across all customers.
*
* Queries PBI_LV_Tickets with Category_1_Code filter for UPDATE and UPDATE-HF.
* Results are cached in session with standard TTL.
* Uses pagination via @odata.nextLink (same as risk radar).
*
* @return array{tickets: array<int, array<string, mixed>>, truncated: bool}
*/
public function fetchUpdateTickets(): array
{
$tenantScope = DebitorCacheControl::resolveTenantScope($this->sessionStore->all());
$cacheKey = DebitorCacheControl::updateTicketsKey($tenantScope);
$cached = $this->sessionStore->get($cacheKey);
if (is_array($cached) && isset($cached['fetched_at']) && (time() - (int) $cached['fetched_at']) < DebitorCacheControl::TTL_STANDARD_SECONDS) {
$tickets = $cached['tickets'] ?? [];
$truncated = (bool) ($cached['truncated'] ?? false);
if (is_array($tickets)) {
return ['tickets' => $tickets, 'truncated' => $truncated];
}
}
$select = 'No,Description,Customer_No,Cust_Name,Category_1_Code,Ticket_State,Created_On,Last_Activity_Date,Support_User_Name';
$baseUrl = $this->settingsGateway->buildEntityUrl(self::ENTITY_TICKETS_LV);
// BC OData often rejects `or` in $filter — fetch each category separately and merge.
$allTickets = [];
$truncated = false;
foreach (['UPDATE', 'UPDATE-HF'] as $category) {
$filter = "Category_1_Code eq '" . $category . "'";
$url = $baseUrl
. '?$top=500'
. '&$select=' . rawurlencode($select)
. '&$filter=' . rawurlencode($filter)
. '&$orderby=' . rawurlencode('Created_On desc');
$partial = $this->paginateOData($url, 10);
foreach ($partial['tickets'] as $ticket) {
$allTickets[] = $ticket;
}
if ($partial['truncated']) {
$truncated = true;
}
}
$result = ['tickets' => $this->dedupeRowsByNo($allTickets), 'truncated' => $truncated];
$this->sessionStore->set($cacheKey, [
'tickets' => $result['tickets'],
'truncated' => $result['truncated'],
'fetched_at' => time(),
]);
return $result;
}
/**
* Get contracts for a customer by customer number.
*
@@ -798,6 +856,116 @@ class BcODataGateway
return $this->extractODataValues($response);
}
/**
* Get all domains (unfiltered, for the domains list page).
*
* @api Called from domains-data endpoint
* @return array<int, array<string, mixed>>
*/
public function listDomains(): array
{
$select = 'No,Customer_No,Customer_Name,URL,State,Administration';
$url = $this->settingsGateway->buildEntityUrl(self::ENTITY_CONTRACT_DOMAINS)
. '?$top=5000'
. '&$select=' . rawurlencode($select)
. '&$orderby=' . rawurlencode('Customer_Name asc');
$response = $this->request('GET', $url);
if ($response === null) {
return [];
}
return $this->extractODataValues($response);
}
/**
* Get all contract lines of type "Domain".
*
* Returns contract line metadata for domain-type lines,
* keyed by DNS number (No field). Used to enrich the domain
* list with contract type information (PI_Header_Type).
*
* @return array<int, array<string, mixed>>
*/
public function listDomainContractLines(): array
{
$filter = "Type eq 'Domain'";
$select = 'No,Header_No,PI_Header_Type,PI_Header_Description,PI_Header_State,Line_State';
$url = $this->settingsGateway->buildEntityUrl(self::ENTITY_CONTRACT_LINES)
. '?$filter=' . rawurlencode($filter)
. '&$top=5000'
. '&$select=' . rawurlencode($select)
. '&$orderby=' . rawurlencode('No asc');
$response = $this->request('GET', $url);
if ($response === null) {
return [];
}
return $this->extractODataValues($response);
}
/**
* Get a single domain by its domain number.
*
* @api Called from domain($id) action
* @return array<string, mixed>|null
*/
public function getDomain(string $domainNo): ?array
{
$domainNo = trim($domainNo);
if ($domainNo === '') {
return null;
}
$escaped = $this->escapeODataStrictUserInput($domainNo);
$filter = "No eq '" . $escaped . "'";
$select = 'No,Customer_No,Customer_Name,URL,State,Administration';
$url = $this->settingsGateway->buildEntityUrl(self::ENTITY_CONTRACT_DOMAINS)
. '?$filter=' . rawurlencode($filter)
. '&$top=1'
. '&$select=' . rawurlencode($select);
$response = $this->request('GET', $url);
if ($response === null) {
return null;
}
$values = $this->extractODataValues($response);
return $values[0] ?? null;
}
/**
* Get active domains for a customer.
*
* @api Called from handover-domains-data endpoint
* @return array<int, array<string, mixed>>
*/
public function getDomainsForCustomer(string $customerNo): array
{
$customerNo = trim($customerNo);
if ($customerNo === '') {
return [];
}
$escaped = $this->escapeODataStrictUserInput($customerNo);
$filter = "Customer_No eq '" . $escaped . "' and State eq 'Aktiv'";
$select = 'No,Customer_No,URL,State';
$url = $this->settingsGateway->buildEntityUrl(self::ENTITY_CONTRACT_DOMAINS)
. '?$filter=' . rawurlencode($filter)
. '&$top=200'
. '&$select=' . rawurlencode($select)
. '&$orderby=' . rawurlencode('URL asc');
$response = $this->request('GET', $url);
if ($response === null) {
return [];
}
return $this->extractODataValues($response);
}
/**
* Get meetings/appointments for a customer.
*

View File

@@ -97,6 +97,12 @@ final class DebitorCacheControl
return 'module.helpdesk.risk-radar.v1.' . $tenantScope . '.' . $periodDays;
}
/** @api Used by BcODataGateway::fetchUpdateTickets() */
public static function updateTicketsKey(string $tenantScope): string
{
return 'module.helpdesk.update-tickets.v1.' . $tenantScope;
}
/**
* @return array<int, string>
*/

View File

@@ -0,0 +1,270 @@
<?php
namespace MintyPHP\Module\Helpdesk\Service;
use MintyPHP\Module\Helpdesk\Repository\UpdateRepository;
/** @api Called from pages/helpdesk/updates action files */
class UpdateService
{
public const STATUS_OPEN = 'open';
public const STATUS_ASSIGNED = 'assigned';
public const ALL_STATUSES = [
self::STATUS_OPEN,
self::STATUS_ASSIGNED,
];
public const CATEGORY_UPDATE = 'UPDATE';
public const CATEGORY_HOTFIX = 'UPDATE-HF';
public const UPDATE_CATEGORIES = [
self::CATEGORY_UPDATE,
self::CATEGORY_HOTFIX,
];
public function __construct(
private readonly UpdateRepository $repository,
private readonly BcODataGateway $bcGateway,
) {
}
/**
* Get the merged list of BC update tickets with local assignment data.
*
* Fetches all UPDATE/UPDATE-HF tickets from BC, then left-joins with
* local helpdesk_updates records to enrich with domain/gitea assignments.
*
* @param array<string, mixed> $filters Optional filters: status, category
* @return array{rows: list<array<string, mixed>>, truncated: bool}
*/
public function getUpdatesList(int $tenantId, array $filters = []): array
{
$bcResult = $this->bcGateway->fetchUpdateTickets();
$bcTickets = $bcResult['tickets'];
$truncated = $bcResult['truncated'];
$localRows = $this->repository->findAllByTenant($tenantId);
$localByTicketNo = [];
foreach ($localRows as $local) {
$ticketNo = trim((string) ($local['ticket_no'] ?? ''));
if ($ticketNo !== '') {
$localByTicketNo[$ticketNo] = $local;
}
}
$filterStatus = trim((string) ($filters['status'] ?? ''));
$filterCategory = trim((string) ($filters['category'] ?? ''));
$filterTicketState = trim((string) ($filters['ticket_state'] ?? ''));
$filterSearch = trim((string) ($filters['search'] ?? ''));
$merged = [];
foreach ($bcTickets as $ticket) {
$ticketNo = trim((string) ($ticket['No'] ?? ''));
if ($ticketNo === '') {
continue;
}
$categoryCode = trim((string) ($ticket['Category_1_Code'] ?? ''));
if (!in_array($categoryCode, self::UPDATE_CATEGORIES, true)) {
continue;
}
$local = $localByTicketNo[$ticketNo] ?? null;
$status = $local !== null ? (string) ($local['status'] ?? self::STATUS_OPEN) : self::STATUS_OPEN;
$ticketState = trim((string) ($ticket['Ticket_State'] ?? ''));
// Apply filters
if ($filterStatus !== '' && $filterStatus !== 'all' && $status !== $filterStatus) {
continue;
}
if ($filterCategory !== '' && $filterCategory !== 'all' && $categoryCode !== $filterCategory) {
continue;
}
if ($filterTicketState !== '' && $filterTicketState !== 'all' && $ticketState !== $filterTicketState) {
continue;
}
$debitorNo = trim((string) ($ticket['Customer_No'] ?? ''));
$debitorName = trim((string) ($ticket['Cust_Name'] ?? ''));
// Search filter: match against ticket no, debitor name/no, domain url, gitea path
if ($filterSearch !== '') {
$searchHaystack = strtolower($ticketNo . ' ' . $debitorName . ' ' . $debitorNo . ' ' . ($local['domain_url'] ?? '') . ' ' . ($local['gitea_path'] ?? ''));
if (strpos($searchHaystack, strtolower($filterSearch)) === false) {
continue;
}
}
$merged[] = [
'ticket_no' => $ticketNo,
'ticket_description' => trim((string) ($ticket['Description'] ?? '')),
'category_code' => $categoryCode,
'debitor_no' => $debitorNo,
'debitor_name' => $debitorName,
'ticket_state' => trim((string) ($ticket['Ticket_State'] ?? '')),
'support_user' => trim((string) ($ticket['Support_User_Name'] ?? '')),
'created_on' => trim((string) ($ticket['Created_On'] ?? '')),
'last_activity' => trim((string) ($ticket['Last_Activity_Date'] ?? '')),
'domain_no' => (string) ($local['domain_no'] ?? ''),
'domain_url' => (string) ($local['domain_url'] ?? ''),
'gitea_path' => (string) ($local['gitea_path'] ?? ''),
'notes' => (string) ($local['notes'] ?? ''),
'status' => $status,
'local_id' => $local !== null ? (int) ($local['id'] ?? 0) : null,
];
}
return ['rows' => $merged, 'truncated' => $truncated];
}
/**
* Assign a domain and gitea path to an update ticket.
*
* Creates a new helpdesk_updates record or updates an existing one.
*
* @return array{ok: bool, id: int|null, errors: array<string, string>}
*/
public function assignUpdate(
int $tenantId,
string $ticketNo,
string $debitorNo,
string $debitorName,
string $categoryCode,
string $domainNo,
string $domainUrl,
string $giteaPath,
string $notes,
int $userId,
): array {
$errors = [];
$ticketNo = trim($ticketNo);
if ($ticketNo === '') {
$errors['ticket_no'] = t('Ticket number is required');
}
$debitorNo = trim($debitorNo);
if ($debitorNo === '') {
$errors['debitor_no'] = t('Debitor number is required');
}
$categoryCode = trim($categoryCode);
if (!in_array($categoryCode, self::UPDATE_CATEGORIES, true)) {
$errors['category_code'] = t('Invalid category');
}
if ($errors !== []) {
return ['ok' => false, 'id' => null, 'errors' => $errors];
}
$domainNo = trim($domainNo);
$domainUrl = trim($domainUrl);
$giteaPath = trim($giteaPath);
$notes = trim($notes);
$status = ($domainNo !== '' || $giteaPath !== '') ? self::STATUS_ASSIGNED : self::STATUS_OPEN;
$existing = $this->repository->findByTicketNo($tenantId, $ticketNo);
if ($existing !== null) {
$existingId = (int) ($existing['id'] ?? 0);
if ($existingId <= 0) {
return ['ok' => false, 'id' => null, 'errors' => ['general' => t('Failed to save')]];
}
$updated = $this->repository->updateAssignment($tenantId, $existingId, [
'domain_no' => $domainNo,
'domain_url' => $domainUrl,
'gitea_path' => $giteaPath,
'notes' => $notes,
'status' => $status,
'updated_by' => $userId,
]);
if (!$updated) {
return ['ok' => false, 'id' => null, 'errors' => ['general' => t('Failed to save')]];
}
return ['ok' => true, 'id' => $existingId, 'errors' => []];
}
$id = $this->repository->insert([
'tenant_id' => $tenantId,
'ticket_no' => $ticketNo,
'category_code' => $categoryCode,
'debitor_no' => $debitorNo,
'debitor_name' => trim($debitorName),
'domain_no' => $domainNo,
'domain_url' => $domainUrl,
'gitea_path' => $giteaPath,
'notes' => $notes,
'status' => $status,
'created_by' => $userId,
]);
if ($id === null) {
return ['ok' => false, 'id' => null, 'errors' => ['general' => t('Failed to save')]];
}
return ['ok' => true, 'id' => $id, 'errors' => []];
}
public static function statusLabel(string $status): string
{
return match ($status) {
self::STATUS_OPEN => t('Unassigned'),
self::STATUS_ASSIGNED => t('Assigned'),
default => $status,
};
}
public static function statusVariant(string $status): string
{
return match ($status) {
self::STATUS_OPEN => 'warning',
self::STATUS_ASSIGNED => 'success',
default => 'neutral',
};
}
public static function ticketStateLabel(string $state): string
{
return match ($state) {
'Offen' => t('Open'),
'In Bearbeitung' => t('In progress'),
'Erledigt' => t('Resolved'),
'Geschlossen' => t('Closed'),
default => $state !== '' ? $state : '—',
};
}
public static function ticketStateVariant(string $state): string
{
return match ($state) {
'Offen' => 'warning',
'In Bearbeitung' => 'info',
'Erledigt' => 'success',
'Geschlossen' => 'neutral',
default => 'neutral',
};
}
public static function categoryLabel(string $code): string
{
return match ($code) {
self::CATEGORY_UPDATE => t('Update'),
self::CATEGORY_HOTFIX => t('Hotfix'),
default => $code,
};
}
public static function categoryVariant(string $code): string
{
return match ($code) {
self::CATEGORY_UPDATE => 'neutral',
self::CATEGORY_HOTFIX => 'warning',
default => 'neutral',
};
}
}