index.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. <?php
  2. declare(strict_types=1);
  3. require_once dirname(__DIR__) . '/src/bootstrap.php';
  4. $auth = app_admin_auth();
  5. $auth->start();
  6. $configRepository = app_config_repository();
  7. $message = null;
  8. $messageType = 'success';
  9. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  10. $action = $_POST['action'] ?? '';
  11. if ($action === 'login') {
  12. $success = $auth->login(
  13. trim((string) ($_POST['username'] ?? '')),
  14. (string) ($_POST['password'] ?? '')
  15. );
  16. if ($success) {
  17. app_redirect(app_url('/admin/'));
  18. }
  19. $message = 'Login fehlgeschlagen. Bitte Zugangsdaten pruefen.';
  20. $messageType = 'error';
  21. }
  22. if ($action === 'save_config' && $auth->isAuthenticated()) {
  23. $config = $configRepository->getConfig();
  24. $newPassword = trim((string) ($_POST['admin_password'] ?? ''));
  25. $config['app'] = [
  26. 'name' => trim((string) ($_POST['app_name'] ?? 'Getraenkeautomat Monitor')),
  27. 'timezone' => trim((string) ($_POST['timezone'] ?? 'Europe/Berlin')),
  28. 'dashboard_refresh_seconds' => max(5, (int) ($_POST['dashboard_refresh_seconds'] ?? 15)),
  29. 'default_from_email' => trim((string) ($_POST['default_from_email'] ?? 'monitor@example.local')),
  30. 'base_path' => app_normalize_base_path((string) ($_POST['base_path'] ?? '')),
  31. ];
  32. $config['api'] = [
  33. 'bearer_token' => trim((string) ($_POST['bearer_token'] ?? 'change-me-token')),
  34. ];
  35. $config['admin'] = [
  36. 'username' => trim((string) ($_POST['admin_username'] ?? 'admin')),
  37. 'password_hash' => $newPassword !== ''
  38. ? password_hash($newPassword, PASSWORD_BCRYPT)
  39. : (string) ($config['admin']['password_hash'] ?? ''),
  40. ];
  41. $config['alerts'] = [
  42. 'webhooks' => normalizeWebhooks($_POST['webhooks'] ?? []),
  43. 'emails' => normalizeEmails($_POST['emails'] ?? []),
  44. ];
  45. $config['machines'] = normalizeMachines($_POST['machines'] ?? []);
  46. $configRepository->saveConfig($config);
  47. $message = 'Konfiguration gespeichert.';
  48. $messageType = 'success';
  49. }
  50. }
  51. $config = $configRepository->getConfig();
  52. if (!$auth->isAuthenticated()) {
  53. renderLogin($message, $messageType);
  54. exit;
  55. }
  56. renderAdmin($config, $message, $messageType);
  57. function renderLogin(?string $message, string $messageType): void
  58. {
  59. ?>
  60. <!DOCTYPE html>
  61. <html lang="de">
  62. <head>
  63. <meta charset="UTF-8">
  64. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  65. <title>Adminpanel Login</title>
  66. <link rel="stylesheet" href="<?= htmlspecialchars(app_url('/styles.css'), ENT_QUOTES) ?>">
  67. </head>
  68. <body>
  69. <main class="auth-page">
  70. <section class="auth-card">
  71. <p class="eyebrow">Adminbereich</p>
  72. <h1>Konfiguration sichern</h1>
  73. <p>Logge dich mit den statischen Zugangsdaten aus der JSON-Config ein.</p>
  74. <?php if ($message !== null): ?>
  75. <div class="message message--<?= htmlspecialchars($messageType, ENT_QUOTES) ?>"><?= htmlspecialchars($message, ENT_QUOTES) ?></div>
  76. <?php endif; ?>
  77. <form method="post">
  78. <input type="hidden" name="action" value="login">
  79. <label>
  80. Benutzername
  81. <input type="text" name="username" required>
  82. </label>
  83. <label>
  84. Passwort
  85. <input type="password" name="password" required>
  86. </label>
  87. <button class="button button--primary" type="submit">Einloggen</button>
  88. <a class="button button--ghost" href="<?= htmlspecialchars(app_url('/'), ENT_QUOTES) ?>">Zurueck zum Dashboard</a>
  89. </form>
  90. </section>
  91. </main>
  92. </body>
  93. </html>
  94. <?php
  95. }
  96. function renderAdmin(array $config, ?string $message, string $messageType): void
  97. {
  98. ?>
  99. <!DOCTYPE html>
  100. <html lang="de">
  101. <head>
  102. <meta charset="UTF-8">
  103. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  104. <title>Adminpanel</title>
  105. <link rel="stylesheet" href="<?= htmlspecialchars(app_url('/styles.css'), ENT_QUOTES) ?>">
  106. </head>
  107. <body>
  108. <main class="admin-page">
  109. <section class="admin-shell">
  110. <div class="admin-header">
  111. <div>
  112. <p class="eyebrow">Adminpanel</p>
  113. <h1>Konfiguration der Automaten</h1>
  114. <p>Hier werden API-Token, Zugangsdaten, Faecher und Alarmwege direkt in der JSON-Config gepflegt.</p>
  115. </div>
  116. <div class="inline-actions">
  117. <a class="button button--ghost" href="<?= htmlspecialchars(app_url('/'), ENT_QUOTES) ?>">Dashboard</a>
  118. <a class="button button--secondary" href="<?= htmlspecialchars(app_url('/admin/logout.php'), ENT_QUOTES) ?>">Logout</a>
  119. </div>
  120. </div>
  121. <?php if ($message !== null): ?>
  122. <div class="message message--<?= htmlspecialchars($messageType, ENT_QUOTES) ?>"><?= htmlspecialchars($message, ENT_QUOTES) ?></div>
  123. <?php endif; ?>
  124. <form method="post" class="admin-form" id="admin-form">
  125. <input type="hidden" name="action" value="save_config">
  126. <section class="form-section">
  127. <h2>Allgemein</h2>
  128. <div class="field-grid">
  129. <label>
  130. App-Name
  131. <input type="text" name="app_name" value="<?= htmlspecialchars((string) ($config['app']['name'] ?? ''), ENT_QUOTES) ?>" required>
  132. </label>
  133. <label>
  134. Zeitzone
  135. <input type="text" name="timezone" value="<?= htmlspecialchars((string) ($config['app']['timezone'] ?? 'Europe/Berlin'), ENT_QUOTES) ?>" required>
  136. </label>
  137. <label>
  138. Auto-Refresh Sekunden
  139. <input type="number" min="5" name="dashboard_refresh_seconds" value="<?= (int) ($config['app']['dashboard_refresh_seconds'] ?? 15) ?>" required>
  140. </label>
  141. <label>
  142. Absender fuer Email
  143. <input type="email" name="default_from_email" value="<?= htmlspecialchars((string) ($config['app']['default_from_email'] ?? ''), ENT_QUOTES) ?>">
  144. </label>
  145. <label>
  146. Basis-Pfad
  147. <input type="text" name="base_path" value="<?= htmlspecialchars((string) ($config['app']['base_path'] ?? ''), ENT_QUOTES) ?>" placeholder="/auswertung">
  148. </label>
  149. </div>
  150. <p class="field-help">Leer lassen fuer den Domain-Root. Fuer Unterordner z. B. <code>/auswertung</code> eintragen.</p>
  151. </section>
  152. <section class="admin-grid">
  153. <section class="form-section">
  154. <h2>API</h2>
  155. <label>
  156. Bearer-Token
  157. <input type="text" name="bearer_token" value="<?= htmlspecialchars((string) ($config['api']['bearer_token'] ?? ''), ENT_QUOTES) ?>" required>
  158. </label>
  159. <p class="field-help">ESP32-Clients senden dieses Token im Header <code>Authorization: Bearer ...</code>.</p>
  160. </section>
  161. <section class="form-section">
  162. <h2>Adminzugang</h2>
  163. <div class="field-grid">
  164. <label>
  165. Benutzername
  166. <input type="text" name="admin_username" value="<?= htmlspecialchars((string) ($config['admin']['username'] ?? ''), ENT_QUOTES) ?>" required>
  167. </label>
  168. <label>
  169. Neues Passwort
  170. <input type="password" name="admin_password" placeholder="Leer lassen, um es nicht zu aendern">
  171. </label>
  172. </div>
  173. </section>
  174. </section>
  175. <section class="form-section">
  176. <div class="panel__header">
  177. <div>
  178. <h2>Webhooks</h2>
  179. <p>Mehrere Ziele sind moeglich. Header koennen als JSON hinterlegt werden.</p>
  180. </div>
  181. <button class="button button--secondary" type="button" data-add="webhook">Webhook hinzufuegen</button>
  182. </div>
  183. <div class="repeat-stack" id="webhook-stack">
  184. <?php foreach (($config['alerts']['webhooks'] ?? []) as $index => $webhook): ?>
  185. <?= renderWebhookRow((int) $index, $webhook) ?>
  186. <?php endforeach; ?>
  187. </div>
  188. </section>
  189. <section class="form-section">
  190. <div class="panel__header">
  191. <div>
  192. <h2>Email-Empfaenger</h2>
  193. <p>Emails werden ueber die Serverkonfiguration von <code>mail()</code> versendet.</p>
  194. </div>
  195. <button class="button button--secondary" type="button" data-add="email">Email-Empfaenger hinzufuegen</button>
  196. </div>
  197. <div class="repeat-stack" id="email-stack">
  198. <?php foreach (($config['alerts']['emails'] ?? []) as $index => $email): ?>
  199. <?= renderEmailRow((int) $index, $email) ?>
  200. <?php endforeach; ?>
  201. </div>
  202. </section>
  203. <section class="form-section">
  204. <div class="panel__header">
  205. <div>
  206. <h2>Automaten und Faecher</h2>
  207. <p>Jeder Automat enthaelt beliebig viele Faecher, die jeweils genau einem Sensor zugeordnet sind.</p>
  208. </div>
  209. <button class="button button--secondary" type="button" data-add="machine">Automat hinzufuegen</button>
  210. </div>
  211. <div class="repeat-stack" id="machine-stack">
  212. <?php foreach (($config['machines'] ?? []) as $machineIndex => $machine): ?>
  213. <?= renderMachineRow((int) $machineIndex, $machine) ?>
  214. <?php endforeach; ?>
  215. </div>
  216. </section>
  217. <div class="section-actions">
  218. <button class="button button--primary" type="submit">Konfiguration speichern</button>
  219. </div>
  220. </form>
  221. </section>
  222. </main>
  223. <template id="tpl-webhook"><?= renderWebhookRow('__INDEX__', []) ?></template>
  224. <template id="tpl-email"><?= renderEmailRow('__INDEX__', []) ?></template>
  225. <template id="tpl-machine"><?= renderMachineRow('__MACHINE__', []) ?></template>
  226. <template id="tpl-slot"><?= renderSlotRow('__MACHINE__', '__SLOT__', []) ?></template>
  227. <script>
  228. const webhookStack = document.getElementById('webhook-stack');
  229. const emailStack = document.getElementById('email-stack');
  230. const machineStack = document.getElementById('machine-stack');
  231. const renderTemplate = (id, replacements) => {
  232. let html = document.getElementById(id).innerHTML;
  233. Object.entries(replacements).forEach(([needle, value]) => {
  234. html = html.replaceAll(needle, value);
  235. });
  236. return html;
  237. };
  238. const countChildren = (node, selector) => node.querySelectorAll(selector).length;
  239. document.addEventListener('click', (event) => {
  240. const addType = event.target.getAttribute('data-add');
  241. const removeType = event.target.getAttribute('data-remove');
  242. if (addType === 'webhook') {
  243. const index = countChildren(webhookStack, '[data-webhook-row]');
  244. webhookStack.insertAdjacentHTML('beforeend', renderTemplate('tpl-webhook', { '__INDEX__': index }));
  245. }
  246. if (addType === 'email') {
  247. const index = countChildren(emailStack, '[data-email-row]');
  248. emailStack.insertAdjacentHTML('beforeend', renderTemplate('tpl-email', { '__INDEX__': index }));
  249. }
  250. if (addType === 'machine') {
  251. const index = countChildren(machineStack, '[data-machine-row]');
  252. machineStack.insertAdjacentHTML('beforeend', renderTemplate('tpl-machine', { '__MACHINE__': index, '__SLOT__': 0 }));
  253. }
  254. if (addType === 'slot') {
  255. const machineIndex = event.target.getAttribute('data-machine-index');
  256. const container = document.querySelector(`[data-slot-stack="${machineIndex}"]`);
  257. const slotIndex = countChildren(container, '[data-slot-row]');
  258. container.insertAdjacentHTML('beforeend', renderTemplate('tpl-slot', {
  259. '__MACHINE__': machineIndex,
  260. '__SLOT__': slotIndex
  261. }));
  262. }
  263. if (removeType) {
  264. const row = event.target.closest(`[data-${removeType}-row]`);
  265. if (row) {
  266. row.remove();
  267. }
  268. }
  269. });
  270. </script>
  271. </body>
  272. </html>
  273. <?php
  274. }
  275. function renderWebhookRow(int|string $index, array $webhook): string
  276. {
  277. $headers = $webhook['headers'] ?? [];
  278. $headerJson = json_encode($headers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  279. ob_start();
  280. ?>
  281. <div class="repeat-card" data-webhook-row>
  282. <div class="panel__header">
  283. <h4>Webhook</h4>
  284. <button class="button button--danger" type="button" data-remove="webhook">Entfernen</button>
  285. </div>
  286. <div class="field-grid">
  287. <label>
  288. ID
  289. <input type="text" name="webhooks[<?= $index ?>][id]" value="<?= htmlspecialchars((string) ($webhook['id'] ?? ''), ENT_QUOTES) ?>">
  290. </label>
  291. <label>
  292. Name
  293. <input type="text" name="webhooks[<?= $index ?>][name]" value="<?= htmlspecialchars((string) ($webhook['name'] ?? ''), ENT_QUOTES) ?>">
  294. </label>
  295. <label>
  296. URL
  297. <input type="url" name="webhooks[<?= $index ?>][url]" value="<?= htmlspecialchars((string) ($webhook['url'] ?? ''), ENT_QUOTES) ?>">
  298. </label>
  299. <label>
  300. Aktiv
  301. <select name="webhooks[<?= $index ?>][enabled]">
  302. <option value="1" <?= !empty($webhook['enabled']) ? 'selected' : '' ?>>Ja</option>
  303. <option value="0" <?= empty($webhook['enabled']) ? 'selected' : '' ?>>Nein</option>
  304. </select>
  305. </label>
  306. </div>
  307. <label>
  308. Header als JSON-Objekt
  309. <textarea name="webhooks[<?= $index ?>][headers_json]"><?= htmlspecialchars((string) $headerJson, ENT_QUOTES) ?></textarea>
  310. </label>
  311. </div>
  312. <?php
  313. return (string) ob_get_clean();
  314. }
  315. function renderEmailRow(int|string $index, array $email): string
  316. {
  317. ob_start();
  318. ?>
  319. <div class="repeat-card" data-email-row>
  320. <div class="panel__header">
  321. <h4>Email-Empfaenger</h4>
  322. <button class="button button--danger" type="button" data-remove="email">Entfernen</button>
  323. </div>
  324. <div class="field-grid">
  325. <label>
  326. ID
  327. <input type="text" name="emails[<?= $index ?>][id]" value="<?= htmlspecialchars((string) ($email['id'] ?? ''), ENT_QUOTES) ?>">
  328. </label>
  329. <label>
  330. Name
  331. <input type="text" name="emails[<?= $index ?>][name]" value="<?= htmlspecialchars((string) ($email['name'] ?? ''), ENT_QUOTES) ?>">
  332. </label>
  333. <label>
  334. Adresse
  335. <input type="email" name="emails[<?= $index ?>][address]" value="<?= htmlspecialchars((string) ($email['address'] ?? ''), ENT_QUOTES) ?>">
  336. </label>
  337. <label>
  338. Aktiv
  339. <select name="emails[<?= $index ?>][enabled]">
  340. <option value="1" <?= !empty($email['enabled']) ? 'selected' : '' ?>>Ja</option>
  341. <option value="0" <?= empty($email['enabled']) ? 'selected' : '' ?>>Nein</option>
  342. </select>
  343. </label>
  344. </div>
  345. </div>
  346. <?php
  347. return (string) ob_get_clean();
  348. }
  349. function renderMachineRow(int|string $machineIndex, array $machine): string
  350. {
  351. ob_start();
  352. ?>
  353. <div class="repeat-card" data-machine-row>
  354. <div class="panel__header">
  355. <div>
  356. <h4>Automat</h4>
  357. <p>Faecher koennen direkt darunter verwaltet werden.</p>
  358. </div>
  359. <div class="inline-actions">
  360. <button class="button button--secondary" type="button" data-add="slot" data-machine-index="<?= htmlspecialchars((string) $machineIndex, ENT_QUOTES) ?>">Fach hinzufuegen</button>
  361. <button class="button button--danger" type="button" data-remove="machine">Automat entfernen</button>
  362. </div>
  363. </div>
  364. <div class="field-grid">
  365. <label>
  366. ID
  367. <input type="text" name="machines[<?= $machineIndex ?>][id]" value="<?= htmlspecialchars((string) ($machine['id'] ?? ''), ENT_QUOTES) ?>">
  368. </label>
  369. <label>
  370. Name
  371. <input type="text" name="machines[<?= $machineIndex ?>][name]" value="<?= htmlspecialchars((string) ($machine['name'] ?? ''), ENT_QUOTES) ?>">
  372. </label>
  373. <label>
  374. Standort
  375. <input type="text" name="machines[<?= $machineIndex ?>][location]" value="<?= htmlspecialchars((string) ($machine['location'] ?? ''), ENT_QUOTES) ?>">
  376. </label>
  377. </div>
  378. <div class="repeat-stack" data-slot-stack="<?= htmlspecialchars((string) $machineIndex, ENT_QUOTES) ?>">
  379. <?php foreach (($machine['slots'] ?? []) as $slotIndex => $slot): ?>
  380. <?= renderSlotRow($machineIndex, (int) $slotIndex, $slot) ?>
  381. <?php endforeach; ?>
  382. </div>
  383. </div>
  384. <?php
  385. return (string) ob_get_clean();
  386. }
  387. function renderSlotRow(int|string $machineIndex, int|string $slotIndex, array $slot): string
  388. {
  389. $webhookIds = implode(',', $slot['webhook_ids'] ?? []);
  390. $emailIds = implode(',', $slot['email_ids'] ?? []);
  391. ob_start();
  392. ?>
  393. <div class="slot-editor" data-slot-row>
  394. <div class="panel__header">
  395. <h5>Fach</h5>
  396. <button class="button button--danger" type="button" data-remove="slot">Fach entfernen</button>
  397. </div>
  398. <div class="field-grid">
  399. <label>
  400. Sensor-ID
  401. <input type="text" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][sensor_id]" value="<?= htmlspecialchars((string) ($slot['sensor_id'] ?? ''), ENT_QUOTES) ?>">
  402. </label>
  403. <label>
  404. Label
  405. <input type="text" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][label]" value="<?= htmlspecialchars((string) ($slot['label'] ?? ''), ENT_QUOTES) ?>">
  406. </label>
  407. <label>
  408. Produktname
  409. <input type="text" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][product_name]" value="<?= htmlspecialchars((string) ($slot['product_name'] ?? ''), ENT_QUOTES) ?>">
  410. </label>
  411. <label>
  412. Voll-Distanz in mm
  413. <input type="number" step="0.01" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][full_distance_mm]" value="<?= htmlspecialchars((string) ($slot['full_distance_mm'] ?? ''), ENT_QUOTES) ?>">
  414. </label>
  415. <label>
  416. Leer-Distanz in mm
  417. <input type="number" step="0.01" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][empty_distance_mm]" value="<?= htmlspecialchars((string) ($slot['empty_distance_mm'] ?? ''), ENT_QUOTES) ?>">
  418. </label>
  419. <label>
  420. Distanz pro Flasche
  421. <input type="number" step="0.01" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][distance_per_unit]" value="<?= htmlspecialchars((string) ($slot['distance_per_unit'] ?? ''), ENT_QUOTES) ?>">
  422. </label>
  423. <label>
  424. Alarm unter Bestand
  425. <input type="number" step="1" min="0" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][alert_below_units]" value="<?= htmlspecialchars((string) ($slot['alert_below_units'] ?? ''), ENT_QUOTES) ?>">
  426. </label>
  427. <label>
  428. Webhook-IDs
  429. <input type="text" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][webhook_ids]" value="<?= htmlspecialchars((string) $webhookIds, ENT_QUOTES) ?>" placeholder="ops,lager">
  430. </label>
  431. <label>
  432. Email-IDs
  433. <input type="text" name="machines[<?= $machineIndex ?>][slots][<?= $slotIndex ?>][email_ids]" value="<?= htmlspecialchars((string) $emailIds, ENT_QUOTES) ?>" placeholder="lager,service">
  434. </label>
  435. </div>
  436. </div>
  437. <?php
  438. return (string) ob_get_clean();
  439. }
  440. function normalizeWebhooks(array $rows): array
  441. {
  442. $items = [];
  443. foreach ($rows as $row) {
  444. $id = trim((string) ($row['id'] ?? ''));
  445. $url = trim((string) ($row['url'] ?? ''));
  446. if ($id === '' && $url === '') {
  447. continue;
  448. }
  449. $headers = json_decode((string) ($row['headers_json'] ?? '{}'), true);
  450. $items[] = [
  451. 'id' => $id,
  452. 'name' => trim((string) ($row['name'] ?? '')),
  453. 'url' => $url,
  454. 'enabled' => (string) ($row['enabled'] ?? '1') === '1',
  455. 'headers' => is_array($headers) ? $headers : [],
  456. ];
  457. }
  458. return array_values($items);
  459. }
  460. function normalizeEmails(array $rows): array
  461. {
  462. $items = [];
  463. foreach ($rows as $row) {
  464. $id = trim((string) ($row['id'] ?? ''));
  465. $address = trim((string) ($row['address'] ?? ''));
  466. if ($id === '' && $address === '') {
  467. continue;
  468. }
  469. $items[] = [
  470. 'id' => $id,
  471. 'name' => trim((string) ($row['name'] ?? '')),
  472. 'address' => $address,
  473. 'enabled' => (string) ($row['enabled'] ?? '1') === '1',
  474. ];
  475. }
  476. return array_values($items);
  477. }
  478. function normalizeMachines(array $rows): array
  479. {
  480. $items = [];
  481. foreach ($rows as $row) {
  482. $id = trim((string) ($row['id'] ?? ''));
  483. $name = trim((string) ($row['name'] ?? ''));
  484. if ($id === '' && $name === '') {
  485. continue;
  486. }
  487. $slots = [];
  488. foreach (($row['slots'] ?? []) as $slot) {
  489. $sensorId = trim((string) ($slot['sensor_id'] ?? ''));
  490. if ($sensorId === '') {
  491. continue;
  492. }
  493. $slots[] = [
  494. 'sensor_id' => $sensorId,
  495. 'label' => trim((string) ($slot['label'] ?? $sensorId)),
  496. 'product_name' => trim((string) ($slot['product_name'] ?? '')),
  497. 'full_distance_mm' => (float) ($slot['full_distance_mm'] ?? 0),
  498. 'empty_distance_mm' => (float) ($slot['empty_distance_mm'] ?? 0),
  499. 'distance_per_unit' => max(0.01, (float) ($slot['distance_per_unit'] ?? 1)),
  500. 'alert_below_units' => max(0, (int) ($slot['alert_below_units'] ?? 0)),
  501. 'webhook_ids' => parseIdList((string) ($slot['webhook_ids'] ?? '')),
  502. 'email_ids' => parseIdList((string) ($slot['email_ids'] ?? '')),
  503. ];
  504. }
  505. $items[] = [
  506. 'id' => $id,
  507. 'name' => $name,
  508. 'location' => trim((string) ($row['location'] ?? '')),
  509. 'slots' => $slots,
  510. ];
  511. }
  512. return array_values($items);
  513. }
  514. function parseIdList(string $value): array
  515. {
  516. $parts = array_map('trim', explode(',', $value));
  517. return array_values(array_filter($parts, static fn (string $item): bool => $item !== ''));
  518. }