Add blacklist rules

This commit is contained in:
David Bomba 2022-04-29 08:47:19 +10:00
parent b127e12778
commit 8cfdbbe3ed
6 changed files with 411 additions and 4 deletions

View File

@ -0,0 +1,200 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Export\CSV;
use App\Libraries\MultiDB;
use App\Models\Client;
use App\Models\Company;
use App\Models\DateFormat;
use App\Models\Task;
use App\Transformers\TaskTransformer;
use App\Utils\Ninja;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\App;
use League\Csv\Writer;
class TaskExport extends BaseExport
{
private Company $company;
protected array $input;
private $entity_transformer;
protected $date_key = 'created_at';
private string $date_format = 'YYYY-MM-DD';
protected array $entity_keys = [
'start_date' => 'start_date',
'end_date' => 'end_date',
'duration' => 'duration',
'rate' => 'rate',
'number' => 'number',
'description' => 'description',
'custom_value1' => 'custom_value1',
'custom_value2' => 'custom_value2',
'custom_value3' => 'custom_value3',
'custom_value4' => 'custom_value4',
'status' => 'status_id',
'project' => 'project_id',
'invoice' => 'invoice_id',
'client' => 'client_id',
];
private array $decorate_keys = [
'status',
'project',
'client',
'invoice',
'start_date',
'end_date',
'duration',
];
public function __construct(Company $company, array $input)
{
$this->company = $company;
$this->input = $input;
$this->entity_transformer = new TaskTransformer();
}
public function run()
{
MultiDB::setDb($this->company->db);
App::forgetInstance('translator');
App::setLocale($this->company->locale());
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->company->settings));
$this->date_format = DateFormat::find($this->company->settings->date_format_id)->format;
//load the CSV document from a string
$this->csv = Writer::createFromString();
//insert the header
$this->csv->insertOne($this->buildHeader());
$query = Task::query()->where('company_id', $this->company->id)->where('is_deleted', 0);
$query = $this->addDateRange($query);
$query->cursor()
->each(function ($entity){
$this->iterateItems($entity);
});
return $this->csv->toString();
}
private function iterateItems(Task $task)
{
$transformed_task = $this->buildRow($task);
$transformed_items = [];
$transformed_task = $this->decorateAdvancedFields($task, $transformed_items);
$entity = [];
if(is_null(json_decode($task->time_log,1)))
{
foreach(array_values($this->input['report_keys']) as $key)
{
$key = str_replace("item.", "", $key);
if(array_key_exists($key, $transformed_task))
$entity[$key] = $transformed_task[$key];
}
$this->csv->insertOne($entity);
}
else {
foreach(json_decode($task->time_log,1) as $item)
{
foreach(array_values($this->input['report_keys']) as $key)
{
$key = str_replace("item.", "", $key);
if(array_key_exists($key, $transformed_task))
$entity[$key] = $transformed_task[$key];
}
if(array_key_exists("start_date",$this->input['report_keys'])){
$entity['start_date'] = Carbon::createFromTimeStamp($item[0])->format($this->date_format);
$entity = array_merge($entity, $transformed_task);
}
if(array_key_exists("end_date",$this->input['report_keys']) && $item[1] > 0){
$entity['end_date'] = Carbon::createFromTimeStamp($item[1])->format($this->date_format);
$entity = array_merge($entity, $transformed_task);
}
elseif(array_key_exists('end_date', $this->input['report_keys'])){
$entity['end_date'] = ctrans('texts.is_running');
$entity = array_merge($entity, $transformed_task);
}
$this->csv->insertOne($entity);
}
}
}
private function buildRow(Task $task) :array
{
$transformed_entity = $this->entity_transformer->transform($task);
$entity = [];
foreach(array_values($this->input['report_keys']) as $key){
if(array_key_exists($key, $transformed_entity))
$entity[$key] = $transformed_entity[$key];
}
return $this->decorateAdvancedFields($task, $entity);
}
private function decorateAdvancedFields(Task $task, array $entity) :array
{
if(array_key_exists('status_id', $entity))
$entity['status_id'] = $task->status()->exists() ? $task->status->name : '';
if(array_key_exists('project_id', $entity))
$entity['project_id'] = $task->project()->exists() ? $task->project->name : '';
if(array_key_exists('client_id', $entity))
$entity['client_id'] = $task->client->present()->name();
return $entity;
}
}

View File

@ -30,11 +30,11 @@ class QuoteReportController extends BaseController
/**
* @OA\Post(
* path="/api/v1/reports/invoices",
* operationId="getInvoiceReport",
* path="/api/v1/reports/quotes",
* operationId="getQuoteReport",
* tags={"reports"},
* summary="Invoice reports",
* description="Export invoice reports",
* summary="Quote reports",
* description="Export quote reports",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\RequestBody(

View File

@ -0,0 +1,84 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\Controllers\Reports;
use App\Export\CSV\TaskExport;
use App\Http\Controllers\BaseController;
use App\Http\Requests\Report\GenericReportRequest;
use App\Utils\Traits\MakesHash;
use Illuminate\Http\Response;
class TaskReportController extends BaseController
{
use MakesHash;
private string $filename = 'tasks.csv';
public function __construct()
{
parent::__construct();
}
/**
* @OA\Post(
* path="/api/v1/reports/tasks",
* operationId="getTaskReport",
* tags={"reports"},
* summary="Task reports",
* description="Export task reports",
* @OA\Parameter(ref="#/components/parameters/X-Api-Secret"),
* @OA\Parameter(ref="#/components/parameters/X-Requested-With"),
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(ref="#/components/schemas/GenericReportSchema")
* ),
* @OA\Response(
* response=200,
* description="success",
* @OA\Header(header="X-MINIMUM-CLIENT-VERSION", ref="#/components/headers/X-MINIMUM-CLIENT-VERSION"),
* @OA\Header(header="X-RateLimit-Remaining", ref="#/components/headers/X-RateLimit-Remaining"),
* @OA\Header(header="X-RateLimit-Limit", ref="#/components/headers/X-RateLimit-Limit"),
* ),
* @OA\Response(
* response=422,
* description="Validation error",
* @OA\JsonContent(ref="#/components/schemas/ValidationError"),
* ),
* @OA\Response(
* response="default",
* description="Unexpected Error",
* @OA\JsonContent(ref="#/components/schemas/Error"),
* ),
* )
*/
public function __invoke(GenericReportRequest $request)
{
// expect a list of visible fields, or use the default
$export = new TaskExport(auth()->user()->company(), $request->all());
$csv = $export->run();
$headers = array(
'Content-Disposition' => 'attachment',
'Content-Type' => 'text/csv',
);
return response()->streamDownload(function () use ($csv) {
echo $csv;
}, $this->filename, $headers);
}
}

View File

@ -0,0 +1,55 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://www.elastic.co/licensing/elastic-license
*/
namespace App\Http\ValidationRules\Account;
use App\Libraries\MultiDB;
use Illuminate\Contracts\Validation\Rule;
/**
* Class BlackListRule.
*/
class BlackListRule implements Rule
{
private array $blacklist = [
'candassociates.com',
];
/**
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$parts = explode("@", $value);
if(is_array($parts))
{
return ! in_array($parts[1], $this->blacklist);
}
else
return true;
}
/**
* @return string
*/
public function message()
{
return "This domain is blacklisted, if you think this is in error, please email contact@invoiceninja.com";
}
}

View File

@ -166,6 +166,7 @@ Route::group(['middleware' => ['throttle:300,1', 'api_db', 'token_auth', 'locale
Route::post('reports/recurring_invoices', 'Reports\RecurringInvoiceReportController');
Route::post('reports/payments', 'Reports\PaymentReportController');
Route::post('reports/products', 'Reports\ProductReportController');
Route::post('reports/tasks', 'Reports\TaskReportController');
Route::get('scheduler', 'SchedulerController@index');
Route::post('support/messages/send', 'Support\Messages\SendingController');

View File

@ -0,0 +1,67 @@
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
*
* @license https://opensource.org/licenses/AAL
*/
namespace Tests\Unit\ValidationRules;
use App\Http\ValidationRules\Account\BlackListRule;
use App\Models\Invoice;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\MockAccountData;
use Tests\TestCase;
/**
* @test
* @covers App\Http\ValidationRules\Account\BlackListRule
*/
class BlacklistValidationTest extends TestCase
{
public function setUp() :void
{
parent::setUp();
}
public function testValidEmailRule()
{
$rules = [
'email' => [new BlackListRule]
];
$data = [
'email' => "jimmy@gmail.com",
];
$v = $this->app['validator']->make($data, $rules);
$this->assertTrue($v->passes());
}
public function testInValidEmailRule()
{
$rules = [
'email' => [new BlackListRule]
];
$data = [
'email' => "jimmy@candassociates.com",
];
$v = $this->app['validator']->make($data, $rules);
$this->assertFalse($v->passes());
}
}