Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vinicius Gusmao - Teste PicPay #64

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[*.yml]
indent_size = 2
41 changes: 41 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
APP_NAME=PicPay
APP_ENV=local
APP_KEY=base64:iO2jYu9l/43w9XrVN+5jPP0nhH96vu9i2EjaKcw7H9U=
APP_DEBUG=true
APP_URL=http://localhost:81

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=picpay
DB_USERNAME=picpay
DB_PASSWORD=picpay

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=cache
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"


39 changes: 39 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
5 changes: 5 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
.phpunit.result.cache
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
40 changes: 11 additions & 29 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,17 @@
![PicPay](https://user-images.githubusercontent.com/1765696/26998603-711fcf30-4d5c-11e7-9281-0d9eb20337ad.png)

# Teste Backend
### INSTALAÇÃO

O desafio é criar uma API REST que busca usuarios pelo nome e username a partir de uma palavra chave. Faça o download do arquivo [users.csv.gz](https://s3.amazonaws.com/careers-picpay/users.csv.gz) que contém o banco de dados que deve ser usado na busca. Ele contém os IDs, nomes e usernames dos usuários.
Após iniciar o Docker no sistema operacional, digite todos os comandos abaixo no diretório raiz do projeto.

###### Exemplo
| ID | Nome | Username |
|--------------------------------------|-------------------|----------------------|
| 065d8403-8a8f-484d-b602-9138ff7dedcf | Wadson marcia | wadson.marcia |
| 5761be9e-3e27-4be8-87bc-5455db08408 | Kylton Saura | kylton.saura |
| ef735189-105d-4784-8e2d-c8abb07e72d3 | Edmundo Cassemiro | edmundo.cassemiro |
| aaa40f4e-da26-42ee-b707-cb81e00610d5 | Raimundira M | raimundiram |
| 51ba0961-8d5b-47be-bcb4-54633a567a99 | Pricila Kilder | pricilakilderitaliani|
- composer install
- docker-compose up
- docker-compose run app php artisan migrate
- docker-compose run app php artisan import:db

URL do sistema:
- localhost:81


Também são fornecidas duas listas de usuários que devem ser utilizadas para priorizar os resultados da busca. A lista 1 tem mais prioridade que a lista 2. Ou seja, se dois usuarios casam com os criterios de busca, aquele que está na lista 1 deverá ser exibido primeiro em relação àquele que está na lista 2. Os que não estão em nenhuma das listas são exibidos em seguida.

As listas podem ser encontradas na raiz deste repositório ([lista_relevancia_1.txt](lista_relevancia_1.txt) e [lista_relevancia_2.txt](lista_relevancia_2.txt)).
Os resultados devem ser retornados paginados de 15 em 15 registros.

Escolha as tecnologias que você vai usar e tente montar uma solução completa para rodar a aplicação.

Faça um ***Fork*** deste repositório e abra um ***Pull Request***, **com seu nome na descrição**, para participar. Assim que terminar, envie um e-mail para ***desafio@picpay.com*** com o seu usuário do Github nos avisando.

-----

### Diferenciais

- Criar um frontend para realizar a busca com uma UX elaborada
- Criar uma solução de autenticação entre o frontend e o backend
- Ter um desempenho elevado num conjunto de dados muito grande
- Utilizar o Docker
Dados de acesso:
- E-mail: picpay@picpay.com
- Senha: chamaeupicpay

101 changes: 101 additions & 0 deletions app/Console/Commands/ImportacaoCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\UsersPicpay;
use App\User;
use DB;
use Hash;

class ImportacaoCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'import:db';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Comando que importa os dados do csv para o banco de dados';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
UsersPicpay::truncate();
User::truncate();

echo "Começou em: ".date("H:i:s").PHP_EOL;
echo "Aguarde a importacao dos dados. Este procedimento levará vários minutos.".PHP_EOL;
echo "Etapa 1 de 5 - Importando o .csv para o banco de dados".PHP_EOL;

$file = "http://www.vgusmao.com.br/picpay/users.csv";
DB::connection()->getpdo()->exec("LOAD DATA LOCAL INFILE '".$file."' INTO TABLE users_picpays FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' (codigo, name, login) ");

echo "Etapa 2 de 5 - Configurando registros com relevância".PHP_EOL;
$handle = fopen("http://www.vgusmao.com.br/picpay/lista_relevancia_1.txt", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
$vetRelevancia1 = array_chunk(explode("\n",$contents), 30);
foreach($vetRelevancia1 as $v):
$v_mod = array_map(function($v){ return "'".$v."'"; }, $v);
$query = implode(',',$v_mod);
DB::update("UPDATE users_picpays SET relevancia = 2 WHERE codigo IN ($query)");
endforeach;

$handle = fopen("http://www.vgusmao.com.br/picpay/lista_relevancia_2.txt", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
$vetRelevancia2 = array_chunk(explode("\n",$contents), 30);
foreach($vetRelevancia2 as $v):
$v_mod = array_map(function($v){ return "'".$v."'"; }, $v);
$query = implode(',',$v_mod);
DB::update("UPDATE users_picpays SET relevancia = 1 WHERE codigo IN ($query)");
endforeach;

echo "Etapa 3 de 5 - Indexando as colunas para pesquisa com o elasticsearch".PHP_EOL;

$fator_incr = 15000;
$chunk_inicial = 1;
$chunk_final = $fator_incr;
$query = UsersPicpay::where('id_sis', '<',$chunk_final)->get()->count();
while($query > 0):
$users = UsersPicpay::where('id_sis', '>=' ,$chunk_inicial)->where('id_sis', '<',$chunk_final)->get();
$users->addToIndex();
$chunk_inicial += $fator_incr;
$chunk_final += $fator_incr;
$query = UsersPicpay::where('id_sis','>',$chunk_inicial)->where('id_sis', '<',$chunk_final)->get()->count();
endwhile;

echo "Etapa 4 de 5 - Criando usuário para logar no sistema.".PHP_EOL;

$user = new User();
$user->name = "DevPHP Picpay";
$user->password = Hash::make('chamaeupicpay');
$user->email = 'picpay@picpay.com';
$user->save();

echo "Etapa 5 de 5 - Importação concluída com sucesso.".PHP_EOL;
echo "Finalizou em: ".date("H:i:s").PHP_EOL;

}
}
42 changes: 42 additions & 0 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];

/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}

/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');

require base_path('routes/console.php');
}
}
51 changes: 51 additions & 0 deletions app/Exceptions/Handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];

/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];

/**
* Report or log an exception.
*
* @param \Exception $exception
* @return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}

/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $exception
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
}
32 changes: 32 additions & 0 deletions app/Http/Controllers/Auth/ForgotPasswordController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;

class ForgotPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/

use SendsPasswordResetEmails;

/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
}
Loading