Lines n/a 0 / 0
Methods n/a 0 / 0
Classes n/a 0 / 0
Name Lines Methods CRAP
 __construct n/a 0 / 0 n/a 0 / 0 1
 log n/a 0 / 0 n/a 0 / 0 4
 dumpLogs n/a 0 / 0 n/a 0 / 0 3
 calculatedScopeIds n/a 0 / 0 n/a 0 / 0 1
 getSpendTime n/a 0 / 0 n/a 0 / 0 1
 readCalculateSkip n/a 0 / 0 n/a 0 / 0 1
 readForceVerbose n/a 0 / 0 n/a 0 / 0 2
 readLastRun n/a 0 / 0 n/a 0 / 0 1
 writeMaintenanceQueries n/a 0 / 0 n/a 0 / 0 4
 writeCalculations n/a 0 / 0 n/a 0 / 0 4
 writeCalculationsLocked n/a 0 / 0 n/a 0 / 0 10
 writeCalculatedScope n/a 0 / 0 n/a 0 / 0 2
 writePostProcessingByScope n/a 0 / 0 n/a 0 / 0 3
 writeCanceledSlots n/a 0 / 0 n/a 0 / 0 2
 deleteOldSlots n/a 0 / 0 n/a 0 / 0 2
8class CalculateSlots
9{
10    protected $verbose = false;
11
12    protected $startTime;
13
14    protected $logList = [];
15
16    /** @var list<int> */
17    private array $calculatedScopeIds = [];
18
19    public function __construct(bool $verbose = false)
20    {
21        $this->verbose = $verbose;
22        $this->startTime = microtime(true);
23    }
24
25    public function log(
26        string $message,
27        ?int $scopeId = null,
28        ?int $availabilityId = null,
29        ?float $durationSeconds = null
30    ): static {
31        $time = $this->getSpendTime();
32        $memory = memory_get_usage() / (1024 * 1024);
33        $text = sprintf("[CalculateSlots %07.3fs %07.1fmb] %s", "$time", $memory, $message);
34        $context = [
35            'component' => 'CalculateSlots',
36            'elapsed' => $time,
37            'memory_mb' => $memory,
38            'scope_id' => $scopeId,
39            'availability_id' => $availabilityId,
40        ];
41        if ($durationSeconds !== null) {
42            $context['duration_seconds'] = $durationSeconds;
43        }
44        $emit = $this->verbose || $availabilityId !== null;
45        if ($emit) {
46            \App::$log->info($message, $context);
47        }
48        $this->logList[] = [
49            'text' => $text,
50            'scope_id' => $scopeId,
51            'availability_id' => $availabilityId,
52            'emitted' => $emit,
53        ];
54        return $this;
55    }
56
57    public function dumpLogs(): void
58    {
59        foreach ($this->logList as $entry) {
60            if ($entry['emitted']) {
61                continue;
62            }
63            \App::$log->info($entry['text'], [
64                'component' => 'CalculateSlots',
65                'scope_id' => $entry['scope_id'],
66                'availability_id' => $entry['availability_id'],
67            ]);
68        }
69        $this->verbose = true;
70    }
71
72    /**
73     * @return list<int>
74     */
75    public function calculatedScopeIds(): array
76    {
77        return $this->calculatedScopeIds;
78    }
79
80    public function getSpendTime(): float
81    {
82        $time = round(microtime(true) - $this->startTime, 3);
83        return $time;
84    }
85
86    protected function readCalculateSkip()
87    {
88        $skip = (new \BO\Zmsbackend\Config\Service\Config())->readProperty('status__calculateSlotsSkip');
89        return $skip;
90    }
91
92    protected function readForceVerbose()
93    {
94        $force = (new \BO\Zmsbackend\Config\Service\Config())->readProperty('status__calculateSlotsForceVerbose');
95        if ($force) {
96            $this->log("Forced verbose, see table config.status__calculateSlotsForceVerbose");
97            $this->dumpLogs();
98        }
99        return $force;
100    }
101
102    protected function readLastRun()
103    {
104        $updateTimestamp = (new \BO\Zmsbackend\Config\Service\Config())->readProperty('status__calculateSlotsLastRun', true);
105        return $updateTimestamp;
106    }
107
108    public function writeMaintenanceQueries(bool $daily = false)
109    {
110        $sqlList = (new \BO\Zmsbackend\Config\Service\Config())->readProperty('status__calculateSlotsMaintenanceSQL');
111        if ($sqlList) {
112            $pdo = \BO\Zmsbackend\Connection\Select::getWriteConnection();
113            foreach (explode("\n", $sqlList) as $sql) {
114                $this->log("Maintenance query: $sql");
115                $pdo->exec($sql);
116            }
117            return \BO\Zmsbackend\Connection\Select::writeCommit();
118        }
119
120        if ($daily) {
121            (new \BO\Zmsbackend\Slot\Service\Slot())->writeOptimizedSlotTables();
122            $this->log("Optimized tables successfully");
123        }
124    }
125
126
127    public function writeCalculations(\DateTimeInterface $now, bool $daily = false): bool
128    {
129        \BO\Zmsbackend\Connection\Select::setTransaction();
130        \BO\Zmsbackend\Connection\Select::getWriteConnection();
131        $this->readForceVerbose();
132        $this->log("Calculate with time " . $now->format('c'));
133        if ($this->readCalculateSkip()) {
134            $this->log("Skip calculation due to config setting status.calculateSlotsSkip");
135            return false;
136        }
137        $startTimestamp = (new \BO\Zmsbackend\Config\Service\Config())->readProperty('status__calculateSlotsLastStart', true);
138        $updateTimestamp = (new \BO\Zmsbackend\Config\Service\Config())->readProperty('status__calculateSlotsLastRun', false);
139        if ($startTimestamp > $updateTimestamp && ((strtotime($startTimestamp) + (60 * 15)) > $now->getTimestamp())) {
140            $this->log("Skip calculation, last start on $startTimestamp is not yet finished, waiting 15 minutes.");
141            return false;
142        }
143        return $this->writeCalculationsLocked($now, $daily);
144    }
145
146    private function writeCalculationsLocked(\DateTimeInterface $now, bool $daily): bool
147    {
148        $config = new \BO\Zmsbackend\Config\Service\Config();
149        $config->replaceProperty('status__calculateSlotsLastStart', $now->format('Y-m-d H:i:s'));
150        if ($daily) {
151            $config->replaceProperty('status__calculateSlotsWithDeleteStart', $now->format('Y-m-d H:i:s'));
152        }
153        \BO\Zmsbackend\Connection\Select::writeCommit();
154        $updateTimestamp = $this->readLastRun();
155        $this->log("Last Run on time=" . $updateTimestamp);
156        if ($daily) {
157            $this->deleteOldSlots($now);
158        }
159        \BO\Zmsbackend\Connection\Select::writeCommit();
160        $scopeList = (new \BO\Zmsbackend\Scope\Service\Scope())->readList(1);
161        \BO\Zmsbackend\Connection\Select::writeCommit();
162        $scopeIds = [];
163        foreach ($scopeList as $scope) {
164            $scopeId = (int) $scope->id;
165            if ($scopeId > 0) {
166                $scopeIds[] = $scopeId;
167            }
168        }
169        $this->calculatedScopeIds = $scopeIds;
170        $scopeLength = count($scopeList) - 1;
171        foreach ($scopeList as $key => $scope) {
172            if ($this->writeCalculatedScope($scope, $now)) {
173                $this->log("Calculated slots $key/$scopeLength for $scope", (int) $scope->id);
174            }
175        }
176
177        $this->writeCanceledSlots($now);
178
179        // The unscoped repair joins every free slot to every appointment. A changed
180        // scope is remapped above. This sweep runs with the daily --delete pass.
181        if ($daily) {
182            $slotQuery = new \BO\Zmsbackend\Slot\Service\Slot();
183            if ($slotsProcessed = $slotQuery->deleteSlotProcessOnProcess()) {
184                $this->log("Finished to free $slotsProcessed slots for changed/deleted processes");
185            }
186
187            $slotQuery->deleteSlotProcessOnSlot();
188
189            if ($slotsProcessed = $slotQuery->updateSlotProcessMapping(null, $now)) {
190                $this->log("Updated Slot-Process-Mapping, mapped $slotsProcessed processes");
191            }
192        }
193
194        (new \BO\Zmsbackend\Config\Service\Config())->replaceProperty('status__calculateSlotsLastRun', $now->format('Y-m-d H:i:s'));
195
196        \BO\Zmsbackend\Connection\Select::writeCommit();
197        $this->log("Slot calculation finished");
198        $this->writeMaintenanceQueries($daily);
199
200        return true;
201    }
202
203    protected function writeCalculatedScope(\BO\Zmsentities\Scope $scope, \DateTimeInterface $now): bool
204    {
205        $slotQuery = new \BO\Zmsbackend\Slot\Service\Slot();
206        $updatedList = $slotQuery->writeByScope($scope, $now);
207        if (count($updatedList)) {
208            $this->writePostProcessingByScope($scope, $now);
209            \BO\Zmsbackend\Connection\Select::writeCommitWithStartLock();
210            $this->readLastRun();
211            \BO\Zmsbackend\Connection\Select::writeCommit();
212            return true;
213        }
214        return false;
215    }
216
217    public function writePostProcessingByScope(\BO\Zmsentities\Scope $scope, \DateTimeInterface $now): void
218    {
219        $slotQuery = new \BO\Zmsbackend\Slot\Service\Slot();
220        if ($slotsProcessed = $slotQuery->deleteSlotProcessOnProcess($scope->id)) {
221            $this->log("Finished to free $slotsProcessed slots for changed/deleted processes", (int) $scope->id);
222        }
223        $slotQuery->writeCanceledByTimeAndScope($now, $scope);
224        $slotQuery->deleteSlotProcessOnSlot($scope->id);
225        //$this->log("Finished to free slots for cancelled availabilities");
226
227        if ($slotsProcessed = $slotQuery->updateSlotProcessMapping($scope->id, $now)) {
228            $this->log("Updated Slot-Process-Mapping, mapped $slotsProcessed processes", (int) $scope->id);
229        }
230    }
231
232    public function writeCanceledSlots(\DateTimeInterface $now, string $modify = '+5 minutes'): bool
233    {
234        \BO\Zmsbackend\Connection\Select::getWriteConnection();
235        $slotQuery = new \BO\Zmsbackend\Slot\Service\Slot();
236        if ($slotQuery->writeCanceledByTime($now->modify($modify))) {
237            \BO\Zmsbackend\Connection\Select::writeCommit();
238            $this->log("Cancelled slots older than " . $now->modify($modify)->format('c'));
239            return true;
240        }
241        return false;
242    }
243
244    public function deleteOldSlots(\DateTimeInterface $now): void
245    {
246        $this->log("Maintenance: Delete slots older than " . $now->format('Y-m-d'));
247        $slotQuery = new \BO\Zmsbackend\Slot\Service\Slot();
248        $pdo = \BO\Zmsbackend\Connection\Select::getWriteConnection();
249        $pdo->exec('SET SESSION innodb_lock_wait_timeout=600');
250        if ($slotQuery->deleteSlotsOlderThan($now)) {
251            \BO\Zmsbackend\Connection\Select::writeCommit();
252            $this->log("Deleted old slots successfully");
253        }
254    }
255}