Files
thetool/application/ADBRimoFcp/ADBRimoFcp.php
2025-09-12 09:18:15 +02:00

80 lines
3.2 KiB
PHP

<?php
class ADBRimoFcp extends TTCrudBaseModel
{
public int $id;
public int $netzgebiet_id;
public ?string $name;
public string $rimo_id;
public ?string $label;
public ?string $building_type;
public ?string $rimo_ex_state;
public ?string $rimo_op_state;
public ?float $gps_lat;
public ?float $gps_long;
public int $create;
public int $edit;
public static function getRimoFcpStatistics(): array {
$db = self::getDB();
$fronkDbName = defined('FRONKDB_DBNAME') ? FRONKDB_DBNAME : 'thetool';
$addressDbName = defined('ADDRESSDB_DBNAME') ? ADDRESSDB_DBNAME : 'addressdb';
$sql = "
-- Use a Common Table Expression (CTE) to pre-calculate counts for each combination of FCP and rimo_type.
WITH RimoTypeCounts AS (
SELECT
hn.fcp_id,
-- Group NULL rimo_types into an 'UNKNOWN' category for clarity.
COALESCE(hn.rimo_type, 'UNKNOWN') AS rimo_type,
COUNT(DISTINCT hn.id) AS hausnummer_count,
COUNT(DISTINCT we.id) AS wohneinheit_count,
COUNT(DISTINCT CASE WHEN ps.code < 899 THEN p.id ELSE NULL END) AS preorder_count
FROM
`{$addressDbName}`.`Hausnummer` AS hn
LEFT JOIN
`{$addressDbName}`.`Wohneinheit` AS we ON hn.id = we.hausnummer_id
LEFT JOIN
`{$fronkDbName}`.`Preorder` AS p ON hn.id = p.adb_hausnummer_id
LEFT JOIN
`{$fronkDbName}`.`Preorderstatus` AS ps ON p.status_id = ps.id
WHERE
hn.fcp_id IS NOT NULL
GROUP BY
hn.fcp_id,
COALESCE(hn.rimo_type, 'UNKNOWN')
)
-- Final SELECT statement to assemble the data for each FCP.
SELECT
fcp.id AS fcp_id,
fcp.name AS fcp_name,
fcp.rimo_id AS fcp_rimo_id,
-- Aggregate total counts for the entire FCP.
SUM(rtc.hausnummer_count) AS total_hausnummer_count,
SUM(rtc.wohneinheit_count) AS total_wohneinheit_count,
SUM(rtc.preorder_count) AS total_active_preorders,
-- Create a single JSON object from all the rimo_type groups for the current FCP.
JSON_OBJECTAGG(
rtc.rimo_type,
JSON_OBJECT(
'hausnummer_count', rtc.hausnummer_count,
'wohneinheit_count', rtc.wohneinheit_count,
'preorder_count', rtc.preorder_count
)
) AS counts_by_rimo_type
FROM
`{$addressDbName}`.`RimoFcp` AS fcp
LEFT JOIN
RimoTypeCounts AS rtc ON fcp.id = rtc.fcp_id
WHERE
rtc.fcp_id IS NOT NULL
GROUP BY
fcp.id, fcp.name, fcp.rimo_id
ORDER BY
fcp.name;
";
$result = $db->query($sql);
return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
}
}