Joywork/ajax/addCheckedToExcel.php

710 lines
24 KiB
PHP
Raw Normal View History

2026-05-22 20:21:54 +02:00
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/config.php");
require_once($_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
if ((int)$_SESSION['id'] === 93) {
error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);
ini_set('display_errors', 1);
}
set_time_limit(0);
ini_set('memory_limit', '8192M');
// hide_client_contacts: при выгрузке выбранных объектов в Excel маскируем телефон
// собственника — если он клиент в системе. Чтобы не делать N+1 запросов в цикле,
// разово собираем список телефонов всех клиентов агентства и проверяем по нему.
$hideContactsExcelOwn = function_exists('should_hide_contacts_for_current_user')
&& should_hide_contacts_for_current_user();
$clientPhonesSet = array(); // нормализованный набор цифр телефона клиентов агентства
if ($hideContactsExcelOwn) {
$agencyIdForPhones = (int) User::getUserAgencyID();
if ($agencyIdForPhones > 0) {
$sqlPh = "SELECT phone FROM clients WHERE id_agent = $agencyIdForPhones OR who_work IN (
SELECT id FROM users WHERE id_manager = $agencyIdForPhones OR id = $agencyIdForPhones
)";
$resPh = mysql_query($sqlPh);
if ($resPh) {
while ($rowPh = mysql_fetch_assoc($resPh)) {
$d = preg_replace('/[^0-9]/', '', $rowPh['phone']);
if ($d !== '') {
$clientPhonesSet[$d] = true;
}
}
}
}
}
$domain = 'https://'.$_SERVER['HTTP_HOST'] . '/photos' . '/';
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$arrColExcel = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF'];
$fields = [
[
'name' => "step",
'title' => '№',
'width' => 5
],
[
'name' => "id",
'title' => 'ID объекта',
'width' => 10
],
[
'name' => "plan",
'title' => 'Фото планировки',
'width' => 20
],
[
'name' => "preview",
'title' => 'Фото превью ссылка',
'width' => 20
],
[
'name' => "type",
'title' => 'Тип рынка',
'width' => 10
],
[
'name' => "objType",
'title' => 'Тип квартиры помещения',
'width' => 20
],
[
'name' => "metro",
'title' => 'Район/метро',
'width' => 25
],
[
'name' => "address",
'title' => 'Адрес',
'width' => 35
],
[
'name' => "allArea",
'title' => 'Метраж общий',
'width' => 10
],
[
'name' => "liveArea",
'title' => 'Метраж жилой',
'width' => 10
],
[
'name' => "kitchenArea",
'title' => 'Метраж кухни',
'width' => 10
],
[
'name' => "floor",
'title' => 'Этаж/Этажность',
'width' => 15
],
[
'name' => "price",
'title' => 'Цена',
'width' => 20
],
[
'name' => "phone",
'title' => 'Телефон',
'width' => 20
],
[
'name' => "linkResource",
'title' => 'Ссылка на первоисточник',
'width' => 20
],
[
'name' => "createDate",
'title' => 'Дата создания',
'width' => 20
],
[
'name' => "contract_type",
'title' => 'Тип договора',
'width' => 20
],
[
'name' => "contract_number",
'title' => 'Номер договора',
'width' => 20
],
[
'name' => "contract_date",
'title' => 'Дата договора',
'width' => 20
],
];
$fieldsAll = [
[ //done
'name' => "id",
'title' => 'SKU',
'width' => 10
],
[ //
'name' => "objType",
'title' => 'Category',
'width' => 20
],
[ // done
'name' => "type",
'title' => 'Characteristic:Тип объекта',
'width' => 35
],
[ // done
'name' => "opis",
'title' => 'Text',
'width' => 35
],
[ // done
'name' => "nazv",
'title' => 'Title',
'width' => 35
],
[ // done
'name' => "photo",
'title' => 'Photo',
'width' => 20,
'action' => 'all',
],
[ // done
'name' => "plan",
'title' => 'Plan photo',
'width' => 20,
'action' => 'all',
],
[ // done
'name' => "price",
'title' => 'Price',
'width' => 15
],
[ // done
'name' => "address",
'title' => 'Characteristic:Адрес',
'width' => 35
],
[ // done
'name' => "metro",
'title' => 'Characteristics:Район/Метро',
'width' => 20
],
[ // done
'name' => "allArea",
'title' => 'Characteristic:Общая площадь',
'width' => 10
],
[ // done
'name' => "liveArea",
'title' => 'Characteristic:Площадь комнат',
'width' => 10
],
[ // done
'name' => "kitchenArea",
'title' => 'Characteristic:Площадь кухни',
'width' => 10
],
[ // done
'name' => "landArea", // Площадь участка
'title' => 'Characteristic:Площадь участка (NO)',
'width' => 35
],
[ // done
'name' => "numberFlat", // колво комнат
'title' => 'Characteristic:Количество комнат',
'width' => 10
],
[ // done
'name' => "floor",
'title' => 'Characteristic:Этажность',
'width' => 15
],
[ // done
'name' => "id2",
'title' => 'External ID',
'width' => 10
],
[ // done
'name' => "id1",
'title' => 'Parent UID',
'width' => 10
],
[ // done
'name' => "manager",
'title' => 'Characteristic:ФИО',
'width' => 10
],
[ // done
'name' => "phone",
'title' => 'Characteristic:Телефон',
'width' => 10
],
[
'name' => "contract_type",
'title' => 'Тип договора',
'width' => 20
],
[
'name' => "contract_number",
'title' => 'Номер договора',
'width' => 20
],
[
'name' => "contract_date",
'title' => 'Дата договора',
'width' => 20
],
];
$objects = [];
$objectIds = '';
$post = clearInputData($_POST);
if ($_SESSION['checked'] && isset($post['objectIds']) && $post['objectIds'] != 'all') {
$objectIds = implode(", ", array_map('intval', $_SESSION['checked']));
} else {
$objectIds = $post['objectIds'];
if ($objectIds == 'all') {
if(isset($_SESSION['agency_objects_export_all_all'])) {
$objectIds = implode(", ", array_map('intval', $_SESSION['agency_objects_export_all_all']));
$fields = $fieldsAll;
} else {
$objectIds = null;
}
}
}
$arrayHeader = [];
for ($i = 0, $l = sizeof($fields); $i < $l; $i++) {
$arrayHeader[$arrColExcel[$i]] = $fields[$i];
}
if ($_SESSION['id']) {
if ($objectIds) {
$sql = "SELECT
objects.id,
objects.komnat,
objects.type,
objects.land_area,
objects.ploshad,
objects.ploshad_komn,
objects.ploshad_k,
objects.land_usage_type_id,
objects.etazh,
objects.dom,
objects.korpus,
objects.litera,
objects.etazh_iz,
objects.etaz_first_type,
objects.stoim,
objects.studio_flag,
objects.operation_type,
objects.phone,
objects.adres,
rayon.rayon,
ads_objects.ads_url,
DATE_FORMAT(objects.date_add,'%d.%m.%Y %H:%i') as date_add
FROM objects
LEFT JOIN rayon on objects.rayon = rayon.id
LEFT JOIN ads_objects ON ads_objects.obj_id = objects.id
WHERE objects.id IN ({$objectIds})
ORDER BY objects.date_add DESC
";
//начитка фото списком
$rezPhotoArray = [];
$sqlPhotoInfo = "SELECT oop.sort_order, oop.object_id, p.photo
FROM objects_object_photo oop, object_photo p
WHERE p.id = oop.object_photo_id AND oop.object_id IN ({$objectIds})";
$rezPhotoInfo = mysql_query($sqlPhotoInfo);
if (mysql_num_rows($rezPhotoInfo) > 0) {
while ($objPhoto = mysql_fetch_assoc($rezPhotoInfo)) {
if (!isset($rezPhotoArray[$objPhoto["object_id"]])) {
$rezPhotoArray[$objPhoto["object_id"]] = [];
}
$rezPhotoArray[$objPhoto["object_id"]]['photo' . $objPhoto['sort_order']] = $objPhoto["photo"];
}
}
// метро
$objMetroArray = [];
$sqlMetro = "SELECT GROUP_CONCAT(metro.metro SEPARATOR ', ') as metro_list, sp_metro.id_obj as id_obj FROM metro, sp_metro WHERE sp_metro.id_metro = metro.id AND sp_metro.id_obj IN ({$objectIds}) GROUP BY sp_metro.id_obj";
$resultMetro = mysql_query($sqlMetro);
while ($mtr = mysql_fetch_assoc($resultMetro)) {
$objMetroArray[$mtr['id_obj']] = $mtr;
}
//начитываем координаты списком
$objCoordinatesArray = [];
$sqlCoordinates = "SELECT address, object_id, latitude, longitude FROM object_location WHERE object_id IN ({$objectIds})";
$rezCoordinatesAll = mysql_query($sqlCoordinates);
if (mysql_num_rows($rezCoordinatesAll) > 0) {
while ($objCoords = mysql_fetch_assoc($rezCoordinatesAll)) {
$objCoordinatesArray[] = $objCoords;
}
}
}
$res = mysql_query($sql);
$z = 1;
while ($obj = mysql_fetch_assoc($res)) {
// Превью фото (ссылка)
$photo = [];
if (isset($rezPhotoArray[$obj["id"]])) {
foreach ($rezPhotoArray[$obj["id"]] as $key => $phot) {
if(!empty($phot)){
$photo[] = $phot;
//break;
}
}
}
// Тип квартиры помещения
$type = 'Объект';
switch ($obj['type']) {
case 1:
if ($obj['komnat'] == 1 && $obj['studio_flag']) {
$type = "Квартира-студия";
} else {
$type = "$obj[komnat]-комнатная квартира";
}
break;
case 2:
$type = "Комната в $obj[komnat]-комнатной квартире";
break;
case 3:
$type = "$obj[komnat]-комнатный дом";
break;
case 4:
switch ($obj['type_category']){
case 1:
$type = "Офис";
break;
case 2:
$type = "Склад";
break;
case 3:
$type = "Торговая площадь";
break;
case 4:
$type = "Производство";
break;
case 5:
$type = "Помещение свободного назначения";
break;
case 6:
$type = "Здание";
break;
case 7:
$type = "Гараж";
break;
case 8:
$type = "Готовый бизнес";
break;
case 9:
$type = "Коммерческая земля";
break;
default: $type = "Помещение";
}
break;
case 5:
$type = "Часть дома";
break;
case 6:
$type = "Комплекс";
break;
case 7:
$type = "Участок";
break;
default:
$type = "$obj[komnat]-комнатная квартира";
}
// Район/метро
$metroRayon = '';
if ($obj['rayon']) {
$metroRayon .= $obj['rayon'] . ' район';
}
if (isset($objMetroArray[$obj['id']])) {
$metroRayon .= ' / ' . $objMetroArray[$obj['id']]['metro_list'];
}
// Адрес
if (isset($objCoordinatesArray)) {
foreach ($objCoordinatesArray as $objCoords) {
if ($objCoords['object_id'] == $obj['id']) {
$objCoordinates = $objCoords;
$obj['latitude'] = $objCoordinates['latitude'];
$obj['longitude'] = $objCoordinates['longitude'];
break;
}
}
} else {
$sql_coordinates = "SELECT address, latitude, longitude FROM object_location WHERE object_id=".$obj['id'];
$rezCoordinates = mysql_query($sql_coordinates);
if (mysql_num_rows($rezCoordinates) > 0) {
$objCoordinates = mysql_fetch_assoc($rezCoordinates);
$obj['latitude'] = $objCoordinates['latitude'];
$obj['longitude'] = $objCoordinates['longitude'];
}
}
if ($objCoordinates && isset($objCoordinates['address'])) {
$address = $objCoordinates['address'];
} else {
$address = $obj['adres'];
if ($obj['dom']) {
$address = $address . ", " . $obj['dom'];
}
if ($obj['korpus']) {
$address = $address . ", корпус " . $obj['korpus'];
}
if ($obj['litera']) {
$address = $address . ", литера " . $obj['litera'];
}
}
// Этаж/Этажность
$etazh = '';
if ($obj['type'] == 3) {
if ($obj['etazh_iz'] * 1 != 0) {
$etazh = 'из ' . $obj['etazh_iz'] . " этажей";
}
}
if ($obj['etazh'] * 1 != 0) {
$etazh = $obj['etazh'] . ' этаж';
if ((int)$obj['etazh'] == 1 && !empty($obj['etaz_first_type'])) {
$etazh = $etaz_first_types[$obj['etaz_first_type']];
}
if ($obj['etazh_iz'] * 1 != 0) {
$etazh .= "&nbsp;из&nbsp;" . $obj['etazh_iz'];
}
}
// Дата создания
list($dateAdd, $timeAdd) = explode(" ", $obj['date_add']);
list($d, $m, $y) = explode(".", $dateAdd);
$date_add = $d . " " . getRusMonth($m) . " " . $y;
$createDate = $date_add . "&nbsp;" . $timeAdd;
$objects[] = [
$z,
'id' => $obj['id'],
'preview' => $photo,
'type' => $obj['operation_type'] == 1 ? "Продажа" : "Аренда",
'objType' => $type,
'metro' => $metroRayon,
'address' => $address,
'allArea' => $obj['type'] == 7 ? $obj['land_area'] * 1 : $obj['ploshad'] * 1,
'liveArea' => $obj['ploshad_komn'],
'landArea' => $obj['land_area'],
'kitchenArea' => $obj['ploshad_k'] * 1,
'floor' => $etazh,
'price' => number_format($obj['stoim'], 0, ',', ' '),
'phone' => $obj['phone'],
'linkResource' => $obj['ads_url'],
'createDate' => $createDate,
];
$z++;
}
}
if (count($objects) > 0) {
$rowStart = 1;
foreach($arrayHeader as $h => $w) {
$sheet->setCellValue($h.$rowStart, $w['title']);
$sheet->getColumnDimension($h)->setWidth($w['width']);
$sheet->getStyle($h.$rowStart)->getFont()->applyFromArray( [ 'name' => 'Arial', 'bold' => TRUE, 'italic' => FALSE, 'strikethrough' => FALSE, 'color' => [ 'rgb' => '808080' ], ] );
$sheet->getStyle($h)->getAlignment()->setWrapText(true);
$sheet->getStyle($h.$rowStart)->getAlignment()->setWrapText(true);
$sheet->getStyle($h.$rowStart)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER)
->setVertical(Alignment::VERTICAL_CENTER);
}
$i = $rowStart + 1;
$k = 1;
foreach ($objects as $object) {
$j = 0;
foreach ($fields as $q => $colSets) {
switch($colSets['name']) {
case 'preview':
if (isset($colSets['action'])) {
if (is_array($object['preview']) && count($object['preview']) > 0) {
$previewUrls = array_map('html_entity_decode', $object['preview']);
$imageIndex = $i; // отдельный индекс для картинок
foreach ($previewUrls as $index => $url) {
$sheet->setCellValue($arrColExcel[$q].$imageIndex, 'Посмотреть фото ' . ($index + 1));
$sheet->getCell($arrColExcel[$q] . $imageIndex)->getHyperlink()->setUrl($url);
$sheet->getStyle($arrColExcel[$q] . $imageIndex)->getFont()->getColor()->setARGB(Color::COLOR_BLUE);
$sheet->getStyle($arrColExcel[$q].$imageIndex)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
$imageIndex++; // увеличить индекс картинки
}
} else {
$sheet->setCellValue($arrColExcel[$q].$i, 'Нет фото');
$sheet->getStyle($arrColExcel[$q].$i)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
}
} else {
if (is_array($object['preview']) && count($object['preview']) > 0) {
$previewUrls = array_map('html_entity_decode', $object['preview']);
$imageIndex = $i; // отдельный индекс для картинок
foreach ($previewUrls as $index => $url) {
$sheet->setCellValue($arrColExcel[$q].$imageIndex, 'Посмотреть фото ' . ($index + 1));
$sheet->getCell($arrColExcel[$q] . $imageIndex)->getHyperlink()->setUrl($url);
$sheet->getStyle($arrColExcel[$q] . $imageIndex)->getFont()->getColor()->setARGB(Color::COLOR_BLUE);
$sheet->getStyle($arrColExcel[$q].$imageIndex)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
$imageIndex++; // увеличить индекс картинки
}
} else {
$sheet->setCellValue($arrColExcel[$q].$i, 'Нет фото');
$sheet->getStyle($arrColExcel[$q].$i)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
}
}
break;
default:
$sheet->setCellValue($arrColExcel[$q].$i, html_entity_decode($object[$colSets['name']]));
}
}
$i = $i + count($object['preview']);
//$i++;
$k++;
continue;
$sheet->setCellValue($arrColExcel[$j].$i, $k);
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['id']));
$j++;
if ($preview = html_entity_decode($object['preview'])) {
$sheet->setCellValue($arrColExcel[$j].$i, 'Посмотреть фото');
$sheet->getCell($arrColExcel[$j] . $i)->getHyperlink()->setUrl(html_entity_decode($object['preview']));
$sheet->getStyle($arrColExcel[$j] . $i)->getFont()->getColor()->setARGB(Color::COLOR_BLUE);
$sheet->getStyle($arrColExcel[$j].$i)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
} else {
$sheet->setCellValue($arrColExcel[$j].$i, 'Нет фото');
$sheet->getStyle($arrColExcel[$j].$i)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
}
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['type']));
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['objType']));
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['metro']));
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['address']));
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['allArea']));
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['liveArea']));
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['kitchenArea']));
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['floor']));
$sheet->getStyle($arrColExcel[$j].$i)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['price']));
$sheet->getStyle($arrColExcel[$j].$i)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_RIGHT);
$j++;
$phoneOwnCell = html_entity_decode($object['phone']);
if ($hideContactsExcelOwn && !empty($phoneOwnCell)) {
$digitsCheck = preg_replace('/[^0-9]/', '', $phoneOwnCell);
if ($digitsCheck !== '' && isset($clientPhonesSet[$digitsCheck])) {
// Собственник этого объекта — клиент агентства, маскируем.
$phoneOwnCell = mask_client_phone($phoneOwnCell);
}
}
$sheet->setCellValue($arrColExcel[$j] . $i, $phoneOwnCell);
$sheet->getStyle($arrColExcel[$j].$i)->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_RIGHT);
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['linkResource']));
$j++;
$sheet->setCellValue($arrColExcel[$j].$i, html_entity_decode($object['createDate']));
$j++;
}
}
$writer = new Xlsx($spreadsheet);
if (
!file_exists($_SERVER['DOCUMENT_ROOT'] . '/server/excel2/')
&& !mkdir($concurrentDirectory = $_SERVER['DOCUMENT_ROOT'] . '/server/excel2/', 0777)
&& !is_dir($concurrentDirectory)
) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
}
$fileName = "my_objects_" . date('d.m.Y_H-i-s') . ".xlsx";
$filePath = '/server/excel2/' . $fileName;
if ($filePath && $fileName) {
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($_SERVER['DOCUMENT_ROOT'] . $filePath);
echo json_encode([
'file' => $filePath,
'result' => 'ok',
'name' => $fileName,
]);
}