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/public_html/lrsys_apps/leo/application/plugins/module_imobles/helpers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

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

include_once __DIR__ . "/../helpers/console/UnitTypeUpdate.php";
include_once __DIR__ . "/../models/DocsModel.php";
include_once __DIR__ . "/../models/EnterprisesModel.php";

class DWVHelper {
    private $docsModel;
    private $enterprisesModel;

    private $access_token = "";
    private $dwv_username = "48991640611";
    private $dwv_password = "vendemuito2020";
        

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

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://dwvapp.com.br/v2/sessions?username=$this->dwv_username&password=$this->dwv_password",
            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_HTTPHEADER => array(
              'Authorization: Bearer 8dbb906a458f68033370eea1c15e4bca9c169keFgIGtGijkGeWEszNH2MLns0aIfHp+MM52GxLxf9uTVtNaNH8Xyu5z8/dX2+dWp6Exg8PV6AkDVapq0P2rZTOzUTiCGNnqHSzR220='
            ),
        ));
        
        $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->credentials->token;
    }

    private function processRequest($url){
        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_HTTPHEADER => array(
            'Authorization: Bearer ' . $this->access_token,
            ),
        ));
        
        $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 processRequestAllPages($url){
        if( strpos($url, "?") > 0){
            $url .= "&";
        } else {
            $url .= "?";
        }
        $url .= "perPage=100";
        $page = 0;
        $data = array();
        $continue = true;
        do {
            $page++;
            $urlPage = $url . "&page=$page";
            $response = $this->processRequest($urlPage);
            if (isset($response->data)){
                $data = array_merge($data, $response->data);
                if($response->page == $response->lastPage || $response->total == 0){
                    $continue = false;
                }
            } else {
                $data = $response;
                $continue = false;
            }
        } while ($continue);
        return $data;        
    }

    private function getAllCities($uf = null){
        $url = "https://dwvapp.com.br/cidades";
        if (!empty($uf)){
            $url .= "?uf=$uf";
        }
        return $this->processRequestAllPages($url);
    }

    private function getAllEnterprises($cityDWVID = null){
        $url = "https://dwvapp.com.br/empreendimentos";
        if (!empty($cityDWVID)){
            $url .= "?cidade_id=$cityDWVID";
        }
        return $this->processRequestAllPages($url);
    }

    private function getEnterpriseDetails($enterpriseDWVID){
        return $this->processRequestAllPages("https://dwvapp.com.br/empreendimentos/$enterpriseDWVID");
    }

    private function locateEnterprise($name, $addressText, $cityID){
        $name = preg_replace('/(residencial|edificio|condominio|'
            . 'res\.+|ed\.+|c\.+|cd\.+|cond\.+|con\.+|co\.+|cod\.+|condo\.+|resid\.+|'
            . 'Condominium|Residential|Building|Residence|Condominio do|Condominio de|Condominio da)\s+/i', '', $name);

        $matches = array();
        $enterprises = ORM::for_table('module_imobles_enterprise')
            ->where_like('name', $name)
            ->where('address_city_id', $cityID)
            ->where('imobles_client', 1)
            ->where_null('delete_at')
            ->find_many();
        foreach($enterprises as $enterprise){
            if (strpos($addressText, $enterprise->address_neightborhood) > 0){
                // Bairro Localizado no endereço;
                array_push($matches, $enterprise);
            } else {
                // echo "BAIRRO NÃO LOCALIZADO NO ENDEREÇO --> $enterprise->address_neightborhood ($enterprise->name)<br>";
            }
        }
        return $matches;
    }

    public function matchEnterprises(){
        $cities =[
            ["idDWV" => 3795, "name" => "Itajaí",             "idImobles" => 4437],
            ["idDWV" => 3696, "name" => "Balneário Camboriú", "idImobles" => 4338],
            ["idDWV" => 3796, "name" => "Itapema",            "idImobles" => 4438],
            ["idDWV" => 3873, "name" => "Porto Belo",         "idImobles" => 4515],
            ["idDWV" => 3708, "name" => "Bombinhas",          "idImobles" => 4350]
        ];

        $countSucess = 0;
        $errors = array();
        $notFound = array();


        foreach ($cities as $city){
            echo "Empreendimentos de <b>" . $city['name'] . '</b> (id: ' . $city['idDWV'] . ")<br>";
            $enterprisesDWV = $this->getAllEnterprises($city['idDWV']);
            echo count($enterprisesDWV) ." Empreendimentos cadastrados na DWV<br>";
            flush();
            ob_flush();
            foreach ($enterprisesDWV as $enterpriseDWV){
                $msgErro = "";
                $enterprises = $this->locateEnterprise($enterpriseDWV->titulo, $enterpriseDWV->endereco, $city['idImobles']);
                if (count($enterprises) == 0){
                    array_push($notFound, "DWV ID: $enterpriseDWV->id -> Nome: $enterpriseDWV->titulo -> Endereço: $enterpriseDWV->endereco <br>");
                } else if (count($enterprises) == 1){
                    $enterprise = $enterprises[0];
                    if(empty($enterprise->dwv_id)){
                        $enterprise->dwv_id = $enterpriseDWV->id;
                        $enterprise->save();
                        $countSucess++;
                        echo "Empreendimento localizado vinculado a DWV: $enterprise->id - $enterprise->name - DWV ID: $enterpriseDWV->id<br>";
                        flush();
                        ob_flush();                        
                    } else if ($enterprise->dwv_id != $enterpriseDWV->id) {
                        $msgErro = "Empreendimento localizado com vinculo DWV_ID diferente: $enterprise->id - $enterprise->name - DWV ID CADASTRADO: $enterprise->dwv_id - DWV ID na API: $enterpriseDWV->id<br>";
                    } else {
                        echo "Empreendimento localizado já vinculado a DWV: $enterprise->id - $enterprise->name - DWV ID: $enterpriseDWV->id<br>";
                    }
                } else {
                    $msgErro = "Mais de 1 empreendimento localizado. Vinculo não realizado:<br>";
                    foreach ($enterprises as $enterprise){
                        $msgErro .= " --- $enterprise->id - $enterprise->name<br>";
                    }
                }
                if (!empty($msgErro)){
                    $msgErro = "$enterpriseDWV->titulo -> $enterpriseDWV->endereco <br>" . $msgErro;
                    array_push($errors, $msgErro);
                }
            }

            echo "<br><hr><br>";
        }

        echo "$countSucess EMPREENDIMENTOS VINCULADOS COM SUCESSO!<br>";
        echo count($errors) . " ERROS IDENTIFICADOS!<br>";
        echo count($notFound) . " EMPREENDIMENTOS NÃO LOCALIZADOS!<br>";

        if (count($errors) > 0){
            echo "<br><hr><br>";
            echo "ERROS IDENTIFICADOS<br>";
            foreach ($errors as $erro){
                echo $erro;
            }
        }

        if (count($notFound) > 0){
            echo "<br><hr><br>";
            echo "EMPREENDIMENTOS NÃO LOCALIZADOS<br>";
            foreach ($notFound as $msg){
                echo $msg;
            }
        }
        echo "<br><br>!!!!! FIM !!!!!<br><br>";
    }

    public function listDWVEnterpriseUnits($enterpriseID){
        $enterprise = ORM::for_table('module_imobles_enterprise')
            ->find_one($enterpriseID);
        if (!$enterprise){
            die("Empreendimento não localizado!");
        }

        if (empty($enterprise->dwv_id)){
            die("DWV_ID Não preenchido para este empreendimento");
        }

        $dwvEnterprise = $this->getEnterpriseDetails($enterprise->dwv_id);
        if (!$dwvEnterprise){
            die("Empreendimento não localizado na DWV: $enterprise->dwv_id");
        }

        // Status Identificados:
        //     DISPONÍVEIS
        //     1  -> Disponível
        //     4  -> Diferenciado
        //     5  -> Showroom
        //     6  -> Decorado
        //     8  -> Penthouse
        //     10 -> Promocional
        //     13 -> Cobertura
        //     17 -> Mobiliado
        //     21 -> Duplex
        //     22 -> Garden

        //     INDISPONÍVEIS
        //     2  -> Vendido
        //     3  -> Reservado
        //     7  -> Consultar
        //     9  -> Contrato
        //     11 -> Indisponível
        //     12 -> Permuta
        //     25 -> Em reserva
        //     26 -> Em permuta

        //     NÃO CADASTRAR
        //     19 -> Garagem
        //     20 -> Comercial

        //     NÃO IDENTIFICADOS
        //     14 ->
        //     15 ->
        //     16 ->
        //     18 ->
        //     23 ->
        //     24 ->

        $statusAvailable = [1, 4, 5, 6, 8, 10, 13, 17, 21, 22];
        $statusUnavailable = [2, 3, 7, 9, 11, 12, 25, 26];

        var_dump($statusAvailable);

        echo "<h1>Empreendimento: $enterprise->name</h1>";
        echo "<h3>ID no Rocket: $enterprise->id</h3>";
        echo "<h3>ID na DWV: $enterprise->dwv_id</h3>";

        echo "<ol>";
        foreach($dwvEnterprise->bloco as $bloco){
            
            echo "<li>Bloco: <b>$bloco->titulo</b> - ID: <b>$bloco->id</b></li>";
            echo "<ol>";
            foreach ($bloco->tipo as $tipo){
                echo "<li><dl>";
                echo "<dt>Tipo: <b>$tipo->titulo</b> - ID: <b>$tipo->id</b></dt>";
                $unidade = $tipo->unidade[0];
                echo "<dd>";
                echo "- Área Privativa: " . number_format($unidade->p_area, 2 , ',', '.') . " <br>";
                echo "- Área Total: " . number_format($unidade->t_area, 2 , ',', '.') . " <br>";
                echo "- Quartos: $unidade->dorms <br>";
                echo "- Suítes: $unidade->suites <br>";
                echo "- Garagens: $unidade->parking_spaces <br>";
                echo "</dd>";
                echo "</dl></li>";
                echo "<ol>";
                $content = array();
                foreach($tipo->unidade as $unidade){
                    $unavailable = null;
                    if(in_array(intval($unidade->status), $statusAvailable)){
                        $unavailable = 0;
                    } else if(in_array(intval($unidade->status), $statusUnavailable)){
                        $unavailable = 1;
                    }

                    // echo "<li>Unidade <b>$unidade->titulo</b> - ID: <b>$unidade->id</b> - Valor <b>R$ " . number_format($unidade->valor, 2 , ',', '.') . "</b> - Status: ". $unidade->options->status->title . " - $unidade->status ($unavailable)</li>";
                    if($unavailable !== null){
                        $content[] = [
                            // "idBloco"       => $bloco->id,
                            // "tituloBloco"   => $bloco->titulo,
                            // "idTipo"        => $tipo->id,
                            // "tituloTipo"    => $tipo->id,
                            // "areaPrivada"   => $unidade->p_area,
                            // "areaTotal"     => $unidade->t_area,
                            // "quartos"       => $unidade->dorms,
                            // "suites"        => $unidade->suites,
                            // "garagens"      => $unidade->parking_spaces,
                            // "status" => $unidade->status,
                            "dwv_id"       => $unidade->id,
                            "number_unity" => htmlentities($unidade->titulo),
                            "amount"       => $unidade->valor,
                            "unavailable"  => $unavailable                            
                        ];
                    }
                }
                echo "JSON Unidades: <br><b>" . json_encode($content) . "</b>";
                echo "</ol><br>";
            }
            echo "</ol>";
        }
        echo "</ol>";

        // echo "<p hidden id='content'>" . json_encode($content) . "</p>";
    }

    public function getAllStatus(){
        $status = array();
        $enterprises = ORM::for_table('module_imobles_enterprise')
            ->where_not_null('dwv_id')
            ->find_many();
        foreach($enterprises as $enterprise){
            $dwvEnterprise = $this->getEnterpriseDetails($enterprise->dwv_id);
            if (!$dwvEnterprise){
                echo "Empreendimento não localizado na DWV: $enterprise->dwv_id";
                continue;
            }

            foreach($dwvEnterprise->bloco as $bloco){
                foreach ($bloco->tipo as $tipo){
                    $content = array();
                    foreach($tipo->unidade as $unidade){
                        if(!in_array($unidade->options->status->title, $status)){
                            $status [$unidade->options->status->id] = $unidade->options->status->title;
                        }
                    }
                }
            }
        }

        ksort($status);
        foreach($status as $key => $value){
            echo "$key -> $value <br/>";
        }
    }

    private function updateUnitPrice($unit, $value){
        $value = Finance::amount_fix(@$value);
        if ($unit->amount == $value) {
            // Value not changed. Do not Update.
            return false;
        } else {
            // Update Unit
            $unit->amount = $value;
            $unit->save();

            // Update Listing
            $sql = "UPDATE module_imobles_listings l
                    SET crawler_price = $value
                    WHERE unit_id = $unit->id AND crawler_type_id = 4";
            ORM::execute($sql);

            // Insert into Listings Prices
            $sql = "INSERT INTO module_imobles_listings_prices 
                    (listing_id, unit_type_id, date, price)
                    VALUES (
                        (
                            SELECT id
                            FROM module_imobles_listings
                            WHERE unit_id = $unit->id AND crawler_type_id = 4 limit 1
                        ),
                        $unit->module_imobles_enterprise_units_type_id, now(),
                        $value
                    )";
            ORM::execute($sql);
            return true;
        }
    }

    public function updatePrices($enterpriseID, $printOnPage){
        $lineBreak = "\n";
        if ($printOnPage){
            $lineBreak = "<br/>";
        }        
        $user = User::_info();
        $this->docsModel = new DocsModel();
        $this->enterprisesModel = new EnterprisesModel();
        $statusAvailable = [1, 4, 5, 6, 8, 10, 13, 17, 21, 22];
        $unitTypeUpdate = new UnitTypeUpdate();
        $message_return = null;
        $enterprises = ORM::for_table('module_imobles_enterprise')
            ->where_null('delete_at')
            ->where_not_null('dwv_id');
        if($enterpriseID !== null){
            $enterprises->where('id', $enterpriseID);
        }
        $enterprises = $enterprises->find_many();
        foreach ($enterprises as $enterprise){
            if(!empty($enterprise->dwv_id)){
                $validUnitsIDs = [];
                $hadChanges = false;
                $unitTypeIDs = array();
                $dwvEnterprise = $this->getEnterpriseDetails($enterprise->dwv_id);
                echo "$lineBreak $lineBreak ======================================================================$lineBreak$lineBreak";
                echo "Empreendimento: $enterprise->id - $enterprise->name (DWV ID: $enterprise->dwv_id) $lineBreak$lineBreak";
                $message_return .= "$lineBreak $lineBreak ======================================================================$lineBreak $lineBreak ";
                $message_return .= "Empreendimento: $enterprise->id - $enterprise->name (DWV ID: $enterprise->dwv_id) $lineBreak $lineBreak ";

                if(empty($dwvEnterprise->bloco)){
                    echo "Nenhum bloco cadastrado na DWV para este empreendimento. Marcando unidades como indisponíveis.$lineBreak";
                    $message_return .= "Nenhum bloco cadastrado na DWV para este empreendimento. Marcando unidades como indisponíveis$lineBreak ";
                    $this->enterprisesModel->setAllUnitsUnavailable($enterprise);
                } else {
                    foreach ($dwvEnterprise->bloco as $dwvBloco){
                        $tower = ORM::for_table("module_imobles_enterprise_towers")
                            ->where("module_imobles_enterprise_id", $enterprise->id)
                            ->where("dwv_id", $dwvBloco->id)
                            ->find_one();
                        if(!$tower){
                            echo "$lineBreak Torre com DWV ID $dwvBloco->id não localizada$lineBreak $lineBreak ";
                            $message_return .= "$lineBreak Torre com DWV ID $dwvBloco->id não localizada$lineBreak $lineBreak ";
                        } else {
                            echo "$lineBreak Torre: $tower->title | dwv_id: $dwvBloco->id$lineBreak $lineBreak ";
                            $message_return .= "$lineBreak Torre: $tower->title | dwv_id: $dwvBloco->id$lineBreak $lineBreak ";
                            $arr_units_aux = ORM::for_table("module_imobles_enterprise_units")
                                                ->select('u.*')
                                                ->select('ut.title')
                                                ->table_alias('u')
                                                ->JOIN('module_imobles_enterprise_units_type', 'ut.id = u.module_imobles_enterprise_units_type_id', 'ut')
                                                ->where_null('u.delete_at')
                                                ->where_not_null('u.dwv_id')
                                                ->where("u.module_imobles_enterprise_towers_id", $tower->id)
                                                ->find_many();
                            $arr_units = array();
                            $arr_units_details = array();
                            foreach($arr_units_aux as $d){
                                $arr_units[] = $d->dwv_id;
                                $arr_units_details[$d->dwv_id] = $d;
                            }
                            if(count($arr_units) == 0){
                                echo "$lineBreak Nenhuma unidade com DWV_ID cadastrada na torre: $tower->title | DWV ID $dwvBloco->id $lineBreak $lineBreak ";
                                $message_return .= "$lineBreak Nenhuma unidade com DWV_ID cadastrada na torre: $tower->title | DWV ID $dwvBloco->id $lineBreak $lineBreak ";
                                continue;
                            }
                            
                            foreach ($dwvBloco->tipo as $dwvTipo){   
                                echo "$lineBreak ##########$lineBreak ";
                                $message_return .= "$lineBreak ##########$lineBreak ";
                                $countUnitsNoChanges = 0;
                                $countUnitsChanges = 0;
                                $countUnitsNotFound = 0;
                                $show_title = true;  
                                $unitsNotFound = array();
                                foreach($dwvTipo->unidade as $dwvUnidade){
                                    if(!isset($arr_units_details[$dwvUnidade->id])){
                                        $unitsNotFound[] = $dwvUnidade;
                                        $countUnitsNotFound++;
                                    } else {
                                        $unit = $arr_units_details[$dwvUnidade->id];
                                        $validUnitsIDs[] = $unit->id;
                                        if($show_title === true){
                                            echo "$lineBreak Tipologia: $unit->title $lineBreak ";
                                            $message_return .= "$lineBreak Tipologia: $unit->title$lineBreak ";
                                            $show_title = false;
                                        }
                                        $unitChanged = false;
                                        if($this->updateUnitPrice($unit, $dwvUnidade->valor)){
                                            echo "Preço da unidade $unit->number_unity alterado: $dwvUnidade->valor $lineBreak ";
                                            $message_return .= "Preço da unidade $unit->number_unity alterado: $dwvUnidade->valor $lineBreak ";
                                            $unitChanged = true;
                                            $hadChanges = true;
                                        } 
                                        $dwvUnavailable = 0;
                                        if ($dwvUnidade->valor == 0 || !in_array($dwvUnidade->status, $statusAvailable)){
                                            $dwvUnavailable = 1;
                                        }
                                        $unavailable = 0;
                                        if(!empty($unit->unavailable) && $unit->unavailable == 1){
                                            $unavailable = 1;
                                        }

                                        if ($unavailable != $dwvUnavailable){
                                            $hadChanges = true;
                                            $unit->unavailable = $dwvUnavailable === 1 ? 1 : null;
                                            $unit->save();
                                            $unitChanged = true;
                                            echo "Unidade $unit->number_unity alterada para " . ($unavailable === 1 ? "INDISPONÍVEL" : "DISPONÍVEL") . "$lineBreak ";
                                            $message_return .= "Unidade $unit->number_unity alterada para " . ($unavailable === 1 ? "INDISPONÍVEL" : "DISPONÍVEL") . "$lineBreak ";
                                        }
                                        if($unitChanged){
                                            if (!in_array($unit->module_imobles_enterprise_units_type_id, $unitTypeIDs)){
                                                $unitTypeIDs[] = $unit->module_imobles_enterprise_units_type_id;
                                            }
                                            $countUnitsChanges++;
                                        } else {
                                            $countUnitsNoChanges++;
                                        }
                                    }
                                }
                                if(count($unitsNotFound) > 0){
                                    foreach($unitsNotFound as $nf){
                                        if($show_title === true){
                                            echo "$lineBreak TIPOLOGIA NÃO ENCONTRADA NO ROCKET: | Área: $nf->p_area | Quartos: $nf->dorms | Suítes: $nf->suites | Garagens:  $nf->parking_spaces $lineBreak $lineBreak ";
                                            $message_return .= "$lineBreak TIPOLOGIA NÃO ENCONTRADA NO ROCKET: | Área: $nf->p_area | Quartos: $nf->dorms | Suítes: $nf->suites | Garagens:  $nf->parking_spaces $lineBreak $lineBreak ";
                                            $show_title = false;
                                        }
                                        echo "Unidade não localizada | unidade: $nf->titulo | dwv_id: $nf->id | dwv_status: $nf->status  $lineBreak ";
                                        $message_return .= "Unidade não localizada | unidade: $nf->titulo | dwv_id: $nf->id | dwv_status: $nf->status  $lineBreak ";
                                    }
                                }
                                echo "$lineBreak $lineBreak TOTAL DE UNIDADES NÃO ATUALIZADS: $countUnitsNoChanges $lineBreak ";
                                echo "TOTAL DE UNIDADES ATUALIZADS: $countUnitsChanges $lineBreak ";
                                echo "TOTAL DE UNIDADES NÃO CADASTRADAS: $countUnitsNotFound $lineBreak ";
                                $message_return .= "$lineBreak $lineBreak TOTAL DE UNIDADES NÃO ATUALIZADS: $countUnitsNoChanges $lineBreak ";
                                $message_return .= "TOTAL DE UNIDADES ATUALIZADS: $countUnitsChanges $lineBreak ";
                                $message_return .= "TOTAL DE UNIDADES NÃO CADASTRADAS: $countUnitsNotFound $lineBreak ";
                            }
                        }
                    }

                    $unitTypeIDs = array_unique($unitTypeIDs);
                    echo "$lineBreak ########## ATUALIZANDO AS TIPOLOGIAS $lineBreak ";
                    $message_return .= "$lineBreak ########## ATUALIZANDO AS TIPOLOGIAS $lineBreak ";
                    if (count($unitTypeIDs) > 0 ){
                        $unitTypeUpdate->SetSearchablesUnitTypes($unitTypeIDs);
                    }
    
                    echo "$lineBreak ########## ATUALIZANDO TABELA DE PREÇOS $lineBreak ";
                    $message_return .= "$lineBreak ########## ATUALIZANDO TABELA DE PREÇOS $lineBreak ";
                    if(!empty($dwvEnterprise->link_tabela_pdf)){
                        $this->updatePricesTable($enterprise, $dwvEnterprise->link_tabela_pdf, $hadChanges);
                    }                    
                }


                if(!empty($validUnitsIDs)){
                    // Deixo como indisponível todas as unidades que não foram tratadas
                    $invalidUnits = ORM::for_table('module_imobles_enterprise_units')
                        ->table_alias('u')
                        ->select_expr('u.*')
                        ->left_outer_join('module_imobles_enterprise_units_type', 'u.module_imobles_enterprise_units_type_id = ut.id', 'ut')
                        ->where('u.crawler_type_id', 4)
                        ->where_not_in('u.id', $validUnitsIDs)
                        ->where_raw('(u.unavailable IS NULL OR u.unavailable IS FALSE)')
                        ->where('u.verified', 1)
                        ->where("ut.module_imobles_enterprise_id", $enterprise->id)
                        ->where_raw('(ut.promotion IS NULL OR u.promotion IS FALSE)')
                        ->find_many();
        
                    if (count($invalidUnits)) {
                        foreach($invalidUnits as $invalid) {
                            $invalid->unavailable = 1;
                            $invalid->updated_at = date('Y-m-d H:i:s');
                            $invalid->updated_by = $user->id;
                            $invalid->save();

                            echo "$lineBreak UNIDADE MARCADA COMO INDISPONÍVEL. UnitID: $invalid->id - UnitNumber: $invalid->unit_number $lineBreak $lineBreak ";
                            $message_return .= "$lineBreak UNIDADE MARCADA COMO INDISPONÍVEL. UnitID: $invalid->id - UnitNumber: $invalid->unit_number $lineBreak $lineBreak ";
                        }
                    }
                }
                
            }
        }
        $time = (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']);
        echo "$lineBreak $lineBreak TEMPO TOTAL DE EXECEÇÃO: $time $lineBreak $lineBreak ";
        $message_return .= "$lineBreak $lineBreak TEMPO TOTAL DE EXECEÇÃO: $time $lineBreak $lineBreak ";
        echo "$lineBreak $lineBreak FIM $lineBreak $lineBreak ";
        $message_return .= "$lineBreak $lineBreak FIM $lineBreak $lineBreak ";
        $message_return = str_replace("\n","<br>",$message_return);

        if(!$printOnPage){
            $name    = 'Mateus Mota'; 
            $email   = 'mateus.mota@myside.com.br'; 
            $subject = 'Atualiações diárias DWV - ' . date("d/m/Y H:i");
            $message = "<html><body><h2>$subject</h2><br/>".$message_return."</body></html>";
            Notify_Email::_send($name, $email, $subject, $message, 0, 0,'leonardo@myside.com.br');
        }
    }

    // Check if Enterprise has a dac with Price Table and if it's not outdated by 7 days
    private function needUpdatePricesTable($enterprise){
        $needUpdate = false;

        $doc = ORM::for_table('module_imobles_docs')
            ->raw_query("
                SELECT 
                    d.id,
                    d.expiration_date,
                    DATEDIFF(now(), expiration_date) AS expiredDays
                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 = $enterprise->id
                    AND d.delete_at IS NULL
                    AND d.module_imobles_docs_category_id
                    AND dc.name = 'TABELA DE PREÇO'
                ORDER BY d.created_at DESC
                LIMIT 1")
            ->find_one();

        if(!$doc || $doc->expiredDays > 7){
            $needUpdate = true;
        }

        return $needUpdate;
    }

    private function updatePricesTable($enterprise, $fileURL, $hadChanges){

        try{
            if ($hadChanges || $this->needUpdatePricesTable($enterprise)){
                echo "Atualizando Tabela de Preços: $fileURL \n";
                $idCategory = 3;
                $expiration_date = date('t-m-Y');
                $issued_date = date('d-m-Y');
                
                $fileName = rawurldecode(basename($fileURL));
                $obs = "URL 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);
            }
        } catch (Exception $e){
            echo $e->getMessage();
        }
    }

    public function getCitiesFromState($uf = null){
        return $this->getAllCities($uf);
    }

    public function getEnterprisesFromCity($cityID = null){
        return $this->getAllEnterprises($cityID);
    }

    public function getEnterpriseById($enterpriseDWVID){
        if (empty($enterpriseDWVID)){
            die("DWV_ID do Empreendimento obrigatório");
        }
        return $this->getEnterpriseDetails($enterpriseDWVID);
    }
}
?>

Anon7 - 2022
AnonSec Team