discovery-tecnologia / dsc-mercado-livre

Biblioteca de integração com o Mercado Livre
Apache License 2.0
72 stars 29 forks source link

Atualização do Category-Predictor #70

Closed e-lyder closed 3 years ago

e-lyder commented 3 years ago

Olá, me chamo Amaral. Gostaria de contribuir para o código... uma atualização para o Predictor que da forma que está já não funciona mais.

    /**
     * @param string $site
     * @param string $title
     * @return Category
     */
    public function findCategoryPredictor($site, $title)
    {
        return $this->getResponse(
            $this->get(
                "/sites/$site/category_predictor/predict",
                [
                    "title" => $title
                ]
            ),
            Category::class
        );
    }

A forma de funcionar, no entanto, é...

    /**
     * @param string $site
     * @param string $title
     * @return Category
     */
    public function findCategoryPredictor($site, $title)
    {
        return $this->getResponse(
            $this->get(
                "/sites/$site/domain_discovery/search",  // este é o novo caminho do ML 
                [
                    // "limit" => '8',
                    "q" => $title
                ]
            ),
            Category::class
        );
    }

E opcionalmente pode-se limitar a resposta entre 1 e 8 (por default a resposta máxima será 8, se não usar o "limit"). Já testei e estou usando na aplicação que estou desenvolvendo. Espero poder contribuir, caso seja oportuno, com o BalanceService (um pequeno get do saldo da conta sem precisar da API do Mercado Pago). Grato à atenção!

dilowagner commented 3 years ago

Opa, legal @e-lyder Consegues abrir um pull request pra gente com a modificacao?

Obrigado pela contribuicao!!!

e-lyder commented 3 years ago

Boa noite @dilowagner! Sou novato nessa de contribuir com pacotes... A função está na classe Dsc\MercadoLivre\Requests\Category\CategoryService.php. Fiz um Fork do pacote mas ainda não tenho certeza de como fazer um Pull Request.

PS: na aplicação que estou trabalhando deixei o client_id, o client_secret, o redirect_url e site_id como parâmetros opcionais na classe e os fixei num arquivo config pra não precisar repetir a chamada sempre que for instanciar um resource.

No config ficou assim...

    'site_id' => env('MELI_SITE_ID', 'MLB'),
    'client_id' => env('MELI_APP_ID', 'MEU_APP_ID'),
    'client_secret' => env('MELI_APP_SECRET', 'MEU_APP_SECRET'),
    'redirect_url' => env('MELI_REDIRECT_URL', 'URL_DE_CALLBACK'),
    'meli_session' => env('MELI_SESSION_NAME', 'meli_session'),

e a instância fica...

<?php
// Consideramos que já existe um autoloader compatível com a PSR-4 registrado

use Dsc\MercadoLivre\Resources\Authorization\AuthorizationService;

$service = new AuthorizationService();

if(isset($_GET['code'])) {
   $service->authorize($_GET['code'], 'https://your-domain.com/login.php');
   header('Location: https://your-domain.com');
}

echo '<br><br><a href="' . $service->getOAuthUrl('https://your-domain/login.php') . '">Login using MercadoLibre oAuth 2.0</a>';

Instanciar a classe Meli fica opcional.

Acredito que a ideia pode exceder a boa prática porém tem sido bastante útil e funcional pra eu trabalhar com multi-contas. Vou implementar no meu Fork na próxima semana, te mando o link e você analisa a viabilidade de utilizar nesse pacote.

E, desculpa; sou prolixo até escrevendo...

e-lyder commented 3 years ago

A função findCategoryPredictor estava retornando os arrays, porém vazios.

1615428469702 Inspecionando, vi que o retorno Json do ML também havia mudado. Então criei a classe Predictor que agora está retornando o array corretamente... e aproveitei a classe AttributeCombination para os atributos.

1615428569671 Segue então a classe funcionando...

<?php

namespace  Dsc\MercadoLivre\Requests\Category;

use Doctrine\Common\Collections\ArrayCollection;
use JMS\Serializer\Annotation as JMS;

class Predictor
{
    /**
     * @var string
     * @JMS\Type("string")
     */
    private $domainId;

    /**
     * @var string
     * @JMS\Type("string")
     */
    private $domainName;

    /**
     * @var string
     * @JMS\Type("string")
     */
    private $categoryId;

    /**
     * @var string
     * @JMS\Type("string")
     */
    private $categoryName;

    /**
     * @var ArrayCollection
     * @JMS\Type("ArrayCollection<Dsc\MercadoLivre\Requests\Category\AttributeCombination>")
     */
    private $attributes;

    /**
    * Get $domainId
    * @return string
    */
    public function getDomainId()
    {
        return $this->domainId;
    }

    /**
    * Set $domainId
    * @param string $domainId
    */
    public function setDomainId($domainId)
    {
        $this->domainId = $domainId;
    }

    /**
    * Get $domainName
    * @return string
    */
    public function getDomainName()
    {
        return $this->domainName;
    }

    /**
    * Set $domainName
    * @param string $domainName
    */
    public function setDomainName($domainName)
    {
        $this->domainName = $domainName;
    }

    /**
    * Get $categoryId
    * @return string
    */
    public function getCategoryId()
    {
        return $this->categoryId;
    }

    /**
    * Set $categoryId
    * @param string $categoryId
    */
    public function setCategoryId($categoryId)
    {
        $this->categoryId = $categoryId;
    }

    /**
    * Get $categoryName
    * @return string
    */
    public function getCategoryName()
    {
        return $this->categoryName;
    }

    /**
    * Set $categoryName
    * @param string $categoryName
    */
    public function setCategoryName($categoryName)
    {
        $this->categoryName = $categoryName;
    }

    /**
    * Get $attributes
    * @return ArrayCollection
    */
    public function getAttributes(): ArrayCollection
    {
        return $this->attributes;
    }

    /**
    * Set $attributes
    * @param ArrayCollection $attributes
    */
    public function setAttributes(ArrayCollection $attributes)
    {
        $this->attributes = $attributes;
    }
}

E na função é só alterar a classe de Category para Predictor;

    /**
     * @param string $site
     * @param string $title
     * @return Category
     */
    public function findCategoryPredictor($site, $title)
    {
        return $this->getResponse(
            $this->get(
                "/sites/$site/domain_discovery/search",  // este é o novo caminho do ML 
                [
                    // "limit" => '8',
                    "q" => $title
                ]
            ),
            Predictor::class
            // Category::class
        );
    }

Agora o teste:

<?php
// Consideramos que já existe um autoloader compatível com a PSR-4 registrado

use Dsc\MercadoLivre\Requests\Category\CategoryService;
use Dsc\MercadoLivre\Environments\Site;

$service = new CategoryService();

// Consulta a lista de categorias a partir do título de um produto
$categories = $service->findCategoryPredictor(Site::BRASIL, 'Celular iPhone');

e o resultado; 1615428569671

Espero ter ajudado.

dilowagner commented 3 years ago

Opa, valeu @e-lyder Vou verificar pra ajustar isso...

dilowagner commented 3 years ago

Valeu mais uma vez pela ajuda @e-lyder Gerada nova versao 2.0.4-rc