Copybara bot | be50d49 | 2023-11-30 00:16:42 +0100 | [diff] [blame] | 1 | <?php |
Adrià Vilanova Martínez | 5af8651 | 2023-12-02 20:44:16 +0100 | [diff] [blame^] | 2 | /* |
| 3 | * hores |
| 4 | * Copyright (c) 2023 Adrià Vilanova Martínez |
| 5 | * |
| 6 | * This program is free software: you can redistribute it and/or modify |
| 7 | * it under the terms of the GNU Affero General Public License as |
| 8 | * published by the Free Software Foundation, either version 3 of the |
| 9 | * License, or (at your option) any later version. |
| 10 | * |
| 11 | * This program is distributed in the hope that it will be useful, |
| 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | * GNU Affero General Public License for more details. |
| 15 | * |
| 16 | * You should have received a copy of the GNU Affero General Public |
| 17 | * License along with this program. |
| 18 | * If not, see http://www.gnu.org/licenses/. |
| 19 | */ |
| 20 | |
Copybara bot | be50d49 | 2023-11-30 00:16:42 +0100 | [diff] [blame] | 21 | class registry { |
| 22 | const LOGS_PAGINATION_LIMIT = 30; |
| 23 | const REGISTRY_PAGINATION_LIMIT = 20; |
| 24 | |
| 25 | const STATE_REGISTERED = 0; |
| 26 | const STATE_MANUALLY_INVALIDATED = 1; |
| 27 | const STATE_VALIDATED_BY_WORKER = 2; |
| 28 | |
| 29 | public static $stateIcons = [ |
| 30 | 0 => "check", |
| 31 | 1 => "delete_forever", |
| 32 | 2 => "verified_user" |
| 33 | ]; |
| 34 | |
| 35 | public static $stateIconColors = [ |
| 36 | 0 => "mdl-color-text--green", |
| 37 | 1 => "mdl-color-text--red", |
| 38 | 2 => "mdl-color-text--green" |
| 39 | ]; |
| 40 | |
| 41 | public static $stateTooltips = [ |
| 42 | 0 => "Registrado", |
| 43 | 1 => "Invalidado manualmente", |
| 44 | 2 => "Validado" |
| 45 | ]; |
| 46 | |
| 47 | public static $workerPendingWhere = "r.workervalidated = 0"; |
| 48 | public static $notInvalidatedWhere = "r.invalidated = 0"; |
| 49 | public static $logsWarnings = "LOCATE('[warning]', logdetails) as warningpos, LOCATE('[error]', logdetails) as errorpos, LOCATE('[fatalerror]', logdetails) as fatalerrorpos"; |
| 50 | |
| 51 | private static function recordLog(&$log, $time, $executedby = -1, $quiet = false) { |
| 52 | global $con; |
| 53 | |
| 54 | $slog = db::sanitize($log); |
| 55 | $sday = (int)$time; |
| 56 | $srealtime = (int)time(); |
| 57 | $sexecutedby = (int)$executedby; |
| 58 | |
| 59 | $status = mysqli_query($con, "INSERT INTO logs (realtime, day, executedby, logdetails) VALUES ($srealtime, $sday, $sexecutedby, '$slog')"); |
| 60 | |
| 61 | if (!$status) { |
| 62 | if (!$quiet) echo "[fatalerror] Couldn't record log into the database!\n"; |
| 63 | return false; |
| 64 | } else { |
| 65 | if (!$quiet) echo "[success] Log recorded into the database.\n"; |
| 66 | return mysqli_insert_id($con); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | public static function getLogs($start = 0, $limit = self::LOGS_PAGINATION_LIMIT) { |
| 71 | global $con; |
| 72 | |
| 73 | $query = mysqli_query($con, "SELECT id, realtime, day, executedby, ".self::$logsWarnings." FROM logs ORDER BY id DESC".db::limitPagination($start, $limit)); |
| 74 | |
| 75 | $return = []; |
| 76 | while ($row = mysqli_fetch_assoc($query)) { |
| 77 | $return[] = $row; |
| 78 | } |
| 79 | |
| 80 | return $return; |
| 81 | } |
| 82 | |
| 83 | public static function getLog($id) { |
| 84 | global $con; |
| 85 | |
| 86 | $sid = (int)$id; |
| 87 | |
| 88 | $query = mysqli_query($con, "SELECT logdetails, ".self::$logsWarnings." FROM logs WHERE id = $sid"); |
| 89 | |
| 90 | if (!mysqli_num_rows($query)) return false; |
| 91 | |
| 92 | $row = mysqli_fetch_assoc($query); |
| 93 | |
| 94 | return $row; |
| 95 | } |
| 96 | |
| 97 | public static function beautifyLog($str) { |
| 98 | $str = str_replace("[info]", "<span style='font-weight: bold;' class='mdl-color-text--blue'>[info]</span>", $str); |
| 99 | $str = str_replace("[warning]", "<span style='font-weight: bold;' class='mdl-color-text--orange'>[warning]</span>", $str); |
| 100 | $str = str_replace("[error]", "<span style='font-weight: bold;' class='mdl-color-text--red'>[error]</span>", $str); |
| 101 | $str = str_replace("[fatalerror]", "<span style='font-weight: bold;' class='mdl-color-text--red-900'>[fatalerror]</span>", $str); |
| 102 | return $str; |
| 103 | } |
| 104 | |
| 105 | private static function addToLog(&$log, $quiet, $msg) { |
| 106 | $log .= $msg; |
| 107 | if (!$quiet) echo $msg; |
| 108 | } |
| 109 | |
| 110 | private static function alreadyRegistered($time, $worker) { |
| 111 | global $con; |
| 112 | |
| 113 | $stime = (int)$time; |
| 114 | $sworker = (int)$worker; |
| 115 | |
| 116 | $query = mysqli_query($con, "SELECT id FROM records WHERE worker = $sworker AND day = $stime AND invalidated = 0 LIMIT 1"); |
| 117 | |
| 118 | return (mysqli_num_rows($query) > 0); |
| 119 | } |
| 120 | |
| 121 | private static function register($time, $worker, $schedule, $creator = -1) { |
| 122 | global $con; |
| 123 | |
| 124 | $sworker = (int)$worker; |
| 125 | $stime = (int)$time; |
| 126 | $srealtime = (int)time(); |
| 127 | $screator = (int)$creator; |
| 128 | $sbeginswork = (int)$schedule["beginswork"]; |
| 129 | $sendswork = (int)$schedule["endswork"]; |
| 130 | $sbeginsbreakfast = (int)$schedule["beginsbreakfast"]; |
| 131 | $sendsbreakfast = (int)$schedule["endsbreakfast"]; |
| 132 | $sbeginslunch = (int)$schedule["beginslunch"]; |
| 133 | $sendslunch = (int)$schedule["endslunch"]; |
| 134 | |
| 135 | return mysqli_query($con, "INSERT INTO records (worker, day, created, creator, beginswork, endswork, beginsbreakfast, endsbreakfast, beginslunch, endslunch) VALUES ($sworker, $stime, $srealtime, $screator, $sbeginswork, $sendswork, $sbeginsbreakfast, $sendsbreakfast, $sbeginslunch, $sendslunch)"); |
| 136 | } |
| 137 | |
| 138 | public static function getWorkerCategory($id) { |
| 139 | global $con; |
| 140 | |
| 141 | $sid = (int)$id; |
| 142 | |
| 143 | $query = mysqli_query($con, "SELECT p.category category FROM workers w INNER JOIN people p ON w.person = p.id WHERE w.id = $sid"); |
| 144 | |
| 145 | if ($query === false || !mysqli_num_rows($query)) { |
| 146 | return false; |
| 147 | } |
| 148 | |
| 149 | $row = mysqli_fetch_assoc($query); |
| 150 | |
| 151 | return $row["category"]; |
| 152 | } |
| 153 | |
| 154 | public static function getDayTypes($time) { |
| 155 | global $con; |
| 156 | |
| 157 | $stime = (int)$time; |
| 158 | |
| 159 | $query = mysqli_query($con, "SELECT id, category, details FROM calendars WHERE begins <= $stime AND ends >= $stime"); |
| 160 | if ($query === false) return false; |
| 161 | |
| 162 | $calendars = []; |
| 163 | while ($row = mysqli_fetch_assoc($query)) { |
| 164 | $calendar = json_decode($row["details"], true); |
| 165 | if (json_last_error() !== JSON_ERROR_NONE) return false; |
| 166 | if (!isset($calendar[$time])) return false; |
| 167 | |
| 168 | $calendars[$row["category"]] = $calendar[$time]; |
| 169 | } |
| 170 | |
| 171 | return $calendars; |
| 172 | } |
| 173 | |
| 174 | private static function getApplicableSchedules($time) { |
| 175 | global $con; |
| 176 | |
| 177 | $stime = (int)$time; |
| 178 | |
| 179 | $query = mysqli_query($con, "SELECT id FROM schedules WHERE begins <= $stime AND ends >= $stime AND active = 1"); |
| 180 | if ($query === false) return false; |
| 181 | |
| 182 | $schedules = []; |
| 183 | while ($row = mysqli_fetch_assoc($query)) { |
| 184 | $schedules[] = $row["id"]; |
| 185 | } |
| 186 | |
| 187 | return $schedules; |
| 188 | } |
| 189 | |
| 190 | public static function generateNow($originaltime, &$logId, $quiet = true, $executedby = -1, $workersWhitelist = false) { |
| 191 | global $con; |
| 192 | |
| 193 | $log = ""; |
| 194 | |
| 195 | if ($workersWhitelist !== false) self::addToLog($log, $quiet, "[info] This is a partial registry generation, because a whitelist of workers was passed: [".implode(", ", $workersWhitelist)."]\n"); |
| 196 | |
| 197 | $datetime = new DateTime(); |
| 198 | $datetime->setTimestamp($originaltime); |
| 199 | self::addToLog($log, $quiet, "[info] Time passed: ".$datetime->format("Y-m-d H:i:s")."\n"); |
| 200 | |
| 201 | $rawdate = $datetime->format("Y-m-d")."T00:00:00"; |
| 202 | self::addToLog($log, $quiet, "[info] Working with this date: $rawdate\n"); |
| 203 | $date = new DateTime($rawdate); |
| 204 | |
| 205 | $time = $date->getTimestamp(); |
| 206 | $dow = (int)$date->format("N") - 1; |
| 207 | self::addToLog($log, $quiet, "[info] Final date timestamp: $time, Dow: $dow\n"); |
| 208 | |
| 209 | $days = self::getDayTypes($time); |
| 210 | if ($days === false) { |
| 211 | self::addToLog($log, $quiet, "[fatalerror] An error occurred while loading the calendars.\n"); |
| 212 | $logId = self::recordLog($log, $time, $executedby, $quiet); |
| 213 | return 1; |
| 214 | } |
| 215 | |
| 216 | $schedules = self::getApplicableSchedules($time); |
| 217 | if ($schedules === false) { |
| 218 | self::addToLog($log, $quiet, "[fatalerror] An error occurred while loading the active schedules.\n"); |
| 219 | $logId = self::recordLog($log, $time, $executedby, $quiet); |
| 220 | return 2; |
| 221 | } |
| 222 | |
| 223 | self::addToLog($log, $quiet, "[info] Found ".count($schedules)." active schedule(s)\n"); |
| 224 | |
| 225 | foreach ($schedules as $scheduleid) { |
| 226 | self::addToLog($log, $quiet, "\n[info] Processing schedule $scheduleid\n"); |
| 227 | |
| 228 | $s = schedules::get($scheduleid); |
| 229 | if ($s === false) { |
| 230 | self::addToLog($log, $quiet, "[fatalerror] An error ocurred while loading schedule with id $scheduleid (it doesn't exist or there was an error with the SQL query)\n"); |
| 231 | $logId = self::recordLog($log, $time, $executedby, $quiet); |
| 232 | return 3; |
| 233 | } |
| 234 | |
| 235 | if ($workersWhitelist !== false && !in_array($s["worker"], $workersWhitelist)) { |
| 236 | self::addToLog($log, $quiet, "[info] This schedule's worker (".$s["worker"].") is not in the whitelist, so skipping\n"); |
| 237 | continue; |
| 238 | } |
| 239 | |
| 240 | $category = self::getWorkerCategory($s["worker"]); |
| 241 | |
| 242 | if (isset($days[$category])) { |
| 243 | self::addToLog($log, $quiet, "[info] Using worker's (".$s["worker"].") category ($category) calendar\n"); |
| 244 | $typeday = $days[$category]; |
| 245 | } else if (isset($days[-1])) { |
| 246 | self::addToLog($log, $quiet, "[info] Using default calendar\n"); |
| 247 | $typeday = $days[-1]; |
| 248 | } else { |
| 249 | self::addToLog($log, $quiet, "[warning] No calendar applies, so skipping this schedule\n"); |
| 250 | continue; |
| 251 | } |
| 252 | |
| 253 | if (!isset($s["days"][$typeday])) { |
| 254 | self::addToLog($log, $quiet, "[info] This schedule doesn't have this type of day ($typeday) set up, so skipping\n"); |
| 255 | continue; |
| 256 | } |
| 257 | |
| 258 | if (!isset($s["days"][$typeday][$dow])) { |
| 259 | self::addToLog($log, $quiet, "[info] This schedule doesn't have a daily schedule for this day of the week ($dow) and type of day ($typeday), so skipping.\n"); |
| 260 | continue; |
| 261 | } |
| 262 | |
| 263 | self::addToLog($log, $quiet, "[info] Found matching daily schedule. We'll proceed to register it\n"); |
| 264 | |
| 265 | if (self::alreadyRegistered($time, $s["worker"])) { |
| 266 | self::addToLog($log, $quiet, "[warning] We're actually NOT going to register it because another registry already exists for this worker at the same day.\n"); |
| 267 | } else { |
| 268 | if (self::register($time, $s["worker"], $s["days"][$typeday][$dow], $executedby)) { |
| 269 | self::addToLog($log, $quiet, "[info] Registered with id ".mysqli_insert_id($con)."\n"); |
| 270 | } else { |
| 271 | self::addToLog($log, $quiet, "[error] Couldn't register this schedule because of an unknown error!\n"); |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | $logId = self::recordLog($log, $time, $executedby, $quiet); |
| 277 | |
| 278 | return 0; |
| 279 | } |
| 280 | |
| 281 | public static function getStatus($row) { |
| 282 | if ($row["invalidated"] == 1) return self::STATE_MANUALLY_INVALIDATED; |
| 283 | elseif ($row["workervalidated"] == 1) return self::STATE_VALIDATED_BY_WORKER; |
| 284 | else return self::STATE_REGISTERED; |
| 285 | } |
| 286 | |
| 287 | private static function magicRecord(&$row) { |
| 288 | $row["state"] = self::getStatus($row); |
| 289 | } |
| 290 | |
| 291 | public static function get($id, $magic = false) { |
| 292 | global $con; |
| 293 | |
| 294 | $sid = (int)$id; |
| 295 | |
| 296 | $query = mysqli_query($con, "SELECT * FROM records WHERE id = $sid LIMIT 1"); |
| 297 | |
| 298 | if (!mysqli_num_rows($query)) return false; |
| 299 | |
| 300 | $row = mysqli_fetch_assoc($query); |
| 301 | if ($magic) self::magicRecord($row); |
| 302 | |
| 303 | return $row; |
| 304 | } |
| 305 | |
| 306 | public static function getRecords($worker = false, $begins = false, $ends = false, $returnInvalid = false, $includeWorkerInfo = false, $sortByDateDesc = false, $start = 0, $limit = self::REGISTRY_PAGINATION_LIMIT, $treatWorkerAttributeAsUser = false, $onlyWorkerPending = false, $magic = true) { |
| 307 | global $con; |
| 308 | |
| 309 | if ($treatWorkerAttributeAsUser && !$includeWorkerInfo) return false; |
| 310 | |
| 311 | $where = []; |
| 312 | |
| 313 | if ($worker !== false) $where[] = ($treatWorkerAttributeAsUser ? "w.person" : "r.worker")." = ".(int)$worker; |
| 314 | |
| 315 | $dateLimit = ($begins !== false && $ends !== false); |
| 316 | if ($dateLimit) { |
| 317 | $where[] = "r.day >= ".(int)$begins; |
| 318 | $where[] = "r.day <= ".(int)$ends; |
| 319 | } |
| 320 | |
| 321 | if (!$returnInvalid || $onlyWorkerPending) $where[] = self::$notInvalidatedWhere; |
| 322 | |
| 323 | if ($onlyWorkerPending) $where[] = self::$workerPendingWhere; |
| 324 | |
| 325 | $query = mysqli_query($con, "SELECT r.*".($includeWorkerInfo ? ", p.id personid, p.name workername, w.company companyid" : "")." FROM records r LEFT JOIN workers w ON r.worker = w.id".($includeWorkerInfo ? " LEFT JOIN people p ON w.person = p.id" : "").(count($where) ? " WHERE ".implode(" AND ", $where) : "")." ORDER BY".($sortByDateDesc ? " r.day DESC, w.company DESC," : "")." id DESC".db::limitPagination($start, $limit)); |
| 326 | |
| 327 | $return = []; |
| 328 | while ($row = mysqli_fetch_assoc($query)) { |
| 329 | if ($magic) self::magicRecord($row); |
| 330 | $return[] = $row; |
| 331 | } |
| 332 | |
| 333 | return $return; |
| 334 | } |
| 335 | |
| 336 | public static function getWorkerRecords($worker, $begins = false, $ends = false, $returnInvalid = false, $onlyWorkerPending = false) { |
| 337 | return self::getRecords($worker, $begins, $ends, $returnInvalid, false, true, 0, 0, false, $onlyWorkerPending); |
| 338 | } |
| 339 | |
| 340 | public static function numRows($includingInvalidated = false) { |
| 341 | global $con; |
| 342 | |
| 343 | $query = mysqli_query($con, "SELECT COUNT(*) count FROM records".($includingInvalidated ? "" : " WHERE invalidated = 0")); |
| 344 | |
| 345 | if (!mysqli_num_rows($query)) return false; |
| 346 | |
| 347 | $row = mysqli_fetch_assoc($query); |
| 348 | |
| 349 | return (isset($row["count"]) ? (int)$row["count"] : false); |
| 350 | } |
| 351 | |
| 352 | public static function numRowsUser($user, $includingInvalidated = true) { |
| 353 | global $con; |
| 354 | |
| 355 | $where = []; |
| 356 | if (!$includingInvalidated) $where[] = "r.invlidated = 0"; |
| 357 | $where[] = "w.person = ".(int)$user; |
| 358 | |
| 359 | $query = mysqli_query($con, "SELECT COUNT(*) count FROM records r LEFT JOIN workers w ON r.worker = w.id".(count($where) ? " WHERE ".implode(" AND ", $where) : "")); |
| 360 | |
| 361 | if (!mysqli_num_rows($query)) return false; |
| 362 | |
| 363 | $row = mysqli_fetch_assoc($query); |
| 364 | |
| 365 | return (isset($row["count"]) ? (int)$row["count"] : false); |
| 366 | } |
| 367 | |
| 368 | public static function checkRecordIsFromPerson($record, $person = "ME", $boolean = false) { |
| 369 | global $con; |
| 370 | |
| 371 | if ($person == "ME") $person = people::userData("id"); |
| 372 | |
| 373 | $srecord = (int)$record; |
| 374 | $sperson = (int)$person; |
| 375 | |
| 376 | $query = mysqli_query($con, "SELECT r.id FROM records r INNER JOIN workers w ON r.worker = w.id INNER JOIN people p ON w.person = p.id WHERE p.id = $sperson AND r.id = $srecord LIMIT 1"); |
| 377 | |
| 378 | if (!mysqli_num_rows($query)) { |
| 379 | if ($boolean) return false; |
| 380 | security::denyUseMethod(security::METHOD_NOTFOUND); |
| 381 | } |
| 382 | |
| 383 | return true; |
| 384 | } |
| 385 | |
| 386 | public static function invalidate($id, $invalidatedby = "ME") { |
| 387 | global $con; |
| 388 | |
| 389 | $sid = (int)$id; |
| 390 | |
| 391 | if ($invalidatedby === "ME") $invalidatedby = people::userData("id"); |
| 392 | $sinvalidatedby = (int)$invalidatedby; |
| 393 | |
| 394 | return mysqli_query($con, "UPDATE records SET invalidated = 1, invalidatedby = $sinvalidatedby WHERE id = $sid LIMIT 1"); |
| 395 | } |
| 396 | |
| 397 | public static function invalidateAll($id, $beginsRawDate, $endsRawDate, $invalidatedby = "ME") { |
| 398 | global $con; |
| 399 | |
| 400 | $beginsDate = new DateTime($beginsRawDate); |
| 401 | $sbegins = (int)$beginsDate->getTimestamp(); |
| 402 | $endsDate = new DateTime($endsRawDate); |
| 403 | $sends = (int)$endsDate->getTimestamp(); |
| 404 | |
| 405 | $sid = (int)$id; |
| 406 | |
| 407 | if ($invalidatedby === "ME") $invalidatedby = people::userData("id"); |
| 408 | $sinvalidatedby = (int)$invalidatedby; |
| 409 | |
| 410 | return mysqli_query($con, "UPDATE records SET invalidated = 1, invalidatedby = $sinvalidatedby WHERE worker = $sid AND invalidated = 0 AND day <= $sends AND day >= $sbegins"); |
| 411 | } |
| 412 | } |