1
0

feat(helpdesk): add ticket file download and inline image preview

New SOAP method getTicketFile() on BcSoapGateway calls BC's
GetTicketFile to retrieve file attachments as Base64, decodes in
memory and returns binary data without writing to disk.

New proxy endpoint helpdesk/ticket-file-data streams files directly
to the browser with correct MIME type. Images served inline, other
files as download attachment.

TicketCommunicationService now attaches file_entry_no and file_name
to file-type events. Frontend renders download links with bi-download
icon and inline image previews for jpg/png/gif attachments.

Works in both ticket detail and debitor detail communication feeds.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-05 22:49:01 +02:00
parent 659a6d71c5
commit 792f706d9e
12 changed files with 310 additions and 2 deletions

View File

@@ -13,6 +13,7 @@ class BcSoapGateway
private const REQUEST_TIMEOUT = 30;
private const CODEUNIT_NAME = 'ICISupportWebserviceAPI';
private const SOAP_ACTION_GET_TICKET_COMMUNICATION_TEXT = 'urn:microsoft-dynamics-schemas/codeunit/ICISupportWebserviceAPI:GetTicketCommunicationText';
private const SOAP_ACTION_GET_TICKET_FILE = 'urn:microsoft-dynamics-schemas/codeunit/ICISupportWebserviceAPI:GetTicketFile';
public function __construct(
private readonly HelpdeskSettingsGateway $settingsGateway,
@@ -167,12 +168,16 @@ XML;
/**
* @return array{headers?: array<int, string>, basic_user?: string, basic_password?: string, error?: string}
*/
private function buildRequestContext(string $endpoint, string $requestBody): array
private function buildRequestContext(string $endpoint, string $requestBody, string $soapAction = ''): array
{
if ($soapAction === '') {
$soapAction = self::SOAP_ACTION_GET_TICKET_COMMUNICATION_TEXT;
}
$headers = [
'Content-Type: text/xml; charset=utf-8',
'Accept: text/xml,application/xml',
'SOAPAction: "' . self::SOAP_ACTION_GET_TICKET_COMMUNICATION_TEXT . '"',
'SOAPAction: "' . $soapAction . '"',
'Content-Length: ' . strlen($requestBody),
];
@@ -290,6 +295,131 @@ XML;
];
}
/**
* Download a ticket file attachment via SOAP GetTicketFile.
*
* Returns the decoded binary data or an error. Does not write to disk.
*
* @return array{ok: bool, data?: string, filename?: string, error?: string}
*/
public function getTicketFile(int $entryNo, string $contactNo = ''): array
{
if ($entryNo <= 0) {
return ['ok' => false, 'error' => 'Invalid entry number'];
}
if (!$this->settingsGateway->isConfigured()) {
return ['ok' => false, 'error' => 'BC connection not configured'];
}
$endpoint = $this->buildSoapEndpoint();
if ($endpoint === null) {
return ['ok' => false, 'error' => 'Could not derive SOAP endpoint'];
}
$requestBody = $this->buildGetTicketFileEnvelope($entryNo, $contactNo);
$request = $this->buildRequestContext($endpoint, $requestBody, self::SOAP_ACTION_GET_TICKET_FILE);
if (isset($request['error'])) {
return ['ok' => false, 'error' => (string) $request['error']];
}
$response = $this->sendSoapRequest(
$endpoint,
self::SOAP_ACTION_GET_TICKET_FILE,
$requestBody,
(array) ($request['headers'] ?? []),
(string) ($request['basic_user'] ?? ''),
(string) ($request['basic_password'] ?? '')
);
$httpCode = (int) ($response['http_code'] ?? 0);
$rawBody = (string) ($response['body'] ?? '');
if ($httpCode < 200 || $httpCode >= 300) {
return ['ok' => false, 'error' => 'SOAP request failed: HTTP ' . $httpCode];
}
return $this->parseGetTicketFileResponse($rawBody);
}
private function buildGetTicketFileEnvelope(int $entryNo, string $contactNo): string
{
$escapedContactNo = htmlspecialchars($contactNo, ENT_XML1 | ENT_QUOTES, 'UTF-8');
return <<<XML
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:microsoft-dynamics-schemas/codeunit/ICISupportWebserviceAPI">
<soap:Body>
<urn:GetTicketFile>
<urn:entryNo>{$entryNo}</urn:entryNo>
<urn:contactNo>{$escapedContactNo}</urn:contactNo>
<urn:iCISupportFilePort></urn:iCISupportFilePort>
</urn:GetTicketFile>
</soap:Body>
</soap:Envelope>
XML;
}
/**
* @return array{ok: bool, data?: string, filename?: string, error?: string}
*/
private function parseGetTicketFileResponse(string $body): array
{
$body = trim($body);
if ($body === '') {
return ['ok' => false, 'error' => 'Empty SOAP response'];
}
$dom = new \DOMDocument();
$previousLibxmlState = libxml_use_internal_errors(true);
$loaded = $dom->loadXML($body);
libxml_clear_errors();
libxml_use_internal_errors($previousLibxmlState);
if (!$loaded) {
return ['ok' => false, 'error' => 'Invalid SOAP XML response'];
}
$xpath = new \DOMXPath($dom);
$faultNode = $xpath->query("//*[local-name()='Fault']/*[local-name()='faultstring']")->item(0);
if ($faultNode instanceof \DOMNode) {
return ['ok' => false, 'error' => 'SOAP fault: ' . trim((string) $faultNode->textContent)];
}
$returnNode = $xpath->query("//*[local-name()='return_value']")->item(0);
$returnValue = ($returnNode instanceof \DOMNode && is_numeric(trim((string) $returnNode->textContent)))
? (int) trim((string) $returnNode->textContent)
: 0;
if ($returnValue !== 100) {
return ['ok' => false, 'error' => 'BC returned error code ' . $returnValue];
}
// Collect Base64 parts
$partNodes = $xpath->query("//*[local-name()='PartData']");
$base64 = '';
if ($partNodes !== false) {
foreach ($partNodes as $node) {
$base64 .= trim((string) $node->textContent);
}
}
if ($base64 === '') {
return ['ok' => false, 'error' => 'No file data in response'];
}
// Handle data URI prefix (data:application/octet-stream;base64,...)
if (str_contains($base64, ',')) {
$base64 = substr($base64, strpos($base64, ',') + 1);
}
$decoded = base64_decode($base64, true);
if ($decoded === false) {
return ['ok' => false, 'error' => 'Base64 decode failed'];
}
return ['ok' => true, 'data' => $decoded];
}
private function buildSoapEndpoint(): ?string
{
$baseUrl = trim($this->settingsGateway->getODataBaseUrl());

View File

@@ -287,6 +287,8 @@ class TicketCommunicationService
'type_variant' => $typeVariant,
'state_subtype' => $stateSubtype,
'message' => $message,
'file_entry_no' => $typeVariant === 'file' ? $entryNo : '',
'file_name' => $typeVariant === 'file' ? $this->extractFilenameFromMessage($message, $recordId) : '',
'source' => $soapMessage !== '' ? 'soap' : 'odata',
];
@@ -1053,6 +1055,29 @@ class TicketCommunicationService
return $result;
}
/**
* Extract a filename from the message or record ID of a file-type log entry.
*/
private function extractFilenameFromMessage(string $message, string $recordId): string
{
// Message itself may contain the filename
$trimmed = trim($message);
if ($trimmed !== '' && str_contains($trimmed, '.') && !str_contains($trimmed, ' ')) {
return $trimmed;
}
// Record_ID sometimes contains the filename
$recordTrimmed = trim($recordId);
if ($recordTrimmed !== '' && str_contains($recordTrimmed, '.')) {
// Extract last segment after colon or space that looks like a filename
if (preg_match('/([^\s:]+\.\w{2,5})$/i', $recordTrimmed, $m)) {
return $m[1];
}
}
return $trimmed !== '' ? $trimmed : '';
}
private function normalizeActorRole(string $createdByType, string $actor): string
{
$type = mb_strtolower(trim($createdByType));