Xinon mobile/improve
This commit is contained in:
@@ -0,0 +1,929 @@
|
||||
<?php
|
||||
|
||||
require_once APPDIR . 'MobileApp/Shared/MobileAppBaseHandler.php';
|
||||
|
||||
/**
|
||||
* Workorder (Aufträge) Handler
|
||||
*
|
||||
* Handles all endpoints for the Workorder module in MobileApp.
|
||||
* API Base: /MobileApp/Workorder/Workorder/{action}
|
||||
*
|
||||
* Ports functionality from WorkorderCompanyController and WorkorderBaseController.
|
||||
*/
|
||||
class WorkorderHandler extends MobileAppBaseHandler {
|
||||
|
||||
protected $requiredPermission = 'RMLCompany';
|
||||
|
||||
/** @var array Status definitions for workorders */
|
||||
protected $statusOptions = [
|
||||
'new' => ['text' => 'Neu', 'color' => 'primary'],
|
||||
'assigned' => ['text' => 'Zugewiesen', 'color' => 'info'],
|
||||
'scheduled' => ['text' => 'Geplant', 'color' => 'warning'],
|
||||
'in_progress' => ['text' => 'In Bearbeitung', 'color' => 'warning'],
|
||||
'correction_requested' => ['text' => 'Korrektur angefordert', 'color' => 'danger'],
|
||||
'intervention_required' => ['text' => 'Eingriff erforderlich', 'color' => 'danger'],
|
||||
'civil_engineering_required' => ['text' => 'Tiefbau benötigt', 'color' => 'orange'],
|
||||
'civil_engineering_completed' => ['text' => 'Tiefbau abgeschlossen', 'color' => 'success'],
|
||||
'problem_solved' => ['text' => 'Problem gelöst', 'color' => 'success'],
|
||||
'documented' => ['text' => 'Dokumentiert', 'color' => 'success'],
|
||||
'completed' => ['text' => 'Abgeschlossen', 'color' => 'secondary'],
|
||||
'charged' => ['text' => 'Verrechnet', 'color' => 'purple'],
|
||||
'cancelled' => ['text' => 'Abgebrochen', 'color' => 'danger'],
|
||||
'archived' => ['text' => 'Archiviert', 'color' => 'muted'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Get workorders list for the company
|
||||
* POST /MobileApp/Workorder/Workorder/get
|
||||
*/
|
||||
public function getAction() {
|
||||
$postData = $this->getPostData();
|
||||
|
||||
$pagination = $postData['pagination'] ?? ['page' => 1, 'per_page' => 20];
|
||||
$filters = $postData['filters'] ?? [];
|
||||
$order = $postData['order'] ?? [];
|
||||
$search = trim($postData['search'] ?? '');
|
||||
|
||||
// Get company for current user
|
||||
$company = WorkorderCompanyModel::getFirst(['addressId' => $this->user->address_id]);
|
||||
if (!$company) {
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'workorders' => [],
|
||||
'pagination' => ['page' => 1, 'per_page' => $pagination['per_page'], 'total' => 0]
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build workorders query
|
||||
$workorders = WorkorderModel::getCompanyWorkorders(
|
||||
$filters,
|
||||
$pagination['per_page'],
|
||||
($pagination['page'] - 1) * $pagination['per_page'],
|
||||
$order,
|
||||
$company->id,
|
||||
$search
|
||||
);
|
||||
|
||||
$totalCount = WorkorderModel::countCompanyWorkorders($filters, $company->id, $search);
|
||||
|
||||
// Transform for mobile app
|
||||
$result = [];
|
||||
foreach ($workorders as $wo) {
|
||||
$result[] = $this->transformWorkorder($wo);
|
||||
}
|
||||
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'workorders' => $result,
|
||||
'pagination' => [
|
||||
'page' => intval($pagination['page']),
|
||||
'per_page' => intval($pagination['per_page']),
|
||||
'total' => $totalCount,
|
||||
'totalPages' => ceil($totalCount / $pagination['per_page'])
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get single workorder details
|
||||
* GET /MobileApp/Workorder/Workorder/getWorkorder?id=X
|
||||
*/
|
||||
public function getWorkorderAction() {
|
||||
$id = intval($this->request->id ?? 0);
|
||||
|
||||
if (!$id) {
|
||||
self::returnJson(['success' => false, 'message' => 'ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify user has access
|
||||
$company = WorkorderCompanyModel::getFirst(['addressId' => $this->user->address_id]);
|
||||
if (!$company) {
|
||||
self::returnJson(['success' => false, 'message' => 'Keine Berechtigung']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get workorder with full joined data
|
||||
$workorder = $this->getWorkorderWithDetails($id, $company->id);
|
||||
if (!$workorder) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrag nicht gefunden']);
|
||||
return;
|
||||
}
|
||||
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'workorder' => $this->transformWorkorder($workorder, true)
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get complete workorder detail (combined endpoint)
|
||||
* Returns workorder, documentation, tenant config, and checklist in one request
|
||||
* GET /MobileApp/Workorder/Workorder/getWorkorderDetail?id=X
|
||||
*/
|
||||
public function getWorkorderDetailAction() {
|
||||
$id = intval($this->request->id ?? 0);
|
||||
|
||||
if (!$id) {
|
||||
self::returnJson(['success' => false, 'message' => 'ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify user has access
|
||||
$company = WorkorderCompanyModel::getFirst(['addressId' => $this->user->address_id]);
|
||||
if (!$company) {
|
||||
self::returnJson(['success' => false, 'message' => 'Keine Berechtigung']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get workorder with full joined data
|
||||
$workorderData = $this->getWorkorderWithDetails($id, $company->id);
|
||||
if (!$workorderData) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrag nicht gefunden']);
|
||||
return;
|
||||
}
|
||||
|
||||
$workorder = $this->transformWorkorder($workorderData, true);
|
||||
|
||||
// Get tenant config
|
||||
$tenantConfig = $this->getTenantConfigFromWorkorder($id);
|
||||
$tenantConfigData = null;
|
||||
$translationMap = [];
|
||||
|
||||
if ($tenantConfig) {
|
||||
$customTypes = json_decode($tenantConfig->documentationTypes, true) ?? [];
|
||||
$translationMap = array_merge(
|
||||
['civil_engineering_photo' => 'Tiefbau_Foto'],
|
||||
array_column($customTypes, 'text', 'value')
|
||||
);
|
||||
|
||||
$tenantConfigData = [
|
||||
'documentationTypes' => $customTypes,
|
||||
'civilEngineeringDocsRequired' => (bool)$tenantConfig->civilEngineeringDocsRequired,
|
||||
'interventionTypes' => json_decode($tenantConfig->interventionTypes, true) ?? [],
|
||||
'requireCableLength' => (bool)$tenantConfig->requireCableLength,
|
||||
'requireCableType' => (bool)$tenantConfig->requireCableType,
|
||||
];
|
||||
}
|
||||
|
||||
// Get documentation
|
||||
$docs = WorkorderDocumentationModel::getAll(
|
||||
['workorderId' => $id],
|
||||
null, 0,
|
||||
['key' => 'create', 'order' => 'ASC']
|
||||
);
|
||||
|
||||
$typeCounts = [];
|
||||
$responseDocs = [];
|
||||
|
||||
foreach ($docs as $doc) {
|
||||
$file = new File($doc->fileId);
|
||||
$documentTypeKey = $doc->documentType;
|
||||
$typeCounts[$documentTypeKey] = ($typeCounts[$documentTypeKey] ?? 0) + 1;
|
||||
$originalFilename = $file->orig_filename ?? $file->filename;
|
||||
$extension = pathinfo($originalFilename, PATHINFO_EXTENSION);
|
||||
$translatedType = $translationMap[$documentTypeKey] ?? $documentTypeKey;
|
||||
$newFilename = "{$translatedType}_{$typeCounts[$documentTypeKey]}." . strtolower($extension);
|
||||
|
||||
$responseDocs[] = [
|
||||
'id' => $doc->id,
|
||||
'fileId' => $doc->fileId,
|
||||
'fileName' => $newFilename,
|
||||
'description' => $doc->description,
|
||||
'documentType' => $documentTypeKey,
|
||||
'documentTypeText' => $translationMap[$documentTypeKey] ?? $documentTypeKey,
|
||||
'userName' => UserModel::getOne($doc->createBy)->name ?? 'Unbekannt',
|
||||
'mimetype' => $file->mimetype ?? 'application/octet-stream',
|
||||
'create' => $doc->create,
|
||||
'createFormatted' => date('d.m.Y H:i', $doc->create),
|
||||
'previewUrl' => "/File/Download/{$doc->fileId}",
|
||||
];
|
||||
}
|
||||
|
||||
// Get journals
|
||||
$journals = WorkorderJournalModel::getAll(
|
||||
['workorderId' => $id],
|
||||
null, 0,
|
||||
['key' => 'create', 'order' => 'DESC']
|
||||
);
|
||||
|
||||
$responseJournals = [];
|
||||
foreach ($journals as $journal) {
|
||||
$responseJournals[] = [
|
||||
'id' => $journal->id,
|
||||
'text' => $journal->text,
|
||||
'statusChange' => $journal->statusChange ?? null,
|
||||
'createByName' => UserModel::getOne($journal->createBy)->name ?? 'Unbekannt',
|
||||
'create' => $journal->create,
|
||||
'createFormatted' => date('d.m.Y H:i', $journal->create),
|
||||
];
|
||||
}
|
||||
|
||||
// Build checklist
|
||||
$docTypes = $tenantConfigData['documentationTypes'] ?? [];
|
||||
$uploadedTypes = array_column((array)$docs, 'documentType');
|
||||
$uploadedTypeCounts = array_count_values($uploadedTypes);
|
||||
|
||||
$checklist = [];
|
||||
$completedCount = 0;
|
||||
|
||||
foreach ($docTypes as $type) {
|
||||
$isCompleted = isset($uploadedTypeCounts[$type['value']]) && $uploadedTypeCounts[$type['value']] > 0;
|
||||
if ($isCompleted) $completedCount++;
|
||||
|
||||
$checklist[] = [
|
||||
'type' => $type['value'],
|
||||
'text' => $type['text'],
|
||||
'required' => $type['required'] ?? false,
|
||||
'completed' => $isCompleted,
|
||||
'count' => $uploadedTypeCounts[$type['value']] ?? 0,
|
||||
];
|
||||
}
|
||||
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'workorder' => $workorder,
|
||||
'tenantConfig' => $tenantConfigData,
|
||||
'docs' => $responseDocs,
|
||||
'journals' => $responseJournals,
|
||||
'checklist' => $checklist,
|
||||
'checklistProgress' => [
|
||||
'completed' => $completedCount,
|
||||
'total' => count($docTypes),
|
||||
'allRequired' => $this->allRequiredCompleted($checklist)
|
||||
]
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get documentation and journals for a workorder
|
||||
* GET /MobileApp/Workorder/Workorder/getDocumentation?workorderId=X
|
||||
*/
|
||||
public function getDocumentationAction() {
|
||||
$workorderId = intval($this->request->workorderId ?? 0);
|
||||
|
||||
if (!$workorderId) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrags-ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get documentation
|
||||
$docs = WorkorderDocumentationModel::getAll(
|
||||
['workorderId' => $workorderId],
|
||||
null, 0,
|
||||
['key' => 'create', 'order' => 'ASC']
|
||||
);
|
||||
|
||||
// Get journals
|
||||
$journals = WorkorderJournalModel::getAll(
|
||||
['workorderId' => $workorderId],
|
||||
null, 0,
|
||||
['key' => 'create', 'order' => 'DESC']
|
||||
);
|
||||
|
||||
// Get tenant config for type translations
|
||||
$tenantConfig = $this->getTenantConfigFromWorkorder($workorderId);
|
||||
$translationMap = [];
|
||||
if ($tenantConfig && !empty($tenantConfig->documentationTypes)) {
|
||||
$customTypes = json_decode($tenantConfig->documentationTypes, true);
|
||||
$customMap = array_column($customTypes, 'text', 'value');
|
||||
$translationMap = array_merge(['civil_engineering_photo' => 'Tiefbau_Foto'], $customMap);
|
||||
}
|
||||
|
||||
// Transform docs
|
||||
$responseDocs = [];
|
||||
$typeCounts = [];
|
||||
|
||||
foreach ($docs as $doc) {
|
||||
$file = new File($doc->fileId);
|
||||
$documentTypeKey = $doc->documentType;
|
||||
$typeCounts[$documentTypeKey] = ($typeCounts[$documentTypeKey] ?? 0) + 1;
|
||||
$originalFilename = $file->orig_filename ?? $file->filename;
|
||||
$extension = pathinfo($originalFilename, PATHINFO_EXTENSION);
|
||||
$translatedType = $translationMap[$documentTypeKey] ?? $documentTypeKey;
|
||||
$newFilename = "{$translatedType}_{$typeCounts[$documentTypeKey]}." . strtolower($extension);
|
||||
|
||||
$responseDocs[] = [
|
||||
'id' => $doc->id,
|
||||
'fileId' => $doc->fileId,
|
||||
'fileName' => $newFilename,
|
||||
'description' => $doc->description,
|
||||
'documentType' => $documentTypeKey,
|
||||
'documentTypeText' => $translationMap[$documentTypeKey] ?? $documentTypeKey,
|
||||
'userName' => UserModel::getOne($doc->createBy)->name ?? 'Unbekannt',
|
||||
'mimetype' => $file->mimetype ?? 'application/octet-stream',
|
||||
'create' => $doc->create,
|
||||
'createFormatted' => date('d.m.Y H:i', $doc->create),
|
||||
'previewUrl' => "/File/Download/{$doc->fileId}",
|
||||
];
|
||||
}
|
||||
|
||||
// Transform journals
|
||||
$responseJournals = [];
|
||||
foreach ($journals as $journal) {
|
||||
$responseJournals[] = [
|
||||
'id' => $journal->id,
|
||||
'text' => $journal->text,
|
||||
'statusChange' => $journal->statusChange ?? null,
|
||||
'createByName' => UserModel::getOne($journal->createBy)->name ?? 'Unbekannt',
|
||||
'create' => $journal->create,
|
||||
'createFormatted' => date('d.m.Y H:i', $journal->create),
|
||||
];
|
||||
}
|
||||
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'docs' => $responseDocs,
|
||||
'journals' => $responseJournals,
|
||||
'docCount' => count($responseDocs),
|
||||
'journalCount' => count($responseJournals)
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tenant configuration
|
||||
* GET /MobileApp/Workorder/Workorder/getTenantConfig?workorderId=X
|
||||
*/
|
||||
public function getTenantConfigAction() {
|
||||
$workorderId = intval($this->request->workorderId ?? 0);
|
||||
|
||||
$tenantConfig = $this->getTenantConfigFromWorkorder($workorderId);
|
||||
|
||||
if (!$tenantConfig) {
|
||||
self::returnJson(['success' => false, 'message' => 'Keine Mandantenkonfiguration gefunden']);
|
||||
return;
|
||||
}
|
||||
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'documentationTypes' => json_decode($tenantConfig->documentationTypes, true) ?? [],
|
||||
'civilEngineeringDocsRequired' => (bool)$tenantConfig->civilEngineeringDocsRequired,
|
||||
'interventionTypes' => json_decode($tenantConfig->interventionTypes, true) ?? [],
|
||||
'requireCableLength' => (bool)$tenantConfig->requireCableLength,
|
||||
'requireCableType' => (bool)$tenantConfig->requireCableType,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload documentation files
|
||||
* POST /MobileApp/Workorder/Workorder/uploadDocumentation
|
||||
*/
|
||||
public function uploadDocumentationAction() {
|
||||
if (empty($_FILES['files']) && empty($_FILES['file'])) {
|
||||
self::returnJson(['success' => false, 'message' => 'Keine Datei hochgeladen']);
|
||||
return;
|
||||
}
|
||||
|
||||
$workorderId = intval($_POST['workorderId'] ?? 0);
|
||||
if (!$workorderId) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrags-ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
$documentType = $_POST['documentType'] ?? 'general';
|
||||
$description = $_POST['description'] ?? '';
|
||||
|
||||
// Handle both single file and multiple files
|
||||
if (!empty($_FILES['files'])) {
|
||||
foreach ($_FILES['files']['name'] as $index => $name) {
|
||||
if ($_FILES['files']['error'][$index] === UPLOAD_ERR_OK) {
|
||||
$_FILES['file'] = [
|
||||
'name' => $name,
|
||||
'type' => $_FILES['files']['type'][$index],
|
||||
'tmp_name' => $_FILES['files']['tmp_name'][$index],
|
||||
'error' => $_FILES['files']['error'][$index],
|
||||
'size' => $_FILES['files']['size'][$index]
|
||||
];
|
||||
$this->saveDocumentation($workorderId, $documentType, $description);
|
||||
}
|
||||
}
|
||||
} else if (!empty($_FILES['file'])) {
|
||||
$this->saveDocumentation($workorderId, $documentType, $description);
|
||||
}
|
||||
|
||||
// Update workorder status if needed
|
||||
$workorder = WorkorderModel::get($workorderId);
|
||||
$oldStatus = $workorder->status;
|
||||
$newStatus = null;
|
||||
|
||||
if (in_array($oldStatus, ['assigned', 'scheduled'])) {
|
||||
$newStatus = 'in_progress';
|
||||
} else if (in_array($oldStatus, ['correction_requested', 'problem_solved', 'civil_engineering_completed'])) {
|
||||
$newStatus = 'assigned';
|
||||
}
|
||||
|
||||
if ($newStatus) {
|
||||
$workorder->status = $newStatus;
|
||||
WorkorderModel::update((array)$workorder);
|
||||
|
||||
WorkorderJournalModel::create([
|
||||
'workorderId' => $workorder->id,
|
||||
'text' => 'Status wurde nach Dokumenten-Upload automatisch geändert.',
|
||||
'statusChange' => $this->getStatusText($oldStatus) . " -> " . $this->getStatusText($newStatus),
|
||||
'create' => time(),
|
||||
'createBy' => $this->user->id,
|
||||
]);
|
||||
}
|
||||
|
||||
self::returnJson(['success' => true, 'message' => 'Datei(en) erfolgreich hochgeladen']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete documentation
|
||||
* POST /MobileApp/Workorder/Workorder/deleteDocumentation
|
||||
*/
|
||||
public function deleteDocumentationAction() {
|
||||
$postData = $this->getPostData();
|
||||
$id = intval($postData['id'] ?? 0);
|
||||
|
||||
if (!$id) {
|
||||
self::returnJson(['success' => false, 'message' => 'Dokumenten-ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
WorkorderDocumentationModel::delete($id);
|
||||
self::returnJson(['success' => true, 'message' => 'Dokument gelöscht']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add journal entry
|
||||
* POST /MobileApp/Workorder/Workorder/addJournal
|
||||
*/
|
||||
public function addJournalAction() {
|
||||
$postData = $this->getPostData();
|
||||
$workorderId = intval($postData['workorderId'] ?? 0);
|
||||
$text = trim($postData['text'] ?? '');
|
||||
|
||||
if (!$workorderId || !$text) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrags-ID und Text sind erforderlich']);
|
||||
return;
|
||||
}
|
||||
|
||||
WorkorderJournalModel::create([
|
||||
'workorderId' => $workorderId,
|
||||
'text' => $text,
|
||||
'createBy' => $this->user->id,
|
||||
'create' => time()
|
||||
]);
|
||||
|
||||
// Return updated journals
|
||||
$journals = WorkorderJournalModel::getAll(
|
||||
['workorderId' => $workorderId],
|
||||
null, 0,
|
||||
['key' => 'create', 'order' => 'DESC']
|
||||
);
|
||||
|
||||
$responseJournals = [];
|
||||
foreach ($journals as $journal) {
|
||||
$responseJournals[] = [
|
||||
'id' => $journal->id,
|
||||
'text' => $journal->text,
|
||||
'statusChange' => $journal->statusChange ?? null,
|
||||
'createByName' => UserModel::getOne($journal->createBy)->name ?? 'Unbekannt',
|
||||
'create' => $journal->create,
|
||||
'createFormatted' => date('d.m.Y H:i', $journal->create),
|
||||
];
|
||||
}
|
||||
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'message' => 'Journaleintrag hinzugefügt',
|
||||
'journals' => $responseJournals
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update additional info (notes)
|
||||
* POST /MobileApp/Workorder/Workorder/updateAdditionalInfo
|
||||
*/
|
||||
public function updateAdditionalInfoAction() {
|
||||
$postData = $this->getPostData();
|
||||
$workorderId = intval($postData['workorderId'] ?? 0);
|
||||
|
||||
if (!$workorderId) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrags-ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
$workorder = WorkorderModel::get($workorderId);
|
||||
if (!$workorder) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrag nicht gefunden']);
|
||||
return;
|
||||
}
|
||||
|
||||
$oldInfo = $workorder->additionalInfo;
|
||||
$newInfo = $postData['additionalInfo'] ?? null;
|
||||
$workorder->additionalInfo = $newInfo;
|
||||
WorkorderModel::update((array)$workorder);
|
||||
|
||||
WorkorderJournalModel::create([
|
||||
'workorderId' => $workorder->id,
|
||||
'text' => "Zusatzinfo geändert.\nAlt: '{$oldInfo}'\nNeu: '{$newInfo}'",
|
||||
'create' => time(),
|
||||
'createBy' => $this->user->id,
|
||||
]);
|
||||
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'message' => 'Zusatzinfo aktualisiert',
|
||||
'newInfo' => $newInfo
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule appointment
|
||||
* POST /MobileApp/Workorder/Workorder/scheduleAppointment
|
||||
*/
|
||||
public function scheduleAppointmentAction() {
|
||||
$postData = $this->getPostData();
|
||||
$workorderId = intval($postData['workorderId'] ?? 0);
|
||||
$appointmentDate = intval($postData['appointmentDate'] ?? 0);
|
||||
|
||||
if (!$workorderId || !$appointmentDate) {
|
||||
self::returnJson(['success' => false, 'message' => 'Erforderliche Felder fehlen']);
|
||||
return;
|
||||
}
|
||||
|
||||
$workorder = WorkorderModel::get($workorderId);
|
||||
if (!$workorder) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrag nicht gefunden']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate time is set
|
||||
$hour = (int)date('H', $appointmentDate);
|
||||
if ($hour >= 23 || $hour < 1) {
|
||||
self::returnJson(['success' => false, 'message' => 'Bitte geben Sie eine Uhrzeit an']);
|
||||
return;
|
||||
}
|
||||
|
||||
$workorder->appointmentDate = $appointmentDate;
|
||||
$workorder->status = 'scheduled';
|
||||
WorkorderModel::update((array)$workorder);
|
||||
|
||||
WorkorderJournalModel::create([
|
||||
'workorderId' => $workorder->id,
|
||||
'text' => 'Termin festgelegt auf: ' . date('d.m.Y H:i', $appointmentDate),
|
||||
'create' => time(),
|
||||
'createBy' => $this->user->id,
|
||||
]);
|
||||
|
||||
self::returnJson(['success' => true, 'message' => 'Termin erfolgreich gespeichert']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request intervention (report problem)
|
||||
* POST /MobileApp/Workorder/Workorder/requestIntervention
|
||||
*/
|
||||
public function requestInterventionAction() {
|
||||
$postData = $this->getPostData();
|
||||
$workorderId = intval($postData['workorderId'] ?? 0);
|
||||
$journalText = trim($postData['journalText'] ?? '');
|
||||
$interventionType = $postData['interventionType'] ?? '';
|
||||
|
||||
if (!$workorderId || !$journalText) {
|
||||
self::returnJson(['success' => false, 'message' => 'Erforderliche Felder fehlen']);
|
||||
return;
|
||||
}
|
||||
|
||||
$workorder = WorkorderModel::get($workorderId);
|
||||
if (!$workorder) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrag nicht gefunden']);
|
||||
return;
|
||||
}
|
||||
|
||||
$oldStatus = $workorder->status;
|
||||
$workorder->status = 'intervention_required';
|
||||
WorkorderModel::update((array)$workorder);
|
||||
|
||||
$fullText = $interventionType ? "{$interventionType}: {$journalText}" : "Eingriff erforderlich: {$journalText}";
|
||||
|
||||
WorkorderJournalModel::create([
|
||||
'workorderId' => $workorder->id,
|
||||
'text' => $fullText,
|
||||
'statusChange' => $this->getStatusText($oldStatus) . " -> " . $this->getStatusText('intervention_required'),
|
||||
'create' => time(),
|
||||
'createBy' => $this->user->id,
|
||||
]);
|
||||
|
||||
self::returnJson(['success' => true, 'message' => 'Eingriff wurde angefordert']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete workorder
|
||||
* POST /MobileApp/Workorder/Workorder/completeWorkorder
|
||||
*/
|
||||
public function completeWorkorderAction() {
|
||||
$postData = $this->getPostData();
|
||||
$workorderId = intval($postData['workorderId'] ?? 0);
|
||||
|
||||
if (!$workorderId) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrags-ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
$workorder = WorkorderModel::get($workorderId);
|
||||
if (!$workorder) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrag nicht gefunden']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate cable data if required
|
||||
$tenantConfig = $this->getTenantConfigFromWorkorder($workorderId);
|
||||
if ($tenantConfig) {
|
||||
if ($tenantConfig->requireCableLength && empty(trim($workorder->cableLength))) {
|
||||
self::returnJson(['success' => false, 'message' => 'Bitte geben Sie die Kabellänge an']);
|
||||
return;
|
||||
}
|
||||
if ($tenantConfig->requireCableType && empty(trim($workorder->cableType))) {
|
||||
self::returnJson(['success' => false, 'message' => 'Bitte geben Sie den Kabeltyp an']);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$oldStatus = $workorder->status;
|
||||
$workorder->status = 'documented';
|
||||
WorkorderModel::update((array)$workorder);
|
||||
|
||||
WorkorderJournalModel::create([
|
||||
'workorderId' => $workorder->id,
|
||||
'text' => 'Arbeitsauftrag zur Prüfung eingereicht.',
|
||||
'statusChange' => $this->getStatusText($oldStatus) . " -> " . $this->getStatusText('documented'),
|
||||
'create' => time(),
|
||||
'createBy' => $this->user->id,
|
||||
]);
|
||||
|
||||
self::returnJson(['success' => true, 'message' => 'Arbeitsauftrag zur Prüfung eingereicht']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update workorder data (cable info)
|
||||
* POST /MobileApp/Workorder/Workorder/updateWorkorderData
|
||||
*/
|
||||
public function updateWorkorderDataAction() {
|
||||
$postData = $this->getPostData();
|
||||
$workorderId = intval($postData['workorderId'] ?? 0);
|
||||
|
||||
if (!$workorderId) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrags-ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
$workorder = WorkorderModel::get($workorderId);
|
||||
if (!$workorder) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrag nicht gefunden']);
|
||||
return;
|
||||
}
|
||||
|
||||
$journalText = "Zusatzdaten aktualisiert:\n";
|
||||
$changed = false;
|
||||
|
||||
if (isset($postData['cableLength'])) {
|
||||
if ($workorder->cableLength != $postData['cableLength']) {
|
||||
$journalText .= "Kabellänge: '{$workorder->cableLength}' -> '{$postData['cableLength']}'\n";
|
||||
$workorder->cableLength = $postData['cableLength'];
|
||||
$changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($postData['cableType'])) {
|
||||
if ($workorder->cableType != $postData['cableType']) {
|
||||
$journalText .= "Kabeltyp: '{$workorder->cableType}' -> '{$postData['cableType']}'\n";
|
||||
$workorder->cableType = $postData['cableType'];
|
||||
$changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$changed) {
|
||||
self::returnJson(['success' => true, 'message' => 'Keine Änderungen vorgenommen']);
|
||||
return;
|
||||
}
|
||||
|
||||
WorkorderModel::update((array)$workorder);
|
||||
|
||||
WorkorderJournalModel::create([
|
||||
'workorderId' => $workorder->id,
|
||||
'text' => $journalText,
|
||||
'create' => time(),
|
||||
'createBy' => $this->user->id,
|
||||
]);
|
||||
|
||||
self::returnJson(['success' => true, 'message' => 'Daten gespeichert']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get checklist status for a workorder
|
||||
* GET /MobileApp/Workorder/Workorder/getChecklist?workorderId=X
|
||||
*/
|
||||
public function getChecklistAction() {
|
||||
$workorderId = intval($this->request->workorderId ?? 0);
|
||||
|
||||
if (!$workorderId) {
|
||||
self::returnJson(['success' => false, 'message' => 'Arbeitsauftrags-ID fehlt']);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get tenant config for required doc types
|
||||
$tenantConfig = $this->getTenantConfigFromWorkorder($workorderId);
|
||||
$docTypes = $tenantConfig ? json_decode($tenantConfig->documentationTypes, true) : [];
|
||||
|
||||
// Get existing documentation
|
||||
$docs = WorkorderDocumentationModel::getAll(['workorderId' => $workorderId]);
|
||||
$uploadedTypes = array_column((array)$docs, 'documentType');
|
||||
$uploadedTypeCounts = array_count_values($uploadedTypes);
|
||||
|
||||
// Build checklist
|
||||
$checklist = [];
|
||||
$completedCount = 0;
|
||||
|
||||
foreach ($docTypes as $type) {
|
||||
$isCompleted = isset($uploadedTypeCounts[$type['value']]) && $uploadedTypeCounts[$type['value']] > 0;
|
||||
if ($isCompleted) $completedCount++;
|
||||
|
||||
$checklist[] = [
|
||||
'type' => $type['value'],
|
||||
'text' => $type['text'],
|
||||
'required' => $type['required'] ?? false,
|
||||
'completed' => $isCompleted,
|
||||
'count' => $uploadedTypeCounts[$type['value']] ?? 0,
|
||||
];
|
||||
}
|
||||
|
||||
self::returnJson([
|
||||
'success' => true,
|
||||
'checklist' => $checklist,
|
||||
'completed' => $completedCount,
|
||||
'total' => count($docTypes),
|
||||
'allRequired' => $this->allRequiredCompleted($checklist)
|
||||
]);
|
||||
}
|
||||
|
||||
// =====================
|
||||
// HELPER METHODS
|
||||
// =====================
|
||||
|
||||
/**
|
||||
* Transform workorder for API response
|
||||
* @param array|object $wo Workorder data (can be array or object from getCompanyWorkorders)
|
||||
* @param bool $detailed Include full customer details
|
||||
*/
|
||||
private function transformWorkorder($wo, $detailed = false) {
|
||||
// Handle both array and object formats
|
||||
$isArray = is_array($wo);
|
||||
$get = function($key, $default = null) use ($wo, $isArray) {
|
||||
if ($isArray) {
|
||||
return $wo[$key] ?? $default;
|
||||
}
|
||||
return $wo->$key ?? $default;
|
||||
};
|
||||
|
||||
// Customer name: use company if available, else customerName (firstname lastname)
|
||||
$customerCompany = $get('customerCompany', '');
|
||||
$customerName = $customerCompany ?: $get('customerName', '');
|
||||
|
||||
// Build address from the joined data
|
||||
$street = $get('street', '');
|
||||
$hausnummer = $get('hausnummer', '');
|
||||
$plz = $get('plz', '');
|
||||
$city = $get('city', '');
|
||||
$customerAddress = trim("{$street} {$hausnummer}, {$plz} {$city}", ', ');
|
||||
|
||||
$status = $get('status');
|
||||
$appointmentDate = $get('appointmentDate');
|
||||
$deadlineDate = $get('deadlineDate');
|
||||
$cableType = $get('cableType', '');
|
||||
$cableLength = $get('cableLength', '');
|
||||
|
||||
$result = [
|
||||
'id' => intval($get('id', 0)),
|
||||
'fcpName' => $get('rimo_fcp_name', ''),
|
||||
'oaid' => $get('oaid', ''),
|
||||
'status' => $status,
|
||||
'statusText' => $this->statusOptions[$status]['text'] ?? $status,
|
||||
'statusColor' => $this->statusOptions[$status]['color'] ?? 'secondary',
|
||||
'customerName' => $customerName,
|
||||
'customerAddress' => $customerAddress,
|
||||
'additionalInfo' => $get('additionalInfo', ''),
|
||||
'appointmentDate' => $appointmentDate ? intval($appointmentDate) : null,
|
||||
'appointmentFormatted' => $appointmentDate ? date('d.m.Y H:i', $appointmentDate) : null,
|
||||
'deadlineDate' => $deadlineDate ? intval($deadlineDate) : null,
|
||||
'deadlineFormatted' => $deadlineDate ? date('d.m.Y', $deadlineDate) : null,
|
||||
'cableType' => $cableType,
|
||||
'cableLength' => $cableLength,
|
||||
'hasCableFlag' => !empty($cableType) || !empty($cableLength),
|
||||
];
|
||||
|
||||
// For detailed view (single workorder), include customer contact info
|
||||
if ($detailed) {
|
||||
$result['customer'] = [
|
||||
'id' => intval($get('id', 0)),
|
||||
'name' => $customerName,
|
||||
'street' => trim("{$street} {$hausnummer}"),
|
||||
'zip' => $plz,
|
||||
'city' => $city,
|
||||
'phone' => $get('phone', ''),
|
||||
'email' => $get('email', ''),
|
||||
'gpsLat' => null, // Not available in this query
|
||||
'gpsLng' => null,
|
||||
];
|
||||
|
||||
$result['campaign'] = $get('networkOwnerName', '');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get status display text
|
||||
*/
|
||||
private function getStatusText($statusKey) {
|
||||
return $this->statusOptions[$statusKey]['text'] ?? ucfirst(str_replace('_', ' ', $statusKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get tenant config from workorder
|
||||
*/
|
||||
private function getTenantConfigFromWorkorder($workorderId) {
|
||||
if (!$workorderId) return null;
|
||||
|
||||
$workorder = WorkorderModel::get($workorderId);
|
||||
if (!$workorder) return null;
|
||||
|
||||
$preorder = new Preorder($workorder->preorderId);
|
||||
if (!$preorder->id) return null;
|
||||
|
||||
$campaign = new Preordercampaign($preorder->preordercampaign_id);
|
||||
if (!$campaign->id) return null;
|
||||
|
||||
$network = NetworkModel::getOne($campaign->network_id);
|
||||
if (!$network) return null;
|
||||
|
||||
return WorkorderTenantConfigModel::getFirst(['addressId' => $network->owner_id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save documentation file
|
||||
*/
|
||||
private function saveDocumentation($workorderId, $documentType, $description) {
|
||||
try {
|
||||
$uploaded = mfUpload::handleFormUpload("file", false, "/Workorder");
|
||||
WorkorderDocumentationModel::create([
|
||||
'workorderId' => $workorderId,
|
||||
'fileId' => $uploaded->id,
|
||||
'description' => $description,
|
||||
'documentType' => $documentType,
|
||||
'create' => time(),
|
||||
'createBy' => $this->user->id
|
||||
]);
|
||||
} catch (Exception $e) {
|
||||
// Log error if necessary
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if all required checklist items are completed
|
||||
*/
|
||||
private function allRequiredCompleted($checklist) {
|
||||
foreach ($checklist as $item) {
|
||||
if ($item['required'] && !$item['completed']) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get single workorder with full joined data (same structure as getCompanyWorkorders)
|
||||
*/
|
||||
private function getWorkorderWithDetails($workorderId, $companyId) {
|
||||
$db = $this->db();
|
||||
$fronkDbName = FRONKDB_DBNAME;
|
||||
$addressDbName = defined('ADDRESSDB_DBNAME') ? ADDRESSDB_DBNAME : 'addressdb';
|
||||
|
||||
$sql = "
|
||||
SELECT w.id, w.status, w.deadlineDate, w.appointmentDate, w.additionalInfo,
|
||||
w.cableType, w.cableLength, hn.rimo_fcp_name,
|
||||
owner_addr.company as networkOwnerName, p.preordercampaign_id,
|
||||
CONCAT_WS(' ', p.firstname, p.lastname) as customerName, p.company as customerCompany, p.oaid,
|
||||
p.phone, p.email, str.name as street, hn.hausnummer, hn.stiege, we.bezeichner as apartment,
|
||||
plz.plz, ort.name as city
|
||||
FROM `{$fronkDbName}`.`Workorder` w
|
||||
JOIN `{$fronkDbName}`.`Preorder` p ON w.preorderId = p.id
|
||||
LEFT JOIN `{$fronkDbName}`.`Preordercampaign` pc ON p.preordercampaign_id = pc.id
|
||||
LEFT JOIN `{$fronkDbName}`.`Network` n ON pc.network_id = n.id
|
||||
LEFT JOIN `{$fronkDbName}`.`Address` owner_addr ON n.owner_id = owner_addr.id
|
||||
LEFT JOIN `{$addressDbName}`.`Hausnummer` hn ON p.adb_hausnummer_id = hn.id
|
||||
LEFT JOIN `{$addressDbName}`.`Strasse` str ON hn.strasse_id = str.id
|
||||
LEFT JOIN `{$addressDbName}`.`Plz` plz ON hn.plz_id = plz.id
|
||||
LEFT JOIN `{$addressDbName}`.`Ortschaft` ort ON hn.ortschaft_id = ort.id
|
||||
LEFT JOIN `{$addressDbName}`.`Wohneinheit` we ON p.adb_wohneinheit_id = we.id
|
||||
WHERE w.id = " . intval($workorderId) . "
|
||||
AND w.companyId = " . intval($companyId) . "
|
||||
LIMIT 1
|
||||
";
|
||||
|
||||
$result = $db->query($sql);
|
||||
return $result ? $result->fetch_assoc() : null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user