Globinours/app/Controllers/DewormingController.php

248 lines
10 KiB
PHP

<?php
declare(strict_types=1);
final class DewormingController
{
public static function renameProduct(): void
{
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!PermissionService::can('medical', 'edit')) {
http_response_code(403);
return;
}
$tables = ['dewormer' => 'ref_dewormers', 'medication' => 'ref_medications', 'vaccine' => 'ref_vaccines'];
$category = (string) ($_POST['category'] ?? '');
$table = $tables[$category] ?? null;
$id = (int) ($_POST['product_id'] ?? 0);
$animalId = (int) ($_POST['animal_id'] ?? 0);
$name = trim((string) ($_POST['name'] ?? ''));
if ($table === null || $id <= 0 || $animalId <= 0 || $name === '' || mb_strlen($name) > 150) {
http_response_code(400);
echo h(t('error.bad_request'));
return;
}
$db = DB::pdo();
$stmt = $db->prepare("SELECT name FROM $table WHERE id=:id");
$stmt->execute([':id' => $id]);
$previous = $stmt->fetchColumn();
if ($previous === false) {
http_response_code(404);
echo h(t('error.not_found'));
return;
}
$duplicate = $db->prepare("SELECT 1 FROM $table WHERE name=:name COLLATE NOCASE AND id<>:id");
$duplicate->execute([':name' => $name, ':id' => $id]);
if ($duplicate->fetchColumn()) {
http_response_code(409);
echo h(t('catalog.name_exists'));
return;
}
$db->prepare("UPDATE $table SET name=:name WHERE id=:id")->execute([':name' => $name, ':id' => $id]);
AuditService::log('catalog_renamed', '/animal/product/rename', 'Intitulé de produit corrigé', 'animal', $animalId, [
'category' => $category,
'product_id' => $id,
'previous_name' => $previous,
'new_name' => $name,
]);
header('Location: /animal?id=' . $animalId . '#tab-med');
}
public static function save(): void
{
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return;
}
if (!PermissionService::can('medical')) {
http_response_code(403);
echo h(t('error.access_denied'));
return;
}
$db = DB::pdo();
$animalId = (int) ($_POST['animal_id'] ?? 0);
$entryId = (int) ($_POST['entry_id'] ?? 0);
$date = trim((string) ($_POST['administered_on'] ?? ''));
$dewormer = (int) ($_POST['dewormer_id'] ?? 0);
if (!$animalId || !self::date($date)) {
http_response_code(400);
echo h(t('deworm.invalid_date'));
return;
}
$s = $db->prepare('SELECT 1 FROM animals WHERE id=? AND deleted_at IS NULL');
$s->execute([$animalId]);
if (!$s->fetchColumn()) {
http_response_code(404);
echo h(t('error.animal_not_found'));
return;
}
if ($entryId > 0) {
$s = $db->prepare('SELECT 1 FROM dewormings WHERE id=? AND animal_id=?');
$s->execute([$entryId, $animalId]);
if (!$s->fetchColumn()) {
http_response_code(404);
echo h(t('error.not_found'));
return;
}
}
if (isset($_POST['create_dewormer'])) {
$name = trim((string) ($_POST['new_dewormer_name'] ?? ''));
if ($name === '') {
http_response_code(400);
echo h(t('deworm.name_required'));
return;
}
$s = $db->prepare('SELECT id FROM ref_dewormers WHERE name=? COLLATE NOCASE');
$s->execute([$name]);
$dewormer = (int) $s->fetchColumn();
if (!$dewormer) {
$db->prepare('INSERT INTO ref_dewormers(name,active_ingredient,form) VALUES(?,?,?)')->execute([
mb_substr($name, 0, 150),
trim((string) ($_POST['new_dewormer_ingredient'] ?? '')) ?: null,
trim((string) ($_POST['new_dewormer_form'] ?? '')) ?: null,
]);
$dewormer = (int) $db->lastInsertId();
}
}
if ($dewormer) {
$s = $db->prepare('SELECT 1 FROM ref_dewormers WHERE id=? AND active=1');
$s->execute([$dewormer]);
if (!$s->fetchColumn()) {
$dewormer = 0;
}
}
$ids = [$animalId];
$litterId = null;
if ($entryId === 0 && isset($_POST['apply_litter'])) {
$s = $db->prepare(
'SELECT l.id FROM litters l LEFT JOIN litter_kittens lk ON lk.litter_id=l.id WHERE l.mother_id=? OR lk.animal_id=? ORDER BY l.id DESC LIMIT 1',
);
$s->execute([$animalId, $animalId]);
$litterId = (int) $s->fetchColumn() ?: null;
if ($litterId) {
$s = $db->prepare(
'SELECT animal_id FROM litter_kittens WHERE litter_id=? UNION SELECT mother_id FROM litters WHERE id=? AND mother_id IS NOT NULL',
);
$s->execute([$litterId, $litterId]);
$ids = array_values(array_unique(array_map('intval', $s->fetchAll(PDO::FETCH_COLUMN))));
}
}
$manual = trim((string) ($_POST['next_due_date'] ?? ''));
if ($manual !== '' && !self::date($manual)) {
http_response_code(400);
echo h(t('deworm.invalid_next_due'));
return;
}
$db->beginTransaction();
try {
$insert = $db->prepare(
'INSERT INTO dewormings(animal_id,dewormer_id,administered_on,dose_text,weight_kg,next_due_date,notes,source_litter_id,created_by) VALUES(?,?,?,?,?,?,?,?,?)',
);
$history = $db->prepare(
"INSERT INTO animal_history(animal_id,action,type,label,details,user_id) VALUES(?,'deworming','deworming','Vermifuge / anti-puce administré',?,?)",
);
if ($entryId > 0) {
$s = $db->prepare('SELECT birth_date FROM animals WHERE id=?');
$s->execute([$animalId]);
$birthDate = $s->fetchColumn() ?: null;
$next = $manual ?: self::nextDue(is_string($birthDate) ? $birthDate : null, $date);
$db->prepare(
"UPDATE dewormings SET dewormer_id=?,administered_on=?,dose_text=?,weight_kg=?,next_due_date=?,notes=?,updated_at=datetime('now') WHERE id=? AND animal_id=?",
)->execute([
$dewormer ?: null,
$date,
trim((string) ($_POST['dose_text'] ?? '')) ?: null,
($_POST['weight_kg'] ?? '') !== '' ? (float) $_POST['weight_kg'] : null,
$next,
trim((string) ($_POST['notes'] ?? '')) ?: null,
$entryId,
$animalId,
]);
$db->prepare(
"INSERT INTO animal_history(animal_id,action,type,label,details,user_id) VALUES(?,'deworming_updated','deworming','Vermifuge / anti-puce corrigé',?,?)",
)->execute([
$animalId,
'Administration : ' . self::fr($date) . ($next ? ' · Prochaine échéance : ' . self::fr($next) : ''),
Auth::id(),
]);
$db->commit();
header('Location: /animal?id=' . $animalId . '#tab-med');
exit();
}
foreach ($ids as $id) {
$s = $db->prepare('SELECT name,birth_date FROM animals WHERE id=? AND deleted_at IS NULL');
$s->execute([$id]);
$animal = $s->fetch();
if (!$animal) {
continue;
}
$next = $manual ?: self::nextDue($animal['birth_date'] ?? null, $date);
$insert->execute([
$id,
$dewormer ?: null,
$date,
trim((string) ($_POST['dose_text'] ?? '')) ?: null,
($_POST['weight_kg'] ?? '') !== '' ? (float) $_POST['weight_kg'] : null,
$next,
trim((string) ($_POST['notes'] ?? '')) ?: null,
$litterId,
Auth::id(),
]);
$history->execute([
$id,
'Administration : ' . self::fr($date) . ($next ? ' · Prochaine échéance : ' . self::fr($next) : ''),
Auth::id(),
]);
}
$perAnimal = (float) str_replace(',', '.', (string) ($_POST['inventory_quantity'] ?? 0));
InventoryService::consumeBatch(
(int) ($_POST['inventory_batch_id'] ?? 0),
$perAnimal * count($ids),
$animalId,
'Vermifuge / anti-puce du ' . $date . ($litterId ? ' · portée #' . $litterId : ''),
);
$db->commit();
header('Location: /animal?id=' . $animalId . '#tab-med');
exit();
} catch (Throwable $e) {
if ($db->inTransaction()) {
$db->rollBack();
}
throw $e;
}
}
public static function nextDue(?string $birth, string $given): string
{
$admin = new DateTimeImmutable($given);
if ($birth && ($born = DateTimeImmutable::createFromFormat('!Y-m-d', $birth))) {
$targets = [
$born->modify('+3 weeks'),
$born->modify('+5 weeks'),
$born->modify('+7 weeks'),
$born->modify('+3 months'),
$born->modify('+4 months'),
$born->modify('+5 months'),
$born->modify('+6 months'),
];
foreach ($targets as $target) {
if ($target > $admin) {
return $target->format('Y-m-d');
}
}
}
return $admin->modify('+3 months')->format('Y-m-d');
}
private static function date(string $v): bool
{
$d = DateTimeImmutable::createFromFormat('!Y-m-d', $v);
return $d && $d->format('Y-m-d') === $v;
}
private static function fr(string $v): string
{
$d = DateTimeImmutable::createFromFormat('!Y-m-d', $v);
return $d ? $d->format('d/m/Y') : $v;
}
}