| Server IP : 162.214.74.102 / Your IP : 216.73.217.114 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/leo/application/plugins/module_imobles/controllers/ |
Upload File : |
<?php
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
include_once "Controller.php";
include_once "CrawlerController.php";
include_once __DIR__ . "/../helpers/CrawlerHelper.php";
include_once __DIR__ . "/../helpers/api/WiserLeadsHelper.php";
include_once __DIR__ . "/../helpers/hubspot/Hubspot.php";
include_once __DIR__ . "/../helpers/api/MainHelper.php";
include_once __DIR__ . "/../helpers/api/CRMScenariosHelper.php";
include_once __DIR__ . "/../helpers/api/CRMGoalsHelper.php";
include_once __DIR__ . "/../helpers/api/CRMJourneyTasksHelper.php";
include_once __DIR__ . "/../helpers/api/CRMHelper.php";
include_once __DIR__ . "/../helpers/api/GPTBrokerHelper.php";
class ApiController extends Controller {
protected $id;
protected $model;
protected $crawlerController;
protected $crawlerHelper;
protected $hubspotHelper;
protected $mainHelper;
protected $crmScenariosHelper;
protected $crmGoalsHelper;
protected $crmJourneyTasksHelper;
protected $crmHelper;
protected $gptBrokerHelper;
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();
$this->hubspotHelper = new hubspotHelper();
$this->mainHelper = new MainHelper();
$this->crmScenariosHelper = new CRMScenariosHelper();
$this->crmGoalsHelper = new CRMGoalsHelper();
$this->crmJourneyTasksHelper = new CRMJourneyTasksHelper();
$this->crmHelper = new CRMHelper();
$this->gptBrokerHelper = new GPTBrokerHelper();
}
public function searchDevelopmentsNew() {
return $this->mainHelper->searchDevelopments();
}
public function developmentDetailsNew() {
return $this->mainHelper->developmentDetails();
}
public function searchDevelopmentsSimilarNew() {
return $this->mainHelper->searchDevelopmentsSimilar();
}
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) {
// TODO: verificar a necessidade desse verificação
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'];
}
}
} else {
$output = array(
"total_count" => count($dataResults),
"results" => array_values($dataResults),
);
return $output;
}
if(!isset($filter['pre_launch']) || $filter['pre_launch'] === false){
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'])) {
$locations_aux = array();
$locations_aux['address_neighborhood'] = $develop['results']['address']['neighborhood'];
$locations_aux['address_city'] = $develop['results']['address']['city'];
$locations_aux['address_state'] = $develop['results']['address']['state_acronym'];
$filter['locations'][] = $locations_aux;
}
$filter['development_ids_not_in'][] = $id;
$results = $this->resultDevelopments($filter);
$results2 = array();
$results3 = array();
// $size = $results['size'];
if (!isset($results['list_size']) || $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'][0]['address_neighborhood']);
$results2 = $this->resultDevelopments($filter);
// if(isset($filter['pre_launch']) && $filter['pre_launch'] === true){
// if (!isset($results2['list_size']) || $results2['list_size'] < $filter['size']) {
// foreach ($results2['results'] as $r) {
// $filter['development_ids_not_in'][] = $r['id'];
// }
// unset($filter['pre_launch']);
// $filter['size'] = $results2['size'] - $results2['list_size'];
// $results3 = $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;
}
}
if (is_array(@$results3['results'])) {
foreach ($results3['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) {
// TODO: ajuste para excluir REVENDA do resultado de busca
$filter['is_new'] = true;
$where = null;
$search_queries = $this->searchWhereJoinDevelopments($filter);
if(isset($filter['pre_launch']) && $filter['pre_launch'] === true){
if(!isset($filter['order_by'])){
$filter['order_by'] = array();
}
array_unshift($filter['order_by'],array("init_sales" => "DESC"));
}
// var_dump($search_queries);exit;
extract($search_queries);
$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)';
$join .= ' LEFT JOIN module_imobles_enterprise_units_type sub_u ON (sub_u.module_imobles_enterprise_id = ent.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 .= ', sub_u.price_min ' . $val;
$orderTypeUnit = " u.price_min " . $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;
case 'init_sales':
$order .= ', ent. pre_launch DESC, ent.init_sales ' . $val;
break;
}
}
}
if (!empty($order)) {
$order = substr($order, 1);
} else {
$order = 'ent.release_date DESC';
}
} else {
$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 por Pré-Lançamento
if (isset($filter['pre_launch']) && $filter['pre_launch'] === true) {
$now = new DateTime('NOW');
$now->modify('-3 months');
$date_aux = $now->format('Y-m-d');
// var_dump($date_aux);exit;
$where .= " AND (ent.init_sales >= '".$date_aux."' OR ent.has_no_ri = 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 . ")";
// $sql .= " AND EXISTS (select sut.id from module_imobles_enterprise_units_type sut "
// ." where sut.module_imobles_enterprise_id=ent.id AND sut.site_enabled = 1 "
// ." AND (IF ent.imobles_client = 1, sut.available_units >= 1, sut.total_listings >=1)"
// ." AND sut.delete_at IS NULL " . $list . ")";
$sql .= " AND ent.searchable = 1 AND sub_u.price_min IS NOT NULL ";
$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.has_no_ri, ent.price_type, 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, ent.pre_launch "
. $sql . " GROUP BY id ORDER BY " . $order . " " . $limit;
// echo $query;exit;
$dat = ORM::for_table('module_imobles_enterprise_towers')
->raw_query($query)->find_array();
// var_dump(count($dat));exit;
$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']]['has_no_ri'] = $d['has_no_ri'];
$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'];
if(!empty($d['price_type']))
{
$dataResults[$d['id']]['development_price_type'] = $d['price_type'];
} else {
$dataResults[$d['id']]['development_price_type'] = null;
}
if($d['pre_launch']== 1)
{
$dataResults[$d['id']]['pre_launch'] = true;
} else {
$dataResults[$d['id']]['pre_launch'] = false;
}
// Incluo os dados do hotsite
if (!empty($d['hotsite_params'])) {
$hotsite_json = json_decode($d['hotsite_params']);
if(isset($hotsite_json->development_hotsite_enabled))
{
$dataResults[$d['id']]['hotsite'] = array("development_hotsite_enabled" => $hotsite_json->development_hotsite_enabled);
}
if(isset($hotsite_json->card_description))
{
$dataResults[$d['id']]['card_description'] = $hotsite_json->card_description;
}
}
// 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 (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';
}
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.sorder, s.module_imobles_enterprise_id, s.src, s.alt_text, 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();
$types = ORM::for_table('module_imobles_enterprise_units_type')
->raw_query(" SELECT "
. " u.price_min as minValue,"
. " u.price_max as 'maxValue',"
. " u.price_avg as averageValue ,"
. " u.total_listings as total_listing ,"
. " u.available_units as disponible_unit ,"
. " 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,"
. " u.promotion,"
. " u.standard_price,"
. " u.desc,"
. " ent.imobles_client "
. " FROM module_imobles_enterprise_units_type u"
. " JOIN module_imobles_enterprise as ent ON (u.module_imobles_enterprise_id=ent.id)"
. " WHERE"
. " u.module_imobles_enterprise_id IN (" . substr($ent, 1) . ") " . $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']);
if(!empty($arr_tags_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'];
}
}
// 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'],
"alt_text" => $im['alt_text'],
"order" => (!empty($im['sorder'])?$im['sorder']:null),
"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,
"is_offer" => $u['promotion']==1?true:false,
);
if ($u['promotion']==1){
$dataArray["description"] = $u['desc'];
$dataArray['standard_price'] = number_format($u["standard_price"], 2, ".", "");
}
$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']) < 10)
{
$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_gallery_imgs[$im['module_imobles_enterprise_id']]) && count($arr_enterprise_gallery_imgs[$im['module_imobles_enterprise_id']]) >= 5)
{
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']);
$alternatives_sizes = array(
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/enterprise/" . $im['module_imobles_enterprise_id'] . "/images/med/" . $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'],
"alt_text" => $im['alt_text'],
"order" => (!empty($im['sorder'])?$im['sorder']:null),
"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";
$query = "SELECT SUM(total_listings) as total_listings, SUM(available_units) as available_units, min(price_min) as price_from
FROM module_imobles_enterprise_units_type
where site_enabled = 1
AND delete_at IS null
AND module_imobles_enterprise_id IN (".$arr_enterprise_ids.")";
// echo $query;exit;
$listings_aux = ORM::for_table('module_imobles_enterprise_towers')
->raw_query($query)->find_one();
$total_listings_aux = $listings_aux->total_listings;
$total_units_aux = $listings_aux->available_units;
$prices_from = $listings_aux->price_from;
// // 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;
$prices_from = 0;
}
// Verifico se é NOINDEX
$no_index = true;
if (isset($filter['url_search']) && !empty($filter['url_search'])) {
$url_aux = $filter['url_search'];
$url_aux = explode('?', $url_aux);
$url_aux = $url_aux[0];
$url = ORM::for_table("module_imobles_dynamic_urls")->where("url", $url_aux)->find_one();
if(isset($url->id) && $url->id > 0){
$no_index = false;
}
}
$totalresults = count($dataResults);
// Pego os Amanities para o filtro
$output = array(
"total_count" => $total_count,
"total_listings" => $total_listings_aux,
"total_units" => $total_units_aux,
"price_from" => $prices_from,
"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),
"tag_noindex" => $no_index
);
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 por Grupos de Amenities
$development_aminities_ids = array();
$unit_type_aminities_ids = array();
$unit_aminities_ids = array();
if (isset($filter['amenities_ids']) && $filter['amenities_ids'] != '') {
foreach($filter['amenities_ids'] as $group_id){
$group = ORM::for_table('module_imobles_enterprise_group_amenities')->find_one($group_id);
$amenities_ids = json_decode($group->amenities_ids);
if(!empty($amenities_ids->development_amenities_ids)){
$development_aminities_ids = array_merge($development_aminities_ids, $amenities_ids->development_amenities_ids);
}
if(!empty($amenities_ids->unit_type_amenities_ids)){
$unit_type_aminities_ids = array_merge($unit_type_aminities_ids, $amenities_ids->unit_type_amenities_ids);
}
if(!empty($amenities_ids->unit_amenities_ids)){
$unit_aminities_ids = array_merge($unit_aminities_ids, $amenities_ids->unit_amenities_ids);
}
}
// var_dump($development_aminities_ids);exit;
$a = implode("','", $development_aminities_ids);
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 . "')) ";
}
$b = implode("','", $unit_type_aminities_ids);
if (!empty($b)) {
$where .= " AND EXISTS (select sub.module_imobles_enterprise_units_type_id
from module_imobles_enterprise_units_type_amenities sub
where sub.module_imobles_enterprise_units_type_id=sub_u.id
AND sub.module_imobles_type_units_amenities_id IN ('" . $b . "')) ";
}
$c = implode("','", $unit_aminities_ids);
if (!empty($c)) {
// $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 ('" . $c . "')) ";
}
}
// 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 ent.release_date >= '" . $filter['release_date_start'] . "' ";
}
if (!empty($filter['release_date_end'])) {
$where .= "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_number'])) {
$address_number .= "OR ent.address_number = '" . ($d['address_number']) . "' "
. "";
}
if (!empty($d['address_state'])) {
$state .= "OR st.uf_state = '" . ($d['address_state']) . "' "
. "";
}
if (!empty($d['address_city'])) {
$city .= "OR c.city_name = '" . ($d['address_city']) . "' ";
}
if (!empty($d['address_log'])) {
$log .= "OR ent.address_log_sanitized = '" . htmlentities(sanitizaText($d['address_log'])) . "' ";
} else {
if (!empty($d['address_neighborhood'])) {
$address_neightborhood .= "OR ent.address_neighborhood_sanitized = '" . htmlentities(sanitizaText($d['address_neighborhood'])) . "' ";
}
}
if (!empty($filter['address_zip'])) {
$zip .= "OR ent.address_zip LIKE '%" . $filter['address_zip'] . "%' "
. "";
}
}
// var_dump($address_neightborhood);exit;
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))";
}
// Pega somente os tipos de unidade que foram tratadas pelo UnitTypeUpdadte
// TODO: Verificar
$whereunit .= " AND (u.price_min IS NOT NULL) ";
// 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['offers'])) {
$subunit .= " AND sub_u.promotion = 1 ";
$whereunit .= " AND u.promotion = 1 ";
}
if (!empty($filter['price_min'])) {
// $subunit .= " AND sub_l.crawler_price>=" . htmlentities(($filter['price_min'])) . " ";
$subunit .= " AND sub_u.price_min >= " . htmlentities(($filter['price_min'])) . " ";
// $whereunit .= " AND l.crawler_price>0 AND l.crawler_price>=" . htmlentities(($filter['price_min'])) . " ";
$whereunit .= " AND u.price_min > 0 AND u.price_min >= " . htmlentities(($filter['price_min'])) . " ";
}
if (!empty($filter['price_max'])) {
// $subunit .= " AND sub_l.crawler_price<=" . htmlentities(($filter['price_max'])) . " ";
$subunit .= " AND sub_u.price_min <= " . htmlentities(($filter['price_max'])) . " ";
// $whereunit .= " AND l.crawler_price>0 AND l.crawler_price<=" . htmlentities(($filter['price_max'])) . " ";
$whereunit .= " AND u.price_min > 0 AND u.price_min <= " . 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'";
}
}
// TODO: verificar se é possível usar o enterprise->searchable
// $where .= " AND EXISTS (Select sub_u.id from module_imobles_enterprise_units_type sub_u"
// . $joinSubunit . " "
// . "WHERE sub_u.module_imobles_enterprise_id=ent.id "
// . "AND sub_u.delete_at IS NULL AND sub_u.site_enabled = 1 AND sub_u.total_listings IS NOT NULL AND sub_u.available_units IS NOT NULL " . @$subunit2 . " " . @$subunit . "" . " limit 1"
// . ")";
$where .= " AND sub_u.delete_at IS NULL AND sub_u.site_enabled = 1 AND sub_u.total_listings IS NOT NULL AND sub_u.available_units IS NOT NULL " . @$subunit . " ";
} 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, "
. " 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.price_type, ent.latitude, ent.longitude, ent.slug as development_slug"
. ", ent.google_place_id, ent.google_rating, ent.google_json, ent.google_rating, ent.link_google, ent.youtube_video"
. ", 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 "
. ", n.params as neighborhood_params, n.id as neighborhood_id, n.google_details as neighborhood_google_place_details, ent.pre_launch, ent.meeting_date, ent.has_no_ri, ent.youtube_json ";
$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)'
. ' 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)'
. ' LEFT JOIN module_imobles_neighborhoods n ON ent.address_neighborhood_sanitized = n.sanitized_name AND ent.address_city_id = n.city_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.'"';
}
// TODO: ajuste para excluir REVENDA do site
$where .= ' AND imobles_client = 1 ';
$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['has_no_ri'] = $d['has_no_ri'];
$dataResults['youtube_json'] = (!empty($d['youtube_json'])?json_decode($d['youtube_json']):null);
$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.alt_text, 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 IN ('[\"23\"]', '[\"2\"]') ")->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'],
"alt_text" => $im['alt_text'],
"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'];
if(!empty($d['price_type']))
{
$dataResults['development_price_type'] = $d['price_type'];
} else {
$dataResults['development_price_type'] = null;
}
// 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'];
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'])));
}
if (!empty($d['google_json'])) {
$google_json = json_decode($d['google_json']);
$dataResults['google_reviews'] = @$google_json->reviews;
} else {
$dataResults['google_reviews'] = null;
}
if (!empty($d['google_rating'])) {
$dataResults['google_rating'] = $d['google_rating'];
} else {
$dataResults['google_rating'] = null;
}
$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'];
$hotsiteTitle = '';
$hotsiteText = '';
if(!empty($d['neighborhood_params'])){
$neighborhoodParams = json_decode($d['neighborhood_params']);
$hotsiteTitle = $neighborhoodParams->hotsite_title;
$hotsiteText = $neighborhoodParams->hotsite_text;
$hotsiteTitle = str_replace('{{enterprise_name}}', $d['development'], $hotsiteTitle);
$hotsiteText = str_replace('{{enterprise_name}}', $d['development'], $hotsiteText);
}
// Pego a imagem do bairro
$neighborhood_images_arr = array();
if(!empty($d['neighborhood_id'])){
$neighborhood_images = ORM::for_table('module_imobles_enterprise_imgs')
->raw_query("SELECT s.module_imobles_enterprise_id, s.src, s.alt_text, s.resized, s.webp, s.tags, s.unit_type_id, s.description, s.neighborhood_id FROM"
. " module_imobles_enterprise_imgs as s"
. " WHERE s.neighborhood_id = ".$d['neighborhood_id']
. " AND s.delete_at IS NULL")->find_array();
if (count($neighborhood_images) > 0) {
foreach ($neighborhood_images 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/neighborhood/" . $im['neighborhood_id'] . "/images/xxl/" . $im['src'],
"840x560" => APP_URL . "/application/plugins/module_imobles/uploads/neighborhood/" . $im['neighborhood_id'] . "/images/xlg/" . $im['src'],
"600x400" => APP_URL . "/application/plugins/module_imobles/uploads/neighborhood/" . $im['neighborhood_id'] . "/images/lrg/" . $im['src'],
"450x300" => APP_URL . "/application/plugins/module_imobles/uploads/neighborhood/" . $im['neighborhood_id'] . "/images/med/" . $im['src'],
"300x200" => APP_URL . "/application/plugins/module_imobles/uploads/neighborhood/" . $im['neighborhood_id'] . "/images/sml/" . $im['src'],
"120x80" => APP_URL . "/application/plugins/module_imobles/uploads/neighborhood/" . $im['neighborhood_id'] . "/images/xsm/" . $im['src']);
if(in_array("DEVELOPMENT_GALLERY_IMGS", $desc_tags))
{
$alternatives_sizes["104x80"] = APP_URL . "/application/plugins/module_imobles/uploads/neighborhood/" . $im['neighborhood_id'] . "/images/thumb/" . $im['src'];
}
}
$webp = false;
if ($im['webp'] == 1) {
$webp = true;
}
$neighborhood_images_arr[] = array(
"type" => 'IMAGE',
"url" => APP_URL . "/application/plugins/module_imobles/uploads/neighborhood/" . $im['neighborhood_id'] . "/images/" . $im['src'],
"description" => $im['description'],
"alt_text" => $im['alt_text'],
"tags" => $desc_tags,
"alternatives_sizes" => $alternatives_sizes,
"webp" => $webp);
}
}
}
$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'],
'hotsite_title' => $hotsiteTitle,
'hotsite_text' => $hotsiteText,
'neighborhood_google_place_details' => json_decode($d['neighborhood_google_place_details']),
'neighborhood_images' => $neighborhood_images_arr
);
$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.sorder, s.module_imobles_enterprise_id, s.src, s.alt_text, 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 "
)->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) {
if(isset($arrayTag[$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'],
"alt_text" => $im['alt_text'],
"tags" => $desc_tags,
"alternatives_sizes" => $alternatives_sizes,
"order" => (!empty($im['sorder'])?$im['sorder']:null),
"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 "
// . " AND (un.unavailable IS NULL OR un.unavailable = 0) "
// . $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();
$types = ORM::for_table('module_imobles_enterprise_units_type')
->raw_query(" SELECT "
. " u.price_min as minValue,"
. " u.price_max as 'maxValue',"
. " u.price_avg as averageValue ,"
. " u.total_listings as total_listing ,"
. " u.available_units as disponible_unit ,"
. " 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.imobles_indicates,"
. " u.module_imobles_enterprise_id,"
. " u.promotion,"
. " u.standard_price,"
. " u.desc,"
. " ent.imobles_client, "
. " SUM(tow.total_units) total_development_units "
. " FROM module_imobles_enterprise_units_type u"
. " JOIN module_imobles_enterprise as ent ON (u.module_imobles_enterprise_id=ent.id) "
. " JOIN module_imobles_enterprise_towers as tow ON ent.id = tow.module_imobles_enterprise_id "
. " WHERE"
. " u.module_imobles_enterprise_id = ".$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.price_min")
->find_array();
$total_units = 0;
$total_development_units = null;
if (count($types) > 0) {
foreach ($types as $u) {
if($total_development_units === null){
$total_development_units = $u['total_development_units'];
}
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']);
if(count($arr_tags_id) == 0)
{
continue;
}
$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'],
"alt_text" => $im['alt_text'],
"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")
->select_expr("sub.icon")
->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"]);
}
}
}
// TODO: recalcular esses valores chumbados para nova ficha do empreendimento.
$financial_information = array(
"rent" => 5000.00,
"itbi" => 500.55,
"notary_fees" => 5000.00,
"condo_fee" => 350.00,
"iptu" => 580.00,
"imobles_index" => -20.00
);
$dataArray = 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,
"financial_information" => $financial_information,
"highlighted" => $u['imobles_indicates']==1?true:false,
"is_offer" => $u['promotion']==1?true:false,
);
if ($u['promotion']==1){
$dataArray["description"] = $u['desc'];
$dataArray['standard_price'] = number_format($u["standard_price"], 2, ".", "");
}
$dataResults['unit_type'] [] = $dataArray;
$total_units += $u['disponible_unit'];
}
}
$amenities = ORM::for_table('module_imobles_enterprise_entreprise_amenities')
->table_alias('s')
->select("sub.name")
->select_expr("sub.type")
->select_expr("sub.icon")
->join('module_imobles_enterprise_amenities', 's.module_imobles_enterprise_amenities_id = sub.id', 'sub')
->where_not_in('sub.id', [311])
->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', 'icon')->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;
}
if (!empty($d['youtube_video'])) {
$dataResults['video_youtube'] = $d['youtube_video'];
} else {
$dataResults['video_youtube'] = null;
}
// TODO: recalcular esses valores chumbados para nova ficha do empreendimento.
$dataResults['price_variation'] = "down";
// Pego o total de unidades disponĩveis
if($total_development_units > 0){
$dataResults['total_units'] = $total_development_units;
} else {
$dataResults['total_units'] = null;
}
// Data de lançamento do empreendimento
$dataResults['meeting_date'] = $d['meeting_date'];
// Pego a data da última atualização da tabela de preço
$query = "SELECT
d.created_at, d.issued_date
FROM
module_imobles_docs d
LEFT JOIN
module_imobles_docs_category dc ON d.module_imobles_docs_category_id = dc.id
WHERE
d.module_imobles_enterprise_id = ".$d['id']."
AND d.delete_at IS NULL
AND d.module_imobles_docs_category_id
AND dc.name IN ('TABELA DE PREÇO')
ORDER BY d.id DESC
LIMIT 1";
$docs_aux = ORM::for_table("module_imobles_docs_category")
->raw_query($query)->find_one();
if(!empty($docs_aux->issued_date)){
$expiration_date = strtotime($docs_aux->issued_date);
$expiration_date = date('Y-m-d',$expiration_date);
$expiration_date = new DateTime($expiration_date);
$now = new DateTime('NOW');
$diff = $expiration_date->diff($now)->days;
if($diff <= 90){
$dataResults['price_table_emission_date'] = $expiration_date->format('Y-m-d');
} else {
$dataResults['price_table_emission_date'] = null;
// Salvo no log o erro na tabela de preços do empreendimento
$data = array(
"development_id" => $d['id'],
"development_url" => $d['site_url'],
"error_type" => "documents",
"erro_msg" => "Tabela de preço expirada há mais de 60 dias");
$log = ORM::for_table('module_imobles_logs')->create();
$log->type = 'development_error';
$log->params = json_encode($data);
$log->save();
}
} else {
if(!empty($docs_aux->created_at)){
$expiration_date = strtotime($docs_aux->created_at);
$expiration_date = date('Y-m-d',$expiration_date);
$expiration_date = new DateTime($expiration_date);
$now = new DateTime('NOW');
$diff = $expiration_date->diff($now)->days;
if($diff <= 90){
$dataResults['price_table_emission_date'] = $expiration_date->format('Y-m-d');
} else {
$dataResults['price_table_emission_date'] = null;
// Salvo no log o erro na tabela de preços do empreendimento
$data = array(
"development_id" => $d['id'],
"development_url" => $d['site_url'],
"error_type" => "documents",
"erro_msg" => "Tabela de preço expirada há mais de 60 dias");
$log = ORM::for_table('module_imobles_logs')->create();
$log->type = 'development_error';
$log->params = json_encode($data);
$log->save();
}
} else {
$dataResults['price_table_emission_date'] = null;
}
}
if($d['pre_launch'] == 1){
$dataResults['pre_launch'] = true;
} else {
$dataResults['pre_launch'] = false;
}
}
}
$output = array(
"results" => ($dataResults),
);
return $output;
}
/**
* 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");
$events = array();
$events_aux = json_decode($jsonStr, true);
if(!empty($events_aux['eventId'])){
$events[] = $events_aux;
} else {
$events = $events_aux;
}
foreach($events as $event){
if(isset($event['subscriptionType'])){
$subscriptionType = $event['subscriptionType'];
switch($subscriptionType){
case 'deal.propertyChange':
if($event['propertyName'] == 'dealtype'){
$hs_helper = new WiserLeadsHelper();
$hs_helper->updateLead($event['objectId'],$event['propertyValue']);
}
// Fazer aqui os tratamentos das automações do MyGPT
if($event['propertyName'] == 'dealstage' && $event['propertyValue'] == '81524401'){
$return = $this->hubspotHelper->webHookNewDeal($event['objectId']);
// if(preg_match('(\@SYNC\@)i',$event['propertyValue'])){
// $name = preg_replace('(\@SYNC\@)i', '', $event['propertyValue']);
// $data = array("dealname" => trim($name));
// $this->hubspotHelper->hubspotUpdateDealProperties($event['objectId'], $data);
// $return = $this->hubspotHelper->webHookNewDeal($event['objectId']);
// }
} else {
$this->hubspotHelper->hubspotImportOpenDeal($event['objectId']);
}
break;
case 'deal.creation':
// Fazer aqui os tratamentos das automações do MyGPT
// $this->hubspotHelper->webHookNewDeal($event['objectId']);
break;
case 'contact.creation':
if (isset($event['objectId'])) {
$client = ORM::for_table('module_imobles_hubspot_contacts')->where('hs_object_id', $event['objectId'])->find_one();
if(isset($client->crm_account_id)){
$client_id = $client->crm_account_id;
$output = array(
"client_id" => $client_id,
"hs_object_id" => $event['objectId']
);
return $output = array("results" => $output);
} else {
// Pego os dados do Cliente no HubSpot
sleep(5);
$url = "https://api.hubapi.com/crm/v3/objects/contacts/"
. $event['objectId']
. "?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,telefone_para_campanha_de_whatsapp";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"authorization: Bearer pat-na1-9cf5e994-25a2-4d6e-90f8-3a175c4b3056"
),
));
$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);
$name = mb_strtoupper($result->properties->firstname . " " . $result->properties->lastname);
$name = trim($name);
// Verifico se o usuário já está cadastrado
$client = ORM::for_table("crm_accounts")->where('phone', $phone)->find_one();
if (!isset($client->id)) {
$client = ORM::for_table("crm_accounts")->create();
$client->account = $name;
$client->fname = $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->save();
$client_id = $client->id();
// 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 myside.com.br!🌃";
} 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 myside.com.br!🌃";
// }
// 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 myside.com.br!🌃";
// }
// }
}
}
// 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;
$updateHs = $this->hubspotHelper->updateSinglePropertie($event['objectId'], 'telefone_para_campanha_de_whatsapp', $phone);
$output = array(
"client_id" => $client_id
);
return $output = array("results" => $output);
}
// Faço o merge dos contatos com mesmo phone no hubspot
if(!empty($client_id)){
// Faço o update do Telefone Sanitizado do Hubpost
$updateHs = $this->hubspotHelper->updateSinglePropertie($event['objectId'], 'telefone_para_campanha_de_whatsapp', $client->phone);
if(isset($updateHs['error']) && $updateHs['error'] === true){
$params = array('type' => 'error', 'msg' => 'hubspotHelper updateSinglePropertie error', 'return' => $updateHs);
$lesdConParams = ORM::for_table('module_imobles_logs')->create();
$lesdConParams->created_at = date('Y-m-d H:i:s');
$lesdConParams->type = 'hs_updateSinglePropertie_error';
$lesdConParams->params = json_encode($params);
$lesdConParams->save();
}
// sleep(3);
$data = array('input_data' => ['client_details' => array('first_name' => $client->account)]);
$data = json_decode(json_encode($data));
$syncHs = $this->hubspotHelper->hubspotSyncLead($client_id, $data, $this->crawlerController);
if(isset($syncHs['success']) && $syncHs['success'] === false){
$params = array('crm_account_id' => $client->id, 'msg' => 'hubspotHelper hubspotSyncLead error', 'return' => $syncHs);
$lesdConParams = ORM::for_table('module_imobles_logs')->create();
$lesdConParams->created_at = date('Y-m-d H:i:s');
$lesdConParams->type = 'hubspot_contact_sync_error';
$lesdConParams->params = json_encode($params);
$lesdConParams->save();
}
$output = array(
"client_id" => $client_id
);
} else {
$output = array(
"error" => true,
"msg" => 'contato não encontrado'
);
}
} else {
$output = array(
"error" => true,
"msg" => 'PHONE NÃO REGISTRADO NO HUBSPOT'
);
Notify_Email::_send('Leonardo Lopes', 'leonardo@myside.com.br', 'Hubspot Webhook | erro sync hubspot', $jsonStr);
}
return $output = array("results" => $output);
}
}
break;
}
}
}
}
/**
* 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;
$location_city_ids = array();
if(isset($data['locations']))
{
foreach($data['locations'] as $locations)
{
if(isset($locations["city_id"]))
{
$location_city_ids[]=$locations["city_id"];
}
}
}
// 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.site_enabled = 1");
$address_neightborhood->where_raw("s.imobles_client = 1");
$address_neightborhood->where_any_is(array(array("s.address_neighborhood_sanitized" => '%' . sanitizaText($term) . '%')), 'like');
if(!empty($location_city_ids))
{
$address_neightborhood->where_in("address_city_id",$location_city_ids);
}
$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->where_raw("s.imobles_client = 1");
if(!empty($location_city_ids))
{
$developments->where_in("address_city_id",$location_city_ids);
}
$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)
);
}
// Faço a procura por rua
if(preg_match('/^(rua|avenida|av|alameda)/i',$term)){
$address_neightborhood = ORM::for_table('module_imobles_enterprise')
->table_alias('s')
->select_many_expr("s.address_log, s.address_neightborhood")
->group_by_expr("s.address_log")
->order_by_asc("s.address_log");
$address_neightborhood->where_raw("s.delete_at IS NULL");
$address_neightborhood->where_raw("s.site_enabled = 1");
$address_neightborhood->where_raw("s.imobles_client = 1");
$address_neightborhood->where_any_is(array(array("s.address_log" => '%' . $term . '%')), 'like');
if(!empty($location_city_ids))
{
$address_neightborhood->where_in("address_city_id",$location_city_ids);
}
$address_neightborhood->limit(10);
$address_neightborhoods = $address_neightborhood->find_many();
if ($address_neightborhoods) {
foreach ($address_neightborhoods as $p) {
$data_aux[] = array(
'type' => "street",
'text' => $p->address_log.' | '.$p->address_neightborhood,
'street_details' => array("street" => $p->address_log,
"neighborhood" => $p->address_neightborhood)
);
}
}
$count_neighborhood = count($address_neightborhoods);
}
// 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")
->select_many('id', 'name', 'address_city_id', 'address_state_id', 'site_url', 'youtube_json', 'site_url_canonical', 'updated_at')
->where('site_enabled', 1)
->where('imobles_client', 1) // TODO: ajuste para retirar os USADOS do site
->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://myside.com.br/".$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://myside.com.br/lancamentos/" . $sanitize_name . "/" . $d->id;
// $dataResults[$d['id']]['hotsite_url'] = $hotsite_url;
// }
// }
$dataResults[$d['id']]['url'] = $d->site_url;
$dataResults[$d['id']]['video_details'] = $d->youtube_json;
$dataResults[$d['id']]['url_canonical'] = null;
$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) {
$updated_time = new DateTime($dyn->updated_at);
$now = new DateTime("NOW");
$diff = $updated_time->diff($now)->days;
// var_dump($updated_time = $now->format("Y-m-d H:i:s"));continue;
switch($dyn->update_frequency){
case "DAILY":
if($diff >= 1){
$updated_time = $now->format("Y-m-d H:i:s");
$dyn->updated_at = $updated_time;
$dyn->save();
}
break;
case "WEEKLY":
if($diff >= 7){
$updated_time = $now->format("Y-m-d H:i:s");
$dyn->updated_at = $updated_time;
$dyn->save();
}
break;
case "MONTHLY":
if($diff >= 28){
$updated_time = $now->format("Y-m-d H:i:s");
$dyn->updated_at = $updated_time;
$dyn->save();
}
break;
default:
$updated_time = $now->format("Y-m-d H:i:s");
$dyn->updated_at = $updated_time;
$dyn->save();
break;
}
$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) {
// $developments = ORM::for_table('module_imobles_enterprise')
// ->where('module_imobles_company_construction_id', $comp->id)
// ->where('site_enabled', 1)
// ->where_null('delete_at')
// ->limit(1)
// ->find_many();
// if(empty($developments[0]))
// {
// continue;
// }
if(empty($comp->site_url))
{
continue;
// $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://myside.com.br/".$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();
// }
}
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))
{
// $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;
$comp_slug = explode("apartamentos-venda-", $comp->slug);
$comp_slug = $comp_slug[1];
$comp_url = "https://myside.com.br/".$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.alt_text, 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 IN('[\"23\"]','[\"2\"]','[\"24\"]','[\"25\"]','[\"16\"]') ")->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'],
"alt_text" => $im['alt_text'],
"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.price_type, 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;
$order = ' ORDER BY release_date DESC';
$enterprises = ORM::for_table('module_imobles_enterprise')
->raw_query($select . $from . $where . $order)->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'],
'development_price_type' => $d['price_type']);
$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.alt_text, 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 (tags LIKE '%5%' OR tags LIKE '%16%') "
. " 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'],
"alt_text" => $im['alt_text'],
"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
u.price_min AS minValue,
u.price_max AS 'maxValue',
u.price_avg 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,
u.total_listings AS total_listing,
u.available_units AS disponible_unit
FROM
module_imobles_enterprise_units_type u
WHERE
u.crawler_type_id = 4
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.price_min, 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;
}
public function getAmenitiesList() {
$categories = ORM::for_table("module_imobles_enterprise_category_amenities")
->where_null("delete_at")
->order_by_asc("sorder")
->find_many();
$data = array();
foreach ($categories as $category) {
$groups = ORM::for_table("module_imobles_enterprise_group_amenities")
->select_many_expr('id, name')
->where_null("delete_at")
->where('category_id', $category->id)
->order_by_asc("sorder")
->find_many();
$options = array();
foreach ($groups as $group) {
$options[] = array(
"title" => $group->name,
"id" => $group->id
);
}
$data[] = array(
"category" => $category->name,
"options" => $options,
"city_ids" => json_decode($category->city_ids)
);
}
$response = array(
"total_count" => count($categories),
"results" => array_values($data),
);
return $response;
}
public function slugRedirect() {
$jsonStr = file_get_contents("php://input");
$data = json_decode($jsonStr, true);
$dataResults = array();
$data_aux = array();
$term = $data['slug'];
$data = ORM::for_table('module_imobles_slug_redirect')
->where('url_origin','https://myside.com.br/'.$term)
->where_null('deleted_at')
->find_one();
if(isset($data->title)){
$results = array(
"url" => $data->url_final,
"title" => $data->title,
"description" => $data->description,
"h1" => $data->h1
);
} else {
$results = array();
}
$response = array(
"results" => $results,
);
return $response;
}
public function crmScenariosList(){
return $this->crmScenariosHelper->listScenarios();
}
public function crmScenariosCreateComment(){
return $this->crmScenariosHelper->createComment();
}
public function crmScenariosEditComment(){
return $this->crmScenariosHelper->editComment();
}
public function crmScenariosDeleteComment(){
return $this->crmScenariosHelper->deleteComment();
}
public function crmScenariosTipologyCreateComment(){
return $this->crmScenariosHelper->createCommentTipology();
}
public function crmScenariosTipologyEditComment(){
return $this->crmScenariosHelper->editCommentTipology();
}
public function crmScenariosTipologyDeleteComment(){
return $this->crmScenariosHelper->deleteCommentTipology();
}
public function crmScenariosApprove(){
return $this->crmScenariosHelper->approveScenario();
}
public function crmScenariosApproveTipology(){
return $this->crmScenariosHelper->approveScenarioTipology();
}
public function crmGoalsList(){
return $this->crmGoalsHelper->listGoals();
}
public function crmGoalsCreateComment(){
return $this->crmGoalsHelper->createComment();
}
public function crmGoalsEditComment(){
return $this->crmGoalsHelper->editComment();
}
public function crmGoalsDeleteComment(){
return $this->crmGoalsHelper->deleteComment();
}
public function crmJourneyTasksList(){
return $this->crmJourneyTasksHelper->listJourneyTasks();
}
public function crmMyWalletPropsList(){
return $this->crmHelper->listMywalletPropsApi();
}
public function crmLogin(){
return $this->crmHelper->login();
}
public function gptBrokerRealtorLogin(){
return $this->gptBrokerHelper->realtorLogin();
}
public function gptBrokerSearchClient(){
return $this->gptBrokerHelper->searchClient();
}
public function gptBrokerSaveTask(){
return $this->gptBrokerHelper->saveTask();
}
public function gptBrokerSaveNote(){
return $this->gptBrokerHelper->saveNote();
}
}