Files
casadoc/public/userportal/api/home-owner-attach.php
T
2026-07-27 21:04:07 +03:00

64 lines
2.4 KiB
PHP

<?php
require __DIR__ . '/_bootstrap.php';
/**
* @OA\Post(
* path="/home-owner-attach.php",
* tags={"Owners"},
* summary="Attach owner to home with share",
* description="Requires ownership of both home and owner. Ensures total share ≤ 100%.",
* security={{"bearerAuth":{}}},
* @OA\RequestBody(required=true, @OA\JsonContent(
* required={"idhome","owner_id","ownership_percentage"},
* @OA\Property(property="idhome", type="integer"),
* @OA\Property(property="owner_id", type="integer"),
* @OA\Property(property="ownership_percentage", type="number", format="float"),
* @OA\Property(property="notes", type="string")
* )),
* @OA\Response(response=200, ref="#/components/responses/Success"),
* @OA\Response(response=403, ref="#/components/responses/Forbidden"),
* @OA\Response(response=422, ref="#/components/responses/ValidationError")
* )
*/
require_method('POST');
$user = require_auth($pdo);
$in = body();
$idhome = (int) ($in['idhome'] ?? 0);
$ownerId = (int) ($in['owner_id'] ?? 0);
$share = $in['ownership_percentage'] ?? null;
$notes = $in['notes'] ?? null;
$fields = [];
if ($idhome <= 0) { $fields['idhome'] = ['Required']; }
if ($ownerId <= 0) { $fields['owner_id'] = ['Required']; }
if ($share === null || !is_numeric($share)) { $fields['ownership_percentage'] = ['Required numeric']; }
if ($fields) {
json_error(422, 'Validation failed', $fields);
}
if (!user_owns_home($pdo, $user, $idhome) || !user_owns_owner($pdo, $user, $ownerId)) {
json_error(403, 'No access to this home or owner');
}
// Already attached?
$exists = $pdo->prepare('SELECT 1 FROM home_owners WHERE home_id = ? AND owner_id = ? LIMIT 1');
$exists->execute([$idhome, $ownerId]);
if ($exists->fetchColumn()) {
json_error(422, 'Owner already attached', ['owner_id' => ['Already attached']]);
}
// Total share ≤ 100.
$sumStmt = $pdo->prepare('SELECT COALESCE(SUM(ownership_percentage), 0) FROM home_owners WHERE home_id = ?');
$sumStmt->execute([$idhome]);
if ((float) $sumStmt->fetchColumn() + (float) $share > 100.0) {
json_error(422, 'Total ownership exceeds 100%', ['ownership_percentage' => ['Sum exceeds 100']]);
}
$pdo->prepare(
'INSERT INTO home_owners (home_id, owner_id, ownership_percentage, notes, created_at, updated_at)
VALUES (?, ?, ?, ?, NOW(), NOW())'
)->execute([$idhome, $ownerId, (float) $share, $notes ?: null]);
json_ok();