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/models/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

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

include_once __DIR__ . "/../../../autoload/My_Model.php";
include_once __DIR__ . "/../factories/EnterprisesFactory.php";
include_once __DIR__ . "/../helpers/CrawlerHelper.php";
include_once __DIR__ . "/../models/NeighborhoodModel.php";
include_once __DIR__ . "/../models/UnityModel.php";
include_once __DIR__ . "/../models/TypeunityModel.php";
include_once __DIR__ . "/../helpers/console/UnitTypeUpdate.php";
include_once __DIR__ . "/../helpers/google/GoogleYoutube.php";
class EnterprisesModel extends My_Model {

    /**
     * @var string
     */
    public $table = 'module_imobles_enterprise';

    public function createEnterprises($data) {
        $enterprises = self::create();
        $this->getNeighborhoodID($data);
        $this->getVideoInfo($enterprises, $data);
        EnterprisesFactory::create($data, $enterprises, true);
        $enterprises->save();
        $this->saveAmenities($data, $enterprises->id);
        $this->updateEnterpriseTowers($data, $enterprises->id);
        return $enterprises;
    }

    public function updateEnterprises($data, $enterprises, $update = false) {
        ORM::for_table($this->table)->create($enterprises);

        if(empty($data['address_neighborhood_id']) || $data['address_neightborhood'] <> $enterprises->address_neightborhood){
            $this->getNeighborhoodID($data);
        }
        $this->getVideoInfo($enterprises, $data);
        EnterprisesFactory::create($data, $enterprises, false, $update);        
        $enterprises->save();
        $this->saveAmenities($data, $enterprises->id);
        $this->updateEnterpriseTowers($data, $enterprises->id);

        $helper = new CrawlerHelper();
        $helper->purgeCache([$enterprises->site_url]);
        return $enterprises;
    }

    public function updateEnterpriseTowers($data, $id) {
        if (isset($data['enterprise_towers_id'])) {
            $towers = $data['enterprise_towers_id'];
            $titles = $data['enterprise_towers_title'];
            $floors = $data['enterprise_towers_floors'];
            $date = $data['enterprise_towers_date_delivery'];
            $status = $data['enterprise_towers_stage'];
            $totalUnits = $data['enterprise_towers_total_units'];
            $dwv_id = $data['enterprise_towers_dwv_id'];
            $helper = new Helper();
            for ($i = 0; $i < count($towers); $i++) {
                if (intval($towers[$i]) > 0) {
                    $a = ORM::for_table('module_imobles_enterprise_towers')->find_one($towers[$i]);
                    $a->title = mb_strtoupper($titles[$i], 'UTF-8');
                    $a->floors = intval($floors[$i]);
                    $a->stage = $status[$i];
                    $a->date_delivery = empty($date[$i]) ? "" : _formatDateDB($date[$i]);
                    $a->alias = $helper->replaceAscii(mb_strtoupper($titles[$i], 'UTF-8'));
                    $a->total_units = intval($totalUnits[$i]);
                    $a->dwv_id = intval($dwv_id[$i]);
                    $a->updated_at = date('Y-m-d H:i:s');
                    $a->save();
                } else {
                    $a = ORM::for_table('module_imobles_enterprise_towers')->create();
                    $a->title = mb_strtoupper($titles[$i], 'UTF-8');
                    $a->floors = intval($floors[$i]);
                    $a->stage = $status[$i];
                    $a->date_delivery = empty($date[$i]) ? "" : _formatDateDB($date[$i]);
                    $a->alias = mb_strtoupper($helper->replaceAscii($titles[$i]), 'UTF-8');
                    $a->module_imobles_enterprise_id = $id;
                    $a->total_units = intval($totalUnits[$i]);
                    $a->dwv_id = intval($dwv_id[$i]);
                    $a->created_at = date('Y-m-d H:i:s');
                    $a->updated_at = date('Y-m-d H:i:s');
                    $a->save();
                }
            }
            if (!empty($data['entreprise_towers_id_remove'])) {
                ORM::for_table('module_imobles_enterprise_towers')
                        ->where_in('id', $data['entreprise_towers_id_remove'])
                        ->delete_many();
            }
        }
    }


    public function saveAmenities($data, $id) {

        ORM::for_table('module_imobles_enterprise_entreprise_amenities')
                ->where('module_imobles_enterprise_id', $id)
                ->delete_many();


        if (isset($data['module_imobles_enterprise_amenities'])) {
            foreach ($data['module_imobles_enterprise_amenities'] as $t) {
                $a = ORM::for_table("module_imobles_enterprise_entreprise_amenities")->create();
                $a->module_imobles_enterprise_id = $id;
                $a->module_imobles_enterprise_amenities_id = $t;
                $a->save();
            }
        }
    }

    public function deleteEnterprises($enterprises) {
        ORM::for_table($this->table)->create($enterprises);

        $now = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
        $user = User::_info();
        $enterprises->delete_at = $now->format('Y-m-d H:i:s');
        $enterprises->delete_by = $user->id;
        $enterprises->save();
        return $enterprises;
    }

    private function getNeighborhoodID(&$data){
        if(!empty($data['address_city_id']) && !empty($data['address_neightborhood'])){
            $neighborhoodModel = new NeighborhoodModel();
            $neighborhood = $neighborhoodModel->getOrCreateNeighborhood($data['address_neightborhood'], $data['address_city_id'], $data['address_state_id']);
            if($neighborhood){
                $data['address_neighborhood_id'] = $neighborhood->id;
            }
        }
    }

    public function processCSVPriceTable($enterpriseID, $csvFilePath){
        $csvParser = new parseCSV();
        $contents = file_get_contents($csvFilePath);
        $priceUnits = $csvParser->parse_string($contents);

        $msg = "";

        $keys = array_keys($priceUnits[0]);
        $minimumKeys1 = ['TORRE', 'UNIDADE', 'VALOR'];
        $minimumKeys2 = ['TORRE', 'UNIDADE', 'IDTIPOUNIDADE'];
        if (array_intersect($minimumKeys1, $keys) !== $minimumKeys1 && array_intersect($minimumKeys2, $keys) !== $minimumKeys2){
            $msg .= "Arquivo não contém os campos mínimos necessários para processamento.";
            $msg .= "<br/><br/>Os campos mínimos são:";
            $msg .= "<br/>'TORRE', 'UNIDADE', 'VALOR'";
            $msg .= "<br/>OU";
            $msg .= "<br/>'TORRE', 'UNIDADE', 'IDTIPOUNIDADE'";
            $msg .= "<br/><br/>Os campos opcionais são:";
            $msg .= "<br/>'ANDAR', 'DISPONIBILIDADE'";
            return $msg;
        }

        $helper = new Helper();
        $unityModel = new UnityModel();

        $towers = ORM::for_table('module_imobles_enterprise_towers')
            ->where('module_imobles_enterprise_id', $enterpriseID)
            ->find_array();
        if (count($towers) == 0){
            $msg = "Nenhuma torre encontrada para o empreendimento ID: $enterpriseID";
            return $msg;
        }

        $towerEmpty = [];
        $towerNotFound = [];
        $unitEmpty = [];
        $unitCreated = [];
        $unitUpdated = [];
        $typeUnitIDinvalid = [];
        $typeUnitIDRequired = [];
        $unavailableUnits = [];
        $validUnitsIDs = [];
        $typeUnitIDinvalidForEnterprise = [];

        foreach ($priceUnits as $key => $p) {

            $where = "u.delete_at is null AND u.verified = 1 AND u.crawler_type_id = 4";

            if (empty($p['TORRE'])){
                $towerEmpty[] = [
                    "line" => $key+2,
                    "data" => $p
                ];
                continue;
            } else {
                $towerAlias = $helper->replaceAscii(mb_strtoupper($p['TORRE'], 'UTF-8'));
                $towerKey = array_search($towerAlias, array_column($towers, 'alias'));
                if($towerKey === false){
                    $towerNotFound[] = [
                        "line" => $key+2,
                        "data" => $p
                    ];
                    continue;
                }
                $tower = $towers[$towerKey];
                $where .= " AND u.module_imobles_enterprise_towers_id = " . $tower['id'];
            }

            if (empty($p['UNIDADE'])){
                $unitEmpty[] = [
                    "line" => $key+2,
                    "data" => $p
                ];
                continue;
            } else {
                $unitNumber = strtoupper($helper->getAlphanumericString($p['UNIDADE']));
                $where .= " AND u.number_unity = '".$unitNumber."'";
            }

            $typeUnitID = 0;
            if(!empty($p['IDTIPOUNIDADE'])){
                $typeUnitID = intval(trim($p['IDTIPOUNIDADE']));
                if ($typeUnitID == 0){
                    $typeUnitIDinvalid[] = [
                        "line" => $key+2,
                        "data" => $p
                    ];
                    continue;
                }
                $where .= " AND u.module_imobles_enterprise_units_type_id = $typeUnitID";
                
            }

            if(empty($p['VALOR'])){
                $price = 0;
            } else {
                // This value will be treated in UnityFactory
                $price = $p['VALOR'];
            }
            
            if($price == 0 || (isset($p['DISPONIBILIDADE']) && trim($p['DISPONIBILIDADE']) != '' && intval($p['DISPONIBILIDADE']) == 0)){
                $unavailable = 1;
            } else {
                $unavailable = 0;
            }

            $data = [];
            $data['module_imobles_enterprise_id'] = $enterpriseID;
            $data['module_imobles_enterprise_towers_id'] = $tower['id'];
            $data['number_unity'] = $unitNumber;
            $data['amount'] = $price;
            $data['unavailable'] = $unavailable;
            if(!empty($p['ANDAR'])){
                $data['floor'] = $p['ANDAR'];
            }
            $data['crawler_type_id'] = 4;
            $data['verified'] = 1;
            
            $unit = ORM::for_table($unityModel->table)
                ->table_alias('u')
                ->where_raw($where)
                ->find_one();

            if(isset($unit->id) && $unit->id > 0){
                // Update price and availability
                $data['module_imobles_enterprise_units_type_id'] = $unit->module_imobles_enterprise_units_type_id;
                $unit = $unityModel->updateEnterprise_unity($data, $unit);
                $unityModel->updateListingPrice($unit, $price);
                $unitUpdated[] = $p['TORRE'] . " | $unitNumber | R$ $price | " . ($unavailable==0?"Disponível":"Indisponível");
                $validUnitsIDs[] = $unit->id;
            } else {
                // If unitTypeID is set, create new unit
                if($typeUnitID > 0){
                    $sql = 
                        "SELECT
                            count(*) as i
                        FROM
                            module_imobles_enterprise_units_type
                        WHERE
                            id = $typeUnitID
                            AND module_imobles_enterprise_id = $enterpriseID";
                    $count = ORM::for_table('module_imobles_enterprise_units_type')
                        ->raw_query($sql)
                        ->find_one();

                    if($count['i'] > 0){
                        $typeUnitModel = new TypeunityModel();
                        $typeunitys = $typeUnitModel->getOne($typeUnitID);
                        $data['alias'] = mb_strtoupper($helper->replaceAscii(@$typeunitys['alias'] . $data['number_unity']), 'UTF-8');
                        $data['module_imobles_enterprise_units_type_id'] = $typeUnitID;
                        $unit = $unityModel->createEnterprise_unity($data);
                        $unit->module_imobles_enterprise_id = $enterpriseID;
                        $unityModel->createUnityListing($unit, $price);
                        $unitCreated[] = $p['TORRE'] . " | $unitNumber | Tipo de Unidade $typeUnitID | R$ $price | " . ($unavailable==0?"Disponível":"Indisponível");
                        $validUnitsIDs[] = $unit->id;
                    } else {
                        $typeUnitIDinvalidForEnterprise[] = [
                            "line" => $key+2,
                            "data" => $p
                        ];
                    }
                } else{
                    // $typeUnitIDRequired[] = "Linha " . ($key+2) . "(" . var_export($p, true) . ")";

                    $typeUnitIDRequired[] = [
                        "line" => $key+2,
                        "data" => $p
                    ];
                }
            }
        }

        // Set as Unavailable all Units not found in CSV
        if (count($validUnitsIDs) > 0){
            $ids = implode(", ", $validUnitsIDs);
            $sql = "SELECT
                    u.*, t.title as towerTitle
                FROM
                    module_imobles_enterprise_units u
                LEFT JOIN
                    module_imobles_enterprise_towers t
                ON
                    t.id = u.module_imobles_enterprise_towers_id
                WHERE
                    u.delete_at IS NULL
                    AND u.verified = 1
                    AND u.crawler_type_id = 4
                    AND t.module_imobles_enterprise_id = $enterpriseID
                    AND u.id NOT IN ($ids)";
            $units = ORM::for_table('module_imobles_enterprise_units')
                ->raw_query($sql)
                ->find_many();
            $user = User::_info();
            foreach($units as $u){
                $u->unavailable = 1;                
                $u->updated_at = date('Y-m-d H:i:s');
                $u->updated_by = $user->id;
                $u->save();
                $unavailableUnits[] = $u->towerTitle . " | " . $u->number_unity . " | ID: " . $u->id;
            }
        }
        
        $typeUnitIDs = array();
        $typeUnits = ORM::for_table('module_imobles_enterprise_units_type')
            ->where('module_imobles_enterprise_id', $enterpriseID)
            ->find_many() ;
        foreach($typeUnits as $t){
            $t->updated_at = date('Y-m-d H:i:s');
            $t->updated_by = $user->id;
            $t->save();
            $typeUnitIDs[] = $t->id;
        }

        $unitTypeUpdate = new UnitTypeUpdate();
        $enterprise = $this->getOne($enterpriseID);

        if ($enterprise->has_listing != 1){
            $enterprise->has_listing = 1;
            $enterprise->save();
        }

        ob_start();
        $unitTypeUpdate->SetSearchablesUnitTypes($typeUnitIDs);
        $msgSetSearchablesUnitTypes = ob_get_contents();
        ob_end_clean();        

        if(count($towerEmpty) > 0){
            $msg .= "<li>Campo Torre não preenchido nas linhas abaixo:</li>";
            $msg .= "<ul>";
            foreach($towerEmpty as $t){
                $text = "Linha " . $t['line'] . "(" . var_export($t['data'], true) . ")"; ;
                $link = "<a
                    class='create_unit'
                    data-enterprise_id='$enterpriseID'
                    data-tower='" . $t['data']['TORRE'] . "'
                    data-unit_number='" . $t['data']['UNIDADE'] . "'
                    data-available='" . $t['data']['DISPONIBILIDADE'] . "'
                    data-floor='" . $t['data']['ANDAR'] . "'
                    data-value='" . $t['data']['VALOR'] . "'
                    data-unit_type_id='" . $t['data']['IDTIPOUNIDADE'] . "'
                    >Cadastrar Unidade</a>";
                $msg .= "<li>$text - $link</li>";
            }
            $msg .= "</ul>";
        }

        if(count($unitEmpty) > 0){
            $msg .= "<li>Campo Unidade não preenchido nas linhas abaixo:</li>";
            $msg .= "<ul>";
            foreach($unitEmpty as $t){
                $text = "Linha " . $t['line'] . "(" . var_export($t['data'], true) . ")"; ;
                $link = "<a
                    class='create_unit'
                    data-enterprise_id='$enterpriseID'
                    data-tower='" . $t['data']['TORRE'] . "'
                    data-unit_number='" . $t['data']['UNIDADE'] . "'
                    data-available='" . $t['data']['DISPONIBILIDADE'] . "'
                    data-floor='" . $t['data']['ANDAR'] . "'
                    data-value='" . $t['data']['VALOR'] . "'
                    data-unit_type_id='" . $t['data']['IDTIPOUNIDADE'] . "'
                    >Cadastrar Unidade</a>";
                $msg .= "<li>$text - $link</li>";
            }
            $msg .= "</ul>";
        }

        if(count($typeUnitIDRequired) > 0){
            $msg .= "<li>Unidades não cadastradas pois o campo Tipo de Unidade não preenchido nas linhas abaixo:</li>";
            $msg .= "<ul>";
            foreach($typeUnitIDRequired as $t){
                $text = "Linha " . $t['line'] . "(" . var_export($t['data'], true) . ")"; ;
                $link = "<a
                    class='create_unit'
                    data-enterprise_id='$enterpriseID'
                    data-tower='" . $t['data']['TORRE'] . "'
                    data-unit_number='" . $t['data']['UNIDADE'] . "'
                    data-available='" . $t['data']['DISPONIBILIDADE'] . "'
                    data-floor='" . $t['data']['ANDAR'] . "'
                    data-value='" . $t['data']['VALOR'] . "'
                    data-unit_type_id='" . $t['data']['IDTIPOUNIDADE'] . "'
                    >Cadastrar Unidade</a>";
                $msg .= "<li>$text - $link</li>";
            }
            $msg .= "</ul>";
        }

        if(count($typeUnitIDinvalid) > 0){
            $msg .= "<li>Campo Tipo de Unidade Inválido nas linhas abaixo:</li>";
            $msg .= "<ul>";
            foreach($typeUnitIDinvalid as $t){
                $text = "Linha " . $t['line'] . "(" . var_export($t['data'], true) . ")"; ;
                $link = "<a
                    class='create_unit'
                    data-enterprise_id='$enterpriseID'
                    data-tower='" . $t['data']['TORRE'] . "'
                    data-unit_number='" . $t['data']['UNIDADE'] . "'
                    data-available='" . $t['data']['DISPONIBILIDADE'] . "'
                    data-floor='" . $t['data']['ANDAR'] . "'
                    data-value='" . $t['data']['VALOR'] . "'
                    data-unit_type_id='" . $t['data']['IDTIPOUNIDADE'] . "'
                    >Cadastrar Unidade</a>";
                $msg .= "<li>$text - $link</li>";
            }
            $msg .= "</ul>";
        }
        
        if(count($towerNotFound) > 0){
            $msg .= "<li>Torre não encontrada nas linhas abaixo:</li>";
            $msg .= "<ul>";
            foreach($towerNotFound as $t){
                $text = "Linha " . $t['line'] . "(" . var_export($t['data'], true) . ")"; ;
                $link = "<a
                    class='create_unit'
                    data-enterprise_id='$enterpriseID'
                    data-tower='" . $t['data']['TORRE'] . "'
                    data-unit_number='" . $t['data']['UNIDADE'] . "'
                    data-available='" . $t['data']['DISPONIBILIDADE'] . "'
                    data-floor='" . $t['data']['ANDAR'] . "'
                    data-value='" . $t['data']['VALOR'] . "'
                    data-unit_type_id='" . $t['data']['IDTIPOUNIDADE'] . "'
                    >Cadastrar Unidade</a>";
                $msg .= "<li>$text - $link</li>";
            }
            $msg .= "</ul>";
        }

        if(count($typeUnitIDinvalidForEnterprise) > 0){
            $msg .= "<li>Campo Tipo de Unidade Inválido para este Empreendimento nas linhas abaixo:</li>";
            $msg .= "<ul>";
            foreach($typeUnitIDinvalidForEnterprise as $t){
                $text = "Linha " . $t['line'] . "(" . var_export($t['data'], true) . ")"; ;
                $link = "<a
                    class='create_unit'
                    data-enterprise_id='$enterpriseID'
                    data-tower='" . $t['data']['TORRE'] . "'
                    data-unit_number='" . $t['data']['UNIDADE'] . "'
                    data-available='" . $t['data']['DISPONIBILIDADE'] . "'
                    data-floor='" . $t['data']['ANDAR'] . "'
                    data-value='" . $t['data']['VALOR'] . "'
                    data-unit_type_id='" . $t['data']['IDTIPOUNIDADE'] . "'
                    >Cadastrar Unidade</a>";
                $msg .= "<li>$text - $link</li>";
            }
            $msg .= "</ul>";
        }

        if(count($unitCreated) > 0){
            $msg .= "<li>Unidades Cadastradas:</li>";
            sort($unitCreated);
            $msg .= "<ul>";
            foreach($unitCreated as $t){
                $msg .= "<li>$t</li>";
            }
            $msg .= "</ul>";
        }

        if(count($unitUpdated) > 0){
            $msg .= "<li>Unidades Atualizadas:</li>";
            sort($unitUpdated);
            $msg .= "<ul>";
            foreach($unitUpdated as $t){
                $msg .= "<li>$t</li>";
            }
            $msg .= "</ul>";
        }

        if(count($unavailableUnits) > 0){
            $msg .= "<li>Unidades marcadas como Indisponíveis por não estarem no CSV:</li>";
            sort($unavailableUnits);
            $msg .= "<ul>";
            foreach($unavailableUnits as $t){
                $msg .= "<li>$t</li>";
            }
            $msg .= "</ul>";
        }

        if(!empty($msg)){
            $msg = "<ul>$msg</ul>";
        }

        $msg = $msg . "<br><br>" . $msgSetSearchablesUnitTypes;
        return $msg;
    }

    private function getVideoInfo($enterprise, &$data){
        if(empty($data['youtube_video'])){
            $data['youtube_json'] = "";
        } else if ($enterprise->youtube_video != $data['youtube_video']){
            $google = new GoogleYoutube();
            $youtube_json = $google->getVideoInfo($data['youtube_video']);
            $data['youtube_json'] = json_encode($youtube_json);
        }
    }

    public function setAllUnitsUnavailable($enterprise){
        $units = 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 = t.id", "t")
            ->where("t.module_imobles_enterprise_id", $enterprise->id)
            ->where_null("u.unavailable")
            ->find_many();

        foreach($units as $u){
            $u->unavailable = 1;
            $u->save();
        }

        $unitTypeUpdate = new UnitTypeUpdate();
        ob_start();
        $unitTypeUpdate->SetSearchablesUnitTypes();
        ob_end_clean();
    }
}

Anon7 - 2022
AnonSec Team