| Server IP : 162.214.74.102 / Your IP : 216.73.216.59 Web Server : Apache System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64 User : lrsys ( 1015) PHP Version : 5.6.40 Disable Function : exec,passthru,shell_exec,system MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /home/lrsys/www/lrsys_apps/imobles/application/plugins/module_imobles/controllers/ |
Upload File : |
<?php
include_once "Controller.php";
include_once "CrawlerController.php";
include_once __DIR__ . "/../helpers/CrawlerHelper.php";
class ApiController extends Controller {
protected $id;
protected $model;
protected $crawlerController;
protected $crawlerHelper;
public function __construct($ui, $_L, $config, $_pd) {
@ini_set('memory_limit', '4095M');
@ini_set('max_execution_time', 0);
@set_time_limit(0);
ignore_user_abort(true); //executa mesmo perdendo a conection
parent::__construct($ui, $_L, $config, $_pd);
$this->crawlerController = new CrawlerController($ui, $_L, $config, $_pd = null);
if (!isset($_SESSION['uid'])) {
$_SESSION['uid'] = 1;
}
$this->crawlerHelper = new CrawlerHelper();
}
public function searchDevelopments() {
ORM::configure('caching', true);
try {
$jsonStr = file_get_contents("php://input");
$filter = json_decode($jsonStr, true);
$jsonStr = ""; //LIMPA
} catch (Exception $e) {
$filter = array();
}
// Verifico se o bairro é válido
if (@$filter['locations'])
{
$address_neightborhood = "";
$address_number = "";
$state = '';
$city = '';
$log = '';
$zip = '';
foreach ($filter['locations'] as $d) {
if (!empty($d['address_neighborhood']))
{
$address_neightborhood = ORM::for_table('module_imobles_enterprise')
->table_alias('s')
->select_expr("s.address_neightborhood")
->where("s.address_neighborhood_sanitized", sanitizaText($d['address_neighborhood']))
->where_raw("s.delete_at IS NULL")->find_one();
if(!isset($address_neightborhood->address_neightborhood))
{
$output = array(
"error" => array("status" => true,
"code" => 404,
"msg" => "Bairro não encontrado | ".$d['address_neighborhood']),
"total_count" => 0,
"page_token" => 0,
"size" => $filter['size'],
"list_size" => 0,
"locations" => @$filter['locations'],
"results" => []);
return $output;
}
}
}
}
return $this->resultDevelopments($filter);
}
public function searchDevelopmentsSimilar() {
ORM::configure('caching', true);
try {
$jsonStr = file_get_contents("php://input");
$filter = json_decode($jsonStr, true);
$jsonStr = ""; //LIMPA
} catch (Exception $e) {
$filter = array();
}
$id = intval(@$filter['development_id']);
$dataResults = array();
if ($id > 0) {
$develop = $this->developmentDetails();
if (count($develop['results']) > 0) {
if ($develop['results']['unit_type']) {
$menorPrice = $develop['results']['unit_type'][0]['min_value'];
$menorArea = $develop['results']['unit_type'][0]['area'];
$arrayBedRooms = array();
foreach ($develop['results']['unit_type'] as $unit) {
if ($unit['area'] < $menorArea) {
$menorArea = $unit['area'];
}
if ($unit['min_value'] < $menorPrice) {
$menorPrice = $unit['min_value'];
}
$arrayBedRooms[$unit['bedrooms']] = $unit['bedrooms'];
}
}
}
if (empty(@$filter['bedrooms'])) {
$filter['bedrooms'] = $arrayBedRooms;
}
if (empty(@$filter['area_min'])) {
$filter['area_min'] = $menorArea;
}
if (empty(@$filter['price_min'])) {
$filter['price_min'] = $menorPrice;
}
if (empty(@$filter['is_new'])) {
$filter['is_new'] = $develop['results']['is_new'];
}
$filter['order_by'][] = array("price" => 'ASC', "release_date" => 'DESC');
if (empty(@$filter['locations'])) {
$filter['locations']['address_neighborhood'] = $develop['results']['address']['neighborhood'];
$filter['locations']['address_city'] = $develop['results']['address']['city'];
}
$filter['development_ids_not_in'][] = $id;
$results = $this->resultDevelopments($filter);
$results2 = array();
// $size = $results['size'];
if ($results['list_size'] < $results['size']) {
//adiciona para não trazer os memos já carregados
foreach ($results['results'] as $r) {
$filter['development_ids_not_in'][] = $r['id'];
}
$filter['size'] = $results['size'] - $results['list_size'];
unset($filter['locations']);
$results2 = $this->resultDevelopments($filter);
}
if (is_array($results['results'])) {
//coloca todos os primeiros que vieram do mesmo bairro do empreendimento informado
foreach ($results['results'] as $re) {
if ($re['address']['neighborhood'] == $develop['results']['address']['neighborhood']) {
$dataResults[] = $re;
}
}
//coloca os demais, que aplicou o filtro e não estão no mesmo bairrro
foreach ($results['results'] as $re) {
if ($re['address']['neighborhood'] != $develop['results']['address']['neighborhood']) {
$dataResults[] = $re;
}
}
}
if (is_array(@$results2['results'])) {
foreach ($results2['results'] as $re) {
$dataResults[] = $re;
}
}
}
$output = array(
"total_count" => count($dataResults),
"results" => array_values($dataResults),
);
return $output;
}
/* * *
* Função simplificada para reuso so search, em consulta de similares
*/
private function resultDevelopments($filter) {
$where = null;
extract($this->searchWhereJoinDevelopments($filter));
$join .= ' LEFT JOIN state st ON(st.id=ent.address_state_id)';
$join .= ' LEFT JOIN city c ON(c.id=ent.address_city_id)';
$join .= ' LEFT JOIN module_imobles_company_construction cp ON(cp.id=ent.module_imobles_company_construction_id)';
$orderTypeUnit = 'u.area asc';
$order = 'ent.id ASC';
if (isset($filter['order_by'])) {
$order = "";
foreach ($filter['order_by'] as $orde) {
foreach ($orde as $key => $val) {
if (strtoupper($val) == 'DESC') {
$val = 'DESC';
} else {
$val = 'ASC';
}
switch ($key) {
case 'price':
$areaResalep = null;
if (isset($filter['is_new']) && $filter['is_new'] === true)
{
$areaResalep = " AND ordp.crawler_type_id = 4 AND ordp.advertiser_id IS NULL ";
}
elseif (isset($filter['is_new']) && $filter['is_new'] === false)
{
$areaResalep = " AND (ordp.crawler_type_id <> 4 OR ordp.crawler_type_id IS NULL) AND ordp.advertiser_id IS NOT NULL ";
}
if($val == "ASC")
{
$max_min = "min";
}
else
{
$max_min = "max";
}
$join .= " JOIN ("
. "select ordp.entreprise_id, ".$max_min."(ordp.crawler_price) as price, avg(ordp.crawler_price) as averagePrice, ent_aux.imobles_client, unit_type_aux.id as unit_type_aux_id "
. "from module_imobles_listings ordp "
. "JOIN module_imobles_enterprise as ent_aux ON ent_aux.id = ordp.entreprise_id "
. "JOIN module_imobles_enterprise_units_type as unit_type_aux ON unit_type_aux.id = ordp.unit_type_id "
. "WHERE (ordp.crawler_businessType <> 'RENTAL' OR ordp.crawler_businessType IS NULL) "
. "AND (ordp.unavailable IS NULL OR ordp.unavailable = 0 ) "
. "AND ordp.delete_at IS NULL "
. "AND ordp.crawler_price > 0 "
. "AND unit_type_aux.delete_at IS NULL "
. "AND unit_type_aux.site_enabled = 1 "
. "AND ent_aux.site_enabled = 1 "
. "AND IF(ent_aux.imobles_client = 1, ordp.crawler_type_id = 4 AND ordp.advertiser_id IS NULL , "
. "(ordp.crawler_type_id IS NULL OR ordp.crawler_type_id <> 4) AND ordp.advertiser_id IS NOT NULL) "
. " AND ordp.crawler_price >= (
select avg(sub_price2.crawler_price)
from module_imobles_listings sub_price2
WHERE sub_price2.unit_type_id=unit_type_aux.id
AND (sub_price2.delete_at IS NULL AND
(sub_price2.crawler_status IS NULL OR sub_price2.crawler_status='ACTIVE')
AND (sub_price2.unavailable IS NULL OR sub_price2.unavailable=0))
AND (sub_price2.crawler_businessType <> 'RENTAL' OR sub_price2.crawler_businessType IS NULL)
AND IF(ent_aux.imobles_client = 1, sub_price2.crawler_type_id = 4 AND sub_price2.advertiser_id IS NULL ,
(sub_price2.crawler_type_id IS NULL OR sub_price2.crawler_type_id <> 4) AND sub_price2.advertiser_id IS NOT NULL )
)*0.6"
. " GROUP BY 1,5 "
. " ORDER BY averagePrice ".$val.") as price_min ON (price_min.entreprise_id=ent.id) ";
$order .= ', price_min.averagePrice ' . $val;
$orderTypeUnit = " avg(l.crawler_price) " . $val;
break;
case 'area':
if($val == "ASC")
{
$max_min = "min";
}
else
{
$max_min = "max";
}
$areaResale = null;
if (isset($filter['is_new']) && $filter['is_new'] === true)
{
$areaResale = " AND ord.crawler_type_id = 4 AND ordp.advertiser_id IS NULL ";
}
elseif (isset($filter['is_new']) && $filter['is_new'] === false)
{
$areaResale = " AND (ord.crawler_type_id <> 4 OR ord.crawler_type_id is null)";
}
$whereunit_order = " AND ("
. "EXISTS ("
. "select sub_w.id "
. "from module_imobles_listings sub_w "
. "where sub_w.unit_type_id=ord.id "
. "AND IF("
. "ent_aux.imobles_client = 1, "
. "sub_w.advertiser_id IS NULL AND sub_w.crawler_type_id = 4 , "
. "sub_w.advertiser_id IS NOT NULL AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL )"
. ") "
. "AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) "
. "AND sub_w.crawler_price>0"
. ")"
. ")";
$join .= ' JOIN ('
. 'select '.$max_min.'(ord.area) as min_area, ord.module_imobles_enterprise_id '
. 'from module_imobles_enterprise_units_type ord '
. 'JOIN module_imobles_enterprise as ent_aux ON ent_aux.id = ord.module_imobles_enterprise_id '
. 'where ord.delete_at is null '
. 'AND ord.site_enabled = 1 '
. " AND ("
. "EXISTS ("
. "select sub_w.id "
. "from module_imobles_listings sub_w "
. "where sub_w.unit_type_id=ord.id "
. "AND IF("
. "ent_aux.imobles_client = 1, "
. "sub_w.advertiser_id IS NULL AND sub_w.crawler_type_id = 4 , "
. "sub_w.advertiser_id IS NOT NULL AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL )"
. ") "
. "AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) "
. "AND sub_w.crawler_price>0 AND sub_w.crawler_price > 0 AND sub_w.unavailable IS NULL AND sub_w.delete_at IS NULL"
. ")"
. ")"
. 'GROUP BY ord.module_imobles_enterprise_id'
. ') as area ON area.module_imobles_enterprise_id=ent.id ';
$order .= ', area.min_area ' . $val;
$orderTypeUnit = " u.area " . $val;
break;
case 'release_date':
$order .= ', ent.release_date ' . $val;
break;
}
}
}
if (!empty($order)) {
$order = substr($order, 1);
} else {
$order = 'ent.release_date DESC';
}
} else {
// TODO: alterar a ordenação padrão para Data de Publicação no Site
$order = 'ent.relevance DESC, ent.release_date DESC';
}
// Verifico se é listagem para o Mapa e retiro a paginação
if (!isset($filter['map_view']) || $filter['map_view'] != true) {
if (!isset($filter['size']) || $filter['size'] < 0) {
$filter['size'] = 10;
} else {
if ($filter['size'] > 1000) {
$filter['size'] = 1000;
}
}
if (!isset($filter['page_token']) || $filter['page_token'] < 1) {
$filter['page_token'] = 1;
}
} else {
$filter['size'] = 10000;
$filter['page_token'] = 1;
}
$limitMaxRegister = $filter['size'] * $filter['page_token'];
$limit = " LIMIT " . $filter['size'] . " offset " . ( $limitMaxRegister - $filter['size']);
// Verifico se tem busca pelo nome do empreendimento
if (isset($filter['development_name']) && !empty($filter['development_name'])) {
$where .= " AND ent.name LIKE '%" . $filter['development_name'] . "%' ";
}
// Verifico se tem busca pelo ID do empreendimento
if (isset($filter['development_ids']) && !empty($filter['development_ids'])) {
$where .= " AND ent.id IN (" . implode(",", $filter['development_ids']) . ") ";
}
// Verifico se tem busca pelo ID do empreendimento retirando empreendimentos
if (isset($filter['development_ids_not_in']) && !empty($filter['development_ids_not_in'])) {
$where .= " AND ent.id NOT IN (" . implode(",", $filter['development_ids_not_in']) . ") ";
}
// Filtro por Novos ou Usados
if (isset($filter['is_new']) && $filter['is_new'] === true) {
$where .= " AND ent.imobles_client = 1 ";
} elseif (isset($filter['is_new']) && $filter['is_new'] === false) {
$where .= " AND (ent.imobles_client IS NULL OR ent.imobles_client <> 1) ";
}
// Verifico se tem busca pelo ID da construtora
if (isset($filter['construction_company_ids']) && !empty($filter['construction_company_ids'])) {
$where .= " AND cp.id IN (" . implode(",", $filter['construction_company_ids']) . ") ";
}
// Verifico se tem busca pelo SLUG da construtora
if (isset($filter['construction_company_slug']) && !empty($filter['construction_company_slug'])) {
$where .= " AND cp.slug = '".$filter['construction_company_slug']."'";
}
$sql = ' FROM module_imobles_enterprise ent '
. " LEFT JOIN (select sub_tow.module_imobles_enterprise_id,sub_tow.stage as stage,min(sub_tow.date_delivery) as date_delivery from module_imobles_enterprise_towers sub_tow GROUP BY 1) as tower"
. " ON (tower.module_imobles_enterprise_id=ent.id )"
. $join . ' WHERE ent.delete_at IS NULL and ent.site_enabled = 1 '
. $where;
$list = "";
if (!empty(@$filterListData['unit_type_id'])) {
$list = " AND sub.module_imobles_enterprise_units_type_id IN (" . @$filterListData['unit_type_id'] . ")";
}
$sql .= " AND EXISTS (select sub.id from module_imobles_enterprise_units sub "
. " JOIN module_imobles_enterprise_units_type sut ON (sut.id=sub.module_imobles_enterprise_units_type_id)"
. " where sut.module_imobles_enterprise_id=ent.id AND sut.site_enabled = 1 AND (sub.unavailable IS NULL OR sub.unavailable=0) AND sub.delete_at IS NULL " . $list . ")";
$dataResults = array();
//TRATAMENTo se somenne total, não busca dados
if (empty(@$filter['count_only']) || @$filter['count_only'] != true || @$filter['count_only'] != 1) {
$query = "SELECT "
. "c.city_name, c.city_ibge,st.uf_state, st.state_name, st.code_state, "
. " tower.stage, DATE(tower.date_delivery) as date_delivery,"
. "ent.id,ent.init_sales,ent.hubspot, ent.name as development, DATE(ent.release_date) as release_date, ent.hotsite_params, "
. "ent.address_log, ent.address_number, ent.address_neightborhood, ent.address_zip, "
. "ent.value_input_porcentage as financing_input, ent.value_installment_porcentage financing_installment, ent.value_founding_porcentage as financing_founding"
. ", ent.google_geometry, ent.latitude, ent.longitude, cp.name as construction_company, cp.id as construction_company_id, ent.imobles_client, ent.site_url, ent.relevance, ent.slug "
. $sql . " GROUP BY id ORDER BY " . $order . " " . $limit;
// echo $query;exit;
$dat = ORM::for_table('module_imobles_enterprise_towers')
->raw_query($query)->find_array();
$list = "";
if (!empty(@$filterListData['unit_type_id'])) {
$list = " AND sub.module_imobles_enterprise_units_type_id IN (" . @$filterListData['unit_type_id'] . ")";
}
if (!empty(@$filterListData['listing_id'])) {
$list = " AND sub_l.id IN (" . @$filterListData['listing_id'] . ")";
}
if (count($dat) > 0) {
$ent = "";
$queryDispobibleUnit = "";
foreach ($dat as $d) {
$dataResults[$d['id']]['id'] = $d['id'];
$dataResults[$d['id']]['name'] = $d['development'];
$dataResults[$d['id']]['hubspot_alias'] = $d['hubspot'];
$dataResults[$d['id']]['development_url'] = $d['site_url'];
$dataResults[$d['id']]['init_sales'] = $d['init_sales'];
$dataResults[$d['id']]['development_id'] = $d['id'];
$dataResults[$d['id']]['relevance'] = $d['relevance'];
$dataResults[$d['id']]['development_slug'] = $d['slug'];
// Incluo os dados do hotsite
if (!empty($d['hotsite_params'])) {
$dataResults[$d['id']]['hotsite'] = json_decode($d['hotsite_params']);
}
// Verifico se é imóvel NOVO ou REVENDA
$dataResults[$d['id']]['is_new'] = false;
if ($d["imobles_client"] == 1) {
$dataResults[$d['id']]['is_new'] = true;
}
//tratamento do stagio conforme regra IMB-18
if (empty($d['stage'])) {
if (strtotime(date("Y-m-d")) >= strtotime($d['release_date'])) {
$dataResults[$d['id']]['construction_status'] = 'Ready to move in';
} else {
$dataResults[$d['id']]['construction_status'] = 'In Works';
}
} else {
$dataResults[$d['id']]['construction_status'] = $d['stage'];
}
if (isset($d['release_date']) && !empty($d['release_date'])) {
$year = date("Y", strtotime($d['release_date']));
if ($year >= 1950) {
$dataResults[$d['id']]['release_date'] = $d['release_date'];
} else {
$dataResults[$d['id']]['release_date'] = "0000-00-00";
}
} else {
$dataResults[$d['id']]['release_date'] = "0000-00-00";
}
$dataResults[$d['id']]['address'] = array(
'country' => 'BR',
'zip_code' => $d['address_zip'],
'city' => $d['city_name'],
'ibge_city_id' => $d['city_ibge'],
'state_acronym' => $d['uf_state'],
'state' => $d['state_name'],
'ibge_state_id' => $d['code_state'],
'street' => $d['address_log'],
'number' => $d['address_number'],
'neighborhood' => $d['address_neightborhood'],
);
$dataResults[$d['id']]['construction_company'] = $d['construction_company'] == null ? "N/A" : $d['construction_company'];
$dataResults[$d['id']]['construction_company_id'] = $d['construction_company_id'] == null ? 0 : $d['construction_company_id'];
$dataResults[$d['id']]['financing']['entry'] = $d['financing_input'];
$dataResults[$d['id']]['financing']['installment'] = $d['financing_installment'];
$dataResults[$d['id']]['financing']['founding'] = $d['financing_founding'];
//IMB-19
if (!empty($d['google_geometry'])) {
$dataResults[$d['id']]['geometry'] = json_decode($d['google_geometry']);
// TODO: RESOLVER O PROBLEMA DE SE PEGAR O LAT/LONG DO GOOGLE
if(isset($dataResults[$d['id']]['geometry']->location))
{
$dataResults[$d['id']]['geometry']->location = array("lat" => floatval($d['latitude']), "lng" => floatval($d['longitude']));
}
} else {
$dataResults[$d['id']]['geometry'] = array("location" => array("lat" => floatval($d['latitude']), "lng" => floatval($d['longitude'])));
}
$ent .= "," . $d['id'];
}
/*
* Pego as imagens de backend
*/
$c = ORM::for_table('module_imobles_enterprise_imgs')
->raw_query("SELECT s.module_imobles_enterprise_id, s.src, s.resized, s.webp, s.tags, s.unit_type_id, s.description, s.id FROM"
. " module_imobles_enterprise_imgs as s"
. " WHERE (s.duplicated IS NULL OR s.duplicated=0) AND type = 'backend' "
. " AND s.module_imobles_enterprise_id IN(" . substr($ent, 1) . ") "
. " AND s.delete_at IS NULL AND s.tags IS NOT NULL "
// . " HAVING count(module_imobles_enterprise_id)<=5"
)->find_array();
/*
* BUSCA as UNIT_TYPES
*/
// Verifico se o empreendimento é novo ou revenda
$filterListMediaPriceLIsting = " AND (sub_price2.delete_at IS NULL AND "
. "(sub_price2.crawler_status IS NULL OR sub_price2.crawler_status='ACTIVE')"
. " AND (sub_price2.unavailable IS NULL OR sub_price2.unavailable=0)) AND (sub_price2.crawler_businessType <> 'RENTAL' OR sub_price2.crawler_businessType IS NULL) AND "
. "IF(ent.imobles_client = 1, sub_price2.crawler_type_id = 4 AND sub_price2.advertiser_id IS NULL , "
. "(sub_price2.crawler_type_id IS NULL OR sub_price2.crawler_type_id <> 4) AND sub_price2.advertiser_id IS NOT NULL ) ";
$query_price = " AND IF(ent.imobles_client = 1, l.crawler_type_id = 4 AND l.advertiser_id IS NULL AND l.crawler_price > 0 , l.crawler_price > 0 AND (l.crawler_type_id IS NULL OR l.crawler_type_id <> 4) AND l.advertiser_id IS NOT NULL AND (l.crawler_businessType <> 'RENTAL' OR l.crawler_businessType IS NULL) )";
$selectTotal = " (select count(sub_l.id) from module_imobles_listings sub_l "
. " where sub_l.unit_type_id=u.id AND (sub_l.unavailable IS NULL OR sub_l.unavailable =0 ) AND sub_l.delete_at IS NULL AND (sub_l.crawler_type_id IS NULL OR sub_l.crawler_type_id <> 4) AND sub_l.advertiser_id IS NOT NULL AND (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL) " . $list . " ) as total_listing, "
. " (select count(sub.id) from module_imobles_enterprise_units sub "
. " where sub.module_imobles_enterprise_units_type_id=u.id AND (sub.unavailable IS NULL OR sub.unavailable=0) AND sub.crawler_type_id=4 AND sub.delete_at IS NULL " . $list . ") as disponible_unit";
$types = ORM::for_table('module_imobles_enterprise_units_type')
->raw_query(" SELECT "
. " min(l.crawler_price) as minValue,"
. " max(l.crawler_price) as 'maxValue',"
. " avg(l.crawler_price) as averageValue ,"
. " u.number_rooms as bedrooms,"
. " u.number_bathroom as bathrooms,"
. " u.area as area,"
. " u.number_suite as suites,"
. " u.number_garage as parking_spaces,"
. " u.id,"
. " u.module_imobles_enterprise_id,"
. " ent.imobles_client,"
. " group_concat(l.id) as list_listings,"
. $selectTotal
. " FROM module_imobles_enterprise_units_type u"
. " JOIN module_imobles_listings l ON (u.id=l.unit_type_id)"
. " JOIN module_imobles_enterprise as ent ON (u.module_imobles_enterprise_id=ent.id)"
// . " LEFT JOIN (select sub_price2.unit_type_id,sub_price2.condo_fee as condo_fee from module_imobles_listings_prices sub_price2 "
// . " WHERE sub_price2.id=(select max(sub_3.id) from module_imobles_listings_prices sub_3 WHERE sub_3.unit_type_id=sub_price2.unit_type_id)) as price_condo"
// . " ON (price_condo.unit_type_id=u.id )"
. " WHERE"
. " l.crawler_price>=(select avg(sub_price2.crawler_price) from module_imobles_listings sub_price2 WHERE sub_price2.unit_type_id=u.id " . $filterListMediaPriceLIsting . ")*0.6"
. " AND (l.unavailable IS NULL OR l.unavailable =0 ) AND l.delete_at IS NULL "
. " AND u.module_imobles_enterprise_id IN (" . substr($ent, 1) . ") " . $query_price . $whereunit
. " GROUP BY u.module_imobles_enterprise_id,u.id, u.number_rooms, u.number_suite, u.area, u.number_garage, u.number_bathroom ORDER BY " . @$orderTypeUnit)
->find_array();
// Faço a contagem das unidades disponíveis para o empreendimento
$arr_count_available = array();
foreach ($types as $u) {
// Pego as imagens da Tipo de Unidade
$arr_unit_type_imgs = array();
if (count($c) > 0 && isset($filter['full_info']) && $filter['full_info'] === true) {
foreach ($c as $im) {
$arr_tags = array();
if ($im['unit_type_id'] != $u['id']) {
continue;
}
if (empty($arr_unit_type_imgs) || count($arr_unit_type_imgs) < 10) {
if (!empty($im['tags']) && $im['tags'] != "null") {
$arr_tags_id = json_decode($im['tags']);
$arr_tags_aux = ORM::for_table('module_imobles_enterprise_img_backend_tags')->select('name')->where_in('id', $arr_tags_id)->find_array();
foreach ($arr_tags_aux as $tags) {
$arr_tags[] = $tags['name'];
}
// Monto o array com os tamanhos alternativos das imagens
$alternatives_sizes = null;
if ($im['resized'] == 1) {
$alternatives_sizes = array("1152x768" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xxl/" . $im['src'],
"840x560" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xlg/" . $im['src'],
"600x400" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/lrg/" . $im['src'],
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/med/" . $im['src'],
"300x200" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/sml/" . $im['src'],
"120x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xsm/" . $im['src'],
"104x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/thumb/" . $im['src']);
}
$webp = false;
if ($im['webp'] == 1) {
$webp = true;
}
$arr_unit_type_imgs[] = array(
"type" => 'IMAGE',
"url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
"description" => $im['description'],
"tags" => $arr_tags,
"alternatives_sizes" => $alternatives_sizes,
"webp" => $webp);
}
} else {
break;
}
}
}
if ($u['averageValue'] < $u['minValue']) {
$u['averageValue'] = $u['minValue'];
}
// Pego os detalhes dos anúncios
$arr_listings = array();
if ($u["imobles_client"] != 1 && isset($filter['full_info']) && $filter['full_info'] === true) {
$selectlistings = "select sub_l.id, sub_l.crawler_price, sub_l.crawler_listing_link, sub_l.crawler_portal, sub_l.crawler_updatedAt, ads.logoUrl, ads.name as advertiser_name "
. "from module_imobles_listings sub_l "
. " JOIN module_imobles_advertisers as ads ON ads.id = sub_l.advertiser_id "
. " where sub_l.unit_type_id= " . $u['id'] . " AND (sub_l.unavailable IS NULL OR sub_l.unavailable = 0 ) AND sub_l.delete_at IS NULL AND "
. "(sub_l.crawler_type_id IS NULL OR sub_l.crawler_type_id <> 4) AND sub_l.advertiser_id IS NOT NULL AND "
. "(sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL)";
$arr_listings_aux = ORM::for_table('module_imobles_enterprise_units_type')
->raw_query($selectlistings)
->find_array();
if (count($arr_listings_aux) > 0) {
$count_aux = 0;
foreach ($arr_listings_aux as $listing_aux) {
if (!empty($listing_aux['logoUrl'])) {
$listing_aux['logoUrl'] = str_replace('{width}', '870', $listing_aux['logoUrl']);
$listing_aux['logoUrl'] = str_replace('{height}', '653', $listing_aux['logoUrl']);
$listing_aux['logoUrl'] = str_replace('{action}', 'fit-in', $listing_aux['logoUrl']);
}
if ($listing_aux['crawler_portal'] == "VIVAREAL") {
$listing_aux['crawler_listing_link'] = "https://vivareal.com.br" . $listing_aux['crawler_listing_link'];
}
if ($listing_aux['crawler_portal'] == "GRUPOZAP") {
$listing_aux['crawler_listing_link'] = "https://zapimoveis.com.br" . $listing_aux['crawler_listing_link'];
}
$arr_listings[] = array("id" => $listing_aux['id'],
"price" => $listing_aux['crawler_price'],
"portal" => $listing_aux['crawler_portal'],
"last_update" => $listing_aux['crawler_updatedAt'],
"logo" => $listing_aux['logoUrl'],
"link" => $listing_aux['crawler_listing_link'],
"advertiser_name" => $listing_aux["advertiser_name"]);
}
}
}
$dataArray = array(
"id" => $u['id'],
"total_listing" => number_format($u['total_listing'], 0, "", ""),
"unit_available" => number_format($u['disponible_unit'], 0, "", ""),
"min_value" => number_format($u['minValue'], 2, ".", ""),
"average_value" => number_format($u['averageValue'], 2, ".", ""),
"max_value" => number_format($u['maxValue'], 2, ".", ""),
"bedrooms" => $u['bedrooms'],
"bathrooms" => $u['bathrooms'],
"area" => $u['area'],
"suites" => $u['suites'],
"parking_spaces" => $u['parking_spaces'],
"medias" => $arr_unit_type_imgs,
"listings_details" => $arr_listings
);
$dataResults[$u['module_imobles_enterprise_id']]['unit_type'] [] = $dataArray;
if (!isset($dataResults[$u['module_imobles_enterprise_id']]['total_units_available'])) {
$dataResults[$u['module_imobles_enterprise_id']]['total_units_available'] = 0;
}
$dataResults[$u['module_imobles_enterprise_id']]['total_units_available'] += $u['disponible_unit'];
}
// $c = ORM::for_table('module_imobles_enterprise_imgs')
// ->raw_query("SELECT s.module_imobles_enterprise_id,s.src, s.tags FROM"
// . " module_imobles_enterprise_imgs s"
// . " WHERE (s.duplicated IS NULL OR s.duplicated=0) "
// . " AND s.module_imobles_enterprise_id IN(" . substr($ent, 1) . ") "
// . " AND s.type = 'backend' AND s.delete_at IS NULL "
// . " LIMIT 5"
// // . " HAVING count(module_imobles_enterprise_id)<=5"
// )->find_array();
if (count($c) > 0) {
$arr_enterprise_imgs = array();
$arr_enterprise_gallery_imgs = array();
foreach ($c as $im) {
if (!empty($im['unit_type_id']) || empty($im['tags'])) {
continue;
}
$arr_tags = array();
if (!isset($dataResults[$im['module_imobles_enterprise_id']]['medias']) || count(@$dataResults[$im['module_imobles_enterprise_id']]['medias']) < 5)
{
$arr_tags_id = json_decode($im['tags']);
if (!empty($arr_tags_id)) {
if(!in_array(10, $arr_tags_id) && !in_array(8, $arr_tags_id) && !in_array(5, $arr_tags_id) && (!isset($filter['full_info']) || $filter['full_info'] !== true))
{
continue;
}
// Conto as imagens de galeria
if(in_array(10, $arr_tags_id))
{
if(isset($arr_enterprise_imgs[$im['module_imobles_enterprise_id']]) && count($arr_enterprise_imgs[$im['module_imobles_enterprise_id']]) >= 6)
{
continue;
}
$arr_enterprise_gallery_imgs[$im['module_imobles_enterprise_id']][]= $im['id'];
}
$arr_tags_aux = ORM::for_table('module_imobles_enterprise_img_backend_tags')->select('name')->where_in('id', $arr_tags_id)->find_array();
foreach ($arr_tags_aux as $tags) {
$arr_tags[] = $tags['name'];
}
} else {
continue;
// $arr_tags = array();
}
// Monto o array com os tamanhos alternativos das imagens
$alternatives_sizes = null;
if ($im['resized'] == 1) {
$alternatives_sizes = array("1152x768" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xxl/" . $im['src'],
"840x560" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xlg/" . $im['src'],
"600x400" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/lrg/" . $im['src'],
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/med/" . $im['src'],
"300x200" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/sml/" . $im['src'],
"120x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xsm/" . $im['src'],
"104x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/thumb/" . $im['src']);
}
$webp = false;
if ($im['webp'] == 1) {
$webp = true;
}
$arr_enterprise_imgs[$im['module_imobles_enterprise_id']][] = array(
"type" => 'IMAGE',
"url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
"description" => $im['description'],
"tags" => $arr_tags,
"alternatives_sizes" => $alternatives_sizes,
"webp" => $webp);
}
}
foreach ($arr_enterprise_imgs as $k => $v) {
$dataResults[$k]['medias'] = $v;
}
}
}
}
// Pego o total de empreendimentos
$enterprise_ids_aux = ORM::for_table('module_imobles_enterprise_towers')
->raw_query("select DISTINCT(ent.id) as enterprise_id " . $sql)->find_many();
$arr_enterprise_ids = array();
foreach ($enterprise_ids_aux as $id_aux)
{
$arr_enterprise_ids[] = $id_aux->enterprise_id;
}
$arr_enterprise_ids = implode(',', $arr_enterprise_ids);
$total_count = count($enterprise_ids_aux);
if($arr_enterprise_ids)
{
// Pego o total de Anúncios
$query = "select COUNT(sub_w.id) as total_listings
from module_imobles_listings sub_w
JOIN module_imobles_enterprise_units_type sut ON (sut.id=sub_w.unit_type_id)
where sub_w.entreprise_id IN (".$arr_enterprise_ids.")
AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)
AND sub_w.crawler_price > 0
AND (sub_w.crawler_status IS NULL OR sub_w.crawler_status='ACTIVE')
AND (sub_w.unavailable IS NULL OR sub_w.unavailable=0)
AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL)
AND sut.site_enabled = 1
AND sut.delete_at IS null";
$listings_aux = ORM::for_table('module_imobles_enterprise_towers')
->raw_query($query)->find_one();
$total_listings_aux = $listings_aux->total_listings;
// Pego o total de Unidades
$query = "select COUNT(sub.id) as total_units
from module_imobles_enterprise_units sub
JOIN module_imobles_enterprise_units_type sut ON (sut.id=sub.module_imobles_enterprise_units_type_id)
JOIN module_imobles_enterprise as ent ON (ent.id=sut.module_imobles_enterprise_id)
where ent.id IN (".$arr_enterprise_ids.")
AND sut.site_enabled = 1
AND sut.delete_at IS null
AND (sub.unavailable IS NULL OR sub.unavailable=0)
AND sub.delete_at IS NULL
AND ent.imobles_client = 1";
$units_aux = ORM::for_table('module_imobles_enterprise_towers')
->raw_query($query)->find_one();
$total_units_aux = $units_aux->total_units;
}
else
{
$total_listings_aux = 0;
$total_units_aux = 0;
}
$totalresults = count($dataResults);
$output = array(
"total_count" => $total_count,
"total_listings" => $total_listings_aux,
"total_units" => $total_units_aux,
"page_token" => $totalresults == 0 ? 0 : ( ($total_count >= $limitMaxRegister ? $filter['page_token'] + 1 : "")),
"size" => $filter['size'],
"list_size" => $totalresults,
"locations" => @$filter['locations'],
"results" => array_values($dataResults),
);
return $output;
}
private function searchWhereJoinDevelopments($filter) {
$where = '';
$join = '';
$whereunit = "";
$filterListData = array();
if (empty(@$filter['unit_type_ids'])) {
// Filtro por Amenities
if (isset($filter['amenities']) && $filter['amenities'] != '') {
$a = implode("','", $filter['amenities']);
if (!empty($a)) {
$where .= " AND EXISTS (select sub.module_imobles_enterprise_id from module_imobles_enterprise_entreprise_amenities sub where sub.module_imobles_enterprise_id=ent.id AND sub.module_imobles_enterprise_amenities_id IN ('" . $a . "'))";
}
}
// Filtro pela Estágio da obra
if (!empty($filter['construction_status'])) {
$subWhere = "";
$stages = "";
foreach ($filter['construction_status'] as $s) {
if ($s == 'Ready to move in') {
$subWhere .= "OR ( tower.stage IS NULL AND (tower.date_delivery<='" . date('Y-m-d') . "')) "
. " OR (tower.stage IS NULL AND tower.date_delivery IS NULL AND ent.release_date<='" . date('Y-m-d') . "') ";
}
if ($s == 'In Works') {
$subWhere .= "OR ( tower.stage IS NULL AND (tower.date_delivery>'" . date('Y-m-d') . "')) "
. " OR (tower.stage IS NULL AND tower.date_delivery IS NULL AND ent.release_date>'" . date('Y-m-d') . "') ";
}
if ($s != "") {
$stages .= ",'" . htmlentities($s) . "'";
}
}
$where .= " AND( tower.stage IN (" . substr($stages, 1) . ") ";
if (!empty($filter['construction_status'])) {
$where .= " OR (" . substr($subWhere, 2) . ")";
}
$where .= ")";
}
// Filtro pela data de entrega
// TODO: alterar o filtro para pegar apenas o release_date do enterprise e desconsiderar a torre
if (!empty($filter['release_date_start'])) {
$where .= "AND ( (tower.date_delivery>='" . $filter['release_date_start'] . "')"
. " OR (tower.stage IS NULL AND tower.date_delivery IS NULL AND ent.release_date>='" . $filter['release_date_start'] . "')) ";
}
if (!empty($filter['release_date_end'])) {
$where .= "AND ( (tower.date_delivery<='" . $filter['release_date_end'] . "') "
. " OR (tower.stage IS NULL AND tower.date_delivery IS NULL AND ent.release_date<='" . $filter['release_date_end'] . "')) ";
}
// Filtro pela Localização
if (@$filter['locations']) {
$address_neightborhood = "";
$address_number = "";
$state = '';
$city = '';
$log = '';
$zip = '';
foreach ($filter['locations'] as $d) {
if (!empty($d['address_neighborhood'])) {
$address_neightborhood .= "OR ent.address_neighborhood_sanitized LIKE '%" . htmlentities(sanitizaText($d['address_neighborhood'])) . "%' ";
}
if (!empty($d['address_number'])) {
$address_number .= "OR ent.address_number = '" . ($d['address_number']) . "' "
. "";
}
if (!empty($d['address_state'])) {
$state .= "OR st.uf_state LIKE '%" . ($d['address_state']) . "%' "
. "";
}
if (!empty($d['address_city'])) {
$city .= "OR c.city_name LIKE '%" . ($d['address_city']) . "%' ";
}
if (!empty($d['address_log'])) {
$log .= "OR (ent.address_log LIKE '%" . htmlentities($d['address_log']) . "%' "
. "OR ent.address_log_sanitized LIKE '%" . htmlentities(sanitizaText($d['address_log'])) . "%' "
. ")";
}
if (!empty($filter['address_zip'])) {
$zip .= "OR ent.address_zip LIKE '%" . $filter['address_zip'] . "%' "
. "";
}
}
if (!empty($address_neightborhood)) {
$where .= " AND (" . substr($address_neightborhood, 2) . ")";
}
if (!empty($address_number)) {
$where .= " AND (" . substr($address_number, 2) . ")";
}
if (!empty($state)) {
$where .= " AND (" . substr($state, 2) . ")";
}
if (!empty($city)) {
$where .= " AND (" . substr($city, 2) . ")";
}
if (!empty($log)) {
$where .= " AND (" . substr($log, 2) . ")";
}
if (!empty($zip)) {
$where .= " AND (" . substr($zip, 2) . ")";
}
}
/*
* Filtro pelo Lat/Long para visualização do MAPA
*/
if (@$filter['viewport'])
{
if(!empty($filter['viewport']['northeast']['lat'])
&& !empty($filter['viewport']['northeast']['lng'])
&& !empty($filter['viewport']['southwest']['lat'])
&& !empty($filter['viewport']['southwest']['lng']))
{
$where .= " AND (ent.latitude >= " .$filter['viewport']['southwest']['lat']
. " AND ent.latitude <= " .$filter['viewport']['northeast']['lat']
. " AND ent.longitude >= " .$filter['viewport']['southwest']['lng']
. " AND ent.longitude <= " .$filter['viewport']['northeast']['lng']
. ") ";
}
}
// Unidades
$subunit = '';
$subunit2 = "";
$filterListMediaPriceLIsting = " AND (sub_price2.delete_at IS NULL AND "
. "(sub_price2.crawler_status IS NULL OR sub_price2.crawler_status='ACTIVE')"
. " AND (sub_price2.unavailable IS NULL OR sub_price2.unavailable=0)"
. ")";
$filterListMediaPriceLIsting .= " AND (sub_price2.crawler_businessType <> 'RENTAL' OR sub_price2.crawler_businessType IS NULL)";
// Filtro por Novos ou Revenda
if (isset($filter['is_new']) && $filter['is_new'] === true) {
$filterListMediaPriceLIsting .= " AND sub_price2.crawler_type_id = 4 AND sub_price2.advertiser_id IS NULL ";
// $subunit2 .= " AND (sub_l.crawler_type_id = 4) ";
$where .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.entreprise_id=ent.id AND sub_w.advertiser_id IS NULL "
. " AND sub_w.crawler_type_id=4 AND sub_w.crawler_price>0 AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)))";
$whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.unit_type_id=u.id AND sub_w.advertiser_id IS NULL "
. " AND sub_w.crawler_type_id=4 AND sub_w.crawler_price>0 AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)))";
} elseif (isset($filter['is_new']) && $filter['is_new'] === false) {
$filterListMediaPriceLIsting .= "AND (sub_price2.crawler_type_id IS NULL OR sub_price2.crawler_type_id <> 4) AND sub_price2.advertiser_id IS NOT NULL ";
// $subunit2 = " AND (sub_l.crawler_type_id<>4 OR sub_l.crawler_type_id IS NULL ) AND (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL) "
// . " AND (sub_l.crawler_status IS NULL OR sub_l.crawler_status='ACTIVE') AND (sub_l.unavailable IS NULL OR sub_l.unavailable=0)";
$where .= ' AND (ent.verified = 1 '
. 'OR ent.crawler_enterprise_id IS NOT NULL OR ent.google_place_id IS NOT NULL) ';
$where .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.entreprise_id=ent.id AND sub_w.advertiser_id IS NOT NULL "
. " AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL ) AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND sub_w.crawler_price>0))";
$whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.unit_type_id=u.id AND sub_w.advertiser_id IS NOT NULL "
. " AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL ) AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND sub_w.crawler_price>0))";
} else {
$filterListMediaPriceLIsting .= " AND IF(ent.imobles_client = 1, sub_price2.crawler_type_id = 4 AND sub_price2.advertiser_id IS NULL ,(sub_price2.crawler_type_id IS NULL OR sub_price2.crawler_type_id <> 4) AND sub_price2.advertiser_id IS NOT NULL) ";
// $subunit2 = " AND (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL)";
$where .= ' AND (ent.verified = 1 OR ent.crawler_enterprise_id IS NOT NULL OR ent.google_place_id IS NOT NULL) ';
$where .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.entreprise_id=ent.id "
. " AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND sub_w.crawler_price > 0))";
$whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.unit_type_id=u.id AND IF(ent.imobles_client = 1, sub_w.advertiser_id IS NULL AND sub_w.crawler_type_id = 4 , sub_w.advertiser_id IS NOT NULL AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL )) AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND sub_w.crawler_price>0))";
}
// Pego os anuncios vinculados ao tipo de unidade
$subunit2 .= " AND IF(ent.imobles_client = 1, (sub_l.crawler_type_id = 4), (sub_l.crawler_type_id<>4 OR sub_l.crawler_type_id IS NULL ) AND (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL) "
. " AND (sub_l.crawler_status IS NULL OR sub_l.crawler_status='ACTIVE') AND (sub_l.unavailable IS NULL OR sub_l.unavailable=0) )";
if (!empty($filter['area_min'])) {
$subunit .= "AND sub_u.area>=" . htmlentities($filter['area_min']) . " ";
$whereunit .= " AND u.area>=" . htmlentities($filter['area_min']) . " ";
}
if (!empty($filter['area_max'])) {
$subunit .= "AND sub_u.area<=" . htmlentities($filter['area_max']) . " ";
$whereunit .= " AND u.area<=" . htmlentities($filter['area_max']) . " ";
}
if (!empty($filter['bedrooms'])) {
$bed = implode("','", $filter['bedrooms']);
if (!empty($bed)) {
$subunit .= "AND sub_u.number_rooms IN ('" . $bed . "') ";
$whereunit .= " AND u.number_rooms IN ('" . $bed . "') ";
}
}
if (!empty($filter['suites'])) {
$s = implode("','", $filter['suites']);
if (!empty($s)) {
$subunit .= "AND sub_u.number_suite IN ('" . $s . "') ";
$whereunit .= " AND u.number_suite IN ('" . $s . "') ";
}
}
if (!empty($filter['bathrooms'])) {
$s = implode("','", $filter['bathrooms']);
if (!empty($s)) {
$subunit .= " AND sub_u.number_bathroom IN ('" . $s . "') ";
$whereunit .= " AND u.number_bathroom IN ('" . $s . "') ";
}
}
if (!empty($filter['parking_spaces'])) {
$s = implode("','", $filter['parking_spaces']);
if (!empty($s)) {
$subunit .= " AND sub_u.number_garage IN ('" . $s . "') ";
$whereunit .= " AND u.number_garage IN ('" . $s . "') ";
}
}
if (!empty($filter['price_min'])) {
$subunit .= " AND sub_l.crawler_price>=" . htmlentities(($filter['price_min'])) . " ";
$whereunit .= " AND l.crawler_price>0 AND l.crawler_price>=" . htmlentities(($filter['price_min'])) . " ";
}
if (!empty($filter['price_max'])) {
$subunit .= " AND sub_l.crawler_price<=" . htmlentities(($filter['price_max'])) . " ";
$whereunit .= " AND l.crawler_price>0 AND l.crawler_price<=" . htmlentities(($filter['price_max'])) . " ";
}
if (!empty($filter['price_max']) || !empty($filter['price_min'])) {
$subunit .= " and sub_l.crawler_price>=(select avg(sub_price2.crawler_price) from module_imobles_listings sub_price2 WHERE sub_price2.unit_type_id=sub_u.id " . $filterListMediaPriceLIsting . ")*0.6";
$whereunit .= " and l.crawler_price>=(select avg(sub_price2.crawler_price) from module_imobles_listings sub_price2 WHERE sub_price2.unit_type_id=u.id " . $filterListMediaPriceLIsting . ")*0.6";
}
$joinSubunit = "";
if (!empty($filter['condo_fee_min']) || !empty($filter['condo_fee_max'])) {
$subInactivePrice = " AND (l.delete_at IS NULL AND "
. "(l.crawler_status IS NULL OR l.crawler_status='ACTIVE')"
. " AND (l.unavailable IS NULL OR l.unavailable=0)"
. ")";
$wherecondo = "select sub_price2.unit_type_id "
. "as unit_type_id, group_concat(sub_price2.listing_id) as listing_id "
. "from module_imobles_listings_prices sub_price2 "
. " join module_imobles_listings as l ON (l.id=sub_price2.listing_id)"
. " WHERE (sub_price2.rental is null or sub_price2.rental<>1)"
. " AND sub_price2.id=(select max(sub_3.id)"
. " from module_imobles_listings_prices sub_3 "
. "where sub_3.listing_id=sub_price2.listing_id "
. " and (sub_3.rental is null or sub_3.rental<>1))"
. " AND sub_price2.condo_fee>0 " . $subInactivePrice
. " GROUP BY (sub_price2.unit_type_id) "
. "HAVING 1=1 "
;
if (!empty($filter['condo_fee_min'])) {
$wherecondo .= " AND AVG(sub_price2.condo_fee)>=" . htmlentities(Finance::amount_fix($filter['condo_fee_min'])) . ""
. "";
}
if (!empty($filter['condo_fee_max'])) {
$wherecondo .= " AND AVG(sub_price2.condo_fee)<=" . htmlentities(Finance::amount_fix($filter['condo_fee_max'])) . ""
. "";
}
//trata aquio os tipos e listings selecionados com base no valor do condominio
$totUnit = ORM::for_table('module_imobles_enterprise_units')
->raw_query($wherecondo)
->find_many();
if (count($totUnit) > 0) {
$unit_type_id = '';
$listing_id = '';
foreach ($totUnit as $t) {
$unit_type_id .= ',' . $t->unit_type_id;
$listing_id .= ',' . $t->listing_id;
}
if (!empty($listing_id)) {
$unit_type_id = substr($unit_type_id, 1);
$listing_id = substr($listing_id, 1);
}
$subunit .= " AND sub_u.id IN (" . $unit_type_id . ")";
$whereunit .= " AND u.id IN (" . $unit_type_id . ")";
$filterListData['listing_id'] = $listing_id;
$filterListData['unit_type_id'] = $unit_type_id;
} else {
$subunit .= " AND '1'<>'1'";
}
if (count($totUnit) > 0) {
} else {
$subunit .= " AND '1'<>'1'";
}
}
$where .= " AND EXISTS (Select sub_u.id from module_imobles_enterprise_units_type"
. " sub_u LEFT JOIN module_imobles_listings "
. "sub_l ON (sub_u.id=sub_l.unit_type_id) " . $joinSubunit . " "
. "WHERE sub_l.crawler_price>0 "
. "AND sub_u.module_imobles_enterprise_id=ent.id "
. "AND sub_u.delete_at IS NULL AND sub_u.site_enabled = 1 " . @$subunit2 . " " . @$subunit . "" . " limit 1"
. ")";
} else {
if (!isset($filter['resale']) || ($filter['resale'] != 1 && $filter['resale'] != true)) {
$where .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w "
. " where sub_w.entreprise_id=ent.id "
. " AND IF(ent.imobles_client = 1, sub_w.advertiser_id IS NULL AND sub_w.crawler_type_id = 4 , "
. " sub_w.advertiser_id IS NOT NULL AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL )) "
. " AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)))";
$whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.unit_type_id=u.id "
. " AND IF(ent.imobles_client = 1, sub_w.advertiser_id IS NULL AND sub_w.crawler_type_id = 4 , "
. " sub_w.advertiser_id IS NOT NULL AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL )) "
. " AND sub_w.crawler_price>0 "
. " AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL)))";
} else {
$where .= ' AND (ent.verified = 1 '
. 'OR ent.crawler_enterprise_id IS NOT NULL OR ent.google_place_id IS NOT NULL) ';
$where .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.entreprise_id=ent.id AND sub_w.advertiser_id IS NOT NULL "
. " AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL ) AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND crawler_price>0))";
$whereunit .= " AND (EXISTS (select sub_w.id from module_imobles_listings sub_w where sub_w.unit_type_id=u.id AND sub_w.advertiser_id IS NOT NULL "
. " AND (sub_w.crawler_type_id<>4 OR sub_w.crawler_type_id IS NULL ) AND (sub_w.crawler_businessType <> 'RENTAL' OR sub_w.crawler_businessType IS NULL) AND crawler_price>0))";
}
$where .= " AND EXISTS (Select sub_u.id from module_imobles_enterprise_units_type sub_u"
. " WHERE sub_u.module_imobles_enterprise_id=ent.id "
. " AND sub_u.delete_at IS NULL and sub_u.id IN ('" . implode("','", $filter['unit_type_ids']) . "')"
. ")";
$whereunit .= " AND u.id IN ('" . implode("','", $filter['unit_type_ids']) . "')";
// $filterListData = implode(",", $filter['unit_type_ids']);
}
$whereunit .= " AND u.delete_at IS NULL AND u.site_enabled = 1 ";
return array('whereunit' => $whereunit, 'where' => $where, 'join' => $join, 'filterListData' => $filterListData);
}
/*
* developmentDetails
* Detalhes de um empreendimento
*/
public function developmentDetails() {
try {
$jsonStr = file_get_contents("php://input");
$filter = json_decode($jsonStr, true);
$jsonStr = ""; //LIMPA
} catch (Exception $e) {
$filter = array();
}
$dataResults = array();
$id = null;
if(isset($filter['development_id']) && !empty($filter['development_id']))
{
$id = intval($filter['development_id']);
}
$slug = null;
if(isset($filter['development_slug']) && !empty($filter['development_slug']))
{
$slug = $filter['development_slug'];
}
if ($id > 0 || !empty($slug))
{
// Verificar se é revenda ou cliente da imobles
// $resale_aux = ORM::for_table("module_imobles_enterprise")->select("imobles_client")->where("id", $id)->find_one();
// if (isset($resale_aux->imobles_client) && $resale_aux->imobles_client == 1) {
// $resale = false;
// } else {
// $resale = true;
// }
$select = "SELECT s.name as property_standard, "
. "c.city_name, c.city_ibge,st.uf_state, st.state_name, st.code_state, "
. " tower.stage, DATE(tower.date_delivery) as date_delivery,"
. " co.name as construction_company, co.id as construction_company_id, co.hotsite_params as construction_company_params, ent.id, ent.name as development, ent.desc, DATE(ent.release_date) as release_date, ent.address_log, ent.address_number, ent.address_neightborhood, ent.address_zip"
. ", ent.google_geometry, ent.latitude, ent.longitude, ent.slug as development_slug"
. ", ent.google_place_id, ent.google_rating, ent.link_google"
. ", ent.link_presentation, ent.value_input_porcentage as financing_input"
. ", ent.value_installment_porcentage financing_installment, ent.value_founding_porcentage as financing_founding, ent.hubspot, ent.init_sales, ent.hotsite_params, ent.imobles_client, ent.site_url, co.slug as construction_company_slug ";
$from = ' FROM module_imobles_enterprise ent '
. " LEFT JOIN (select sub_tow.module_imobles_enterprise_id,sub_tow.stage as stage,min(sub_tow.date_delivery) as date_delivery from module_imobles_enterprise_towers sub_tow GROUP BY 1) as tower"
. " ON (tower.module_imobles_enterprise_id=ent.id )"
. ' LEFT JOIN state st ON(st.id=ent.address_state_id)'
. ' LEFT JOIN city c ON(c.id=ent.address_city_id)'
. ' LEFT JOIN module_imobles_company_construction co ON(co.id=ent.module_imobles_company_construction_id)'
. ' LEFT JOIN module_imobles_enterprise_standard s ON(s.id=ent.module_imobles_enterprise_standard_id)'
;
if($id > 0)
{
$where = ' WHERE ent.delete_at IS NULL AND site_enabled = 1 AND ent.id= ' . $id;
}
else
{
$where = ' WHERE ent.delete_at IS NULL AND site_enabled = 1 AND ent.slug= "' .$slug.'"';
}
$dat = ORM::for_table('module_imobles_enterprise')
->raw_query($select . $from . $where)->find_array();
if (count($dat) > 0) {
$d = $dat[0];
if (isset($d['imobles_client']) && $d['imobles_client'] == 1) {
$resale = false;
} else {
$resale = true;
}
$dataResults['name'] = $d['development'];
$dataResults['description'] = $d['desc'];
$dataResults['resale'] = $resale;
$dataResults['construction_company'] = $d['construction_company'];
$dataResults['construction_company_id'] = $d['construction_company_id'];
$dataResults['construction_company_slug'] = $d['construction_company_slug'];
// Verifico se temos os parâmetros adicionais da construtora
$dataResults['construction_company_params'] = null;
if (!empty($d['construction_company_id'])) {
// Pego as imagens de backend da Construtora
$tags = ORM::for_table('module_imobles_enterprise_img_backend_tags')
->table_alias('s');
$tags = $tags->find_many();
$arrayTag = array();
foreach ($tags as $t) {
$arrayTag[$t->id] = $t->name;
}
// Pego as imagens de backend da construtora
$imagB = ORM::for_table('module_imobles_enterprise_imgs')
->raw_query("SELECT s.module_imobles_enterprise_id, s.src, s.resized, s.webp, s.tags, s.unit_type_id, s.description, s.construction_company_id FROM"
. " module_imobles_enterprise_imgs as s"
. " WHERE (s.duplicated IS NULL OR s.duplicated=0) AND type = 'backend' "
. " AND s.construction_company_id IN(" . $d['construction_company_id'] . ") "
. " AND s.delete_at IS NULL AND s.tags IS NOT NULL ")->find_array();
if (count($imagB) > 0) {
foreach ($imagB as $im) {
$desc_tags = array();
try {
$tagsIm = json_decode($im['tags']);
if ($tagsIm) {
foreach ($tagsIm as $t) {
$desc_tags[] = $arrayTag[$t];
}
}
} catch (Exception $e) {
$desc_tags = "";
}
// Monto o array com os tamanhos alternativos das imagens
$alternatives_sizes = null;
if ($im['resized'] == 1) {
$alternatives_sizes = array("1152x768" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/xxl/" . $im['src'],
"840x560" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/xlg/" . $im['src'],
"600x400" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/lrg/" . $im['src'],
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/med/" . $im['src'],
"300x200" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/sml/" . $im['src'],
"120x80" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/xsm/" . $im['src']);
if(in_array("DEVELOPMENT_GALLERY_IMGS", $desc_tags))
{
$alternatives_sizes["104x80"] = APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/thumb/" . $im['src'];
}
}
$webp = false;
if ($im['webp'] == 1) {
$webp = true;
}
$dataResults['construction_company_params']['medias'][] = array(
"type" => 'IMAGE',
"url" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/" . $im['src'],
"description" => $im['description'],
"tags" => $desc_tags,
"alternatives_sizes" => $alternatives_sizes,
"webp" => $webp);
}
}
if (!empty($d['construction_company_params'])) {
$dataResults['construction_company_params']['hotsite'] = json_decode($d['construction_company_params']);
}
}
$dataResults['hubspot_alias'] = $d['hubspot'];
$dataResults['development_url'] = $d['site_url'];
$dataResults['init_sales'] = $d['init_sales'];
$dataResults['development_id'] = $d['id'];
$dataResults['development_slug'] = $d['development_slug'];
// Verifico se é imóvel NOVO ou REVENDA
$dataResults['is_new'] = false;
if ($d["imobles_client"] == 1) {
$dataResults['is_new'] = true;
}
//tratamento do stagio conforme regra IMB-18
if (empty($d['stage'])) {
if (strtotime(date("Y-m-d")) >= strtotime($d['release_date'])) {
$dataResults['construction_status'] = 'Ready to move in';
} else {
$dataResults['construction_status'] = 'In Works';
}
$dataResults['release_date'] = $d['release_date'];
} else {
$dataResults['construction_status'] = $d['stage'];
$dataResults['release_date'] = $d['release_date'];
}
$dataResults['property_standard'] = $d['property_standard'];
$dataResults['financing']['entry'] = $d['financing_input'];
$dataResults['financing']['installment'] = $d['financing_installment'];
$dataResults['financing']['founding'] = $d['financing_founding'];
//IMB-19
if (!empty($d['google_geometry'])) {
$dataResults['geometry'] = json_decode($d['google_geometry']);
// TODO: RESOLVER O PROBLEMA DE SE PEGAR O LAT/LONG DO GOOGLE
$dataResults['geometry']->location = array("lat" => floatval($d['latitude']), "lng" => floatval($d['longitude']));
} else {
$dataResults['geometry'] = array("location" => array("lat" => floatval($d['latitude']), "lng" => floatval($d['longitude'])));
}
$dataResults['google']['place_id'] = $d['google_place_id'];
$dataResults['google']['rating'] = $d['google_rating'];
$dataResults['google']['link'] = $d['link_google'];
$dataResults['link_presentation'] = $d['link_presentation'];
$dataResults['address'] = array(
'country' => 'BR',
'zip_code' => $d['address_zip'],
'city' => $d['city_name'],
'ibge_city_id' => $d['city_ibge'],
'state_acronym' => $d['uf_state'],
'state' => $d['state_name'],
'ibge_state_id' => $d['code_state'],
'street' => $d['address_log'],
'number' => $d['address_number'],
'neighborhood' => $d['address_neightborhood'],
);
$tags = ORM::for_table('module_imobles_enterprise_img_backend_tags')
->table_alias('s');
$tags = $tags->find_many();
$arrayTag = array();
foreach ($tags as $t) {
$arrayTag[$t->id] = $t->name;
}
// Pego as imagens de backend
$imagB = ORM::for_table('module_imobles_enterprise_imgs')
->raw_query("SELECT s.module_imobles_enterprise_id, s.src, s.resized, s.webp, s.tags, s.unit_type_id, s.description FROM"
. " module_imobles_enterprise_imgs as s"
. " WHERE (s.duplicated IS NULL OR s.duplicated=0) AND type = 'backend' "
. " AND s.module_imobles_enterprise_id IN(" . $d['id'] . ") "
. " AND s.delete_at IS NULL AND s.tags IS NOT NULL "
// . " HAVING count(module_imobles_enterprise_id)<=5"
)->find_array();
// $imagB = ORM::for_table('module_imobles_enterprise_imgs')
// ->raw_query("SELECT s.module_imobles_enterprise_id,s.src, s.tags FROM"
// . " module_imobles_enterprise_imgs s"
// . " WHERE (s.duplicated IS NULL OR s.duplicated=0) AND s.delete_at IS NULL AND s.type='backend' AND s.module_imobles_enterprise_id IN(" . $d['id'] . ")"
// // . " HAVING count(module_imobles_enterprise_id)<=5"
// )->find_array();
if (count($imagB) > 0) {
foreach ($imagB as $im) {
if (!empty($im['unit_type_id']) || empty($im['tags'])) {
continue;
}
$desc_tags = array();
try {
$tagsIm = json_decode($im['tags']);
if ($tagsIm) {
foreach ($tagsIm as $t) {
$desc_tags[] = $arrayTag[$t];
}
}
} catch (Exception $e) {
$desc_tags = "";
}
// Monto o array com os tamanhos alternativos das imagens
$alternatives_sizes = null;
if ($im['resized'] == 1) {
$alternatives_sizes = array("1152x768" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xxl/" . $im['src'],
"840x560" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xlg/" . $im['src'],
"600x400" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/lrg/" . $im['src'],
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/med/" . $im['src'],
"300x200" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/sml/" . $im['src'],
"120x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xsm/" . $im['src']);
if(in_array("DEVELOPMENT_GALLERY_IMGS", $desc_tags))
{
$alternatives_sizes["104x80"] = APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/thumb/" . $im['src'];
}
}
$webp = false;
if ($im['webp'] == 1) {
$webp = true;
}
$dataResults['medias'][] = array(
"type" => 'IMAGE',
"url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
"description" => $im['description'],
"tags" => $desc_tags,
"alternatives_sizes" => $alternatives_sizes,
"webp" => $webp);
}
}
$filterListMediaPriceLIsting = " AND (sub_price2.delete_at IS NULL AND "
. "(sub_price2.crawler_status IS NULL OR sub_price2.crawler_status='ACTIVE')"
. " AND (sub_price2.unavailable IS NULL OR sub_price2.unavailable=0)"
. ")";
if ($resale === false) {
$query_resale_listing = " AND sub_l.crawler_type_id = 4 AND sub_l.advertiser_id IS NULL ";
$query_resale_unit = " AND sub.crawler_type_id = 4 ";
$query_resale = " AND u.crawler_type_id = 4 ";
$query_resale .= " AND l.crawler_type_id = 4 AND l.advertiser_id IS NULL AND l.crawler_price > 0 AND u.delete_at IS NULL ";
$filterListMediaPriceLIsting .= " AND sub_price2.crawler_type_id = 4 AND sub_price2.advertiser_id IS NULL ";
$selectCount = "NULL as total_listing, "
. " (select count(sub.id) from module_imobles_enterprise_units sub "
. " where sub.module_imobles_enterprise_units_type_id=u.id AND (sub.unavailable IS NULL OR sub.unavailable=0) " . $query_resale_unit . " AND sub.delete_at IS NULL) as disponible_unit";
} else {
$query_resale_listing = " AND ( sub_l.crawler_type_id <> 4 OR sub_l.crawler_type_id IS NULL) AND sub_l.advertiser_id IS NOT NULL AND (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL)";
$query_resale_unit = " AND ( sub.crawler_type_id <> 4 OR sub.crawler_type_id IS NULL)";
// $query_resale = " AND ( u.crawler_type_id <> 4 OR u.crawler_type_id IS NULL)";
$query_resale = " ";
$selectCount = " (select count(sub_l.id) from module_imobles_listings sub_l "
. " where sub_l.unit_type_id=u.id AND (sub_l.unavailable IS NULL OR sub_l.unavailable =0 ) AND sub_l.delete_at IS NULL " . $query_resale_listing . " ) as total_listing, "
. "NULL as disponible_unit";
$filterListMediaPriceLIsting .= "AND (sub_price2.crawler_type_id IS NULL OR sub_price2.crawler_type_id <> 4) AND sub_price2.advertiser_id IS NOT NULL AND (sub_price2.crawler_businessType <> 'RENTAL' OR sub_price2.crawler_businessType IS NULL) ";
$query_resale .= " AND l.crawler_price > 0 AND u.delete_at IS NULL AND (l.crawler_type_id IS NULL OR l.crawler_type_id <> 4) AND l.advertiser_id IS NOT NULL AND (l.crawler_businessType <> 'RENTAL' OR l.crawler_businessType IS NULL) ";
}
$arr_unit_type_imgs = array();
//BUSCA UNIT_TYPE
$types = ORM::for_table('module_imobles_enterprise_units_type')
->raw_query(" SELECT "
. " min(l.crawler_price) as minValue,"
. " max(l.crawler_price) as 'maxValue',"
. " avg(l.crawler_price) as averageValue ,"
. " u.number_rooms as bedrooms,"
. " u.number_bathroom as bathrooms,"
. " u.area as area,"
. " u.number_suite as suites,"
. " u.number_garage as parking_spaces,"
. " u.id,"
. " u.module_imobles_enterprise_id,"
. " group_concat(l.id) as list_listings,"
. $selectCount
. " FROM module_imobles_enterprise_units_type u"
. " JOIN module_imobles_listings l ON (u.id=l.unit_type_id)"
. " JOIN module_imobles_enterprise_units un ON (un.id=l.unit_id)"
. " WHERE"
. " (l.unavailable IS NULL OR l.unavailable =0)"
. " AND l.delete_at IS NULL "
. " AND un.delete_at IS NULL "
. $query_resale
. " and l.crawler_price>=(select avg(sub_price2.crawler_price) from module_imobles_listings sub_price2 WHERE sub_price2.unit_type_id=u.id " . $filterListMediaPriceLIsting . ")*0.6"
. " AND u.module_imobles_enterprise_id IN (" . $d['id'] . ")"
. " AND u.delete_at IS NULL AND u.site_enabled = 1 "
. " GROUP BY u.module_imobles_enterprise_id, u.id, u.number_rooms, u.number_suite, u.area, u.number_garage, u.number_bathroom "
. " ORDER BY averageValue ASC ")
->find_array();
if (count($types) > 0) {
foreach ($types as $u) {
if (count($imagB) > 0) {
foreach ($imagB as $im) {
$arr_tags = array();
if ($im['unit_type_id'] != $u['id'] || empty($im['tags'])) {
continue;
}
if (empty($arr_unit_type_imgs[$u['id']]) || count($arr_unit_type_imgs[$u['id']]) < 10) {
// TODO: erro quando imageem está quebrada ou sem tags
$arr_tags_id = json_decode($im['tags']);
$arr_tags_aux = ORM::for_table('module_imobles_enterprise_img_backend_tags')->select('name')->where_in('id', $arr_tags_id)->find_array();
foreach ($arr_tags_aux as $tags) {
$arr_tags[] = $tags['name'];
}
// Monto o array com os tamanhos alternativos das imagens
$alternatives_sizes = null;
if ($im['resized'] == 1) {
$alternatives_sizes = array("1152x768" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xxl/" . $im['src'],
"840x560" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xlg/" . $im['src'],
"600x400" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/lrg/" . $im['src'],
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/med/" . $im['src'],
"300x200" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/sml/" . $im['src'],
"120x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xsm/" . $im['src']);
if(in_array("DEVELOPMENT_GALLERY_IMGS", $arr_tags))
{
$alternatives_sizes["104x80"] = APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/thumb/" . $im['src'];
}
}
$webp = false;
if ($im['webp'] == 1) {
$webp = true;
}
$arr_unit_type_imgs[$u['id']][] = array(
"type" => 'IMAGE',
"url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
"description" => $im['description'],
"tags" => $arr_tags,
"alternatives_sizes" => $alternatives_sizes,
"webp" => $webp);
} else {
break;
}
}
}
//bbusca os tipos de unidade
$am = ORM::for_table('module_imobles_enterprise_units_type_amenities')
->table_alias('s')
->select("sub.name")
->select_expr("sub.type")
->join('module_imobles_type_units_amenities', 's.module_imobles_type_units_amenities_id = sub.id', 'sub')
->where('s.module_imobles_enterprise_units_type_id', $u['id'])
->find_array();
if ($u['averageValue'] < $u['minValue']) {
$u['averageValue'] = $u['minValue'];
}
// Pego os detalhes dos anúncios
$arr_listings = array();
if ($resale === true) {
$selectlistings = "select sub_l.id, sub_l.crawler_price, sub_l.crawler_listing_link, sub_l.crawler_portal, sub_l.crawler_updatedAt, ads.logoUrl, ads.name as advertiser_name "
. "from module_imobles_listings sub_l "
. " JOIN module_imobles_advertisers as ads ON ads.id = sub_l.advertiser_id "
. " where sub_l.unit_type_id= " . $u['id'] . " AND (sub_l.unavailable IS NULL OR sub_l.unavailable = 0 ) AND sub_l.delete_at IS NULL AND "
. "(sub_l.crawler_type_id IS NULL OR sub_l.crawler_type_id <> 4) AND sub_l.advertiser_id IS NOT NULL AND "
. "(sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL)";
$arr_listings_aux = ORM::for_table('module_imobles_enterprise_units_type')
->raw_query($selectlistings)
->find_array();
if (count($arr_listings_aux) > 0) {
$count_aux = 0;
foreach ($arr_listings_aux as $listing_aux) {
if (!empty($listing_aux['logoUrl'])) {
$listing_aux['logoUrl'] = str_replace('{width}', '870', $listing_aux['logoUrl']);
$listing_aux['logoUrl'] = str_replace('{height}', '653', $listing_aux['logoUrl']);
$listing_aux['logoUrl'] = str_replace('{action}', 'fit-in', $listing_aux['logoUrl']);
}
if ($listing_aux['crawler_portal'] == "VIVAREAL") {
$listing_aux['crawler_listing_link'] = "https://vivareal.com.br" . $listing_aux['crawler_listing_link'];
}
if ($listing_aux['crawler_portal'] == "GRUPOZAP") {
$listing_aux['crawler_listing_link'] = "https://zapimoveis.com.br" . $listing_aux['crawler_listing_link'];
}
$arr_listings[] = array("id" => $listing_aux['id'],
"price" => $listing_aux['crawler_price'],
"portal" => $listing_aux['crawler_portal'],
"last_update" => $listing_aux['crawler_updatedAt'],
"logo" => $listing_aux['logoUrl'],
"link" => $listing_aux['crawler_listing_link'],
"advertiser_name" => $listing_aux["advertiser_name"]);
}
}
}
$dataResults['unit_type'] [] = array(
"id" => $u['id'],
"total_listing" => $u['total_listing'],
"unit_available" => $u['disponible_unit'],
"min_value" => number_format($u['minValue'], 2, ".", ""),
"average_value" => number_format($u['averageValue'], 2, ".", ""),
"max_value" => number_format($u['maxValue'], 2, ".", ""),
"bedrooms" => $u['bedrooms'],
"bathrooms" => $u['bathrooms'],
"area" => $u['area'],
"suites" => $u['suites'],
"parking_spaces" => $u['parking_spaces'],
"amenities" => $am,
"medias" => @$arr_unit_type_imgs[$u['id']],
"listings_details" => $arr_listings
);
}
}
$amenities = ORM::for_table('module_imobles_enterprise_entreprise_amenities')
->table_alias('s')
->select("sub.name")
->select_expr(" sub.type")
->join('module_imobles_enterprise_amenities', 's.module_imobles_enterprise_amenities_id = sub.id', 'sub')
->where('s.module_imobles_enterprise_id', $d['id'])
->find_array();
$dataResults['amenities'] = $amenities;
// Pego os amenities obrigatórios
$required_amenities = ORM::for_table("module_imobles_enterprise_amenities")->select_many('name', 'type')->where("required", 1)->find_array();
$dataResults['required_amenities'] = $required_amenities;
// Pego os dados do Hotsite
if (!empty($d['hotsite_params'])) {
$dataResults['hotsite'] = json_decode($d['hotsite_params']);
} else {
$dataResults['hotsite'] = null;
}
}
}
$output = array(
// "time" => (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']),
"results" => ($dataResults),
);
return $output;
// header('Content-Type: application/json');
// echo json_encode($output);
// exit();
}
/**
* Send Message
* Função que faz o cadastro do novo Lead e o envio da primeira mensagem por whats
*
* @param
* @return JSON
*/
public function mandeUmZapHubspot() {
$jsonStr = file_get_contents("php://input");
$data = json_decode($jsonStr, true);
foreach ($data as $event) {
if (isset($event['objectId'])) {
// Pego os dados do Cliente no HubSpot
$url = "https://api.hubapi.com/crm/v3/objects/contacts/"
. $event['objectId']
. "?hapikey=2149faed-582c-48fa-950e-01d9cd403b06"
. "&properties=phone,email,firstname,lastname,apto_de_interesse_atual,"
. "n_mero_de_quartos,lancamentos_interesse,horario_de_preferencia_de_contato,canal_de_contato,"
. "data_de_entrega___cta_lista,lista_detalhes_da_solicitacao,quartos___cta_lista,"
. "faixa_de_preco___cta_lista,data_de_entrega___cta_lista,bairro";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json_response = curl_exec($ch);
$result = json_decode($json_response);
if (isset($result->properties->phone)) {
// Trato o Telefone cadastrado no Hubspot
$phone = preg_replace('/\D/', '', $result->properties->phone);
if (!preg_match('/^\+/', trim($result->properties->phone))) {
if (!preg_match('/^55/', $phone)) {
$phone = "55" . $phone;
}
}
$name = mb_strtoupper($result->properties->firstname . " " . $result->properties->lastname);
// Verifico se o usuário já está cadastrado
$client = ORM::for_table("crm_accounts")->where('code', $result->id)->find_one();
if (!isset($client->id)) {
$client = ORM::for_table("crm_accounts")->create();
$client->account = $name;
$client->phone = $phone;
$client->email = $result->properties->email;
$client->kind_of_person = 'PF';
$client->code = $result->id;
$client->created_at = date('Y-m-d H:i:s');
$client_id = $client->save();
// Verifico o horário para saber se deve ser enviada a mensagem automática
$dataAux = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
$hora_aux = intval($dataAux->format('H'));
$send_msg = false;
if ($dataAux->format('D') != 'Sun' && $dataAux->format('D') != 'Sat') {
if ($hora_aux <= 7 || $hora_aux >= 20) {
$send_msg = true;
}
} elseif ($dataAux->format('D') == 'Sat') {
if ($hora_aux <= 7 || $hora_aux >= 19) {
$send_msg = true;
}
} else {
$send_msg = true;
}
$firstname = trim(strtolower($result->properties->firstname));
if (preg_match('/testezap/i', $firstname)) {
$send_msg = true;
}
// Envio a mensagaem automática
$msg = null;
if ($send_msg === true) {
// Pego os empreendimentos de interesse
$enterprises_selecteds = array();
if (!empty($result->properties->apto_de_interesse_atual)) {
if (preg_match('/Solicitacao de Lista/i', $result->properties->apto_de_interesse_atual)) {
if (preg_match('/CTA/i', $result->properties->apto_de_interesse_atual)) {
$arr_msg_lista = explode("-", $result->properties->lista_detalhes_da_solicitacao);
} else {
$arr_msg_lista = explode("|", $result->properties->lista_detalhes_da_solicitacao);
}
unset($arr_msg_lista[count($arr_msg_lista) - 1]);
// var_dump($arr_msg_lista);exit;
$msg_lista = null;
foreach ($arr_msg_lista as $item_msg) {
if (!empty(trim($item_msg))) {
$msg_lista .= trim($item_msg) . ", ";
}
}
// Monto a mensagem para solicitação de lista
$msg = "Olá " . $name . ", tudo bem? 😃\n\n"
. "Entro em contato porque você solicitou a lista de empreendimentos no " . $msg_lista . " em nosso site.\n\n"
. "Estamos offline agora 🌙, e não gostamos de enviar qualquer informação para desperdiçar seu "
. "tempo com bobagens. Fazemos um trabalho CUSTOMIZADO e trabalhamos com TODOS apartamentos de Goiânia: na planta, prontos, novos e revenda! 😉\n\n"
. "Amanhã entraremos em contato já com uma lista inicial para customizar às suas necessidades. Qual o melhor horário?\n\n"
. "🔍 Enquanto isso, se quiser ir deixando mais detalhes aqui que me ajudem a acertar na mosca o que você busca, fique à vontade!\n\n"
. "Uma ótima noite da equipe imobles.com!🌃";
} else {
// $arr_enterprises = explode(';', $result->properties->apto_de_interesse_atual);
// $enterprise_selected = trim($arr_enterprises[0]);
// $enterprise_aux = ORM::for_table('module_imobles_enterprise')->select("id")->where("hubspot", $enterprise_selected)->find_one();
// if (isset($enterprise_aux->id))
// {
// // Pego os dados do empreendimento via API
// $url = "https://imobles.lrsys.com.br/?ng=api&key=gg7m8b7ruqaptg4a0jc9f4604qrsm1et7b66c3nx&method=plugin&plugin=module_imobles&pl_method=developmentDetails";
// $postdata = '{"development_id" : ' . $enterprise_aux->id . '}';
// $ch = curl_init($url);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
// $json_response = curl_exec($ch);
// $result_ent = json_decode($json_response);
// $enterprises_selecteds[] = $result;
//
// $arr_unit_types = $result_ent->results->unit_type;
// $price = 0;
// $unit_type = null;
// foreach ($arr_unit_types as $unit_type_aux)
// {
// if ($price == 0 || $price > $unit_type_aux->min_value)
// {
// $price = $unit_type_aux->min_value;
// $unit_type = $unit_type_aux;
// }
// }
//
// // Pego a data de lançamento
// $release_date = $result_ent->results->release_date;
// if($dataAux->format('Y-m-d') > $release_date)
// {
// $msg_unit = "Quanto ao plano de pagamento 💰, o valor total da unidade mais em conta de " . $unit_type->area . "m2 com " . $unit_type->bedrooms
// . " quartos" . ($unit_type->suites > 0 ? ", sendo " . $unit_type->suites . " suite" . ($unit_type->suites > 1 ? "s" : "") . "," : ",")
// . " fica em torno de R$" . number_format($unit_type->min_value, 0, ",", ".") . ", e como esse é um imóvel já pronto para morar, "
// . "a entrada é normalmente 20% (R$" . number_format(($unit_type->min_value*0.2), 0, ",", ".") . ") e o restante é financiado com o banco.\n\n";
//
//
// $msg = "*" . $result_ent->results->name . " - Plano de Pagamento*\n\n"
// . "Olá, " . $name . " Tudo bem? 😃\n\n"
// . "Conforme sua solicitação em nosso site, seguem as informações sobre o plano de pagamento do *" . $result_ent->results->name . "* 👇\n\n"
// . "Primeiro, uma apresentação para sua referência: \n\n"
// . $result_ent->results->link_presentation . " \n\n"
// . $msg_unit
// . "Trabalhamos com todos os imóveis de Goiânia: na planta, prontos, novos e revenda 😉. \n\n"
// . "Então gostaríamos de preparar uma lista com opções, assim você pode reunir informações, comparar os apartamentos e fazer o melhor negócio! \n\n"
// . "O que você acha? \n\n"
// . "Aah e antes que eu esqueça, se você quiser já pode ir deixando suas dúvidas aqui. Agora estamos descansando 🌙, mas amanhã, assim que chegarmos, "
// . "entraremos em contato para explicar TODOS os detalhes! \n\n"
// . "Uma ótima noite da equipe imobles.com!🌃";
// }
// else
// {
// $msg_unit = "💰 O preço da unidade mais em conta de " . $unit_type->area . "m2 com " . $unit_type->bedrooms
// . " quartos" . ($unit_type->suites > 0 ? ", sendo " . $unit_type->suites . " suite" . ($unit_type->suites > 1 ? "s" : "") . "," : ",")
// . " fica em torno de R$" . number_format($unit_type->min_value, 0, ",", ".") . ".\n\n"
// . "O plano de pagamento funciona assim:\n\n"
// . "R$" . (number_format(($unit_type->min_value * $result_ent->results->financing->founding), 0, ",", ".")) . " devem ser pagos até a entrega das chaves, em 35 meses;\n\n"
// . "A entrada padrão é de R$" . (number_format(($unit_type->min_value * $result_ent->results->financing->entry), 0, ",", ".")) . ";\n\n"
// . "As parcelas mensais são de R$" . (number_format(($unit_type->min_value * $result_ent->results->financing->installment), 0, ",", ".")) . ";\n\n"
// . "Além disso, tem um valor de parcelas intermediárias, que pode ser ajustado conforme for melhor para você.\n\n";
//
//
// $msg = "*" . $result_ent->results->name . " - Plano de Pagamento*\n\n"
// . "Olá, " . $name . " Tudo bem? 😃\n\n"
// . "Conforme você solicitou, seguem as informações do *" . $result_ent->results->name . "* 👇\n\n"
// . "Antes dos valores, separei uma apresentação do empreendimento para sua referência: \n\n"
// . $result_ent->results->link_presentation . " \n\n"
// . $msg_unit
// . "Trabalhamos com todos os imóveis de Goiânia: na planta, prontos, novos e revenda 😉. \n\n"
// . "Então gostaríamos de preparar uma lista com opções, assim você pode reunir informações, comparar os apartamentos e fazer o melhor negócio! \n\n"
// . "O que você acha? \n\n"
// . "Aah e antes que eu esqueça, se você quiser já pode ir deixando suas dúvidas aqui. Agora estamos descansando 🌙, mas amanhã, assim que chegarmos, "
// . "entraremos em contato para explicar TODOS os detalhes! \n\n"
// . "Uma ótima noite da equipe imobles.com!🌃";
// }
// }
}
}
// Faço o envio da mensagem pelo MandeUmZap
if (!empty($msg)) {
$send_msg = $this->crawlerController->mandeUmZapSendMessage($phone, $name, $msg);
if ($send_msg["success"] == true) {
echo "OK";
} else {
echo "ERROR";
}
}
}
} else {
$client_id = $client->id;
$client->account = $name;
$client->email = $result->properties->email;
$client->phone = $phone;
$client->updated_at = date('Y-m-d H:i:s');
$client->save();
}
}
}
}
}
/**
* getLocations
* Retorna uma localização baseada na string de pesquisa.
* Utilizada em autocomplete
* TODO: tratar os LIMITs via PAYLOAD | incluir filtro por cidade
* @param STRING
* @return JSON
*/
public function getLocations() {
$jsonStr = file_get_contents("php://input");
$data = json_decode($jsonStr, true);
$dataResults = array();
$data_aux = array();
$term = $data['term'];
$count_neighborhood = 0;
$count_development = 0;
// Verifico se tem revenda
$resale = false;
if (isset($data['resale']) && $data['resale'] == true) {
$resale = true;
}
// Faço a procura por bairros
$address_neightborhood = ORM::for_table('module_imobles_enterprise')
->table_alias('s')
->select_expr("s.address_neightborhood")
->group_by_expr("s.address_neighborhood_sanitized")
->order_by_asc("s.address_neightborhood");
$address_neightborhood->where_raw("s.delete_at IS NULL");
$address_neightborhood->where_raw("s.has_listing IS NOT NULL");
$address_neightborhood->where_any_is(array(array("s.address_neighborhood_sanitized" => '%' . sanitizaText($term) . '%')), 'like');
$address_neightborhood->limit(10);
$address_neightborhoods = $address_neightborhood->find_many();
if ($address_neightborhoods) {
foreach ($address_neightborhoods as $p) {
$data_aux[] = array(
'type' => "neighborhood",
'text' => $p->address_neightborhood
);
}
}
$count_neighborhood = count($address_neightborhoods);
// Faço a procura por empreendimentos
$developments = ORM::for_table('module_imobles_enterprise')
->table_alias('s');
$developments->select_expr("s.alias, s.id, s.name, s.address_neightborhood, s.site_url");
$developments->where_any_is(array(array("s.name" => '%' . $term . '%'),
array("s.alias" => '%' . $term . '%')
), 'like');
$developments->where_raw("s.delete_at IS NULL");
// $developments->where_raw("s.has_listing IS NOT NULL");
$developments->where_raw("s.site_enabled = 1");
$developments->limit(10);
$developments = $developments->find_many();
$count_development = count($developments);
foreach ($developments as $p) {
$data_aux[] = array(
'type' => "development",
'text' => $p->name . " (" . $p->address_neightborhood . ")",
'development_details' => array("id" => $p->id,
"name" => $p->name,
"neighborhood" => $p->address_neightborhood,
"site_url" => $p->site_url)
);
}
// Retorno da função
$dataResults = $data_aux;
$output = array(
// "time" => (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']),
"total_count" => count($dataResults),
"total_neigborhood" => $count_neighborhood,
"total_development" => $count_development,
"results" => $dataResults
);
return $output;
// header('Content-Type: application/json');
// echo json_encode($output);
// exit();
}
/*
* @sitemapGenerator
* Função que retorna as URLs dos empreendimentos ativos no site
*/
public function sitemapGenerator() {
ORM::configure('caching', true); // nao vi diferença
$dataResults = array();
$enterprises = ORM::for_table("module_imobles_enterprise")
->where('site_enabled', 1)
->where_null("delete_at")
->find_many();
foreach ($enterprises as $d) {
$dataResults[$d['id']]['id'] = $d->id;
$dataResults[$d['id']]['name'] = $d->name;
$dataResults[$d['id']]['hotsite_url'] = null;
if (empty($d->site_url)) {
$sanitize_name = $this->crawlerHelper->sanitizaUrl($d->name);
$city = ORM::for_table('city')->find_one($d->address_city_id);
if ($city)
{
$city_sanitized = $this->crawlerHelper->sanitizaUrl($city->city_name);
}
else
{
$city_sanitized = "goiania";
}
$state = ORM::for_table("state")->find_one($d->address_state_id);
if ($state)
{
$state_sanitized = $this->crawlerHelper->sanitizaUrl($state->uf_state);
}
else
{
$state_sanitized = "go";
}
$development_slug = "apartamento-venda-".$sanitize_name."-".$city_sanitized."-".$state_sanitized;
$check_slug = ORM::for_table("module_imobles_enterprise")
->where("slug", $development_slug)
->where_not_in("id", [$d->id])
->find_one();
if(isset($check_slug->id) && $check_slug->id > 0)
{
continue;
}
$d->slug = $development_slug;
$d->site_url = "https://imobles.com/".$development_slug;
$d->save();
}
// if (!empty($d->hotsite_params)) {
// $hotsiteparams = json_decode($d->hotsite_params);
// if (!empty($d->hotsite_params) && ($hotsiteparams->development_hotsite_enabled == 1)) {
// $sanitize_name = $this->crawlerHelper->sanitizaUrl($d->name);
// $hotsite_url = "https://imobles.com/lancamentos/" . $sanitize_name . "/" . $d->id;
// $dataResults[$d['id']]['hotsite_url'] = $hotsite_url;
// }
// }
$dataResults[$d['id']]['url'] = $d->site_url;
$dataResults[$d['id']]['url_canonical'] = $d->url_canonical;
$dataResults[$d['id']]['updated_at'] = $d->updated_at;
}
$totalresults = count($dataResults);
$output = array(
// "time" => (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']),
"total_count" => count($enterprises),
"results" => array_values($dataResults),
);
return $output;
// header('Content-Type: application/json');
// echo json_encode($output);
// exit();
}
public function dynamicUrls() {
$dynamic_urls = ORM::for_table("module_imobles_dynamic_urls")
->where_null("deleted_at")
->find_many();
$foo = -1;
$data = array();
foreach ($dynamic_urls as $dyn) {
$foo++;
$data['vendas-' . $foo]['id'] = $dyn->id;
$data['vendas-' . $foo]['name'] = null;
$data['vendas-' . $foo]['url'] = $dyn->url;
$data['vendas-' . $foo]['url_canonical'] = null;
$data['vendas-' . $foo]['update_frequency'] = $dyn->update_frequency;
$data['vendas-' . $foo]['updated_at'] = $dyn->updated_at;
}
$response = array(
"total_count" => count($dynamic_urls),
"results" => array_values($data),
);
return $response;
}
public function constructionCompanyUrls() {
$companies = ORM::for_table('module_imobles_company_construction')
->where_not_null('hotsite_params')
->where_null('delete_at')
->find_many();
$foo = -1;
$data = array();
$count = 0;
foreach ($companies as $comp) {
if(empty($comp->site_url))
{
$sanitize_name = $this->crawlerHelper->sanitizaUrl($comp->name);
$city = ORM::for_table('city')->find_one($comp->city_id);
if ($city)
{
$city_sanitized = $this->crawlerHelper->sanitizaUrl($city->city_name);
}
else
{
$city_sanitized = "goiania";
}
$state = ORM::for_table("state")->find_one($comp->state_id);
if ($state)
{
$state_sanitized = $this->crawlerHelper->sanitizaUrl($state->uf_state);
}
else
{
$state_sanitized = "go";
}
$comp_slug = "apartamentos-venda-construtora-".$sanitize_name."-".$city_sanitized."-".$state_sanitized;
$comp_url = "https://imobles.com/".$comp_slug;
$check_slug = ORM::for_table("module_imobles_company_construction")
->where("slug", $comp_slug)
->where_not_in("id", [$comp->id])
->find_one();
if(isset($check_slug->id) && $check_slug->id > 0)
{
continue;
}
else
{
$comp->site_url = $comp_url;
$comp->slug = $comp_slug;
$comp->save();
}
}
$data['vendas-' . $foo]['id'] = $comp->id;
$data['vendas-' . $foo]['name'] = $comp->name;
$data['vendas-' . $foo]['url'] = $comp->site_url;
$data['vendas-' . $foo]['url_canonical'] = null;
$data['vendas-' . $foo]['updated_at'] = $comp->updated_at;
if (!empty($comp->hotsite_params))
{
$params = json_decode($comp->hotsite_params);
if (isset($params->construction_company_hotsite_enabled) && intval($params->construction_company_hotsite_enabled == 1))
{
$comp_slug = explode("apartamentos-venda-", $comp->slug);
$comp_slug = $comp_slug[1];
$comp_url = "https://imobles.com/".$comp_slug;
$data['ggg-' . $foo]['id'] = $comp->id;
$data['ggg-' . $foo]['name'] = $comp->name;
$data['ggg-' . $foo]['url'] = $comp_url;
$data['ggg-' . $foo]['url_canonical'] = null;
$data['ggg-' . $foo]['updated_at'] = $comp->updated_at;
$count++;
}
}
$foo++;
}
$response = array(
"total_count" => $count,
"results" => array_values($data),
);
return $response;
}
/*
* companyConstructionDetails
* Detalhes da construtora
*/
public function companyConstructionDetails() {
try {
$jsonStr = file_get_contents("php://input");
$filter = json_decode($jsonStr, true);
$jsonStr = ""; //LIMPA
} catch (Exception $e) {
$filter = array();
}
$dataResults = array();
$id = null;
if(isset($filter['company_construction_id']) && !empty($filter['company_construction_id']))
{
$id = intval($filter['company_construction_id']);
}
$slug = null;
if(isset($filter['company_construction_slug']) && !empty($filter['company_construction_slug']))
{
$slug = $filter['company_construction_slug'];
}
if ($id > 0 || !empty($slug))
{
// $d = ORM::for_table('module_imobles_company_construction')->find_one($id);
$select = "SELECT const.*, "
. "c.city_name, c.city_ibge,st.uf_state, st.state_name, st.code_state ";
$from = ' FROM module_imobles_company_construction const '
. ' LEFT JOIN state st ON(st.id=const.state_id)'
. ' LEFT JOIN city c ON(c.id=const.city_id)';
if ($id > 0)
{
$where = ' WHERE const.delete_at IS NULL AND const.id= ' . $id;
}
else{
$where = ' WHERE const.delete_at IS NULL AND const.slug= "' . $slug.'"';
}
$d = ORM::for_table('module_imobles_company_construction')
->raw_query($select . $from . $where)->find_one();
if (!empty($d) > 0) {
$id = $d['id'];
$dataResults['name'] = $d['name'];
$dataResults['address'] = array(
'country' => 'BR',
'zip_code' => $d['address_zip'],
'city' => $d['city_name'],
'ibge_city_id' => $d['city_ibge'],
'state_acronym' => $d['uf_state'],
'state' => $d['state_name'],
'ibge_state_id' => $d['code_state'],
'street' => $d['address_log'],
'number' => $d['address_number']
);
// verifico se está vinculado ao Google Maps
$dataResults['google_place'] = null;
if (!empty($d['google_place_json'])) {
$dataResults['google_place'] = json_decode($d['google_place_json']);
}
// Pego as imagens de backend da Construtora
$tags = ORM::for_table('module_imobles_enterprise_img_backend_tags')
->table_alias('s');
$tags = $tags->find_many();
$arrayTag = array();
foreach ($tags as $t) {
$arrayTag[$t->id] = $t->name;
}
$imagB = ORM::for_table('module_imobles_enterprise_imgs')
->raw_query("SELECT s.module_imobles_enterprise_id, s.src, s.resized, s.webp, s.tags, s.unit_type_id, s.description, s.construction_company_id FROM"
. " module_imobles_enterprise_imgs as s"
. " WHERE (s.duplicated IS NULL OR s.duplicated=0) AND type = 'backend' AND unit_type_id IS NULL "
. " AND s.construction_company_id IN(" . $id . ") "
. " AND s.delete_at IS NULL AND s.tags IS NOT NULL ")->find_array();
if (count($imagB) > 0) {
foreach ($imagB as $im) {
$desc_tags = array();
try {
$tagsIm = json_decode($im['tags']);
if ($tagsIm) {
foreach ($tagsIm as $t) {
$desc_tags[] = $arrayTag[$t];
}
}
} catch (Exception $e) {
$desc_tags = "";
}
// Monto o array com os tamanhos alternativos das imagens
$alternatives_sizes = null;
if ($im['resized'] == 1) {
$alternatives_sizes = array("1152x768" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/xxl/" . $im['src'],
"840x560" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/xlg/" . $im['src'],
"600x400" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/lrg/" . $im['src'],
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/med/" . $im['src'],
"300x200" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/sml/" . $im['src'],
"120x80" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/xsm/" . $im['src'],
"104x80" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/thumb/" . $im['src']);
}
$webp = false;
if ($im['webp'] == 1) {
$webp = true;
}
$dataResults['medias'][] = array(
"type" => 'IMAGE',
"url" => APP_URL . "/application/plugins/module_imobles/uploads/companyconstruction/" . $im['construction_company_id'] . "/images/" . $im['src'],
"description" => $im['description'],
"tags" => $desc_tags,
"alternatives_sizes" => $alternatives_sizes,
"webp" => $webp);
}
}
if (!empty($d['hotsite_params'])) {
$dataResults['hotsite'] = json_decode($d['hotsite_params']);
}
$dataResults['id'] = $d['id'];
$dataResults['slug'] = $d['slug'];
// Pego os empreendimentos da construtora
$select = "SELECT ent.name, ent.release_date, ent.id, ent.init_sales, ent.slug as development_slug,"
. "ent.address_log, ent.address_number, ent.address_neightborhood, ent.address_zip, ent.site_url, ent.hotsite_params, imobles_client, "
. "ent.value_input_porcentage as financing_input, ent.value_installment_porcentage financing_installment, ent.value_founding_porcentage as financing_founding, ent.hubspot, "
. "c.city_name, c.city_ibge,st.uf_state, st.state_name, st.code_state ";
$from = ' FROM module_imobles_enterprise ent '
. ' LEFT JOIN state st ON(st.id=ent.address_state_id)'
. ' LEFT JOIN city c ON(c.id=ent.address_city_id)';
$where = ' WHERE ent.delete_at IS NULL AND ent.site_enabled = 1 AND ent.imobles_client = 1 AND ent.module_imobles_company_construction_id = ' . $id;
$enterprises = ORM::for_table('module_imobles_enterprise')
->raw_query($select . $from . $where)->find_array();
foreach ($enterprises as $d) {
// Dados do endereço
$arr_address = array(
'country' => 'BR',
'zip_code' => $d['address_zip'],
'city' => $d['city_name'],
'ibge_city_id' => $d['city_ibge'],
'state_acronym' => $d['uf_state'],
'state' => $d['state_name'],
'ibge_state_id' => $d['code_state'],
'street' => $d['address_log'],
'number' => $d['address_number'],
'neighborhood' => $d['address_neightborhood']);
$arr_enterprises = array("name" => $d["name"],
"release_date" => $d["release_date"],
"address" => $arr_address,
"development_id" => $d["id"],
"init_sales" => $d["init_sales"]);
$arr_enterprises['hubspot_alias'] = $d['hubspot'];
$arr_enterprises['development_url'] = $d['site_url'];
$arr_enterprises['development_slug'] = $d['development_slug'];
$arr_enterprises['financing']['entry'] = $d['financing_input'];
$arr_enterprises['financing']['installment'] = $d['financing_installment'];
$arr_enterprises['financing']['founding'] = $d['financing_founding'];
// Verifico se tem os dados do hotsite
if (!empty($d['hotsite_params'])) {
$arr_enterprises['hotsite'] = json_decode($d['hotsite_params']);
}
// Pego as imagens do empreendimento
$arr_medias = array();
$imagB = ORM::for_table('module_imobles_enterprise_imgs')
->raw_query("SELECT s.module_imobles_enterprise_id, s.src, s.resized, s.webp, s.tags, s.unit_type_id, s.description, s.construction_company_id FROM"
. " module_imobles_enterprise_imgs as s"
. " WHERE (s.duplicated IS NULL OR s.duplicated=0) AND type = 'backend' "
. " AND s.module_imobles_enterprise_id IN(" . $d["id"] . ") "
. " AND s.delete_at IS NULL AND s.tags IS NOT NULL ")->find_array();
if (count($imagB) > 0) {
foreach ($imagB as $im) {
$desc_tags = array();
try {
$tagsIm = json_decode($im['tags']);
if ($tagsIm) {
foreach ($tagsIm as $t) {
$desc_tags[] = $arrayTag[$t];
}
}
} catch (Exception $e) {
$desc_tags = "";
}
// Monto o array com os tamanhos alternativos das imagens
$alternatives_sizes = null;
if ($im['resized'] == 1) {
$alternatives_sizes = array("1152x768" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xxl/" . $im['src'],
"840x560" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xlg/" . $im['src'],
"600x400" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/lrg/" . $im['src'],
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/med/" . $im['src'],
"300x200" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/sml/" . $im['src'],
"120x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/xsm/" . $im['src'],
"104x80" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/thumb/" . $im['src']);
}
$webp = false;
if ($im['webp'] == 1) {
$webp = true;
}
$arr_medias[] = array(
"type" => 'IMAGE',
"url" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/" . $im['src'],
"description" => $im['description'],
"tags" => $desc_tags,
"alternatives_sizes" => $alternatives_sizes,
"webp" => $webp);
}
}
// Pego os tipos de unidade do empreendimento
$filterListMediaPriceLIsting = " AND (sub_price2.delete_at IS NULL AND "
. "(sub_price2.crawler_status IS NULL OR sub_price2.crawler_status='ACTIVE')"
. " AND (sub_price2.unavailable IS NULL OR sub_price2.unavailable=0)"
. ")";
if ($d["imobles_client"] == 1) {
$query_resale_listing = " AND sub_l.crawler_type_id = 4 AND sub_l.advertiser_id IS NULL ";
$query_resale_unit = " AND sub.crawler_type_id = 4 ";
$query_resale = " AND u.crawler_type_id = 4 ";
$query_resale .= " AND l.crawler_type_id = 4 AND l.advertiser_id IS NULL AND l.crawler_price > 0 ";
$filterListMediaPriceLIsting .= " AND sub_price2.crawler_type_id = 4 AND sub_price2.advertiser_id IS NULL ";
$selectCount = "NULL as total_listing, "
. " (select count(sub.id) from module_imobles_enterprise_units sub "
. " where sub.module_imobles_enterprise_units_type_id=u.id AND (sub.unavailable IS NULL OR sub.unavailable=0) " . $query_resale_unit . " AND sub.delete_at IS NULL) as disponible_unit";
} else {
$query_resale_listing = " AND ( sub_l.crawler_type_id <> 4 OR sub_l.crawler_type_id IS NULL) AND sub_l.advertiser_id IS NOT NULL AND (sub_l.crawler_businessType <> 'RENTAL' OR sub_l.crawler_businessType IS NULL)";
$query_resale_unit = " AND ( sub.crawler_type_id <> 4 OR sub.crawler_type_id IS NULL)";
// $query_resale = " AND ( u.crawler_type_id <> 4 OR u.crawler_type_id IS NULL)";
$query_resale = " ";
$selectCount = " (select count(sub_l.id) from module_imobles_listings sub_l "
. " where sub_l.unit_type_id=u.id AND (sub_l.unavailable IS NULL OR sub_l.unavailable =0 ) AND sub_l.delete_at IS NULL " . $query_resale_listing . " ) as total_listing, "
. "NULL as disponible_unit";
$filterListMediaPriceLIsting .= "AND (sub_price2.crawler_type_id IS NULL OR sub_price2.crawler_type_id <> 4) AND sub_price2.advertiser_id IS NOT NULL AND (sub_price2.crawler_businessType <> 'RENTAL' OR sub_price2.crawler_businessType IS NULL) ";
$query_resale .= " AND l.crawler_price > 0 AND (l.crawler_type_id IS NULL OR l.crawler_type_id <> 4) AND l.advertiser_id IS NOT NULL AND (l.crawler_businessType <> 'RENTAL' OR l.crawler_businessType IS NULL) ";
}
//BUSCA UNIT_TYPE
$types = ORM::for_table('module_imobles_enterprise_units_type')
->raw_query(" SELECT "
. " min(l.crawler_price) as minValue,"
. " max(l.crawler_price) as 'maxValue',"
. " avg(l.crawler_price) as averageValue ,"
. " u.number_rooms as bedrooms,"
. " u.number_bathroom as bathrooms,"
. " u.area as area,"
. " u.number_suite as suites,"
. " u.number_garage as parking_spaces,"
. " u.id,"
. " u.module_imobles_enterprise_id,"
. " group_concat(l.id) as list_listings,"
. $selectCount
. " FROM module_imobles_enterprise_units_type u"
. " JOIN module_imobles_listings l ON (u.id=l.unit_type_id)"
. " WHERE"
. " (l.unavailable IS NULL OR l.unavailable =0)"
. " AND l.delete_at IS NULL "
. $query_resale
. " and l.crawler_price>=(select avg(sub_price2.crawler_price) from module_imobles_listings sub_price2 WHERE sub_price2.unit_type_id=u.id " . $filterListMediaPriceLIsting . ")*0.6"
. " AND u.module_imobles_enterprise_id IN (" . $d['id'] . ")"
. " AND u.delete_at IS NULL AND u.site_enabled = 1 "
. " GROUP BY u.module_imobles_enterprise_id, u.id, u.number_rooms, u.number_suite, u.area, u.number_garage, u.number_bathroom"
. " ORDER BY u.number_rooms, u.area")
->find_array();
if (count($types) > 0) {
foreach ($types as $u) {
$arr_enterprises['unit_type'] [] = array(
"id" => $u['id'],
"total_listing" => $u['total_listing'],
"unit_available" => $u['disponible_unit'],
"min_value" => number_format($u['minValue'], 2, ".", ""),
"average_value" => number_format($u['averageValue'], 2, ".", ""),
"max_value" => number_format($u['maxValue'], 2, ".", ""),
"bedrooms" => $u['bedrooms'],
"bathrooms" => $u['bathrooms'],
"area" => $u['area'],
"suites" => $u['suites'],
"parking_spaces" => $u['parking_spaces']
);
}
}
$arr_enterprises["midias"] = $arr_medias;
$dataResults['developments'][] = $arr_enterprises;
}
}
}
$output = array(
"results" => ($dataResults),
);
return $output;
}
}