Joywork/engine/classes/Installments.php
2026-05-22 21:21:54 +03:00

389 lines
14 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
class Installments
{
private $db;
public $id = null;
public $name = null;
public $description = null;
public $type = null;
public $initial_payment = null;
public $payment_period = null;
public $allow_change_on_close = null;
public $interest_rate = null;
public $comment = null;
public $agency_id = null;
public $is_archive = null;
public $created_at = null;
public $updated_at = null;
public $user_agency_id;
public $user_id;
public $user;
public function __construct($id = null, $customDb)
{
$pdo = $customDb ? $customDb : new MysqlPdo(hst, ndb, user, pass);
$sql = "SET NAMES 'utf8'";
$pdo->query($sql);
$this->db = $pdo;
$this->user_agency_id = isset($_SESSION['agency_id']) ? $_SESSION['agency_id'] : 0;
$this->user_id = isset($_SESSION['id']) ? $_SESSION['id'] : 0;
$this->user = new User;
if ($id && is_int($id))
{
$sql = $this->db->query("SELECT * FROM installments WHERE `installments.id` = {$id}");
$installment = $this->db->fetch_assoc($sql);
if ($installment)
{
$this->id = $installment['id'];
$this->name = $installment['name'];
$this->description = $installment['description'];
$this->type = $installment['type'];
$this->initial_payment = $installment['initial_payment'];
$this->payment_period = $installment['payment_period'];
$this->allow_change_on_close = $installment['allow_change_on_close'];
$this->interest_rate = $installment['interest_rate'];
$this->comment = $installment['comment'];
$this->agency_id = $installment['agency_id'];
$this->is_archive = $installment['is_archive'];
$this->created_at = $installment['created_at'];
$this->updated_at = $installment['updated_at'];
}
}
}
private function installments($is_archive = 0)
{
$agency_id = $this->user_agency_id;
$sql = "SELECT * FROM installments WHERE `agency_id` = $agency_id AND `is_archive` = $is_archive";
if ($res = $this->db->query($sql))
{
$installments = array();
while ($cs = $this->db->fetch_assoc($res))
{
// Декодируем payment_period из JSON в массив
if (!empty($cs['payment_period'])) {
$decoded = json_decode($cs['payment_period'], true);
$cs['payment_period'] = ($decoded !== null && is_array($decoded)) ? $decoded : [];
} else {
$cs['payment_period'] = [];
}
$installments[] = $cs;
}
return $installments;
}
return [];
}
public function getInstallments()
{
return $this->installments(0);
}
public function getArchiveInstallments()
{
return $this->installments(1);
}
public function getById($id)
{
$id = (int) $id;
$sql = "SELECT * FROM installments WHERE id = $id LIMIT 1";
$result = $this->db->query($sql);
$row = $this->db->fetch_assoc($result);
if ($row && !empty($row['payment_period'])) {
$decoded = json_decode($row['payment_period'], true);
$valid_periods = ['monthly', 'quarterly', 'yearly'];
$row['payment_period'] = ($decoded !== null && is_array($decoded))
? array_intersect($decoded, $valid_periods)
: [];
} else {
$row['payment_period'] = [];
}
return $row;
}
public function addEdit($installment)
{
$agency_id = $this->user_agency_id;
if (!$installment || !$agency_id) {
return false;
}
// Обработка входных данных
$name = isset($installment->name) ? trim($installment->name) : '';
$type = isset($installment->type) ? trim($installment->type) : '';
// Сериализация payment_period в JSON строку
$payment_period = isset($installment->payment_period)
? (is_array($installment->payment_period)
? json_encode($installment->payment_period)
: json_encode([$installment->payment_period])) // Если строка, преобразуем в массив
: json_encode([]); // Пустой массив по умолчанию
$description = isset($installment->description) ? trim($installment->description) : null;
$initial_payment = isset($installment->initial_payment) ? (float) $installment->initial_payment : null;
$allow_change_on_close = isset($installment->allow_change_on_close) ? (int) $installment->allow_change_on_close : 0;
$interest_rate = isset($installment->interest_rate) ? (float) $installment->interest_rate : null;
$comment = isset($installment->comment) ? trim($installment->comment) : null;
// Проверка корректности JSON
if ($payment_period === false) {
error_log('JSON encoding failed for payment_period: ' . print_r($installment->payment_period, true));
return false;
}
// Проверка на некорректное значение
if (!is_array($installment->payment_period) && $installment->payment_period === 'Array') {
error_log('Invalid payment_period value: ' . print_r($installment->payment_period, true));
return false;
}
if (!empty($installment->id) && $this->getById($installment->id)) {
$id = (int) $installment->id;
$sql = "UPDATE installments
SET agency_id = $agency_id,
name = '$name',
type = '$type',
payment_period = '$payment_period',
description = " . ($description !== null ? "'$description'" : "NULL") . ",
initial_payment = " . ($initial_payment !== null ? $initial_payment : "NULL") . ",
allow_change_on_close = $allow_change_on_close,
interest_rate = " . ($interest_rate !== null ? $interest_rate : "NULL") . ",
comment = " . ($comment !== null ? "'$comment'" : "NULL") . ",
is_archive = 0
WHERE id = $id";
$result = $this->db->query($sql);
return $result ? $this->getById($id) : false;
} else {
$sql = "INSERT INTO installments (agency_id, name, type, payment_period, description, initial_payment, allow_change_on_close, interest_rate, comment, is_archive)
VALUES ($agency_id, '$name', '$type', '$payment_period', " .
($description !== null ? "'$description'" : "NULL") . ", " .
($initial_payment !== null ? $initial_payment : "NULL") . ", " .
"$allow_change_on_close, " .
($interest_rate !== null ? $interest_rate : "NULL") . ", " .
($comment !== null ? "'$comment'" : "NULL") . ", " .
"0)";
$result = $this->db->query($sql);
if ($result) {
$new_id = $this->db->insert_id;
return $this->getById($new_id);
} else {
return false;
}
}
}
public function toArchiveOrRecover($installment_id, $status)
{
$installment_id = (int) $installment_id;
$status = ($status == 1) ? 1 : 0;
if (!$installment_id || !$this->user_agency_id || !$this->getById($installment_id)) {
return false;
}
if ($status === 1) {
$this->db->query("DELETE FROM complex_house_installments WHERE installment_id = {$installment_id}");
}
$sql = "UPDATE `installments` SET `is_archive` = $status WHERE `id` = {$installment_id}";
$result = $this->db->query($sql);
return $result ? true : false;
}
public function delete($installment_id)
{
$installment_id = (int) $installment_id;
// Проверка наличия ID, агентства и существования рассрочки
if (!$installment_id || !$this->user_agency_id || !$this->getById($installment_id)) {
return false;
}
$this->db->query("DELETE FROM complex_house_installments WHERE installment_id = {$installment_id}");
// Удаление записи
$sql = "DELETE FROM installments WHERE id = $installment_id AND agency_id = {$this->user_agency_id}";
$result = $this->db->query($sql);
return $result ? true : false;
}
public function updateHouseInstallments($house_id, $installments)
{
// Удаляем старые связи
$this->db->query("DELETE FROM complex_house_installments WHERE house_id = " . (int)$house_id);
$hasInstallments = !empty($installments) && is_array($installments);
if ($hasInstallments) {
// Добавляем новые записи
foreach ($installments as $i) {
$installment_id = (int)$i['id'];
$end_date = !empty($i['end_date']) ? "'" . date('Y-m-d', strtotime($i['end_date'])) . "'" : "NULL";
$this->db->query("
INSERT INTO complex_house_installments (house_id, installment_id, end_date)
VALUES ($house_id, $installment_id, $end_date)
");
}
// Обновляем payment_types и installment_price у помещений
$rooms = $this->db->query("
SELECT complex_rooms.id, complex_rooms.payment_types, complex_rooms.total_amount
FROM complex_rooms
JOIN complex_floors ON complex_floors.id = complex_rooms.floor_id
JOIN complex_entrances ON complex_floors.complex_entrance_id = complex_entrances.id
JOIN complex_houses ON complex_entrances.complex_house_id = complex_houses.id
WHERE complex_houses.id = " . (int)$house_id
);
while ($room = $this->db->fetch_assoc($rooms)) {
$roomId = (int)$room['id'];
$totalAmount = (float)$room['total_amount'];
$paymentTypes = json_decode($room['payment_types'], true);
if (!is_array($paymentTypes)) {
$paymentTypes = [];
}
if (!in_array('INSTALLMENT', $paymentTypes)) {
$paymentTypes[] = 'INSTALLMENT';
$updatedJson = json_encode(array_values($paymentTypes));
$escapedJson = "'" . addslashes($updatedJson) . "'";
$this->db->query("
UPDATE complex_rooms
SET
payment_types = $escapedJson,
installment_price = $totalAmount
WHERE id = $roomId
");
}
}
} else {
// Удаляем INSTALLMENT из payment_types
$rooms = $this->db->query("
SELECT complex_rooms.id, complex_rooms.payment_types
FROM complex_rooms
JOIN complex_floors ON complex_floors.id = complex_rooms.floor_id
JOIN complex_entrances ON complex_floors.complex_entrance_id = complex_entrances.id
JOIN complex_houses ON complex_entrances.complex_house_id = complex_houses.id
WHERE complex_houses.id = " . (int)$house_id
);
while ($room = $this->db->fetch_assoc($rooms)) {
$roomId = (int)$room['id'];
$paymentTypes = json_decode($room['payment_types'], true);
if (!is_array($paymentTypes)) {
$paymentTypes = [];
}
if (in_array('INSTALLMENT', $paymentTypes)) {
$filteredTypes = [];
foreach ($paymentTypes as $type) {
if ($type !== 'INSTALLMENT') {
$filteredTypes[] = $type;
}
}
$updatedJson = json_encode($filteredTypes);
$escapedJson = "'" . addslashes($updatedJson) . "'";
$this->db->query("
UPDATE complex_rooms
SET payment_types = $escapedJson
WHERE id = $roomId
");
}
}
}
}
public function getByHouseId($house_id)
{
$sql = "SELECT
i.id,
i.name,
i.type,
i.description,
i.initial_payment,
i.payment_period,
i.interest_rate,
i.comment,
chi.end_date as house_installment_end_date
FROM complex_house_installments chi
LEFT JOIN installments i ON i.id = chi.installment_id
WHERE chi.house_id = {$house_id}
AND i.is_archive = 0
AND (chi.end_date IS NULL OR chi.end_date >= CURDATE())";
$result = $this->db->query($sql);
$installmentsMap = [];
while ($row = $this->db->fetch_assoc($result)) {
$row['payment_period'] = explode(',', $row['payment_period']);
// Исключаем дубликаты по i.id
if (!isset($installmentsMap[$row['id']])) {
$installmentsMap[$row['id']] = $row;
}
}
return array_values($installmentsMap);
}
public function getByComplexId($complex_id)
{
$sql = "SELECT
i.id,
i.name,
i.type,
i.description,
i.initial_payment,
i.payment_period,
i.interest_rate,
i.comment,
chi.end_date as house_installment_end_date,
chi.house_id
FROM complex_house_installments chi
LEFT JOIN installments i ON i.id = chi.installment_id
LEFT JOIN complex_houses ch ON ch.id = chi.house_id
WHERE ch.complex_id = {$complex_id}
AND i.is_archive = 0
AND (chi.end_date IS NULL OR chi.end_date >= CURDATE())";
$result = $this->db->query($sql);
$installmentsMap = [];
while ($row = $this->db->fetch_assoc($result)) {
$row['payment_period'] = explode(',', $row['payment_period']);
// Используем ID в качестве ключа — исключаем дубликаты
if (!isset($installmentsMap[$row['id']])) {
$installmentsMap[$row['id']] = $row;
}
}
return array_values($installmentsMap);
}
}