Ir para conteúdo
AnthraxisBR

Qual desses dois códigos é mais eficiente?

Recommended Posts

Tenho dois códigos que fazem a mesma coisa, mas de maneira diferente, um calcula de uma vez e coloca na array, outro, eu calculo um valor de cada vez.

 

O que calcula de uma vez:

<?php
public static function get_count_companies_by_tax_regime_by_financial_movement($tax_regime)
    {
        $sql = 'SELECT cod,internal_control_group,company_tax_regime FROM data_companies WHERE company_tax_regime = "' . $tax_regime . '"';
        $rs = MySQLComponents::get_rs_array_stmt_PDO($sql);
        $companies_cod = array_column($rs, 'cod');
        $SQL_companies_cod = implode("','", $companies_cod);
        $count = count($emps);
        $exercise = date('Y-m') . '-01';
        $sql_2 = 'SELECT * FROM fiscal_obligations_control WHERE relationship IN("' . $SQL_companies_cod . '") AND exercise = "' . $exercise . '"';
        $rs_2 = MySQLComponents::get_rs_array_stmt_PDO($sql_2);
        $CM = 0;
        $SM = 0;
        $outstanding= 0;
        foreach ($rs_2 as $row) {
            $apuracao = $row['status_apuracao'];
            if($apuracao == 0){
                $outstanding = $outstanding +1;
            }elseif($apuracao == 1){
                $SM = $SM + 1;
            }elseif($apuracao == 3 OR $apuracao == 4){
                $CM = $CM + 1;
            }else{
                return 0;
                break;
            }
        }
        $response = [];
        $response['CM'] = $CM;
        $response['SM'] = $SM;
        $response['outstanding'] = $outstanding;
        return $response;
    }

 

E fiz esse outro que calcula 1 valor de cada vez:

 

<?php
public static function get_count_companies_by_tax_regime_by_financial_movement($tax_regime, $financial_movement)
    {
        $sql = 'SELECT cod,internal_control_group,company_tax_regime FROM data_companies WHERE company_tax_regime = "' . $tax_regime . '"';
        $rs = MySQLComponents::get_rs_array_stmt_PDO($sql);
        $companies_cod = array_column($rs, 'cod');
        $SQL_companies_cod = implode("','", $companies_cod);
        $count = count($emps);
        $exercise = date('Y-m') . '-01';
        $sql_2 = 'SELECT * FROM fiscal_obligations_control WHERE relationship IN("' . $SQL_companies_cod . '") AND exercise = "' . $exercise . '"';
        $rs_2 = MySQLComponents::get_rs_array_stmt_PDO($sql_2);
        $value = 0;
        foreach ($rs_2 as $row) {
            $apuracao = $row['status_apuracao'];
            if ($apuracao == $financial_movement) {
                $value = $value + 1;
            } elseif ($apuracao == 1 OR $apuracao == 3 OR $apuracao == 4) {
                // Não soma
            } else {
                return 0;
                break;
            }
        }
        return $value;
    }

 

A primeira, eu chamaria uma vez, e espalharia os dados da array, mas ela é muito especifica.

 

A segunda precisa ser chamada toda vez que precisa de um dado, porém ele é mais 'abstrata'.

 

As duas são chamadas da mesma forma com uma requisição ajax quando o elemento com o data-attr "get_count_companies", com "primary-param", com "secondary-param", e param-numbs, e também com o className 'get_data_from_db'  é carregado, depois ele passa para o Controller, que identifica e chama essa função dentro do model, essa parte é ok, a dúvida é sobre o método, pois tenho vários métodos parecidos.

 

A dúvida é:

 

Citar

Entre esses dois métodos qual é o mais eficiente ?

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Teus códigos ao mesmo tempo que faz consulta no banco, faz calculo, estoura pipoca, ainda retorna um array.

 

Já ouviu falar em métodos privados, conceito de models, repositorios, services etc?

Compartilhar este post


Link para o post
Compartilhar em outros sites
2 minutos atrás, Williams Duarte disse:

Teus códigos ao mesmo tempo que faz consulta no banco, faz calculo, estoura pipoca, ainda retorna um array.

 

Já ouviu falar em métodos privados, models, repositorios, services etc?

 

Sobre os métodos privado, models e repositórios é exatamente o que eu to tentando aprender, mas eu estou tendo muitos problemas pra entender a hora separar coisas de um método, eu to tentando dividir o máximo que eu consigo, tipo, uma função fazer apenas uma coisa, mas por exemplo.

 

Eu entendi que:

 

get_count_companies_by_tax_regime_by_financial_movement

 

Esse método de fazer a conta, era uma coisa só.

 

Mas agora que você disse, dei uma analisada melhor, parece que ele é várias coisas:

 

1 - Consulta

2 - Construção de Array

3 - Cálculo

 

Mas mesmo sabendo disso, não consigo imaginar como separar essas coisas em por exemplo um private function que faça a busca somente para essa classe, outro que monte a array, e um que calcule, até porque o calculo é o que vai preencher a array

 

.

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Primeiro passo é dar um nome mais conciso, ver o oque este método vai fazer ou retornar!

 

Este método faz oque?

 

Conta o total de empresas por regime tributário, e ao mesmo tempo por movimento financeiro?

 

Não está muito claro e bem confuso.

 

Métodos privados nada mais é do quebrar a aplicação em pequenos trechos de códigos, estes são auxiliares para os métodos protegidos ou públicos.

 

Seus exemplos acima, você pode quebrar em dois métodos privados, já que os métodos públicos nada mais é, do que sua interface, sendo interface, deixe as regras de negocio separados em métodos privados, ou use patterns.

 

 

  • +1 1

Compartilhar este post


Link para o post
Compartilhar em outros sites

Apenas complementando, abra seu projeto em linux e use a biblioteca PHPMD, verá sua complexidade ciclomática no espaço (e eu nem precisei rodar para saber disso).

 

Existem um trilhão de regras, patterns e dicas para escrever um código mais eficiente, a maioria são boas, só que extensas. As que eu acho mais simples e diretas são Object Calisthenics ( do livro  The ThoughtWorks Anthology). Se colocar seu código conforme as 9 regras, terá um código bem eficiente:

http://williamdurand.fr/2013/06/03/object-calisthenics/

https://pt.slideshare.net/guilhermeblanco/php-para-adultos-clean-code-e-object-calisthenics

 

Entretanto, não menospreze as demais, existe muita coisa boa (conforme já foi mencionado no tópico).

  • +1 1

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom dia!

 

@Williams Duarte Primeiro obrigado por responder quase todas as minhas perguntas kk

 

9 horas atrás, Williams Duarte disse:

Conta o total de empresas por regime tributário, e ao mesmo tempo por movimento financeiro?

 

É bem isso mesmo, eu preciso contar quantas empresas tiveram movimentação financeiro por regime (Simples, presumido e real), preciso disso pois tem um cálculo de eficiência dos funcionários com base nas obrigações que ele deveria fazer, e a movimentação financeira tem um valor grande nesse grau de eficiência, porque se tem movimentação, teve mais trabalho.

 

Eu tentei mudar o método, mas acabei deixando maior ainda ... Consegue apontar onde eu poderia fazer quebras pra eu dar uma estudada ?

 

<?php
private static function make_imploded_list_by_field($field_values,$separator,$field)
    {
        // Retira o campo correspondente ao relacionamento da array
        $field_to_implode = array_column($field_values, $field);
        // IMPLODE e dispôe em linha separador por '","'
        $imploded_field = implode($separator, $field_to_implode);
        return $imploded_field;
    }
    
    public static function get_count_companies_by_tax_regime_by_financial_movement($tax_regime, $responsible, $exercise)
    {
        // Verifica se o o responsável foi definido, se não, define como o usuário da sessão
        if ($responsible == '') {
            $responsible = $_SESSION['relationship'];
        }
        // Verifica se o exercicio foi definido, se nao, define o mês atual ---> .'-01' no final é apenas padrão do banco de dados.
        if ($exercise == '') {
            $exercise = date('Y-m') . '-01';
        } else {
            //Se o exercicio foi definido, executa função componente de formatação de data.
            $exercise = Components::exec_format_date($exercise, 'm/Y', 'Y-m') . '-01';
        }
        // Método para agilizar a interpretação que busca na tabela cache se o usuário POSSUI a algúm grupo como responsável.
        $user_group = geralModel::verif_if_collaborator_has_group($responsible);
        // Se o usuário possuir grupo busca os usuários relacionados a este grupo
        if ($user_group != '') {
            // Efetua a busca
            $relacionated_collaborators = geralModel::list_collaborator_dependents($responsible);
            //Função para criar lista de busca separada por '","'
            $SQL_collaborators_cod = self::make_imploded_list_by_field($relacionated_collaborators,'","','user_relationship');
            // Complemento para a query de consulta
            $sql_final_comp = '  exercise_responsible IN ("' . $SQL_collaborators_cod . '")';
        } else {
            //Se o usuário não possuir grupo, usar o complemento simples para a query
            $sql_final_comp = ' exercise_responsible = "' . $responsible . '"';
        }
        //Query para buscar as empresas para o regime tributário definido
        $sql = 'SELECT cod,internal_control_group,company_tax_regime FROM data_companies WHERE company_tax_regime = "' . $tax_regime . '"';
        //Função componente para eecução da query
        $rs = MySQLComponents::get_rs_array_stmt_PDO($sql);
        //
        $SQL_companies_cod = self::make_imploded_list_by_field($rs,'","','cod');
       //Query que busca dentro da tabema do controle de obrigações as empresas para o exercicio/responsavel/regime definidos
        $sql_2 = 'SELECT * FROM fiscal_obligations_control WHERE relationship IN("' . $SQL_companies_cod . '") AND exercise = "' . $exercise . '" AND ' . $sql_final_comp . '';
        //Função componente para execução de query
        $rs_2 = MySQLComponents::get_rs_array_stmt_PDO($sql_2);
        //Define como 0 as váriaveis 
        //$CM = Com Movimento
        //$SM = Sem Movimento
        //$outstandig = Pendentes
        $CM = 0;
        $SM = 0;
        $outstanding = 0;
        //Abreo loop pela $rs_2 
        foreach ($rs_2 as $row) {
            //Define a variavel apuração
            $apuracao = $row['status_apuracao'];
            //Comparativos de soma
            if ($apuracao == 0) {
                $outstanding = $outstanding + 1;
            } elseif ($apuracao == 1) {
                $SM = $SM + 1;
            } elseif ($apuracao == 2 or $apuracao == 3 or $apuracao == 4) {
                $CM = $CM + 1;
            } else {
                return 0;
                break;
            }
        }
        //Inicia e grava os dados na array
        $response = [];
        $response['CM'] = $CM;
        $response['SM'] = $SM;
        $response['outstanding'] = $outstanding;
        //Devovle a array resposta
        return $response;
    }

 

@Gabriel Heming Muito bom esse texto sobre Object Calisthenics, é de fácil compreensão, me sacou uma dúvida sobre divisão de arquivos/classes que eu tava a muito tempo, também vou estudar esse slide, mas o melhor é ir aprendendo nomes de coisas pra estudar, como por exemplo eu não conhecia o termo ' complexidade ciclomática' kk

 

Obrigado de novo!

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Recomendo que veja este vídeo!

Assiste, vai te ajudar entender um pouco mais sobre S.O.L.I.D. já mencionado no slide.

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por gersonab
      Procuro uma revenda de hospedagem confiável, ja adianto que uolhost e locaweb estão fora dos planos.
    • Por vinicius.david
      Por padrão é possível pesquisar por diversos critérios: nome, tag e outros. Gostaria de ativar a busca por nome de marca  ou fabricante, ambos são a mesma coisa.
      Os arquivos completos são: 
      SEARCH -> onde é feito todo o processo de procura no site:
      <?php class ControllerProductSearch extends Controller { public function index() { $data['marketshop_search_product_per_row'] = $this->config->get('marketshop_search_product_per_row'); $data['marketshop_percentage_discount_badge'] = $this->config->get('marketshop_percentage_discount_badge'); $this->load->language('product/search'); $this->load->model('catalog/category'); $this->load->model('catalog/product'); $this->load->model('tool/image'); if (isset($this->request->get['path'])) { $parts = explode('_', (string)$this->request->get['path']); } else { $parts = array(); } if (isset($parts[0])) { $data['category_id'] = $parts[0]; } else { $data['category_id'] = 0; } if (isset($parts[1])) { $data['child_id'] = $parts[1]; } else { $data['child_id'] = 0; } $data['categories_NOVO'] = array(); $categories_NOVO = $this->model_catalog_category->getCategories(0); foreach ($categories_NOVO as $category_NOVO) { $children_NOVO_data = array(); if ($category_NOVO['category_id'] == $data['category_id']) { $children_NOVO = $this->model_catalog_category->getCategories($category_NOVO['category_id']); foreach($children_NOVO as $child) { $filter_data_NOVO = array('filter_category_id' => $child['category_id'], 'filter_sub_category' => true); $children_NOVO_data[] = array( 'category_id' => $child['category_id'], 'name' => $child['name'], 'href' => $this->url->link('product/category', 'path=' . $category_NOVO['category_id'] . '_' . $child['category_id']) ); } } $filter_data_NOVO = array( 'filter_category_id' => $category_NOVO['category_id'], 'filter_sub_category' => true ); $data['categories_NOVO'][] = array( 'category_id' => $category_NOVO['category_id'], 'name' => $category_NOVO['name'], 'children' => $children_NOVO_data, 'href' => $this->url->link('product/category', 'path=' . $category_NOVO['category_id']) ); } if (isset($this->request->get['search'])) { $search = $this->request->get['search']; } else { $search = ''; } if (isset($this->request->get['tag'])) { $tag = $this->request->get['tag']; } elseif (isset($this->request->get['search'])) { $tag = $this->request->get['search']; } else { $tag = ''; } if (isset($this->request->get['description'])) { $description = $this->request->get['description']; } else { $description = ''; } if (isset($this->request->get['manufacturer_id'])) { $manufacturer_id = (int)$this->request->get['manufacturer_id']; } else { $manufacturer_id = 0; } if (isset($this->request->get['category_id'])) { $category_id = $this->request->get['category_id']; } else { $category_id = 0; } if (isset($this->request->get['sub_category'])) { $sub_category = $this->request->get['sub_category']; } else { $sub_category = ''; } if (isset($this->request->get['sort'])) { $sort = $this->request->get['sort']; } else { $sort = 'p.sort_order'; } if (isset($this->request->get['order'])) { $order = $this->request->get['order']; } else { $order = 'ASC'; } if (isset($this->request->get['page'])) { $page = $this->request->get['page']; } else { $page = 1; } if (isset($this->request->get['limit'])) { $limit = (int)$this->request->get['limit']; } else { $limit = $this->config->get($this->config->get('config_theme') . '_product_limit'); } if (isset($this->request->get['search'])) { $this->document->setTitle($this->language->get('heading_title') . ' - ' . $this->request->get['search']); } elseif (isset($this->request->get['tag'])) { $this->document->setTitle($this->language->get('heading_title') . ' - ' . $this->language->get('heading_tag') . $this->request->get['tag']); } else { $this->document->setTitle($this->language->get('heading_title')); } $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home') ); $url = ''; if (isset($this->request->get['search'])) { $url .= '&search=' . urlencode(html_entity_decode($this->request->get['search'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['tag'])) { $url .= '&tag=' . urlencode(html_entity_decode($this->request->get['tag'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['description'])) { $url .= '&description=' . $this->request->get['description']; } if (isset($this->request->get['category_id'])) { $url .= '&category_id=' . $this->request->get['category_id']; } if (isset($this->request->get['sub_category'])) { $url .= '&sub_category=' . $this->request->get['sub_category']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['page'])) { $url .= '&page=' . $this->request->get['page']; } if (isset($this->request->get['limit'])) { $url .= '&limit=' . $this->request->get['limit']; } $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('product/search', $url) ); if (isset($this->request->get['search'])) { $data['heading_title'] = $this->language->get('heading_title') . ' - ' . $this->request->get['search']; } else { $data['heading_title'] = $this->language->get('heading_title'); } $data['text_empty'] = $this->language->get('text_empty'); $data['text_search'] = $this->language->get('text_search'); $data['text_keyword'] = $this->language->get('text_keyword'); $data['text_category'] = $this->language->get('text_category'); $data['text_sub_category'] = $this->language->get('text_sub_category'); $data['text_quantity'] = $this->language->get('text_quantity'); $data['text_manufacturer'] = $this->language->get('text_manufacturer'); $data['text_model'] = $this->language->get('text_model'); $data['text_price'] = $this->language->get('text_price'); $data['text_tax'] = $this->language->get('text_tax'); $data['text_points'] = $this->language->get('text_points'); $data['text_compare'] = sprintf($this->language->get('text_compare'), (isset($this->session->data['compare']) ? count($this->session->data['compare']) : 0)); $data['text_sort'] = $this->language->get('text_sort'); $data['text_limit'] = $this->language->get('text_limit'); $data['entry_search'] = $this->language->get('entry_search'); $data['entry_description'] = $this->language->get('entry_description'); $data['button_search'] = $this->language->get('button_search'); $data['button_cart'] = $this->language->get('button_cart'); $data['button_wishlist'] = $this->language->get('button_wishlist'); $data['button_compare'] = $this->language->get('button_compare'); $data['button_list'] = $this->language->get('button_list'); $data['button_grid'] = $this->language->get('button_grid'); $data['compare'] = $this->url->link('product/compare'); $this->load->model('catalog/category'); // 3 Level Category Search $data['categories'] = array(); $categories_1 = $this->model_catalog_category->getCategories(0); foreach ($categories_1 as $category_1) { $level_2_data = array(); $categories_2 = $this->model_catalog_category->getCategories($category_1['category_id']); foreach ($categories_2 as $category_2) { $level_3_data = array(); $categories_3 = $this->model_catalog_category->getCategories($category_2['category_id']); foreach ($categories_3 as $category_3) { $level_3_data[] = array( 'category_id' => $category_3['category_id'], 'name' => $category_3['name'], ); } $level_2_data[] = array( 'category_id' => $category_2['category_id'], 'name' => $category_2['name'], 'children' => $level_3_data ); } $data['categories'][] = array( 'category_id' => $category_1['category_id'], 'name' => $category_1['name'], 'children' => $level_2_data ); } $data['products'] = array(); /* MARCOS */ $limit=20; /* FIM MARCOS */ if (isset($this->request->get['search']) || isset($this->request->get['tag'])) { $filter_data = array( 'filter_name' => $search, 'filter_tag' => $tag, 'filter_description' => $description, 'filter_manufacturer' => $manufacturer_id, //vini 'filter_category_id' => $category_id, 'filter_sub_category' => $sub_category, 'sort' => $sort, 'order' => $order, 'start' => ($page - 1) * $limit, 'limit' => $limit ); $this->log->write($filter_data); /* MARCOS - MULTIPLICAR PRODUTOS - 24.10.2018 - PARA DESATIVAR A FUNÇÃO BASTA PASSAR FALSE NA VARIAVEL MULTIPLICAR_PRODUTOS */ $multiplicar_produtos = true; $results = $this->model_catalog_product->getProducts($filter_data, $multiplicar_produtos); $product_total = $this->model_catalog_product->getTotalProducts($filter_data, $multiplicar_produtos); /* MARCOS - MULTIPLICAR PRODUTOS - 24.10.2018 - PARA DESATIVAR A FUNÇÃO BASTA PASSAR FALSE NA VARIAVEL MULTIPLICAR_PRODUTOS */ foreach ($results as $result) { if ($result['image']) { // $image = $this->model_tool_image->resize($result['image'], $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height')); $image = HTTP_SERVER . 'image/' . $result['image']; } else { $image = $this->model_tool_image->resize('placeholder.png', $this->config->get($this->config->get('config_theme') . '_image_product_width'), $this->config->get($this->config->get('config_theme') . '_image_product_height')); } if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) { $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']); } else { $price = false; } if ((float)$result['special']) { $special = $this->currency->format($this->tax->calculate($result['special'], $result['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']); } else { $special = false; } if ($this->config->get('config_tax')) { $tax = $this->currency->format((float)$result['special'] ? $result['special'] : $result['price'], $this->session->data['currency']); } else { $tax = false; } if ($this->config->get('config_review_status')) { $rating = (int)$result['rating']; } else { $rating = false; } $data['products'][] = array( 'quantity' => $result['quantity'], 'text_out_of_stock' => $result['stock_status'], 'parcelamento' => $this->load->controller('extension/module/joseanmatias_parcelamento/parcelamentomarcos', $result), 'product_id' => $result['product_id'], 'thumb' => $image, 'name' => $result['name'], 'tamanhos' => $result['tamanhos'], 'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, $this->config->get($this->config->get('config_theme') . '_product_description_length')) . '..', 'manufacturer_id' => $result['manufacturer'], //vini 'price' => $price, 'special' => $special, 'tax' => $tax, 'minimum' => $result['minimum'] > 0 ? $result['minimum'] : 1, 'rating' => $result['rating'], 'href' => $this->url->link('product/product', 'product_id=' . $result['product_id'] . $url), 'saving' => $result['price'] == 0 ? 100 : round((($result['price'] - $result['special'])/$result['price'])*100, 0) ); } $url = ''; if (isset($this->request->get['search'])) { $url .= '&search=' . urlencode(html_entity_decode($this->request->get['search'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['tag'])) { $url .= '&tag=' . urlencode(html_entity_decode($this->request->get['tag'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['description'])) { $url .= '&description=' . $this->request->get['description']; } if (isset($this->request->get['category_id'])) { $url .= '&category_id=' . $this->request->get['category_id']; } if (isset($this->request->get['sub_category'])) { $url .= '&sub_category=' . $this->request->get['sub_category']; } if (isset($this->request->get['limit'])) { $url .= '&limit=' . $this->request->get['limit']; } $data['sorts'] = array(); $data['sorts'][] = array( 'text' => $this->language->get('text_default'), 'value' => 'p.sort_order-ASC', 'href' => $this->url->link('product/search', 'sort=p.sort_order&order=ASC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_name_asc'), 'value' => 'pd.name-ASC', 'href' => $this->url->link('product/search', 'sort=pd.name&order=ASC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_name_desc'), 'value' => 'pd.name-DESC', 'href' => $this->url->link('product/search', 'sort=pd.name&order=DESC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_price_asc'), 'value' => 'p.price-ASC', 'href' => $this->url->link('product/search', 'sort=p.price&order=ASC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_price_desc'), 'value' => 'p.price-DESC', 'href' => $this->url->link('product/search', 'sort=p.price&order=DESC' . $url) ); if ($this->config->get('config_review_status')) { $data['sorts'][] = array( 'text' => $this->language->get('text_rating_desc'), 'value' => 'rating-DESC', 'href' => $this->url->link('product/search', 'sort=rating&order=DESC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_rating_asc'), 'value' => 'rating-ASC', 'href' => $this->url->link('product/search', 'sort=rating&order=ASC' . $url) ); } $data['sorts'][] = array( 'text' => $this->language->get('text_model_asc'), 'value' => 'p.model-ASC', 'href' => $this->url->link('product/search', 'sort=p.model&order=ASC' . $url) ); $data['sorts'][] = array( 'text' => $this->language->get('text_model_desc'), 'value' => 'p.model-DESC', 'href' => $this->url->link('product/search', 'sort=p.model&order=DESC' . $url) ); $url = ''; if (isset($this->request->get['search'])) { $url .= '&search=' . urlencode(html_entity_decode($this->request->get['search'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['tag'])) { $url .= '&tag=' . urlencode(html_entity_decode($this->request->get['tag'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['description'])) { $url .= '&description=' . $this->request->get['description']; } if (isset($this->request->get['category_id'])) { $url .= '&category_id=' . $this->request->get['category_id']; } if (isset($this->request->get['sub_category'])) { $url .= '&sub_category=' . $this->request->get['sub_category']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } $data['limits'] = array(); $limits = array_unique(array($this->config->get($this->config->get('config_theme') . '_product_limit'), 25, 50, 75, 100)); sort($limits); foreach($limits as $value) { $data['limits'][] = array( 'text' => $value, 'value' => $value, 'href' => $this->url->link('product/search', $url . '&limit=' . $value) ); } $url = ''; if (isset($this->request->get['search'])) { $url .= '&search=' . urlencode(html_entity_decode($this->request->get['search'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['tag'])) { $url .= '&tag=' . urlencode(html_entity_decode($this->request->get['tag'], ENT_QUOTES, 'UTF-8')); } if (isset($this->request->get['description'])) { $url .= '&description=' . $this->request->get['description']; } if (isset($this->request->get['category_id'])) { $url .= '&category_id=' . $this->request->get['category_id']; } if (isset($this->request->get['sub_category'])) { $url .= '&sub_category=' . $this->request->get['sub_category']; } if (isset($this->request->get['sort'])) { $url .= '&sort=' . $this->request->get['sort']; } if (isset($this->request->get['order'])) { $url .= '&order=' . $this->request->get['order']; } if (isset($this->request->get['limit'])) { $url .= '&limit=' . $this->request->get['limit']; } $pagination = new Pagination(); $pagination->total = $product_total; $pagination->page = $page; $pagination->limit = $limit; $pagination->url = $this->url->link('product/search', $url . '&page={page}'); $data['pagination'] = $pagination->render(); $data['results'] = sprintf($this->language->get('text_pagination'), ($product_total) ? (($page - 1) * $limit) + 1 : 0, ((($page - 1) * $limit) > ($product_total - $limit)) ? $product_total : ((($page - 1) * $limit) + $limit), $product_total, ceil($product_total / $limit)); // http://googlewebmastercentral.blogspot.com/2011/09/pagination-with-relnext-and-relprev.html if ($page == 1) { $this->document->addLink($this->url->link('product/search', '', true), 'canonical'); } elseif ($page == 2) { $this->document->addLink($this->url->link('product/search', '', true), 'prev'); } else { $this->document->addLink($this->url->link('product/search', $url . '&page='. ($page - 1), true), 'prev'); } if ($limit && ceil($product_total / $limit) > $page) { $this->document->addLink($this->url->link('product/search', $url . '&page='. ($page + 1), true), 'next'); } if (isset($this->request->get['search']) && $this->config->get('config_customer_search')) { $this->load->model('account/search'); if ($this->customer->isLogged()) { $customer_id = $this->customer->getId(); } else { $customer_id = 0; } if (isset($this->request->server['REMOTE_ADDR'])) { $ip = $this->request->server['REMOTE_ADDR']; } else { $ip = ''; } $search_data = array( 'keyword' => $search, 'category_id' => $category_id, 'sub_category' => $sub_category, 'description' => $description, 'products' => $product_total, 'customer_id' => $customer_id, 'ip' => $ip ); $this->model_account_search->addSearch($search_data); } } $data['search'] = $search; $data['description'] = $description; $data['category_id'] = $category_id; $data['sub_category'] = $sub_category; $data['sort'] = $sort; $data['order'] = $order; $data['limit'] = $limit; $data['column_left'] = $this->load->controller('common/column_left'); $data['hd_ct23'] = $this->load->controller('common/hd_ct23'); $data['hd_ct13'] = $this->load->controller('common/hd_ct13'); $data['column_right'] = $this->load->controller('common/column_right'); $data['content_top'] = $this->load->controller('common/content_top'); $data['content_bottom'] = $this->load->controller('common/content_bottom'); $data['footer'] = $this->load->controller('common/footer'); $data['header'] = $this->load->controller('common/header'); $this->response->setOutput($this->load->view('product/search', $data)); } } E o model/catalog/product onde é feito o processo de seleção no banco de dados, as modificações estão em: 
      CTRL+F => $sql .= " LEFT JOIN " . DB_PREFIX . "manufacturer m ON (m.manufacturer_id = p.manufacturer_id) ";
      CTRL+F =>  $sql .= " OR LCASE(m.name) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";
      <?php class ModelCatalogProduct extends Model { public function updateViewed($product_id) { $this->db->query("UPDATE " . DB_PREFIX . "product SET viewed = (viewed + 1) WHERE product_id = '" . (int) $product_id . "'"); } /*public function getProduct($product_id) {*/ public function getProduct($product_id, $multiplicar_produtos = false, $model = false) { $subquery_tamanhos = "(SELECT group_concat(ovd.name ORDER BY ovd.option_value_id ASC SEPARATOR ', ') FROM oc_product_option_value pov LEFT JOIN oc_option_value_description ovd on pov.option_value_id = ovd.option_value_id WHERE pov.option_id = 16 AND pov.product_id = p.product_id AND pov.quantity > 0) as tamanhos"; $from = "oc_product"; $where = "p.product_id = '" . (int) $product_id . "'"; if($multiplicar_produtos) { $from = "view_oc_product_with_options"; $where = "p.model = '" . $model . "'"; } $query = $this->db->query("SELECT DISTINCT *, ".$subquery_tamanhos." , pd.name AS name, p.image, m.name AS manufacturer, (SELECT price FROM " . DB_PREFIX . "product_discount pd2 WHERE pd2.product_id = p.product_id AND pd2.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "' AND pd2.quantity = '1' AND ((pd2.date_start = '0000-00-00' OR pd2.date_start < NOW()) AND (pd2.date_end = '0000-00-00' OR pd2.date_end > NOW())) ORDER BY pd2.priority ASC, pd2.price ASC LIMIT 1) AS discount, (SELECT price FROM " . DB_PREFIX . "product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special, (SELECT points FROM " . DB_PREFIX . "product_reward pr WHERE pr.product_id = p.product_id AND pr.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "') AS reward, (SELECT ss.name FROM " . DB_PREFIX . "stock_status ss WHERE ss.stock_status_id = p.stock_status_id AND ss.language_id = '" . (int) $this->config->get('config_language_id') . "') AS stock_status, (SELECT wcd.unit FROM " . DB_PREFIX . "weight_class_description wcd WHERE p.weight_class_id = wcd.weight_class_id AND wcd.language_id = '" . (int) $this->config->get('config_language_id') . "') AS weight_class, (SELECT lcd.unit FROM " . DB_PREFIX . "length_class_description lcd WHERE p.length_class_id = lcd.length_class_id AND lcd.language_id = '" . (int) $this->config->get('config_language_id') . "') AS length_class, (SELECT AVG(rating) AS total FROM " . DB_PREFIX . "review r1 WHERE r1.product_id = p.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating, (SELECT COUNT(*) AS total FROM " . DB_PREFIX . "review r2 WHERE r2.product_id = p.product_id AND r2.status = '1' GROUP BY r2.product_id) AS reviews, p.sort_order FROM ".$from." p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) LEFT JOIN " . DB_PREFIX . "manufacturer m ON (p.manufacturer_id = m.manufacturer_id) WHERE ".$where." AND pd.language_id = '" . (int) $this->config->get('config_language_id') . "' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "'"); if ($query->num_rows) { /* MARCOS - IMAGEM DE PRODUTO INDIVIDUAL COMO "CAPA" DENTRO DA PAGINA DE PRODUTO, APENAS REMOVER ESTE CÓDIGO CASO QUEIRA REMOVER 02.10.2018 */ if (!$query->row['image']) { $imagem_produto_individual = $this->db->query(" SELECT pi.image FROM oc_product_relaciona pr LEFT JOIN oc_productind_image pi on pr.product_ind_id = pi.productind_id WHERE pr.product_kit_id = '" . (int) $product_id . "' ORDER BY pi.sort_order ASC LIMIT 1"); if ($imagem_produto_individual->num_rows) { $query->row['image'] = $imagem_produto_individual->row['image']; } } /* MARCOS - IMAGEM DE PRODUTO INDIVIDUAL COMO "CAPA" DENTRO DA PAGINA DE PRODUTO, APENAS REMOVER ESTE CÓDIGO CASO QUEIRA REMOVER 02.10.2018 */ if($multiplicar_produtos) { $query->row['image'] = $multiplicar_produtos; } if ($this->config->get('product_video_status')) { return array( 'product_id' => $query->row['product_id'], 'name' => $query->row['name'], 'description' => $query->row['description'], 'meta_title' => $query->row['meta_title'], 'meta_description' => $query->row['meta_description'], 'meta_keyword' => $query->row['meta_keyword'], 'tag' => $query->row['tag'], 'model' => $query->row['model'], /* MARCOS */ 'subtitulo' => $query->row['subtitulo'], 'descricaorapida' => $query->row['descricaorapida'], 'ousadia' => $query->row['ousadia'], 'itens_inclusos' => $query->row['itens_inclusos'], 'como_usar' => $query->row['como_usar'], 'criando_cena' => $query->row['criando_cena'], 'video' => $query->row['video'], 'tamanhos' => $query->row['tamanhos'], /* MARCOS */ 'sku' => $query->row['sku'], 'upc' => $query->row['upc'], 'ean' => $query->row['ean'], 'jan' => $query->row['jan'], 'isbn' => $query->row['isbn'], 'mpn' => $query->row['mpn'], 'location' => $query->row['location'], 'quantity' => $query->row['quantity'], 'stock_status' => $query->row['stock_status'], 'image' => $query->row['image'], 'manufacturer_id' => $query->row['manufacturer_id'], 'manufacturer' => $query->row['manufacturer'], 'price' => ($query->row['discount'] ? $query->row['discount'] : $query->row['price']), 'special' => $query->row['special'], 'reward' => $query->row['reward'], 'points' => $query->row['points'], 'tax_class_id' => $query->row['tax_class_id'], 'date_available' => $query->row['date_available'], 'weight' => $query->row['weight'], 'weight_class_id' => $query->row['weight_class_id'], 'length' => $query->row['length'], 'width' => $query->row['width'], 'height' => $query->row['height'], 'length_class_id' => $query->row['length_class_id'], 'subtract' => $query->row['subtract'], 'rating' => round($query->row['rating']), 'reviews' => $query->row['reviews'] ? $query->row['reviews'] : 0, 'minimum' => $query->row['minimum'], 'sort_order' => $query->row['sort_order'], 'status' => $query->row['status'], 'date_added' => $query->row['date_added'], 'date_modified' => $query->row['date_modified'], 'viewed' => $query->row['viewed'], ); } else { return array( 'product_id' => $query->row['product_id'], 'name' => $query->row['name'], 'description' => $query->row['description'], 'meta_title' => $query->row['meta_title'], 'meta_description' => $query->row['meta_description'], 'meta_keyword' => $query->row['meta_keyword'], 'tag' => $query->row['tag'], 'model' => $query->row['model'], /* MARCOS */ 'subtitulo' => $query->row['subtitulo'], 'descricaorapida' => $query->row['descricaorapida'], 'ousadia' => $query->row['ousadia'], 'itens_inclusos' => $query->row['itens_inclusos'], 'como_usar' => $query->row['como_usar'], 'criando_cena' => $query->row['criando_cena'], 'tamanhos' => $query->row['tamanhos'], /* MARCOS */ 'sku' => $query->row['sku'], 'upc' => $query->row['upc'], 'ean' => $query->row['ean'], 'jan' => $query->row['jan'], 'isbn' => $query->row['isbn'], 'mpn' => $query->row['mpn'], 'location' => $query->row['location'], 'quantity' => $query->row['quantity'], 'stock_status' => $query->row['stock_status'], 'image' => $query->row['image'], 'manufacturer_id' => $query->row['manufacturer_id'], 'manufacturer' => $query->row['manufacturer'], 'price' => ($query->row['discount'] ? $query->row['discount'] : $query->row['price']), 'special' => $query->row['special'], 'reward' => $query->row['reward'], 'points' => $query->row['points'], 'tax_class_id' => $query->row['tax_class_id'], 'date_available' => $query->row['date_available'], 'weight' => $query->row['weight'], 'weight_class_id' => $query->row['weight_class_id'], 'length' => $query->row['length'], 'width' => $query->row['width'], 'height' => $query->row['height'], 'length_class_id' => $query->row['length_class_id'], 'subtract' => $query->row['subtract'], 'rating' => round($query->row['rating']), 'reviews' => $query->row['reviews'] ? $query->row['reviews'] : 0, 'minimum' => $query->row['minimum'], 'sort_order' => $query->row['sort_order'], 'status' => $query->row['status'], 'date_added' => $query->row['date_added'], 'date_modified' => $query->row['date_modified'], 'viewed' => $query->row['viewed'], ); } } else { return false; } } /* MARCOS */ public function getprodutosind($product_id) { $query = $this->db->query("SELECT TABLE_PRODUCTIND_DESCRIPTION.productind_id, TABLE_PRODUCTIND_DESCRIPTION.name, TABLE_PRODUCTIND.como_usar, TABLE_PRODUCTIND.image, TABLE_PRODUCTIND.descricaorapida, TABLE_PRODUCTIND.composicao, TABLE_PRODUCT_RELACIONA.QTDE FROM " . DB_PREFIX . "product_relaciona TABLE_PRODUCT_RELACIONA, " . DB_PREFIX . "productind_description TABLE_PRODUCTIND_DESCRIPTION, " . DB_PREFIX . "productind TABLE_PRODUCTIND WHERE TABLE_PRODUCT_RELACIONA.product_ind_id = TABLE_PRODUCTIND_DESCRIPTION.productind_id AND TABLE_PRODUCT_RELACIONA.product_ind_id = TABLE_PRODUCTIND.productind_id AND TABLE_PRODUCT_RELACIONA.product_kit_id = '" . (int) $product_id . "'"); return $query->rows; } /* FIM MARCOS */ public function getProducts($data = array(), $multiplicar_produtos = false) { /* MARCOS - LÓGICA PARA MULTIPLICAR PRODUTOS NO CATÁLOGO - ULTIMO EDIT: 31.10.2018 - Com a variável multiplicar_produtos = false, o processo ocorre normalmente, padrão opencart. - Quando passamos a variável multiplicar_produtos = true, primeiramente verificamos se há ou não filtro. - Se existir filtro, iremos desabilitar o multiplicar_produtos, deixar o opencart fazer toda a rotina automaticamente, e lá em baixo, através da variável $old_multiplicar_produtos, pegamos todos os produtos e "abrimos" dependendo da quantidade de opções, através da tabela criada view_oc_product_with_options. - Por esse motivo, precisamos desabilitar a paginação lá no category.php quando existe filtro. Pois ele vai retornar uma quantidade de produtos maior que a padrão (21), logo, não vai criar toda a paginação necessária - Caso não exista paginação, o processo é mais simples, a unica questão é alternar o nome da tabela de oc_product para view_oc_product_with_options, pois esta já retorna uma tabela de produtos com todas as cores em forma de produtos também. */ /* $old_multiplicar_produtos = false; if (!empty($data['filter_filter']) && $multiplicar_produtos == true) { $multiplicar_produtos = false; $old_multiplicar_produtos = true; }aquii */ $from = "oc_product"; if($multiplicar_produtos) { $from = "view_oc_product_with_options"; } $sql = "SELECT p.product_id, (SELECT AVG(rating) AS total FROM " . DB_PREFIX . "review r1 WHERE r1.product_id = p.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating, (SELECT price FROM " . DB_PREFIX . "product_discount pd2 WHERE pd2.product_id = p.product_id AND pd2.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "' AND pd2.quantity = '1' AND ((pd2.date_start = '0000-00-00' OR pd2.date_start < NOW()) AND (pd2.date_end = '0000-00-00' OR pd2.date_end > NOW())) ORDER BY pd2.priority ASC, pd2.price ASC LIMIT 1) AS discount, (SELECT price FROM " . DB_PREFIX . "product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special"; if($multiplicar_produtos) { $sql .= ", p.image, p.model"; } if (!empty($data['filter_category_id'])) { if (!empty($data['filter_sub_category'])) { $sql .= " FROM " . DB_PREFIX . "category_path cp LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (cp.category_id = p2c.category_id)"; } else { $sql .= " FROM " . DB_PREFIX . "product_to_category p2c"; } if (!empty($data['filter_filter'])) { $sql .= " LEFT JOIN " . DB_PREFIX . "product_filter pf ON (p2c.product_id = pf.product_id) LEFT JOIN ".$from." p ON (pf.product_id = p.product_id)"; } else { $sql .= " LEFT JOIN ".$from." p ON (p2c.product_id = p.product_id)"; } } else { $sql .= " FROM ".$from." p"; } $sql .= " LEFT JOIN " . DB_PREFIX . "manufacturer m ON (m.manufacturer_id = p.manufacturer_id) ";//vini $sql .= " LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE pd.language_id = '" . (int) $this->config->get('config_language_id') . "' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "'"; if (!empty($data['filter_category_id'])) { if (!empty($data['filter_sub_category'])) { $sql .= " AND cp.path_id = '" . (int) $data['filter_category_id'] . "'"; } else { $sql .= " AND p2c.category_id = '" . (int) $data['filter_category_id'] . "'"; } if (!empty($data['filter_filter'])) { $implode = array(); $filters = explode(',', $data['filter_filter']); foreach ($filters as $filter_id) { $implode[] = (int) $filter_id; } $sql .= " AND pf.filter_id IN (" . implode(',', $implode) . ")"; // FixFilter $minq=$this->db->query(" SELECT id.product_id FROM(SELECT product_id, count(i.product_id) as t, c.filter_group as b FROM (SELECT f.filter_id, f.product_id, p.filter_group_id FROM ". DB_PREFIX ."product_filter f left join ". DB_PREFIX ."filter p ON p.filter_id = f.filter_id where p.filter_id IN (" . implode(',', $implode) . ") GROUP BY product_id , filter_group_id) as i, (select count(distinct filter_group_id) as filter_group from ". DB_PREFIX ."filter_description f_b WHERE f_b.filter_id in (" . implode(',', $implode) . ")) as c GROUP BY product_id HAVING t = b) as id"); $min=array(); for($x=0;$x<count($minq->rows);$x++){ foreach($minq->rows[$x] as $value){ $min[]=$value; } } $imp=implode(',',$min); // FixFilter END } } if (!empty($data['filter_name']) || !empty($data['filter_tag'])) { $sql .= " AND ("; if (!empty($data['filter_name'])) { $implode = array(); $words = explode(' ', trim(preg_replace('/\s+/', ' ', $data['filter_name']))); foreach ($words as $word) { $implode[] = "pd.name LIKE '%" . $this->db->escape($word) . "%'"; } if ($implode) { $sql .= " " . implode(" AND ", $implode) . ""; } if (!empty($data['filter_description'])) { $sql .= " OR pd.description LIKE '%" . $this->db->escape($data['filter_name']) . "%'"; } } if (!empty($data['filter_name']) && !empty($data['filter_tag'])) { $sql .= " OR "; } if (!empty($data['filter_tag'])) { $implode = array(); $words = explode(' ', trim(preg_replace('/\s+/', ' ', $data['filter_tag']))); foreach ($words as $word) { $implode[] = "pd.tag LIKE '%" . $this->db->escape($word) . "%'"; } if ($implode) { $sql .= " " . implode(" AND ", $implode) . ""; } } if (!empty($data['filter_name'])) { if($multiplicar_produtos) { $sql .= " OR LCASE(p.model) LIKE '%" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "%'"; } else { $sql .= " OR LCASE(p.model) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(m.name) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'";//vini } $sql .= " OR LCASE(p.sku) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.upc) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.ean) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.jan) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.isbn) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.mpn) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; } $sql .= ")"; } if (!empty($data['filter_manufacturer_id'])) { $sql .= " AND p.manufacturer_id = '" . (int) $data['filter_manufacturer_id'] . "'"; } // FixFilter if(isset($filters)){ if(!count($min)){ $imp='0000000'; } $sql .= " AND p.product_id IN(".$imp.")"; } // FixFilter END if(!$multiplicar_produtos) { $sql .= " GROUP BY p.product_id"; } $sort_data = array( 'pd.name', 'p.model', 'p.quantity', 'p.price', 'rating', 'p.sort_order', 'p.date_added', ); if (isset($data['sort']) && in_array($data['sort'], $sort_data)) { if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') { $sql .= " ORDER BY p.quantity<1, LCASE(" . $data['sort'] . ")"; //alteração vini, enviar produto sem estoque para o ultima lugar na lista } elseif ($data['sort'] == 'p.price') { $sql .= " ORDER BY p.quantity<1, (CASE WHEN special IS NOT NULL THEN special WHEN discount IS NOT NULL THEN discount ELSE p.price END)"; } else { $sql .= " ORDER BY p.quantity<1, " . $data['sort']; //alteração vini, enviar produto sem estoque para o ultima lugar na lista } } else { $sql .= " ORDER BY p.quantity<1, p.sort_order"; //alteração vini, enviar produto sem estoque para o ultima lugar na lista } if (isset($data['order']) && ($data['order'] == 'DESC')) { $sql .= " DESC, LCASE(pd.name) DESC"; } else { $sql .= " ASC, LCASE(pd.name) ASC"; } if(!isset($data["retorna_total"])) { if (isset($data['start']) || isset($data['limit'])) { if($data['limit'] != -1) { if ($data['start'] < 0) { $data['start'] = 0; } if ($data['limit'] < 1) { $data['limit'] = 20; } $sql .= " LIMIT " . (int) $data['start'] . "," . (int) $data['limit']; } } } $product_data = array(); $query = $this->db->query($sql); if(isset($data["retorna_total"])) { $product_data = $query->num_rows; } else { foreach ($query->rows as $result) { if($multiplicar_produtos) { //MOD $product_data[] = $this->getProduct($result['product_id'], $result['image'], $result['model']); } else { //MOD /* if (!empty($data['filter_filter']) && $old_multiplicar_produtos == true) { $pegar_filhos = $this->db->query('SELECT * FROM view_oc_product_with_options WHERE product_id = ' . $result["product_id"]); foreach($pegar_filhos->rows as $pf) { $product_data[] = $this->getProduct($pf['product_id'], $pf['image']); } } else { */ $product_data[] = $this->getProduct($result['product_id']); // } } } } return $product_data; } public function getProductRelaciona($product_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_relaciona where product_kit_id = '" . (int) $product_id . "'"); foreach ($query->rows as $result) { $product_data[$result['product_kit_id']] = $this->getproductind($result['product_kit_id']); } return $product_data; } /* FIM MARCOS */ public function getProductSpecials($data = array()) { $sql = "SELECT DISTINCT ps.product_id, (SELECT AVG(rating) FROM " . DB_PREFIX . "review r1 WHERE r1.product_id = ps.product_id AND r1.status = '1' GROUP BY r1.product_id) AS rating FROM " . DB_PREFIX . "product_special ps LEFT JOIN " . DB_PREFIX . "product p ON (ps.product_id = p.product_id) LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "' AND ps.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) GROUP BY ps.product_id"; $sort_data = array( 'pd.name', 'p.model', 'ps.price', 'rating', 'p.sort_order', ); if (isset($data['sort']) && in_array($data['sort'], $sort_data)) { if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') { $sql .= " ORDER BY LCASE(" . $data['sort'] . ")"; } else { $sql .= " ORDER BY " . $data['sort']; } } else { $sql .= " ORDER BY p.sort_order"; } if (isset($data['order']) && ($data['order'] == 'DESC')) { $sql .= " DESC, LCASE(pd.name) DESC"; } else { $sql .= " ASC, LCASE(pd.name) ASC"; } if (isset($data['start']) || isset($data['limit'])) { if ($data['start'] < 0) { $data['start'] = 0; } if ($data['limit'] < 1) { $data['limit'] = 20; } $sql .= " LIMIT " . (int) $data['start'] . "," . (int) $data['limit']; } $product_data = array(); $query = $this->db->query($sql); foreach ($query->rows as $result) { $product_data[$result['product_id']] = $this->getProduct($result['product_id']); } return $product_data; } public function getLatestProducts($limit) { $product_data = $this->cache->get('product.latest.' . (int) $this->config->get('config_language_id') . '.' . (int) $this->config->get('config_store_id') . '.' . $this->config->get('config_customer_group_id') . '.' . (int) $limit); if (!$product_data) { $query = $this->db->query("SELECT p.product_id FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "' ORDER BY p.date_added DESC LIMIT " . (int) $limit); foreach ($query->rows as $result) { $product_data[$result['product_id']] = $this->getProduct($result['product_id']); } $this->cache->set('product.latest.' . (int) $this->config->get('config_language_id') . '.' . (int) $this->config->get('config_store_id') . '.' . $this->config->get('config_customer_group_id') . '.' . (int) $limit, $product_data); } return $product_data; } public function getPopularProducts($limit) { $product_data = $this->cache->get('product.popular.' . (int) $this->config->get('config_language_id') . '.' . (int) $this->config->get('config_store_id') . '.' . $this->config->get('config_customer_group_id') . '.' . (int) $limit); if (!$product_data) { $query = $this->db->query("SELECT p.product_id FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "' ORDER BY p.viewed DESC, p.date_added DESC LIMIT " . (int) $limit); foreach ($query->rows as $result) { $product_data[$result['product_id']] = $this->getProduct($result['product_id']); } $this->cache->set('product.popular.' . (int) $this->config->get('config_language_id') . '.' . (int) $this->config->get('config_store_id') . '.' . $this->config->get('config_customer_group_id') . '.' . (int) $limit, $product_data); } return $product_data; } public function getBestSellerProducts($limit) { $product_data = $this->cache->get('product.bestseller.' . (int) $this->config->get('config_language_id') . '.' . (int) $this->config->get('config_store_id') . '.' . $this->config->get('config_customer_group_id') . '.' . (int) $limit); if (!$product_data) { $product_data = array(); $query = $this->db->query("SELECT op.product_id, SUM(op.quantity) AS total FROM " . DB_PREFIX . "order_product op LEFT JOIN `" . DB_PREFIX . "order` o ON (op.order_id = o.order_id) LEFT JOIN `" . DB_PREFIX . "product` p ON (op.product_id = p.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE o.order_status_id > '0' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "' GROUP BY op.product_id ORDER BY total DESC LIMIT " . (int) $limit); foreach ($query->rows as $result) { $product_data[$result['product_id']] = $this->getProduct($result['product_id']); } $this->cache->set('product.bestseller.' . (int) $this->config->get('config_language_id') . '.' . (int) $this->config->get('config_store_id') . '.' . $this->config->get('config_customer_group_id') . '.' . (int) $limit, $product_data); } return $product_data; } public function getProductAttributes($product_id) { $product_attribute_group_data = array(); $product_attribute_group_query = $this->db->query("SELECT ag.attribute_group_id, agd.name FROM " . DB_PREFIX . "product_attribute pa LEFT JOIN " . DB_PREFIX . "attribute a ON (pa.attribute_id = a.attribute_id) LEFT JOIN " . DB_PREFIX . "attribute_group ag ON (a.attribute_group_id = ag.attribute_group_id) LEFT JOIN " . DB_PREFIX . "attribute_group_description agd ON (ag.attribute_group_id = agd.attribute_group_id) WHERE pa.product_id = '" . (int) $product_id . "' AND agd.language_id = '" . (int) $this->config->get('config_language_id') . "' GROUP BY ag.attribute_group_id ORDER BY ag.sort_order, agd.name"); foreach ($product_attribute_group_query->rows as $product_attribute_group) { $product_attribute_data = array(); $product_attribute_query = $this->db->query("SELECT a.attribute_id, ad.name, pa.text FROM " . DB_PREFIX . "product_attribute pa LEFT JOIN " . DB_PREFIX . "attribute a ON (pa.attribute_id = a.attribute_id) LEFT JOIN " . DB_PREFIX . "attribute_description ad ON (a.attribute_id = ad.attribute_id) WHERE pa.product_id = '" . (int) $product_id . "' AND a.attribute_group_id = '" . (int) $product_attribute_group['attribute_group_id'] . "' AND ad.language_id = '" . (int) $this->config->get('config_language_id') . "' AND pa.language_id = '" . (int) $this->config->get('config_language_id') . "' ORDER BY a.sort_order, ad.name"); foreach ($product_attribute_query->rows as $product_attribute) { $product_attribute['text'] = html_entity_decode($product_attribute['text'], ENT_QUOTES, 'UTF-8'); $product_attribute_data[] = array( 'attribute_id' => $product_attribute['attribute_id'], 'name' => $product_attribute['name'], 'text' => $product_attribute['text'], ); } $product_attribute_group_data[] = array( 'attribute_group_id' => $product_attribute_group['attribute_group_id'], 'name' => $product_attribute_group['name'], 'attribute' => $product_attribute_data, ); } return $product_attribute_group_data; } public function getProductOptions($product_id) { $product_option_data = array(); $product_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option po LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) LEFT JOIN " . DB_PREFIX . "option_description od ON (o.option_id = od.option_id) WHERE po.product_id = '" . (int) $product_id . "' AND od.language_id = '" . (int) $this->config->get('config_language_id') . "' ORDER BY o.sort_order"); foreach ($product_option_query->rows as $product_option) { $product_option_value_data = array(); $product_option_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_id = '" . (int) $product_id . "' AND pov.product_option_id = '" . (int) $product_option['product_option_id'] . "' AND ovd.language_id = '" . (int) $this->config->get('config_language_id') . "' ORDER BY ov.sort_order"); foreach ($product_option_value_query->rows as $product_option_value) { $product_option_value_data[] = array( 'product_option_value_id' => $product_option_value['product_option_value_id'], 'option_value_id' => $product_option_value['option_value_id'], 'name' => $product_option_value['name'], 'image' => $product_option_value['image'], 'quantity' => $product_option_value['quantity'], 'subtract' => $product_option_value['subtract'], 'price' => $product_option_value['price'], 'price_prefix' => $product_option_value['price_prefix'], 'weight' => $product_option_value['weight'], 'weight_prefix' => $product_option_value['weight_prefix'], ); } $product_option_data[] = array( 'product_option_id' => $product_option['product_option_id'], 'product_option_value' => $product_option_value_data, 'option_id' => $product_option['option_id'], 'name' => $product_option['name'], 'type' => $product_option['type'], 'parent_option' => $product_option['parent_option'], 'value' => $product_option['value'], 'required' => $product_option['required'], ); } return $product_option_data; } public function getProductDiscounts($product_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_discount WHERE product_id = '" . (int) $product_id . "' AND customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "' AND quantity > 1 AND ((date_start = '0000-00-00' OR date_start < NOW()) AND (date_end = '0000-00-00' OR date_end > NOW())) ORDER BY quantity ASC, priority ASC, price ASC"); return $query->rows; } public function getProductImages($product_id) { // $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_image WHERE product_id = '" . (int)$product_id . "' ORDER BY sort_order ASC"); //marcos // $query = $this->db->query("SELECT product_image_id, product_id, image, sort_order FROM ". DB_PREFIX ."product_image WHERE product_id = '". (int)$product_id ."' union SELECT productind_image_id as product_image_id, productind_id as product_id, image, sort_order FROM ". DB_PREFIX ."productind_image WHERE productind_id = '". (int)$product_id ."' ORDER BY sort_order ASC "); // ESTE RETORNA TAMBÉM A IMAGEM DO KIT - IGUAL NA HOT1304 //$query = $this->db->query("SELECT null as product_image_id , product_id, image, null as sort_order FROM ". DB_PREFIX ."product WHERE product_id = '". (int)$product_id ."' union SELECT productind_image_id as product_image_id, productind_id as product_id, image, sort_order FROM ". DB_PREFIX . "productind_image as aa,". DB_PREFIX . "product_relaciona as bb WHERE bb.product_kit_id = '". (int)$product_id ."' and aa.productind_id = bb.product_ind_id ORDER BY sort_order ASC"); // ESTE RETORNA SOMENTE AS IMAGENS DO PRODUTO INDIVIDUAL $query = $this->db->query("SELECT productind_image_id as product_image_id, productind_id as product_id, image, sort_order FROM " . DB_PREFIX . "productind_image as aa," . DB_PREFIX . "product_relaciona as bb WHERE bb.product_kit_id = '" . (int) $product_id . "' and aa.productind_id = bb.product_ind_id ORDER BY sort_order ASC"); return $query->rows; } public function getProductRelated($product_id) { $product_data = array(); $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_related pr LEFT JOIN " . DB_PREFIX . "product p ON (pr.related_id = p.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE pr.product_id = '" . (int) $product_id . "' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "'"); foreach ($query->rows as $result) { $product_data[$result['related_id']] = $this->getProduct($result['related_id']); } return $product_data; } public function getProductLayoutId($product_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_layout WHERE product_id = '" . (int) $product_id . "' AND store_id = '" . (int) $this->config->get('config_store_id') . "'"); if ($query->num_rows) { return $query->row['layout_id']; } else { return 0; } } public function getCategories($product_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int) $product_id . "'"); return $query->rows; } public function getTotalProducts($data = array(), $multiplicar_produtos = false) { /* $sql = "SELECT COUNT(DISTINCT p.product_id) AS total"; $from = "oc_product"; if($multiplicar_produtos) { $from = "view_oc_product_with_options"; $sql = "SELECT COUNT(p.product_id) AS total"; } if (!empty($data['filter_category_id'])) { if (!empty($data['filter_sub_category'])) { $sql .= " FROM " . DB_PREFIX . "category_path cp LEFT JOIN " . DB_PREFIX . "product_to_category p2c ON (cp.category_id = p2c.category_id)"; } else { $sql .= " FROM " . DB_PREFIX . "product_to_category p2c"; } if (!empty($data['filter_filter'])) { $sql .= " LEFT JOIN " . DB_PREFIX . "product_filter pf ON (p2c.product_id = pf.product_id) LEFT JOIN " . DB_PREFIX . "product p ON (pf.product_id = p.product_id)"; } else { $sql .= " LEFT JOIN ".$from." p ON (p2c.product_id = p.product_id)"; } } else { $sql .= " FROM ".$from." p"; } $sql .= " LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE pd.language_id = '" . (int) $this->config->get('config_language_id') . "' AND p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "'"; if (!empty($data['filter_category_id'])) { if (!empty($data['filter_sub_category'])) { $sql .= " AND cp.path_id = '" . (int) $data['filter_category_id'] . "'"; } else { $sql .= " AND p2c.category_id = '" . (int) $data['filter_category_id'] . "'"; } if (!empty($data['filter_filter'])) { $implode = array(); $filters = explode(',', $data['filter_filter']); foreach ($filters as $filter_id) { $implode[] = (int) $filter_id; } $sql .= " AND pf.filter_id IN (" . implode(',', $implode) . ")"; // FixFilter $minq=$this->db->query(" SELECT id.product_id FROM(SELECT product_id, count(i.product_id) as t, c.filter_group as b FROM (SELECT f.filter_id, f.product_id, p.filter_group_id FROM ". DB_PREFIX ."product_filter f left join ". DB_PREFIX ."filter p ON p.filter_id = f.filter_id where p.filter_id IN (" . implode(',', $implode) . ") GROUP BY product_id , filter_group_id) as i, (select count(distinct filter_group_id) as filter_group from ". DB_PREFIX ."filter_description f_b WHERE f_b.filter_id in (" . implode(',', $implode) . ")) as c GROUP BY product_id HAVING t = b) as id"); $min=array(); for($x=0;$x<count($minq->rows);$x++){ foreach($minq->rows[$x] as $value){ $min[]=$value; } } $imp=implode(',',$min); // FixFilter END } } if (!empty($data['filter_name']) || !empty($data['filter_tag'])) { $sql .= " AND ("; if (!empty($data['filter_name'])) { $implode = array(); $words = explode(' ', trim(preg_replace('/\s+/', ' ', $data['filter_name']))); foreach ($words as $word) { $implode[] = "pd.name LIKE '%" . $this->db->escape($word) . "%'"; } if ($implode) { $sql .= " " . implode(" AND ", $implode) . ""; } if (!empty($data['filter_description'])) { $sql .= " OR pd.description LIKE '%" . $this->db->escape($data['filter_name']) . "%'"; } } if (!empty($data['filter_name']) && !empty($data['filter_tag'])) { $sql .= " OR "; } if (!empty($data['filter_tag'])) { $implode = array(); $words = explode(' ', trim(preg_replace('/\s+/', ' ', $data['filter_tag']))); foreach ($words as $word) { $implode[] = "pd.tag LIKE '%" . $this->db->escape($word) . "%'"; } if ($implode) { $sql .= " " . implode(" AND ", $implode) . ""; } } if (!empty($data['filter_name'])) { $sql .= " OR LCASE(p.model) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.sku) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.upc) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.ean) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.jan) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.isbn) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; $sql .= " OR LCASE(p.mpn) = '" . $this->db->escape(utf8_strtolower($data['filter_name'])) . "'"; } $sql .= ")"; } if (!empty($data['filter_manufacturer_id'])) { $sql .= " AND p.manufacturer_id = '" . (int) $data['filter_manufacturer_id'] . "'"; } // FixFilter if(isset($filters)){ if(!count($min)){ $imp='0000000'; } $sql .= " AND p.product_id IN(".$imp.")"; } // FixFilter END $query = $this->db->query($sql); $return = $query->row['total']; return $return; */ $data["retorna_total"] = "sim"; $total = $this->getProducts($data, true, true); return $total; } public function getProfile($product_id, $recurring_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "recurring r JOIN " . DB_PREFIX . "product_recurring pr ON (pr.recurring_id = r.recurring_id AND pr.product_id = '" . (int) $product_id . "') WHERE pr.recurring_id = '" . (int) $recurring_id . "' AND status = '1' AND pr.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "'"); return $query->row; } public function getProfiles($product_id) { $query = $this->db->query("SELECT rd.* FROM " . DB_PREFIX . "product_recurring pr JOIN " . DB_PREFIX . "recurring_description rd ON (rd.language_id = " . (int) $this->config->get('config_language_id') . " AND rd.recurring_id = pr.recurring_id) JOIN " . DB_PREFIX . "recurring r ON r.recurring_id = rd.recurring_id WHERE pr.product_id = " . (int) $product_id . " AND status = '1' AND pr.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "' ORDER BY sort_order ASC"); return $query->rows; } public function getTotalProductSpecials() { $query = $this->db->query("SELECT COUNT(DISTINCT ps.product_id) AS total FROM " . DB_PREFIX . "product_special ps LEFT JOIN " . DB_PREFIX . "product p ON (ps.product_id = p.product_id) LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int) $this->config->get('config_store_id') . "' AND ps.customer_group_id = '" . (int) $this->config->get('config_customer_group_id') . "' AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW()))"); if (isset($query->row['total'])) { return $query->row['total']; } else { return 0; } } ################################################# ################ COMPLEMENTO BLING ############# ################################################# //Plugin public function getAllProduct() { $query = $this->db->query("SELECT pd.product_id, pd.name, pd.description, p.model, p.sku, p.quantity, p.price, p.weight, p.length, p.width, p.height,p.date_added, pa.text AS attribute FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON pd.product_id = p.product_id LEFT JOIN " . DB_PREFIX . "product_attribute pa ON pa.product_id = p.product_id GROUP BY p.product_id" ); return $query->rows; } //Products by filters public function getAllProductFilters($filters) { $filters = urldecode($filters); $filter = explode('|', $filters); $startDate = $filter[0]; $finishDate = $filter[1]; if ($startDate == date('Y-m-d')) { $d = date('d') + 1; $y = date('Y'); $m = date('m'); $finishDate = $y . "-" . $m . "-" . $d; } $query = $this->db->query("SELECT pd.product_id, pd.name, pd.description, p.model, p.sku, p.quantity, p.price, p.weight, p.length, p.width, p.height,p.date_added, pa.text AS attribute FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON pd.product_id = p.product_id LEFT JOIN " . DB_PREFIX . "product_attribute pa ON pa.product_id = p.product_id WHERE p.date_added BETWEEN '" . $startDate . "' AND '" . $finishDate . "' AND p.status = '1' GROUP BY p.product_id" ); return $query->rows; } //Products by filters public function getCountProduct() { $query = $this->db->query("SELECT COUNT(product_id) as NrProducts FROM " . DB_PREFIX . "product "); return $query->rows; } //Insert products public function insert_oc_products($parameter) { if (strlen($parameter->descricaoComplementar) > 64) { $parameter->descricaoComplementar = substr($parameter->descricaoComplementar, 0, 64); } $idProd = (int) $parameter->id; if ($idProd == 0) { $sql = $this->db->query("INSERT INTO " . DB_PREFIX . "product (model, sku, upc, ean, jan, isbn, mpn, location, quantity, stock_status_id, image, manufacturer_id, shipping, price, points, tax_class_id, date_available, weight, weight_class_id, length, width, height, length_class_id, subtract, minimum, sort_order, status, viewed, date_added, date_modified ) VALUES ('" . strip_tags($parameter->descricaoComplementar) . "', '" . strip_tags($parameter->codigo) . "','','','','','','','" . $parameter->estoqueAtual . "','1','','0','0','" . $parameter->preco . "','0', '9','" . date('Y-m-d') . "', '" . $parameter->peso . "', '1','" . $parameter->profundidadeProduto . "','" . $parameter->larguraProduto . "','" . $parameter->alturaProduto . "','1','0','1','0','1','0', NOW(), NOW())"); $query = $this->db->query("SELECT model, sku, quantity, MAX(product_id) as maximo FROM `" . DB_PREFIX . "product`"); return $query->rows; } else { $sql = $this->db->query("UPDATE " . DB_PREFIX . "product SET model = '" . strip_tags($parameter->descricaoComplementar) . "', sku = '" . strip_tags($parameter->codigo) . "', quantity = '" . $parameter->estoqueAtual . "', price = '" . $parameter->preco . "', weight = '" . $parameter->peso . "', length = '" . $parameter->profundidadeProduto . "', width = '" . $parameter->larguraProduto . "', height = '" . $parameter->alturaProduto . "', date_modified = NOW() WHERE product_id = '" . $idProd . "'"); return array('id' => $idPrd, 'returnUp' => $sql); } } public function update_oc_description($parameter, $id) { $sql = $this->db->query("UPDATE " . DB_PREFIX . "product_description SET `name` = '" . strip_tags($parameter->nome) . "', `description` = '" . htmlentities($parameter->descricaoComplementar) . "' WHERE `product_id` = '" . $id . "'"); return $sql; } public function insert_oc_description($parameter, $id) { $sql = $this->db->query("INSERT INTO " . DB_PREFIX . "product_description (`product_id`, `language_id`, `name`, `description`, `tag`, `meta_title`, `meta_description`, `meta_keyword`) VALUES('" . $id . "','" . (int) $this->config->get('config_language_id') . "','" . strip_tags($parameter->nome) . "','" . htmlentities($parameter->descricaoComplementar) . "','','','','')"); $query = $this->db->query("SELECT MAX(product_id) as idMax FROM " . DB_PREFIX . "product_description"); return $query->rows; } public function delete_oc_products($id) { $del = $this->db->query("DELETE FROM `" . DB_PREFIX . "product` WHERE product_id = '" . $id . "'"); return true; } //Get products variations public function getVariation($parameters) { $query = $this->db->query("SELECT pd.name as variationName, od.name as nomeTipoVariacao, ovd.name as tipoVariacao, pov.quantity as quantidadeVariacao, pov.price as precoVaricao, pov.price_prefix as prefixPrecoVaricao, pov.weight as pesoVaricao, pov.weight_prefix as prefixPesoVaricao, pov.product_option_value_id as idVariation FROM " . DB_PREFIX . "option_description od LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON ( od.option_id = ovd.option_id ) LEFT JOIN " . DB_PREFIX . "product_option_value pov ON ( ovd.option_value_id = pov.option_value_id ) LEFT JOIN " . DB_PREFIX . "product_description pd ON ( pov.product_id = pd.product_id ) WHERE pd.product_id = '" . $parameters['product_id'] . "'"); return $query->rows; } public function update_stock_product($id, $qtd) { $up = $this->db->query("UPDATE `" . DB_PREFIX . "product` SET `quantity`= '" . $qtd . "' WHERE `product_id` = '" . $id . "'"); if ($up) { return true; } else { return false; } } public function update_stock_variation($id, $qtd) { $up = $this->db->query("UPDATE `" . DB_PREFIX . "product_option_value` SET `quantity`= '" . $qtd . "' WHERE `product_option_value_id` = '" . $id . "' "); if ($up) { return true; } else { return false; } } } Encontrei estas duas soluções na internet para ativar a função de procura de um produto na loja OC 2.3.0.2 por marca de modelo(fabriicante)
      Tem-se o módulo - Search by Manufacturer: https://www.opencart.com/index.php?rout ... n_id=30878
      e o site: https://stackoverflow.com/questions/447 ... nufacturer
      Ambas aplicam a mesma função mas sem sucesso. Obrigado pela ajuda
       
    • Por Pedro Marcelino
      Eu fiz um filtro com todos os usuários cadastrados no sistema, e quando clico no card do usuário  abre um modal com mais informações sobre ele. Agora vem o problema, preciso pegar o código do usuário que esta no card, e mandar ele para o modal para assim conseguir fazer a query para puxar as informações que estão no banco. lembrando que preciso pegar o valor e jogar em uma variável, mas só pegar em qual o usuario clicar para ver mais informações
    • Por Pedro Marcelino
      Eu fiz um filtro com todos os usuários cadastrados no sistema, e quando clico no card do usuário  abre um modal com mais informações sobre ele. Agora vem o problema, preciso pegar o código do usuário que esta no card, e mandar ele para o modal para assim conseguir fazer a query para puxar as informações que estão no banco
    • Por Eduardo S. B. de Oliveira
      Senhores, preciso de uma ajuda, estou criando um formulário onde o checkbox fique "checked" quando clicar em cima, mas o detalhe e que quando atualizar a pagina o checkbox permaneça marcado. É possível? 
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.