Merge branch 'trunk'

This commit is contained in:
Vincent BRIDIER 2025-04-23 11:59:47 +02:00
commit 1ea25ed3c7
No known key found for this signature in database
GPG key ID: 8571BFA20420D512
61 changed files with 1443 additions and 2965 deletions

View file

@ -14,15 +14,6 @@ DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
DB_CONNECTION_OLD=mysql
DB_HOST_OLD=127.0.0.1
DB_PORT_OLD=3306
DB_DATABASE_OLD=ldccrm_12_2020
DB_USERNAME_OLD=root
DB_PASSWORD_OLD=
MIGRATIONPAGINATION=20000
BROADCAST_DRIVER=log
CACHE_DRIVER=apc
QUEUE_CONNECTION=database
@ -42,18 +33,14 @@ MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
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}"
# Sentry
SENTRY_LARAVEL_DSN=
# ADMIN SECURE
# - API ENDPOINT (Optional)
LDC_WEB_API_ENDPOINT="https://ldc-web.ldc.fr/api/ldc-networks"
# - API KEY
LDC_WEB_API_KEY=""
# - LIST SEPARATED WITH ',' (Optional)
LDC_WEB_CIDR_MANUAL_ALLOWED_LIST=""

View file

@ -14,15 +14,6 @@ DB_DATABASE=testing_ldccrm_12_2020
DB_USERNAME=root
DB_PASSWORD=DBPASSWORD
DB_CONNECTION_OLD=mysql
DB_HOST_OLD=127.0.0.1
DB_PORT_OLD=3306
DB_DATABASE_OLD="ldc-crm"
DB_USERNAME_OLD=root
DB_PASSWORD_OLD=
MIGRATIONPAGINATION=20000
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=database

View file

@ -1,4 +1,4 @@
FROM registry.s-web.fr/ldc-web/projets/ldc-web-images-docker/ldcweb-production-8.2:latest
FROM registry.s-web.fr/ldc-web/projets/ldc-web-images-docker/ldcweb-production-8.3:latest
COPY --chown=www-data:www-data . /app/srcs
USER root
RUN chmod -R 755 /app/srcs/storage

View file

@ -1,69 +0,0 @@
<?php
use phpseclib3\Crypt\Rijndael;
class CPlatosChiffrement
{
private static $cipher = MCRYPT_RIJNDAEL_128; // Algorithme utilisé pour le cryptage des blocs
//private static $key = "yY75y2kLQ"; // Clé de cryptage PROD
private static $key = "123456789"; // Clé de cryptage DEV
private static $mode = 'cbc'; // Mode opératoire (traitement des blocs)
public static function crypt($data)
{
$keyHash = md5(self::$key);
$data = mcrypt_encrypt(self::$cipher, self::getKey($keyHash), $data, self::$mode, self::getIv($keyHash));
return base64_encode($data);
}
public static function decrypt($data)
{
$keyHash = md5(self::$key);
$data = base64_decode($data);
$data = mcrypt_decrypt(self::$cipher, self::getKey($keyHash), $data, self::$mode, self::getIv($keyHash));
return rtrim($data);
}
public static function getIv($keyHash)
{
$iv = substr($keyHash, 0, mcrypt_get_block_size(self::$cipher, self::$mode));
return $iv;
}
public static function getKey($keyHash)
{
$key = substr($keyHash, 0, mcrypt_get_key_size(self::$cipher, self::$mode));
return $key;
}
private function encryptRJ256($key, $iv, $text)
{
$cipher = new Rijndael('cbc');
$cipher->setBlockLength(128);
// keys are null-padded to the closest valid size
// longer than the longest key and it's truncated
$cipher->setKeyLength(128);
$cipher->setKey($key);
// the IV defaults to all-NULLs if not explicitly defined
$cipher->setIV($iv);
$cipher->disablePadding();
$length = strlen($text);
$pad = 32 - ($length % 32);
$text = str_pad($text, $length + $pad, chr(0));
return base64_encode($cipher->encrypt($text));
}
private function decryptRJ256($key, $iv, $text)
{
$cipher = new Rijndael('cbc'); // could use CRYPT_RIJNDAEL_MODE_CBC
$cipher->setBlockLength(128);
// keys are null-padded to the closest valid size
// longer than the longest key and it's truncated
$cipher->setKeyLength(128);
$cipher->setKey($key);
// the IV defaults to all-NULLs if not explicitly defined
$cipher->setIV($iv);
$cipher->disablePadding();
return $cipher->decrypt(base64_decode($text));
}
}

View file

@ -1,96 +0,0 @@
<?php
class Database
{
static $instance;
private static $host;
private static $database;
private static $user;
private static $password;
public function __construct($host, $database, $user, $password)
{
self::$host = $host;
self::$database = $database;
self::$user = $user;
self::$password = $password;
}
public static function Instance()
{
if (!self::$instance) {
try {
self::$instance = new \PDO('mysql:host=' . self::$host . ';dbname=' . self::$database . ';charset=UTF8', self::$user, self::$password, array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION));
} catch (\Exception $e) {
die($e->getMessage());
}
}
return self::$instance;
}
public function request($statement, $params = false)
{
try {
$db = self::Instance();
$query = $db->prepare($statement);
if ($params) {
$query->execute($params);
} else {
$query->execute();
}
} catch (\PDOException $e) {
die($e->getMessage());
}
$query->setFetchMode(\PDO::FETCH_ASSOC);
$result = $query->fetch();
$query->closeCursor();
return ($result);
}
public function requestAll($statement, $params = false)
{
try {
$db = self::Instance();
$query = $db->prepare($statement);
if ($params) {
$query->execute($params);
} else {
$query->execute();
}
} catch (\PDOException $e) {
die($e->getMessage());
}
$query->setFetchMode(\PDO::FETCH_ASSOC);
$result = $query->fetchAll();
$query->closeCursor();
return ($result);
}
public function requestPush($statement, $params = false)
{
try {
$db = self::Instance();
$query = $db->prepare($statement);
if ($params)
$query->execute($params);
else
$query->execute();
return true;
} catch (\PDOException $e) {
die($e->getMessage());
}
}
public function requestPushInsert($statement, $params)
{
try {
$db = self::Instance();
$query = $db->prepare($statement);
$query->execute($params);
return $db->lastInsertId();
} catch (\PDOException $e) {
file_put_contents("errors_sql.txt", implode(',', $params) . PHP_EOL, FILE_APPEND);
}
}
}

View file

@ -1,91 +0,0 @@
<?php
ini_set("memory_limit", "-1");
set_time_limit(0);
error_reporting(E_ALL);
require_once 'Db.php';
require_once 'CPlatosChiffrement.class.php';
// FIXME: utiliser crm V2
require_once 'LDCCRM_V1.php';
$db = new Database('localhost', 'ldc-crm', 'ldc-crmadm', 'wai6dahB');
//$db = new Database('192.168.30.3', 'ldc-crm', 'ldc-crmadm', 'wai6dahB');
$apiCrm = new \LDCCRM\ApiV1('http://crm.test', 'giu6OCyG6FuJvM56zFntDcrtDI23GU7WNnkvOk9rPPTOzKArI8IV9nqgEAnsA8wEQUDnKheQ9FDfKUwG');
$siteId = 17;
$siteName = "REGHALAL";
$accounts = $db->requestAll("SELECT *
FROM useraccount
INNER JOIN siteuser su ON useraccount.user_id = su.siteuser_useraccountId
WHERE su.siteuser_siteId = :siteid
AND user_status = 1
AND user_lastUpdateDate >= '2018-03-01'
AND (user_emailCheckStatus <> 0 OR user_emailCheckStatus IS NULL)
AND (user_lastCnxDateHeure IS NOT NULL AND user_lastCnxDateHeure <> '0000-00-00 00:00:00')", ['siteid' => $siteId]);
foreach ($accounts as $account) {
$isSingleOptin = false;
$oldCRMid = $account['user_id'];
$civility = $account['user_civilite'];
$firstname = $account['user_prenom'];
$lastname = $account['user_nom'];
$birthdate = $account['user_dateNaissance'];
$address1 = !empty($account['user_adresse1']) ? $account['user_adresse1'] : null;
$address2 = !empty($account['user_adresse2']) ? $account['user_adresse2'] : null;
$postcode = (!empty($account['user_codePostal']) && $account['user_codePostal'] !== 0 ? $account['user_codePostal'] : null);
$city = !empty($account['user_ville']) ? $account['user_ville'] : null;
$optin = $account['user_inscritNewsletter'];
$haschcode = $account['user_hashcode'];
$status = $account['user_status'];
$created_at = $account['user_creationDate'];
$updated_at = $account['user_lastUpdateDate'];
$email = $account['user_email'];
$password = CPlatosChiffrement::decrypt($account['user_pwd']);
$last_cnx = $account['user_lastCnxDateHeure'];
if (empty($firstname) && empty($lastname))
$isSingleOptin = true;
// Récupération des champs complémentaires
$fields = [['fieldkey' => 'created_at', 'fieldvalue' => $created_at], ['fieldkey' => 'updated_at', 'fieldvalue' => $updated_at], ['fieldkey' => 'last_cnx', 'fieldvalue' => $last_cnx]];
if (!$isSingleOptin) {
$crmUser = $apiCrm->createCustomer($email, $password, $firstname, $lastname, $optin, $birthdate, null, $address1, $address2, $city, $postcode, "France");
if ($crmUser->status === 'OK') {
$newCRMId = $crmUser->user->crm_id;
$activate = $apiCrm->activateCustomer($newCRMId);
if ($activate->status === 'NOK') {
file_put_contents("Export_errors.txt", "OLD CRM ID : $oldCRMid - NEW CRM ID : $newCRMId - ACTIVATE API ERROR : " . $activate->code . " - " . $activate->message . PHP_EOL, FILE_APPEND);
}
} else {
file_put_contents("Export_errors.txt", "OLD CRM ID : $oldCRMid - API ERROR : " . $crmUser->code . " - " . $crmUser->message . PHP_EOL, FILE_APPEND);
continue;
}
} else {
$result = $apiCrm->createSingleOptin($email);
if ($result->status === 'OK') {
$newCRMId = "SINGLEOPTIN";
} else {
file_put_contents("Export_errors.txt", "OLD CRM ID : $oldCRMid - API ERROR : " . $crmUser->code . " - " . $crmUser->message . PHP_EOL, FILE_APPEND);
continue;
}
}
write("$oldCRMid;$newCRMId;$email;" . json_encode($fields) . PHP_EOL, $siteName);
}
function write($text, $siteName)
{
if (!file_exists("Export_$siteName.csv"))
file_put_contents("Export_$siteName.csv", "\xEF\xBB\xBF", FILE_APPEND); // BOM UTF-8
file_put_contents("Export_$siteName.csv", $text, FILE_APPEND);
}

View file

@ -1,9 +0,0 @@
CREATE TABLE `legaulois_migration` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`user_id` BIGINT(20) NOT NULL DEFAULT '0',
`pwd` VARCHAR(255) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=0;

View file

@ -1,80 +0,0 @@
<?php
ini_set("memory_limit", "-1");
set_time_limit(0);
error_reporting(E_ALL);
require_once 'Db.php';
$db = new Database('192.168.31.102', 'ldccrm_12_2020', 'ldccrmadm', 'wai6dahB'); // INFOS NOUVELLE CRM
$newBrandId = 2; // BRAND ID de la migration
/**
* @return Generator
*/
$fileData = function() {
$file = fopen(__DIR__ . '/Export_REGHALAL.csv', 'r');
if (!$file)
die('file does not exist or cannot be opened');
while (($line = fgets($file)) !== false) {
yield $line;
}
fclose($file);
};
foreach ($fileData() as $line) {
$isSingleOptin = false;
$datas = explode(";", $line);
$oldCrmId = $datas[0];
$newCrmId = $datas[1];
$email = $datas[2];
$otherFields = json_decode($datas[3]);
if ($newCrmId === 'SINGLEOPTIN')
$isSingleOptin = true;
foreach ($otherFields as $otherField){
// created_at - updated_at - last_cnx ne bougent pas car génériques et db sur nouvelle CRM sinon DB sur nouveau site.
switch($otherField->fieldkey){
case 'created_at':
if (!$isSingleOptin) {
$query = "UPDATE customers SET created_at = :nvalue WHERE id = :newid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId]);
$query = "UPDATE customer_infos SET created_at = :nvalue WHERE customer_id = :newid AND brand_id = :brandid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId, 'brandid' => $newBrandId]);
$query = "UPDATE customer_login SET created_at = :nvalue WHERE customer_id = :newid AND brand_id = :brandid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId, 'brandid' => $newBrandId]);
$query = "UPDATE customer_opt_in_history SET created_at = :nvalue WHERE customer_id = :newid AND brand_id = :brandid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId, 'brandid' => $newBrandId]);
}else{
$query = "UPDATE single_optin SET created_at = :nvalue, updated_at = :nvalue WHERE email = :email AND brand_id = :brandid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'email' => $email, 'brandid' => $newBrandId]);
}
break;
case 'updated_at':
if (!$isSingleOptin) {
$query = "UPDATE customers SET updated_at = :nvalue WHERE id = :newid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId]);
$query = "UPDATE customer_infos SET updated_at = :nvalue WHERE customer_id = :newid AND brand_id = :brandid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId, 'brandid' => $newBrandId]);
$query = "UPDATE customer_login SET updated_at = :nvalue WHERE customer_id = :newid AND brand_id = :brandid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId, 'brandid' => $newBrandId]);
$query = "UPDATE customer_opt_in_history SET updated_at = :nvalue WHERE customer_id = :newid AND brand_id = :brandid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId, 'brandid' => $newBrandId]);
}
break;
case 'last_cnx':
if (!$isSingleOptin) {
$query = "UPDATE customer_login SET last_connection = :nvalue WHERE customer_id = :newid AND brand_id = :brandid";
$db->requestPush($query, ['nvalue' => $otherField->fieldvalue, 'newid' => $newCrmId, 'brandid' => $newBrandId]);
}
break;
}
//var_dump($otherField);
}
}

View file

@ -1,89 +0,0 @@
<?php
ini_set("memory_limit", "-1");
set_time_limit(0);
error_reporting(E_ALL);
require_once 'Db.php';
require_once 'CPlatosChiffrement.class.php';
$db = new Database('localhost', 'ldc-crm', 'root', '');
//$db = new Database('192.168.34.2', 'ldc-crm', 'ldc-crmadm', 'wai6dahB');
if (!isset($argv[1]) || !isset($argv[2]))
die('params missing');
$name = $argv[1];
$siteId = $argv[2];
$table = $name."_migration";
$maxdate = date("Y-m-d", strtotime("-36 month", time()));
$db->requestPush("CREATE TABLE IF NOT EXISTS $table (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`user_id` BIGINT(20) NOT NULL DEFAULT '0',
`firstname` VARCHAR(255) NOT NULL DEFAULT '0',
`lastname` VARCHAR(255) NOT NULL DEFAULT '0',
`birthdate` VARCHAR(255) NULL DEFAULT '0',
`address` VARCHAR(255) NULL DEFAULT '0',
`address2` VARCHAR(255) NULL DEFAULT '0',
`city` VARCHAR(255) NULL DEFAULT '0',
`postcode` VARCHAR(255) NULL DEFAULT '0',
`optin` INT(11) NOT NULL DEFAULT '0',
`email` VARCHAR(255) NOT NULL DEFAULT '0',
`pwd` VARCHAR(255) NOT NULL DEFAULT '0',
`created_at` TIMESTAMP NOT NULL,
`updated_at` TIMESTAMP NOT NULL,
`last_cnx` TIMESTAMP NOT NULL,
PRIMARY KEY (`id`)
) COLLATE='utf8_unicode_ci' ENGINE=InnoDB AUTO_INCREMENT=0;");
$getAccounts = function ($skip) use ($db, $siteId, $maxdate){
return $db->requestAll("SELECT *
FROM useraccount
INNER JOIN siteuser su ON useraccount.user_id = su.siteuser_useraccountId
WHERE su.siteuser_siteId = :siteid
AND user_id >= 701697
AND user_status = 1
AND user_lastUpdateDate >= :maxdate
AND (user_emailCheckStatus <> 0 OR user_emailCheckStatus IS NULL)
AND (user_lastCnxDateHeure IS NOT NULL AND user_lastCnxDateHeure <> '0000-00-00 00:00:00')
AND user_lastCnxDateHeure >= :maxdate
AND user_email IS NOT NULL LIMIT 4600 OFFSET ". ($skip * 4600), ['siteid' => $siteId, 'maxdate' => $maxdate]);
};
$k = 0;
while (count($accounts = $getAccounts($k++))) {
$sql = [];
$toto = "";
foreach ($accounts as $account){
$crm_id = $account['user_id'];
$civility = $account['user_civilite'];
$firstname = ucfirst($account['user_prenom']);
$lastname = ucfirst($account['user_nom']);
$birthdate = $account['user_dateNaissance'];
$address1 = !empty($account['user_adresse1']) ? $account['user_adresse1'] : null;
$address2 = !empty($account['user_adresse2']) ? $account['user_adresse2'] : null;
$postcode = (!empty($account['user_codePostal']) && $account['user_codePostal'] !== 0 ? $account['user_codePostal'] : null);
$city = !empty($account['user_ville']) ? $account['user_ville'] : null;
$optin = $account['user_inscritNewsletter'];
$haschcode = $account['user_hashcode'];
$status = $account['user_status'];
$created_at = $account['user_creationDate'];
$updated_at = $account['user_lastUpdateDate'];
$email = strtolower($account['user_email']);
//$password = CPlatosChiffrement::decrypt($account['user_pwd']);
$password = "toto";
$last_cnx = $account['user_lastCnxDateHeure'];
$datas = [
$crm_id,
$firstname,
$lastname,
$birthdate,
$address1,
$address2,
$city,
$postcode,
$optin,
$email,
$password,
$created_at,
$updated_at,
$last_cnx
];
$toto = "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$db->requestPushInsert("INSERT INTO $table (user_id, firstname, lastname, birthdate, address, address2, city, postcode, optin, email, pwd, created_at, updated_at, last_cnx) VALUES $toto", $datas);
}
}

View file

@ -1,79 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
/**
* Command Name: LDC Web Status Checker
* Description: Envoi des infos Serveur/Laravel vers LDC Web
* Version: 1.1
* Author: Vincent BRIDIER
* Author URI: vincent.bridier@ldc.fr
*
* @codeCoverageIgnore
*
*/
class LdcWebStatusChecker extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'ldcweb:statuschecker';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Envoi des infos Serveur/Laravel vers LDC Web';
/**
* Execute the console command.
*
* @return mixed
*/
public function handle(): mixed
{
$data = [];
$data['uuid'] = config('ldcweb.project_uuid');
// Sitemap.xml ?
if (file_exists(public_path() . '/sitemap.xml')) {
$data['sitemap'] = 'true';
} else {
$data['sitemap'] = 'false';
}
// Robots.txt ?
if (file_exists(public_path() . '/robots.txt')) {
$data['robots'] = 'true';
} else {
$data['robots'] = 'false';
}
// Check logs.
$data['logs'] = 0;
$patherror = storage_path('/logs');
$files = glob($patherror . '/*.log');
if (count($files) > 0) {
foreach ($files as $file) {
$data['logs'] = $data['logs'] + filesize($file);
}
}
$data['code']['version'] = app()->version();
// Send by cURL.
$url = 'https://ldc-web.ldc.fr/api/status-checker';
$ch = curl_init($url);
$payload = ['token' => 'CE8S52Qq7stf5k8frF4T', 'datas' => json_encode($data)];
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
return 0;
}
}

View file

@ -1,72 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Lib\MigrateOldData;
use App\Models\Brand;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
/**
* @codeCoverageIgnore
*/
class MigrateCrmUsers extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrate:crm';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Migrate crm users';
/**
* Execute the console command.
*
* @return integer
*/
public function handle(): int
{
try {
$table = $this->ask('What is the tmp table name with users data ?');
try {
DB::connection(config('database.oldDB'))->table($table)->exists();
} catch (\Exception $e) {
$this->error(sprintf('%s table not found on old crm database', $table));
return -1;
}
$brandname = $this->ask('What is the brand name ?');
$brand = Brand::query()->where('name', 'LIKE', "%$brandname%")->first();
if (!$brand) {
if (!$this->confirm(sprintf('Would you like to use %s ? ', $brandname))) {
$this->info('Command cancelled');
return 0;
}
if ($this->confirm('Would you like to create a new one ?')) {
$brand = new Brand();
$brand->name = $brandname;
$brand->save();
} else {
$this->info('Command cancelled');
return 0;
}
}
$mgOldData = new MigrateOldData();
$mgOldData->runMigration($brand, $table);
} catch (\Exception $e) {
$this->error(sprintf('Failed %s', $e));
return -1;
} //end try
return 0;
}
}

View file

@ -16,8 +16,9 @@ enum CustomerExportType: int
* Optionnal labels definition
*/
private const LABELS = [
self::singleOptin->name => 'Les single optins uniquement',
self::singleOptin->name => 'Les single-optins uniquement',
self::customer->name => 'Les clients uniquement acceptant de recevoir les newsletters',
self::both->name => 'La totalité des client acceptant de recevoir les newsletters',
self::both->name => 'La totalité des single-optins ainsi que des clients acceptant
de recevoir les newsletters',
];
}

View file

@ -1,13 +0,0 @@
<?php
namespace App\Exceptions;
/**
* This class Exception is used to skip a row import from
* database migration (2016 -> 2020)
*
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
class AbortRowImportException extends \RuntimeException
{
}

View file

@ -70,7 +70,7 @@ class StatsController extends Controller
->whereIn('answer_id', $answers->pluck('id'))
->get()->map(function ($custAnswer) {
return [
'answer_id' => $custAnswer->answer_id,
'answer_id' => $custAnswer->answer_id,
'created_at' => $custAnswer->created_at->isoFormat('YYYY-MM-DD'),
];
})->groupBy(['created_at', 'answer_id'])->map(function ($day) {

View file

@ -22,7 +22,7 @@ class GetBrandStatsRequest extends BaseApiRequest
public function rules(): array
{
try {
if (Carbon::parse($this->end)->floatDiffInMonths(Carbon::parse($this->start)) > 3) {
if (Carbon::parse($this->end)->floatDiffInMonths(Carbon::parse($this->start), true) > 3) {
throw ValidationException::withMessages([
'Vous devez sélectionner une période de maximum 3 mois'
]);
@ -36,7 +36,7 @@ class GetBrandStatsRequest extends BaseApiRequest
throw $e;
}
return [
'start' => 'required|date|date_format:Y-m-d',
'start' => 'required|date|date_format:Y-m-d|before_or_equal:end',
'end' => 'required|date|date_format:Y-m-d|after_or_equal:start',
];
}

View file

@ -23,7 +23,7 @@ class GetQuestionStatsRequest extends BaseApiRequest
public function rules(): array
{
try {
if (Carbon::parse($this->end)->floatDiffInMonths(Carbon::parse($this->start)) > 3) {
if (Carbon::parse($this->end)->floatDiffInMonths(Carbon::parse($this->start), true) > 3) {
throw ValidationException::withMessages([
'Vous devez sélectionner une période de maximum 3 mois'
]);
@ -37,7 +37,7 @@ class GetQuestionStatsRequest extends BaseApiRequest
throw $e;
}
return [
'start' => 'required|date|date_format:Y-m-d',
'start' => 'required|date|date_format:Y-m-d|before_or_equal:end',
'end' => 'required|date|date_format:Y-m-d|after_or_equal:start',
];
}

View file

@ -19,7 +19,7 @@ class GetBrandStatsRequest extends BaseApiRequest
public function rules(): array
{
try {
if (Carbon::parse($this->end)->floatDiffInMonths(Carbon::parse($this->start)) > 3) {
if (Carbon::parse($this->end)->floatDiffInMonths(Carbon::parse($this->start), true) > 3) {
throw ValidationException::withMessages([
'Vous devez sélectionner une période de maximum 3 mois'
]);
@ -27,13 +27,13 @@ class GetBrandStatsRequest extends BaseApiRequest
} catch (\Exception $e) {
if (\get_class($e) !== ValidationException::class) {
throw ValidationException::withMessages([
'Les dates séléectionnées ne sembles pas être valides'
'Les dates sélectionnées ne sembles pas être valides'
]);
}
throw $e;
}
return [
'start' => 'required|date|date_format:Y-m-d',
'start' => 'required|date|date_format:Y-m-d|before_or_equal:end',
'end' => 'required|date|date_format:Y-m-d|after_or_equal:start',
];
}

View file

@ -19,7 +19,7 @@ class GetQuestionStatsRequest extends BaseApiRequest
public function rules(): array
{
try {
if (Carbon::parse($this->end)->floatDiffInMonths(Carbon::parse($this->start)) > 3) {
if (Carbon::parse($this->end)->floatDiffInMonths(Carbon::parse($this->start), true) > 3) {
throw ValidationException::withMessages([
'Vous devez sélectionner une période de maximum 3 mois'
]);
@ -33,7 +33,7 @@ class GetQuestionStatsRequest extends BaseApiRequest
throw $e;
}
return [
'start' => 'required|date|date_format:Y-m-d',
'start' => 'required|date|date_format:Y-m-d|before_or_equal:end',
'end' => 'required|date|date_format:Y-m-d|after_or_equal:start',
];
}

View file

@ -30,9 +30,9 @@ class StatsByBrandRequest extends FormRequest
{
if ($this->post()) {
try {
if ((Carbon::parse($this->end)->diffInDays(Carbon::parse($this->start)) + 1) > 365) {
if ((Carbon::parse($this->end)->diffInDays(Carbon::parse($this->start)->addDay(), true)) > 365) {
throw ValidationException::withMessages([
'Vous devez sélectionner une période de maximum 1 ans'
'Vous devez sélectionner une période de maximum 1 an'
]);
}
} catch (\Exception $e) {

View file

@ -30,7 +30,7 @@ class StatsByQuestionRequest extends FormRequest
{
if ($this->post()) {
try {
if ((Carbon::parse($this->end)->diffInDays(Carbon::parse($this->start)) + 1) > 365) {
if ((Carbon::parse($this->end)->diffInDays(Carbon::parse($this->start)->addDay(), true)) > 365) {
throw ValidationException::withMessages([
'Vous devez sélectionner une période de maximum 1 ans'
]);

View file

@ -36,8 +36,8 @@ class ApiResponse extends JsonResource
{
//phpcs:enable
return [
'status' => $this->status->value(),
'data' => (array)($this->data ?? []),
'status' => $this->status->value(),
'data' => (array)($this->data ?? []),
'version' => '3.0.6'
];
}

View file

@ -37,7 +37,7 @@ class QuestionStatsResource extends JsonResourceCollection
//phpcs:enable
return [
'answers' => (new AnswersResource($this->question->answers))->toArray($request),
'stats' => $this->collection->toArray()
'stats' => $this->collection->toArray()
];
}
}

View file

@ -1,251 +0,0 @@
<?php
namespace App\Lib;
use App\Exceptions\AbortRowImportException;
use App\Models\Brand;
use App\Models\Customer;
use App\Models\CustomerInfo;
use App\Models\CustomerLogin;
use App\Models\SingleOptin;
use Carbon\Exceptions\InvalidFormatException;
use Database\migrations\LeGaulois2016Migration;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
/**
* @codeCoverageIgnore
*/
class MigrateOldData extends LeGaulois2016Migration
{
/** @var \App\Models\Brand */
private $brand;
/** @var string */
private $table;
/**
* RunMigration.
*
* @param \App\Models\Brand $brand
* @param string $table
* @return void
*/
public function runMigration(Brand $brand, string $table): void
{
$this->table = $table;
$this->brand = $brand;
$this->instruct();
$this->up();
}
/**
* Instruct.
*
* @return array
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
*/
public function instruct(): array
{
//phpcs:enable
$this->initFile();
$cleanDegeu = function (string $str) {
return html_entity_decode(
trim(str_replace('\\', '', ucwords(stripcslashes(strtolower($str))))),
ENT_QUOTES | ENT_HTML5,
'UTF-8'
);
};
return [
'Users' => [
'table' => $this->table,
'model' => Customer::class,
'comment' => sprintf('Migrating %s customers', $this->brand->name),
'bind' => [
'email' => [
'apply' => function ($v, $model) use ($cleanDegeu) {
$v = \mb_convert_encoding($v, "UTF-8");
$v = explode('#|#', $v);
$oldId = $v[0];
$first_name = $cleanDegeu($v[1]);
$last_name = $cleanDegeu($v[2]);
$birth_date = $v[3];
$address = $cleanDegeu($v[4]);
$address2 = $cleanDegeu($v[5]);
$city = $cleanDegeu($v[6]);
$postcode = $v[7];
$user_inscritNewsletter = $v[8];
$email = strtolower($v[9]);
$pwd = $v[10];
$created_at = $v[11];
$updated_at = $v[12];
$last_cnx = $v[13];
// * Just save Single optin.
if (empty($first_name) && empty($last_name)) {
$sglOptin = SingleOptin::query()->where('email', strtolower($email))
->whereHas('brand', function (Builder $q) {
$q->where('id', $this->brand->id);
})->firstOrNew();
$sglOptin->email = strtolower($email);
$sglOptin->brand_id = $this->brand->id;
$sglOptin->save();
} else {
// * Validate Data.
$d = [
'first_name' => $first_name,
'last_name' => $last_name,
'address' => $address,
'address2' => $address2,
'city' => $city,
'postcode' => $postcode,
];
$validator = Validator::make($d, [
'first_name' => 'min:2',
'last_name' => 'min:2'
]);
if ($validator->fails()) {
throw new AbortRowImportException();
}
$rules = [
'address' => 'string|min:2',
'address2' => 'string|min:2',
'city' => 'string|min:2',
'postcode' => 'digits_between:4,5'
];
$validate = function (array $data, array $rule) {
return Validator::make($data, $rule)->fails();
};
foreach ($rules as $key => $rule) {
if ($validate([$key => $d[$key]], [$key => $rule])) {
${$key} = null;
}
}
$model = Customer::where('email', $email)->firstOrNew();
$model->email = $email;
$model->created_at = $created_at;
$model->updated_at = $updated_at;
$model->save();
// * Filtre birthdate puisque c'est du sale dans la vielle crm.
try {
$expl = explode('-', $birth_date);
$d = Carbon::parse($birth_date);
if (
$d->toDateString() === sprintf(
'%s-%s-%s',
$expl[2] ?? '',
$expl[1] ?? '',
$expl[0] ?? ''
)
) {
$birth_date = $d->toDateString();
}
} catch (InvalidFormatException $e) {
$birth_date = '';
}
if ($birth_date === '0000-00-00') {
$birth_date = '';
}
$city = !empty($city) ? $city : null;
$postcode = !empty($postcode) ? $postcode : null;
$address = !empty($address) ? $address : null;
$address2 = !empty($address2) ? $address2 : null;
$cInfo = new CustomerInfo();
$cInfo->hashcode = Str::uuid();
$cInfo->firstname = ucfirst(strtolower($first_name));
$cInfo->lastname = ucfirst(strtolower($last_name));
$cInfo->birth_date = !strlen($birth_date) ? null : $birth_date;
$cInfo->address = $address;
$cInfo->address2 = $address2;
$cInfo->city = $city;
$cInfo->postcode = $postcode;
$cInfo->opt_in = $user_inscritNewsletter ? true : false;
$cInfo->brand_id = $this->brand->id;
$cInfo->customer_id = $model->id;
$cInfo->created_at = $created_at;
$cInfo->updated_at = $updated_at;
$cInfo->save();
$cLogin = new CustomerLogin();
$cLogin->password = Hash::make(trim($pwd));
$cLogin->brand_id = $this->brand->id;
$cLogin->customer_id = $model->id;
$cLogin->status = true;
$cLogin->created_at = $created_at;
$cLogin->updated_at = $updated_at;
$cLogin->last_connection = $last_cnx;
$cLogin->save();
$this->write(
[
'new' => $model->id,
'old' => $oldId,
'hashcode' => $cInfo->hashcode,
'created_at' => $created_at,
'updated_at' => $updated_at
]
);
} //end if
throw new AbortRowImportException();
},
'name' => [
'user_id',
'firstname',
'lastname',
'birthdate',
'address',
'address2',
'city',
'postcode',
'optin',
'email',
'pwd',
'created_at',
'updated_at',
'last_cnx'
]
],
]
],
];
}
/**
* Create the migration file.
*
* @return void
*/
public function initFile(): void
{
File::put(storage_path('crm_migration.csv'), sprintf('new;old;hashcode;created_at;updated_at') . PHP_EOL);
}
/**
* Write date in the migration file.
*
* @param array $data
* @return void
*/
public function write(array $data): void
{
foreach ($data as &$d) {
$d = sprintf('"%s"', $d);
}
File::append(storage_path('crm_migration.csv'), implode(';', $data) . PHP_EOL);
}
}

View file

@ -15,8 +15,8 @@ use Illuminate\Database\Eloquent\Model;
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*
* @property-read \App\Models\Answer $answers Answer hasMany relation.
* @property-read \App\Models\Brand $brand Brand BelongsTo relation.
* @property-read \Illuminate\Support\Collection $answers Answer hasMany relation.
* @property-read \App\Models\Brand $brand Brand BelongsTo relation.
*/
class Question extends Model
{

View file

@ -1,6 +1,6 @@
{
"name": "ldc/ldccrm",
"version": "4.0.8",
"version": "4.0.9",
"type": "project",
"description": "LDC CRM",
"license": "MIT",
@ -12,7 +12,7 @@
"laravel"
],
"platform": {
"php": "^8.2"
"php": "^8.3"
},
"repositories": [
{
@ -21,37 +21,38 @@
}
],
"require": {
"php": "^8.2",
"php": "^8.3",
"ext-curl": "*",
"ext-dom": "*",
"ext-json": "*",
"arondeparon/laravel-request-sanitizer": "^5.0",
"axlon/laravel-postal-code-validation": "^3.2",
"diglactic/laravel-breadcrumbs": "^8.1",
"diglactic/laravel-breadcrumbs": "^9.0",
"doctrine/dbal": "^3.0",
"doctrine/inflector": "^2.0",
"guzzlehttp/guzzle": "^7.4",
"laravel/framework": "^10.0",
"laravel/framework": "^11.0",
"laravel/tinker": "^2.8",
"laravel/ui": "^4.2",
"league/csv": "^9.7",
"mews/purifier": "^3.4",
"propaganistas/laravel-phone": "^5.0",
"rennokki/laravel-eloquent-query-cache": "^3.0",
"sentry/sentry-laravel": "^3.4",
"uwil/k8s-laravel": "^1.2"
"rennokki/laravel-eloquent-query-cache": "^3.5",
"sentry/sentry-laravel": "^4.10",
"uwil/admin-secure-laravel": "^3.0",
"uwil/k8s-laravel": "^1.4"
},
"require-dev": {
"brianium/paratest": "^7.2",
"fakerphp/faker": "^1.9.1",
"laravel-lang/common": "^4.0",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^7.0",
"nunomaduro/collision": "^8.1",
"phpunit/phpunit": "^10.0",
"respect/validation": "^2.2",
"slevomat/coding-standard": "^8.10",
"spatie/laravel-ignition": "^2.3",
"symfony/process": "^6.2"
"symfony/process": "^7.2"
},
"config": {
"optimize-autoloader": true,

2282
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -66,26 +66,6 @@ return [
]) : [],
],
'oldcrm' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL_OLD'),
'host' => env('DB_HOST_OLD', '127.0.0.1'),
'port' => env('DB_PORT_OLD', '3306'),
'database' => env('DB_DATABASE_OLD', 'forge'),
'username' => env('DB_USERNAME_OLD', 'forge'),
'password' => env('DB_PASSWORD_OLD', ''),
'unix_socket' => env('DB_SOCKET_OLD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),

View file

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Schema::table('customer_logins', function (Blueprint $table) {
$table->timestamp('last_connection')->nullable()->default(null)->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
Schema::table('customer_logins', function (Blueprint $table) {
$table->timestamp('last_connection')->nullable(false)->change();
});
}
};

View file

@ -1,293 +0,0 @@
<?php
namespace Database\migrations;
use App\Exceptions\AbortRowImportException;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use PDOException;
use ReflectionFunction;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Terminal;
/**
* Migration Intructions
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
* Examples
*[
* 'content_ocb' => [
* 'model' => OCBContent::class,
* 'bind' => [
* 'id' => 'ocb_id',
* 'picture' => 'ocb_img',
* 'content' => 'ocb_content',
* 'status' => 'ocb_is_published',
* 'type' => [
* 'apply' => function ($value) {
* switch ($value) {
* case 'VOLAILLE':
* return OCBType::poultry();
* case 'LAPIN':
* return OCBType::rabbit();
* case 'OEUF':
* return OCBType::egg();
* }
* },
* 'name' => 'ocb_type',
* 'default' => ''
* ],
* 'order' => 'ocb_position',
* 'created_at' => [
* 'name' => '',
* 'default' => date('Y-m-d H:i:s')
* ],
* 'updated_at' => [
* 'name' => '',
* 'default' => date('Y-m-d H:i:s')
* ]
* ]
* ],
* 'Recipe ratings' => [
* 'table' => 'recipe',
* 'comment' => 'Add ratings to recipes',
* 'model' => Rating::class,
* 'bind' => [
* 'anyprop' => [
* 'apply' => function ($recipe_id) {
* $recipe_rating = $this->oldDB->table('recipe_rating')
* ->select('recipe_rating_value')
* ->where('recipe_rating_recipe_id', '=', $recipe_id)
* ->get();
* $count = $recipe_rating->count();
* $sum = $recipe_rating->sum(function ($obj) {
* return $obj->recipe_rating_value;
* });
* $this->newDB->table('ratings')
* ->insert([
* 'total' => $sum,
* 'count' => $count,
* 'rating' => $count ? floatval($sum / $count) : 0,
* 'recipes_id' => $recipe_id,
* 'created_at' => date('Y-m-d H:i:s'),
* 'updated_at' => date('Y-m-d H:i:s'),
* ]);
* throw new AbortRowImportException();
* },
* 'name' => 'recipe_id'
* ]
* ]
* ],
*]
*
* @param array $instructions
* @return void
*/
/**
* Helps to migration from legaulois2016 to legaulois2020
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
*/
abstract class LeGaulois2016Migration extends Migration
{
/** @var ConsoleOutput */
private $output = null;
/** @var ConsoleSectionOutput */
private $outputSection = null;
/** @var \Illuminate\Database\ConnectionInterface */
private $oldDB = null;
/** @var \Illuminate\Database\ConnectionInterface */
private $newDB = null;
/** @var array */
private $instructions = null;
public function __construct()
{
$oldDB = config(sprintf('database.connections.%s', config('database.oldDB')));
$newDB = config(sprintf('database.connections.%s', config('database.newDB')));
if (!$oldDB) {
throw new Exception(sprintf('Unknown database connection %s for newDB', config('database.newDB')));
}
if (!$newDB) {
throw new Exception(sprintf('Unknown database connection %s for oldDB', config('database.oldDB')));
}
$this->oldDB = DB::connection(config('database.oldDB'));
$this->newDB = DB::connection(config('database.newDB'));
}
public function up()
{
$this->instructions = $this->instruct();
$this->processData();
}
public function down()
{
// Do nothing
}
public function __get(string $name)
{
if ($name === 'oldDB') {
return $this->oldDB;
}
if ($name === 'newDB') {
return $this->newDB;
}
}
/**
* Set migration instructions to execute on "up" only
* @param array $instructions
* see Instructions in \App\Database\Migrations\LeGaulois2016Migration
*/
abstract public function instruct(): array;
/**
* Core execution on instruction
*
* @return void
*/
private function processData()
{
$getOldData = function ($keyOrKeys, $array) {
if (is_array($keyOrKeys)) {
$o = [];
foreach ($keyOrKeys as $key) {
$o[] = strval($array[$key]);
}
return implode('#|#', $o);
}
return $array[$keyOrKeys] ?? null;
};
foreach ($this->instructions as $oldTableName => $modelData) {
$migrationName = $oldTableName;
$oldTableName = $modelData['table'] ?? $oldTableName;
$rowNbrs = $this->oldDB->table($oldTableName)->count();
$rowInserted = 0;
$this->consoleLog($this->renderProgress($migrationName, $rowInserted, $rowNbrs));
$i = 0;
$page = 1;
$perPage = env('MIGRATIONPAGINATION', 300);
do {
$results = $this->oldDB->table($oldTableName)->paginate($perPage, ['*'], 'page', $page);
$i += $perPage;
$page++;
foreach ($results as $oldData) {
$model = null;
try { // Try to get exisiting model ID (to avoid SQL Integrity violations doing delete and create)
$model = $modelData['model']::findOrFail(
$getOldData($modelData['bind']['id'] ?? 0, (array)$oldData)
);
} catch (ModelNotFoundException $e) {
$model = new $modelData['model']();
}
try { // bind each property to it's data and save
foreach ($modelData['bind'] as $modelAttr => $oldModelAttr) {
if (is_array($oldModelAttr)) {
if (array_key_exists('apply', $oldModelAttr)) {
$argC = (new ReflectionFunction($oldModelAttr['apply']))->getNumberOfParameters();
$argV = [
$getOldData($oldModelAttr['name'], (array)$oldData)
];
if ($argC > 1) {
$argV[] = $model;
}
$model[$modelAttr] =
call_user_func_array($oldModelAttr['apply'], $argV) ??
$oldModelAttr['default'] ??
null;
} else {
$model[$modelAttr] =
$getOldData($oldModelAttr['name'], (array)$oldData) ??
$oldModelAttr['default'] ??
null;
}
} else {
$model[$modelAttr] = ((array)$oldData)[$oldModelAttr];
}
}
$model->save();
} catch (QueryException $e) {
File::append(\storage_path('error_migration.txt'), implode(',', $e->getBindings()) . PHP_EOL);
} catch (AbortRowImportException $e) {
// DO nothing
} finally {
++$rowInserted;
if (rand(0, 15) == 10) { // prevent screen ficklering
$this->consoleLog($this->renderProgress($migrationName, $rowInserted, $rowNbrs));
}
}
}
} while ($i <= $rowNbrs);
if (array_key_exists('comment', $modelData)) {
$migrationName .= sprintf(' <%s> ', $modelData['comment']);
}
$terminal = new Terminal();
$consoleLength = $terminal->getWidth();
$r = round(80 * 100 / $consoleLength) - strlen($migrationName);
$r = $r >= 0 ? $r : 0;
$this->consoleLog(sprintf('%s%smigrated', $migrationName, str_repeat(' ', $r)));
$this->consoleLog("", true); // Cariage return
}
}
/**
* Prints a message to the console
*
* @param string $message
* @param boolean $newLine
* @return void
*/
private function consoleLog(string $message, bool $newLine = false)
{
if (!$this->output) {
$this->output = new ConsoleOutput();
}
if ($newLine) {
$this->outputSection = null;
$this->output->write(sprintf("<info>%s</info>", $message));
} else {
if (!$this->outputSection) {
$this->outputSection = $this->output->section();
}
$this->outputSection->overwrite(sprintf('<info>%s</info>', $message));
}
}
/**
* Render the progressbar to a string
*
* @param string $oldTableName
* @param integer $count
* @param integer $total
* @return string
*/
private function renderProgress(string $oldTableName, int $count, int $total)
{
$total = !$total ? 1 : $total;
$oldTableName = sprintf('%s ', $oldTableName);
$percent = $count * 100 / $total;
$percentText = sprintf(' [%d of %d]', $count, $total);
$terminal = new Terminal();
$consoleLength = $terminal->getWidth();
$bar = $consoleLength - strlen($oldTableName) - strlen($percentText);
$bar = $bar < 0 ? 0 : $bar;
$prog = round($percent / 100 * $bar);
$rep = $bar - $prog;
return $oldTableName . str_repeat('#', $prog) . str_repeat('_', $rep >= 0 ? $rep : 0) . $percentText;
}
}

View file

@ -10,7 +10,8 @@ data:
APP_DEBUG: "${APP_APP_DEBUG}"
APP_URL: "https://${APP_DOMAIN}"
LOG_CHANNEL: "k8s"
DB_HOST: "mariadb.common-services"
DB_HOST: "${APP_DB_HOST}"
DB_PORT: "${APP_DB_PORT}"
DB_DATABASE: "${APP_DB_DATABASE}"
DB_USERNAME: "${APP_DB_USERNAME}"
DB_PASSWORD: "${APP_DB_PASSWORD}"
@ -23,6 +24,7 @@ data:
MAIL_FROM_ADDRESS: "${APP_MAIL_FROM_ADDRESS}"
MAIL_FROM_NAME: "${APP_APP_NAME}"
SENTRY_LARAVEL_DSN: "${APP_SENTRY_LARAVEL_DSN}"
LDC_WEB_API_KEY: "${APP_LDC_WEB_API_KEY}"
---
apiVersion: v1

2
package-lock.json generated
View file

@ -1,5 +1,5 @@
{
"name": "crm",
"name": "srcs",
"lockfileVersion": 3,
"requires": true,
"packages": {

View file

@ -2,8 +2,7 @@
@section('title', __('Édition d\'un :model', ['model' => __('models.classes.activity_log')]))
@section('description', __('Édition d\'un :model déjà existant', ['model' => __('models.classes.activity_log')]))
@section('breadcrumb',
request()->route()->getName())
@section('breadcrumb', request()->route()->getName())
@section('content')
<div class="d-flex justify-content-between flex-md-nowrap align-items-center flex-wrap pb-3">

View file

@ -3,8 +3,7 @@
@section('title', sprintf('%s - %s', __('models.classes.answers'), Str::ucfirst(__('création'))))
@section('description', __('Création d\'une :model', ['model' => __('models.classes.answers')]))
@section('metaIndex', 'noindex,nofollow')
@section('breadcrumb',
request()->route()->getName())
@section('breadcrumb', request()->route()->getName())
@section('content')
<div class="card border-0">

View file

@ -3,8 +3,7 @@
@section('title', sprintf('%s - %s', __('models.classes.answers'), Str::ucfirst(__('édition'))))
@section('description', __('Édition d\'une :model', ['model' => __('models.classes.answers')]))
@section('metaIndex', 'noindex,nofollow')
@section('breadcrumb',
request()->route()->getName())
@section('breadcrumb', request()->route()->getName())
@section('content')
<div class="card border-0">

View file

@ -1,14 +1,11 @@
<div class="table-responsive">
<table class="table-hover fix-action m-0 table">
<thead class="border-top-0 border-start-0 border-end-0 border border-2">
@php
$cols = [
@include('bo.modules.table-col-sorter', [
'cols' => [
'answer' => __('Réponse'),
'updated_at' => __('Date d\'ajout en base'),
];
@endphp
@include('bo.modules.table-col-sorter', [
'cols' => $cols,
],
'mobileHide' => ['status'],
'ignore' => ['updated_at'],
])

View file

@ -1,16 +1,13 @@
<div class="table-responsive">
<table class="table-hover fix-action m-0 table">
<thead class="border-top-0 border-start-0 border-end-0 border border-2">
@php
$cols = [
@include('bo.modules.table-col-sorter', [
'cols' => [
'name' => __('Nom'),
'status' => __('Nombre de comptes'),
'optin' => __('Nombre d\'optins'),
'updated_at' => __('Date d\'ajout en base'),
];
@endphp
@include('bo.modules.table-col-sorter', [
'cols' => $cols,
],
'mobileHide' => ['status'],
'ignore' => ['status', 'optin', 'updated_at'],
])
@ -23,8 +20,9 @@
<td class="text-center align-middle">{{ $brandModel->customer_infos_count }}</td>
<td class="text-center align-middle">{{ $brandModel->customer_infos_optin_count }}</td>
<td class="text-center align-middle">
<span
class="badge bg-warning text-bg-warning text-wrap">{{ $brandModel->updated_at->formatLocalized('%d/%m/%Y à %H:%M') }}</span>
<span class="badge bg-warning text-bg-warning text-wrap">
{{ $brandModel->updated_at }}
</span>
</td>
<td class="text-end align-middle">
@can('update', \App\Models\Brand::class)

View file

@ -30,7 +30,7 @@
<fieldset>
<legend>{{ __('La marque concernée') }}</legend>
<div class="input-group mb-3">
<label class="input-group-text" for="exportBrand">{{ __('Les client de la marque') }}</label>
<label class="input-group-text" for="exportBrand">{{ __('Les clients de la marque') }}</label>
<select class="form-select" id="exportBrand" name="brand" required>
<option value="" selected>{{ __('Choissez une marque') }}</option>
@foreach ($brands as $i => $brand)

View file

@ -3,8 +3,7 @@
@section('title', sprintf('%s - %s', __('models.classes.customers'), Str::ucfirst(__('aperçu'))))
@section('description', __('Aperçu d\'un :model', ['model' => __('models.classes.customers')]))
@section('metaIndex', 'noindex,nofollow')
@section('breadcrumb',
request()->route()->getName())
@section('breadcrumb', request()->route()->getName())
@section('content')
<div class="card border-0">

View file

@ -30,7 +30,7 @@
<fieldset>
<legend>{{ __('La marque concernée') }}</legend>
<div class="input-group mb-3">
<label class="input-group-text" for="exportBrand">{{ __('Les client de la marque') }}</label>
<label class="input-group-text" for="exportBrand">{{ __('Les clients de la marque') }}</label>
<select class="form-select" id="exportBrand" name="brand" required>
<option value="" selected>{{ __('Choissez une marque') }}</option>
@foreach ($brands as $i => $brand)

View file

@ -1,14 +1,15 @@
<div class="table-responsive">
<table class="table-hover table text-center">
<thead class="border-top-0 border-start-0 border-end-0 border border-2">
@php
$cols = [
@include('bo.modules.table-col-sorter', [
'cols' => [
'question' => __('Question'),
'brand_id' => __('Marque'),
'answers' => __('Réponses'),
];
@endphp
@include('bo.modules.table-col-sorter', ['cols' => $cols, 'mobileHide' => ['status'], 'ignore' => ['answers']])
],
'mobileHide' => ['status'],
'ignore' => ['answers']
])
</thead>
<tbody>
@if (count($questionModels))

View file

@ -1,17 +1,14 @@
<div class="table-responsive">
<table class="table-hover fix-action m-0 table">
<thead class="border-top-0 border-start-0 border-end-0 border border-2">
@php
$cols = [
@include('bo.modules.table-col-sorter', [
'cols' => [
'name' => __('Nom'),
'brand_id' => __('Marque'),
'bearer_token_date' => __('Date du Bearer token'),
'generateToken' => __('Regénerer un token'),
'created_at' => __('Date de création'),
];
@endphp
@include('bo.modules.table-col-sorter', [
'cols' => $cols,
],
'mobileHide' => ['status'],
'ignore' => ['generateToken'],
])

View file

@ -1,15 +1,13 @@
<div class="table-responsive">
<table class="table-hover fix-action m-0 table">
<thead class="border-top-0 border-start-0 border-end-0 border border-2">
@php
$cols = [
@include('bo.modules.table-col-sorter', [
'cols' => [
'hashcode' => __('Hashcode'),
'email' => __('E-mail'),
'brand_id' => __('Marque'),
'created_at' => __('Date opt-in'),
];
@endphp
@include('bo.modules.table-col-sorter', [
'cols' => $cols,
],
'mobileHide' => ['status'],
'ignore' => ['status', 'optin', 'updated_at'],
])
@ -18,6 +16,7 @@
@if ($singleoptinModels->count())
@foreach ($singleoptinModels as $singleoptinModel)
<tr>
<td class="text-center align-middle">{{ $singleoptinModel->hashcode }}</td>
<td class="text-center align-middle">{{ $singleoptinModel->email }}</td>
<td class="text-center align-middle">{{ $singleoptinModel->brand->name }}</td>
<td class="text-center align-middle">

View file

@ -2,8 +2,7 @@
@section('title', __('Création d\'un :model', ['model' => __('models.classes.user')]))
@section('description', __('Création d\'un tout nouveau :model', ['model' => __('models.classes.user')]))
@section('breadcrumb',
request()->route()->getName())
@section('breadcrumb', request()->route()->getName())
@section('content')
<div class="d-flex justify-content-between flex-md-nowrap align-items-center flex-wrap pb-3">

View file

@ -2,8 +2,7 @@
@section('title', __('Édition d\'un :model', ['model' => __('models.classes.user')]))
@section('description', __('Édition d\'un :model déjà existant', ['model' => __('models.classes.user')]))
@section('breadcrumb',
request()->route()->getName())
@section('breadcrumb', request()->route()->getName())
@section('content')
<div class="d-flex justify-content-between flex-md-nowrap align-items-center flex-wrap pb-3">

View file

@ -14,7 +14,7 @@ use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
Route::prefix('bo')->name('bo.')->group(function () {
Route::middleware(['throttle:web', 'admin-secure'])->prefix('bo')->name('bo.')->group(function () {
// * Authenticable routes
Route::namespace('\App\Http\Controllers\Bo')
->group(function () {

View file

@ -10,7 +10,6 @@ use App\Models\Service;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Testing\AssertableJsonString;
use Illuminate\Testing\TestResponse;
use Tests\CreatesApplication;
class ApiBase extends BaseTestCase
@ -39,8 +38,12 @@ class ApiBase extends BaseTestCase
* @param array $headers
* @return \Illuminate\Testing\TestResponse
*/
protected function callApi(string $method, string $uri, array $data = [], array $headers = []): TestResponse
{
protected function callApi(
string $method,
string $uri,
array $data = [],
array $headers = []
): \Illuminate\Testing\TestResponse {
if (!isset($data['timestamp'])) {
$data['timestamp'] = \time();
}
@ -63,7 +66,7 @@ class ApiBase extends BaseTestCase
string $uri,
array $data = [],
array $headers = []
): TestResponse {
): \Illuminate\Testing\TestResponse {
$data['bearer_token'] = $service->bearer_token;
$data['timestamp'] = \gmdate('Y-m-d H:i:s');

View file

@ -15,11 +15,11 @@ class ApiTest extends ApiBase
use DatabaseTransactions;
/**
* Test ApiV2 only handle json calls
* Test ApiV2 only handle json calls.
*
* @return void
*/
public function testOnlyJsonCallsAreHandled()
public function testOnlyJsonCallsAreHandled(): void
{
$response = $this->call('get', route('apiV2.ping'), [
'timestamp' => \gmdate('Y-m-d H:i:s')
@ -32,7 +32,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testTimestampMiddleware()
public function testTimestampMiddleware(): void
{
$response = $this->json('get', route('apiV2.ping'), [
'timestamp' => \gmdate('Y-m-d H:i:s')
@ -46,7 +46,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testTimestampMiddlewareCheckFailMissing()
public function testTimestampMiddlewareCheckFailMissing(): void
{
$response = $this->json('get', route('apiV2.ping'), []);
$json = $response->decodeResponseJson();
@ -62,7 +62,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testTimestampMiddlewareCheckFailWrongFormat()
public function testTimestampMiddlewareCheckFailWrongFormat(): void
{
$response = $this->json('get', route('apiV2.ping'), ['timestamp' => \gmdate('Y/m/d')]);
$json = $response->decodeResponseJson();
@ -78,7 +78,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testTimestampMiddlewareCheckFailIfTooOld()
public function testTimestampMiddlewareCheckFailIfTooOld(): void
{
$response = $this->json('get', route('apiV2.ping'), [
'timestamp' => \gmdate('Y-m-d H:i:s', \time() - config('api.timestampTimeout', 10))
@ -98,7 +98,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testApiThrottle()
public function testApiThrottle(): void
{
for ($i = config('api.apiRequestRatePerMinute', 100); $i >= 0; $i--) {
$this->json('get', route('apiV2.ping'), [
@ -115,11 +115,11 @@ class ApiTest extends ApiBase
}
/**
* Test wrong http method call
* Test wrong http method call.
*
* @return void
*/
public function testWrongMethodCall()
public function testWrongMethodCall(): void
{
$response = $this->json('post', route('apiV2.ping'), [
'timestamp' => \gmdate('Y-m-d H:i:s', \time())
@ -130,11 +130,11 @@ class ApiTest extends ApiBase
}
/**
* Test Auth fail when no token
* Test Auth fail when no token.
*
* @return void
*/
public function testAuthFailNoToken()
public function testAuthFailNoToken(): void
{
$response = $this->json('get', route('apiV2.customers.show', [
'serviceCustomer' => Str::uuid()
@ -147,11 +147,11 @@ class ApiTest extends ApiBase
}
/**
* Test Auth fail when unknown token
* Test Auth fail when unknown token.
*
* @return void
*/
public function testAuthFailUnknownToken()
public function testAuthFailUnknownToken(): void
{
$response = $this->json('get', route('apiV2.customers.show', [
'serviceCustomer' => Str::uuid()
@ -165,19 +165,19 @@ class ApiTest extends ApiBase
}
/**
* Test Auth fail when wrong signature
* Test Auth fail when wrong signature.
*
* @return void
*/
public function testAuthFailWrongSignature()
public function testAuthFailWrongSignature(): void
{
$service = Service::query()->firstOrFail();
$response = $this->json('get', route('apiV2.customers.show', [
'serviceCustomer' => Str::uuid()
]), [
'bearer_token' => $service->bearer_token,
'timestamp' => \gmdate('Y-m-d H:i:s', \time()),
'signature' => 'sdqdqsdqd'
'timestamp' => \gmdate('Y-m-d H:i:s', \time()),
'signature' => 'sdqdqsdqd'
]);
$json = $response->decodeResponseJson();
$this->assertApiResponseStatusIs($json, ApiStatus::KO);

View file

@ -19,27 +19,27 @@ class ArcadiaTest extends ApiBase
*
* @return void
*/
public function testArcadiaSendOrderDefault()
public function testArcadiaSendOrderDefault(): void
{
extract($this->getCustomer());
$data = [
'deliver' => [
'email' => $customer->email,
'deliver' => [
'email' => $customer->email,
'firstname' => $info->firstname,
'lastname' => $info->lastname,
'phone' => $info->phone,
'address' => $info->address,
'address2' => $info->address2,
'city' => $info->city,
'postcode' => $info->postcode,
'lastname' => $info->lastname,
'phone' => $info->phone,
'address' => $info->address,
'address2' => $info->address2,
'city' => $info->city,
'postcode' => $info->postcode,
],
'operation' => 16,
'label_type_support' => 'Send Departaimants',
'order_date' => \date('Y/m/d H:i:s'),
'state_order' => ArcadiaOrderType::cb->value(),
'support_code' => 1,
'label_type_support' => 'Fond carte Aimanté',
'order_num' => 23,
'operation' => 16,
'label_type_support' => 'Send Departaimants',
'order_date' => \date('Y/m/d H:i:s'),
'state_order' => ArcadiaOrderType::cb->value(),
'support_code' => 1,
'label_type_support' => 'Fond carte Aimanté',
'order_num' => 23,
'package_unit_weight' => 0,
];
$response = $this->callApiWithToken($service, 'post', route(
@ -56,26 +56,26 @@ class ArcadiaTest extends ApiBase
*
* @return void
*/
public function testArcadiaSendOrderGame()
public function testArcadiaSendOrderGame(): void
{
extract($this->getCustomer());
$data = [
'deliver' => [
'email' => $customer->email,
'deliver' => [
'email' => $customer->email,
'firstname' => $info->firstname,
'lastname' => $info->lastname,
'phone' => $info->phone,
'address' => $info->address,
'address2' => $info->address2,
'city' => $info->city,
'postcode' => $info->postcode,
'lastname' => $info->lastname,
'phone' => $info->phone,
'address' => $info->address,
'address2' => $info->address2,
'city' => $info->city,
'postcode' => $info->postcode,
],
'operation' => 16,
'order_date' => date('Y/m/d H:i:s'),
'support_code' => 32,
'operation' => 16,
'order_date' => date('Y/m/d H:i:s'),
'support_code' => 32,
'label_type_support' => 'Jeux Reghalal',
'code_unique' => \strtoupper(\str_replace('-', '', (string)Str::uuid())),
'code_on_pack' => '2563547'
'code_unique' => \strtoupper(\str_replace('-', '', (string)Str::uuid())),
'code_on_pack' => '2563547'
];
$response = $this->callApiWithToken($service, 'post', route(
'apiV2.arcadia.outgoingMailGame',

View file

@ -21,11 +21,11 @@ class CustomerTest extends ApiBase
use DatabaseTransactions;
/**
* Test Customer relations to its related models
* Test Customer relations to its related models.
*
* @return void
*/
public function testCustomerRelations()
public function testCustomerRelations(): void
{
extract($this->getCustomer());
$infos = $customer->infos;
@ -46,7 +46,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiAuthenticateCustomerShouldWork()
public function testApiAuthenticateCustomerShouldWork(): void
{
extract($this->getCustomer(true));
@ -58,7 +58,7 @@ class CustomerTest extends ApiBase
'post',
route('apiV2.customers.authenticate', []),
[
'email' => $customer->email,
'email' => $customer->email,
'password' => 'testPassword'
]
);
@ -84,7 +84,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiAuthenticateCustomerShouldFailIfWrongPassword()
public function testApiAuthenticateCustomerShouldFailIfWrongPassword(): void
{
extract($this->getCustomer());
$response = $this->callApiWithToken(
@ -92,7 +92,7 @@ class CustomerTest extends ApiBase
'post',
route('apiV2.customers.authenticate', []),
[
'email' => $customer->email,
'email' => $customer->email,
'password' => 'azdqdqdazd'
]
);
@ -113,7 +113,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiAuthenticateCustomerShouldFailIfWrongEmail()
public function testApiAuthenticateCustomerShouldFailIfWrongEmail(): void
{
extract($this->getCustomer());
$response = $this->callApiWithToken(
@ -121,7 +121,7 @@ class CustomerTest extends ApiBase
'post',
route('apiV2.customers.authenticate', []),
[
'email' => 'wrongemail@hotmail.fr',
'email' => 'wrongemail@hotmail.fr',
'password' => 'azdqdqdazd'
]
);
@ -142,7 +142,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiAuthenticateCustomerShouldFailIfCustomerNotActivated()
public function testApiAuthenticateCustomerShouldFailIfCustomerNotActivated(): void
{
$login = CustomerLogin::query()->where('status', false)->firstOrFail();
/** @var \App\Models\Brand $brand */
@ -156,7 +156,7 @@ class CustomerTest extends ApiBase
'post',
route('apiV2.customers.authenticate', []),
[
'email' => $customer->email,
'email' => $customer->email,
'password' => 'testPassword'
]
);
@ -172,12 +172,12 @@ class CustomerTest extends ApiBase
}
/**
* Customer store ok
* Customer store ok.
* route: apiV2.customers.store
*
* @return void
*/
public function testApiStoreCustomerOk()
public function testApiStoreCustomerOk(): void
{
extract($this->getCustomer());
@ -230,22 +230,22 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiStoreCustomerShouldFailIfCustomerAlreadyExists()
public function testApiStoreCustomerShouldFailIfCustomerAlreadyExists(): void
{
extract($this->getCustomer());
$data = [
'firstname' => 'Jean',
'lastname' => 'Bond',
'firstname' => 'Jean',
'lastname' => 'Bond',
'birth_date' => \date('1992-03-08'),
'address' => '10 rue des toto',
'email' => 'newcustomer@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
'address' => '10 rue des toto',
'email' => 'newcustomer@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
];
$this->createNewCustomer($data, $brand);
@ -259,26 +259,26 @@ class CustomerTest extends ApiBase
}
/**
* Customer store validationFailures
* Customer store validationFailures.
* route: apiV2.customers.store
*
* @return void
*/
public function testApiStoreCustomerValidationFailures()
public function testApiStoreCustomerValidationFailures(): void
{
extract($this->getCustomer());
$data = [
'firstname' => 'Jean',
'lastname' => 'Bond',
'firstname' => 'Jean',
'lastname' => 'Bond',
'birth_date' => \date('1992-03-08'),
'address' => '10 rue des toto',
'email' => 'newcustomer.failures@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
'address' => '10 rue des toto',
'email' => 'newcustomer.failures@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
];
$sendData = $data;
@ -343,12 +343,12 @@ class CustomerTest extends ApiBase
}
/**
* Test activate customer ok
* Test activate customer ok.
* route: apiV2.customers.activate
*
* @return void
*/
public function testActivateCustomerOk()
public function testActivateCustomerOk(): void
{
extract($this->getCustomer(false));
@ -364,12 +364,12 @@ class CustomerTest extends ApiBase
}
/**
* Test activate customer already activated
* Test activate customer already activated.
* route: apiV2.customers.activate
*
* @return void
*/
public function testActivateCustomerAlreadyActivated()
public function testActivateCustomerAlreadyActivated(): void
{
extract($this->getCustomer(true));
@ -387,40 +387,40 @@ class CustomerTest extends ApiBase
}
/**
* Test customer update ok
* Test customer update ok.
* route: apiV2.customers.update
*
* @return void
*/
public function testApiUpdateCustomerOk()
public function testApiUpdateCustomerOk(): void
{
extract($this->getCustomer());
$data = [
'firstname' => 'Jean2',
'lastname' => 'Bond2',
'firstname' => 'Jean2',
'lastname' => 'Bond2',
'birth_date' => \date('1992-03-09'),
'address' => '10 rue des toto',
'email' => 'newcustomertoupdate@hotmail.fr',
'password' => '123.Mot.De.P4sseNew',
'phone' => '+33654821563',
'country' => Country::luxembourg->value(),
'city' => 'Connerré2',
'postcode' => '72161',
'opt_in' => 0
'address' => '10 rue des toto',
'email' => 'newcustomertoupdate@hotmail.fr',
'password' => '123.Mot.De.P4sseNew',
'phone' => '+33654821563',
'country' => Country::luxembourg->value(),
'city' => 'Connerré2',
'postcode' => '72161',
'opt_in' => 0
];
$newdata = [
'firstname' => 'Jean3',
'lastname' => 'Bond3',
'firstname' => 'Jean3',
'lastname' => 'Bond3',
'birth_date' => \date('1992-03-07'),
'address' => '10 rue des toto3',
'email' => 'newcustomertoupdate3@hotmail.fr',
'password' => '123.Mot.De.P4sseNew3',
'phone' => '+33654821564',
'country' => Country::france->value(),
'city' => 'Connerré3',
'postcode' => '72163',
'opt_in' => 1
'address' => '10 rue des toto3',
'email' => 'newcustomertoupdate3@hotmail.fr',
'password' => '123.Mot.De.P4sseNew3',
'phone' => '+33654821564',
'country' => Country::france->value(),
'city' => 'Connerré3',
'postcode' => '72163',
'opt_in' => 1
];
$this->createNewCustomer($data, $brand);
@ -460,26 +460,26 @@ class CustomerTest extends ApiBase
}
/**
* Test customer update should fail if no changes are provided
* Test customer update should fail if no changes are provided.
* route: apiV2.customers.update
*
* @return void
*/
public function testApiUpdateCustomerShouldFailWhenNothingChanges()
public function testApiUpdateCustomerShouldFailWhenNothingChanges(): void
{
extract($this->getCustomer());
$data = [
'firstname' => 'Jean2',
'lastname' => 'Bond2',
'firstname' => 'Jean2',
'lastname' => 'Bond2',
'birth_date' => \date('1992-03-09'),
'address' => '10 rue des toto',
'email' => 'anewcustomertoupdate@hotmail.fr',
'password' => '123.Mot.De.P4sseNew',
'phone' => '+33654821563',
'country' => Country::luxembourg->value(),
'city' => 'Connerré2',
'postcode' => '72161',
'opt_in' => 0
'address' => '10 rue des toto',
'email' => 'anewcustomertoupdate@hotmail.fr',
'password' => '123.Mot.De.P4sseNew',
'phone' => '+33654821563',
'country' => Country::luxembourg->value(),
'city' => 'Connerré2',
'postcode' => '72161',
'opt_in' => 0
];
$this->createNewCustomer($data, $brand);
@ -494,12 +494,12 @@ class CustomerTest extends ApiBase
}
/**
* Test customer show ok
* Test customer show ok.
* route: apiV2.customers.show
*
* @return void
*/
public function testApiGetCustomerOk()
public function testApiGetCustomerOk(): void
{
extract($this->getCustomer());
@ -522,12 +522,12 @@ class CustomerTest extends ApiBase
}
/**
* Test customer show using email ok
* Test customer show using email ok.
* route: apiV2.customers.show
*
* @return void
*/
public function testApiGetCustomerByEmailOk()
public function testApiGetCustomerByEmailOk(): void
{
extract($this->getCustomer());
@ -550,12 +550,12 @@ class CustomerTest extends ApiBase
}
/**
* Test customer show not found
* Test customer show not found.
* route: apiV2.customers.show
*
* @return void
*/
public function testApiGetCustomerNotFound()
public function testApiGetCustomerNotFound(): void
{
extract($this->getCustomer());
$csClassName = \array_slice(explode('\\', get_class($customer)), -1)[0];
@ -587,7 +587,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiDestroyCustomer()
public function testApiDestroyCustomer(): void
{
extract($this->getCustomer());
$csClassName = \array_slice(explode('\\', get_class($customer)), -1)[0];
@ -620,7 +620,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiCompletelyDestroyCustomer()
public function testApiCompletelyDestroyCustomer(): void
{
$customer = Customer::whereHas('logins', null, '>', 1)->firstOrFail();
@ -672,13 +672,13 @@ class CustomerTest extends ApiBase
}
/**
* Make sute a customer exists and contains data
* Make sute a customer exists and contains data.
*
* @param array $data
* @param \App\Models\Brand $brand
* @return void
*/
private function createNewCustomer(array $data, Brand $brand)
private function createNewCustomer(array $data, Brand $brand): void
{
$customer = Customer::whereEmail($data['email'])
->whereHas('brands', function ($q) use ($brand) {

View file

@ -16,7 +16,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionIndex()
public function testQuestionIndex(): void
{
extract($this->getCustomer());
@ -66,7 +66,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionIndexWithAnswers()
public function testQuestionIndexWithAnswers(): void
{
extract($this->getCustomer(true, false));
@ -141,7 +141,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionIndexWithAnswersWhenCustomerNotFound()
public function testQuestionIndexWithAnswersWhenCustomerNotFound(): void
{
extract($this->getCustomer(true, false));
$service = Service::whereHas('brand', function ($q) use ($brand) {
@ -162,7 +162,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testCustomerUnAnsweredIndex()
public function testCustomerUnAnsweredIndex(): void
{
extract($this->getCustomer(true, false));
@ -237,7 +237,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testUnAnsweredIndexWhenCustomerNotFound()
public function testUnAnsweredIndexWhenCustomerNotFound(): void
{
extract($this->getCustomer(true, false));
$service = Service::whereHas('brand', function ($q) use ($brand) {
@ -258,7 +258,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionSetAnswer()
public function testQuestionSetAnswer(): void
{
extract($this->getCustomer(true, false));
$question = Question::whereHas('brand', function ($q) use ($brand) {
@ -275,7 +275,7 @@ class QuestionTest extends ApiBase
['serviceCustomer' => $info->hashcode]
), [
'question' => $question->id,
'answers' => [$answer->id]
'answers' => [$answer->id]
]);
$json = $response->decodeResponseJson();
$this->assertApiResponseStatusIs($json, ApiStatus::OK);
@ -293,7 +293,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionSetAnswerWhenCustomerNotFound()
public function testQuestionSetAnswerWhenCustomerNotFound(): void
{
extract($this->getCustomer(true, false));
$service = Service::whereHas('brand', function ($q) use ($brand) {

View file

@ -16,17 +16,17 @@ class SingleOptinTest extends ApiBase
use DatabaseTransactions;
/**
* Test set single optin on
* Test set single optin on.
* route: apiV2.optin
*
* @return void
*/
public function testSetSingleOptinOn()
public function testSetSingleOptinOn(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'post', route('apiV2.optin'), [
'email' => 'singleoptin@hotmail.fr',
'email' => 'singleoptin@hotmail.fr',
'opt_in' => 1
]);
$json = $response->decodeResponseJson();
@ -38,17 +38,17 @@ class SingleOptinTest extends ApiBase
}
/**
* Test set single optin off
* Test set single optin off.
* route: apiV2.optin
*
* @return void
*/
public function testSetSingleOptinOff()
public function testSetSingleOptinOff(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'post', route('apiV2.optin'), [
'email' => 'singleoptin@hotmail.fr',
'email' => 'singleoptin@hotmail.fr',
'opt_in' => 0
]);
$json = $response->decodeResponseJson();
@ -65,7 +65,7 @@ class SingleOptinTest extends ApiBase
*
* @return void
*/
public function testSingleOptinShouldFailIfCustomerExists()
public function testSingleOptinShouldFailIfCustomerExists(): void
{
$service = Service::firstOrFail();
$this->storeCustomer($service);
@ -77,7 +77,7 @@ class SingleOptinTest extends ApiBase
$singleOptin->saveOrFail();
$response = $this->callApiWithToken($service, 'post', route('apiV2.optin'), [
'email' => 'singleoptin@hotmail.fr',
'email' => 'singleoptin@hotmail.fr',
'opt_in' => 1
]);
@ -88,12 +88,12 @@ class SingleOptinTest extends ApiBase
}
/**
* Test set single optin off using hashcode
* Test set single optin off using hashcode.
* route: apiV2.optout-hashcode
*
* @return void
*/
public function testSetSingleOptoutWithHashcode()
public function testSetSingleOptoutWithHashcode(): void
{
$service = Service::firstOrFail();
@ -116,12 +116,12 @@ class SingleOptinTest extends ApiBase
}
/**
* Test set single optin off using hashcode fails if does not exists
* Test set single optin off using hashcode fails if does not exists.
* route: apiV2.optout-hashcode
*
* @return void
*/
public function testSetSingleOptoutWithHashcodeFailsIfDoesNotExists()
public function testSetSingleOptoutWithHashcodeFailsIfDoesNotExists(): void
{
$service = Service::firstOrFail();
@ -144,25 +144,25 @@ class SingleOptinTest extends ApiBase
}
/**
* Store a customer in DB
* Store a customer in DB.
*
* @param \App\Models\Service $service
* @return void
*/
private function storeCustomer(Service $service)
private function storeCustomer(Service $service): void
{
$data = [
'firstname' => 'Jean',
'lastname' => 'Bond',
'firstname' => 'Jean',
'lastname' => 'Bond',
'birth_date' => \date('1992-03-08'),
'address' => '10 rue des totos',
'email' => 'singleoptin@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
'address' => '10 rue des totos',
'email' => 'singleoptin@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
];
$this->callApiWithToken($service, 'post', route('apiV2.customers.store'), $data);
}

View file

@ -23,13 +23,13 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByBrand()
public function testStatsByBrand(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV2.stats.brandStats'), [
'start' => Carbon::now()->subMonths(3)->isoFormat('YYYY-MM-DD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -57,13 +57,13 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByBrandShouldFailWithInvalidDate()
public function testStatsByBrandShouldFailWithInvalidDate(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV2.stats.brandStats'), [
'start' => Carbon::now()->subMonths(3)->subDay()->isoFormat('YYYY-MM-DD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -77,13 +77,13 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByBrandShouldFailWithInvalidDateFormat()
public function testStatsByBrandShouldFailWithInvalidDateFormat(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV2.stats.brandStats'), [
'start' => Carbon::now()->subMonths(3)->subDay()->isoFormat('YYYY-MM-DD HH:mmDD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -97,7 +97,7 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByQuestion()
public function testStatsByQuestion(): void
{
$service = Service::firstOrFail();
$question = Question::whereBrandId($service->brand->id)->firstOrFail();
@ -116,7 +116,7 @@ class StatsTest extends ApiBase
$response = $this->callApiWithToken($service, 'get', route('apiV2.stats.questionStats', $question), [
'start' => $start->isoFormat('YYYY-MM-DD'),
'end' => $end->isoFormat('YYYY-MM-DD')
'end' => $end->isoFormat('YYYY-MM-DD')
]);
$datesIndexes = [];
@ -150,14 +150,14 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByQuestionShouldFailWithInvalidQuestion()
public function testStatsByQuestionShouldFailWithInvalidQuestion(): void
{
$service = Service::firstOrFail();
$question = Question::where('brand_id', '!=', $service->brand->id)->firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV2.stats.questionStats', $question), [
'start' => Carbon::now()->subMonths(3)->subDay()->isoFormat('YYYY-MM-DD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -171,14 +171,14 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByQuestionShouldFailWithInvalidDate()
public function testStatsByQuestionShouldFailWithInvalidDate(): void
{
$service = Service::firstOrFail();
$question = Question::whereBrandId($service->brand->id)->firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV2.stats.questionStats', $question), [
'start' => Carbon::now()->subMonths(3)->subDay()->isoFormat('YYYY-MM-DD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -192,14 +192,14 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByQuestionShouldFailWithInvalidDateFormat()
public function testStatsByQuestionShouldFailWithInvalidDateFormat(): void
{
$service = Service::firstOrFail();
$question = Question::whereBrandId($service->brand->id)->firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV2.stats.questionStats', $question), [
'start' => Carbon::now()->subMonths(3)->isoFormat('YYYY-MM Ddh'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();

View file

@ -10,7 +10,6 @@ use App\Models\Service;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Testing\AssertableJsonString;
use Illuminate\Testing\TestResponse;
use Tests\CreatesApplication;
class ApiBase extends BaseTestCase
@ -25,13 +24,13 @@ class ApiBase extends BaseTestCase
* @param \App\Enums\ApiStatus $status
* @return void
*/
protected function assertApiResponseStatusIs(AssertableJsonString $json, ApiStatus $status)
protected function assertApiResponseStatusIs(AssertableJsonString $json, ApiStatus $status): void
{
$json->assertFragment(['status' => $status->value]);
}
/**
* Raw Function to call api
* Raw Function to call api.
*
* @param string $method
* @param string $uri
@ -39,8 +38,12 @@ class ApiBase extends BaseTestCase
* @param array $headers
* @return \Illuminate\Testing\TestResponse
*/
protected function callApi(string $method, string $uri, array $data = [], array $headers = []): TestResponse
{
protected function callApi(
string $method,
string $uri,
array $data = [],
array $headers = []
): \Illuminate\Testing\TestResponse {
if (!isset($data['timestamp'])) {
$data['timestamp'] = \time();
}
@ -48,7 +51,7 @@ class ApiBase extends BaseTestCase
}
/**
* Raw Function to call api with Token
* Raw Function to call api with Token.
*
* @param \App\Models\Service $service
* @param string $method
@ -63,7 +66,7 @@ class ApiBase extends BaseTestCase
string $uri,
array $data = [],
array $headers = []
): TestResponse {
): \Illuminate\Testing\TestResponse {
$data['bearer_token'] = $service->bearer_token;
$data['timestamp'] = \gmdate('Y-m-d H:i:s');
@ -78,7 +81,7 @@ class ApiBase extends BaseTestCase
}
/**
* Get Customer models with given status (active or not)
* Get Customer models with given status (active or not).
*
* @param boolean $status The customer status for a brand.
* @param boolean $random Randomize the customer to get.

View file

@ -19,7 +19,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testOnlyJsonCallsAreHandled()
public function testOnlyJsonCallsAreHandled(): void
{
$response = $this->call('get', route('apiV4.ping'), [
'timestamp' => \gmdate('Y-m-d H:i:s')
@ -32,7 +32,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testTimestampMiddleware()
public function testTimestampMiddleware(): void
{
$response = $this->json('get', route('apiV4.ping'), [
'timestamp' => \gmdate('Y-m-d H:i:s')
@ -46,13 +46,13 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testTimestampMiddlewareCheckFailMissing()
public function testTimestampMiddlewareCheckFailMissing(): void
{
$response = $this->json('get', route('apiV4.ping'), []);
$json = $response->decodeResponseJson();
$this->assertApiResponseStatusIs($json, ApiStatus::KO);
$json->assertFragment(['data' => [
'code' => ApiError::wrongTimeStamp->value(),
'code' => ApiError::wrongTimeStamp->value(),
'message' => ApiError::wrongTimeStamp->label()
]]);
}
@ -62,13 +62,13 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testTimestampMiddlewareCheckFailWrongFormat()
public function testTimestampMiddlewareCheckFailWrongFormat(): void
{
$response = $this->json('get', route('apiV4.ping'), ['timestamp' => \gmdate('Y/m/d')]);
$json = $response->decodeResponseJson();
$this->assertApiResponseStatusIs($json, ApiStatus::KO);
$json->assertFragment(['data' => [
'code' => ApiError::wrongTimeStamp->value(),
'code' => ApiError::wrongTimeStamp->value(),
'message' => ApiError::wrongTimeStamp->label()
]]);
}
@ -78,7 +78,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testTimestampMiddlewareCheckFailIfTooOld()
public function testTimestampMiddlewareCheckFailIfTooOld(): void
{
$response = $this->json('get', route('apiV4.ping'), [
'timestamp' => \gmdate('Y-m-d H:i:s', \time() - config('api.timestampTimeout', 10))
@ -98,7 +98,7 @@ class ApiTest extends ApiBase
*
* @return void
*/
public function testApiThrottle()
public function testApiThrottle(): void
{
for ($i = config('api.apiRequestRatePerMinute', 100); $i >= 0; $i--) {
$this->json('get', route('apiV4.ping'), [
@ -115,11 +115,11 @@ class ApiTest extends ApiBase
}
/**
* Test wrong http method call
* Test wrong http method call.
*
* @return void
*/
public function testWrongMethodCall()
public function testWrongMethodCall(): void
{
$response = $this->json('post', route('apiV4.ping'), [
'timestamp' => \gmdate('Y-m-d H:i:s', \time())
@ -130,11 +130,11 @@ class ApiTest extends ApiBase
}
/**
* Test Auth fail when no token
* Test Auth fail when no token.
*
* @return void
*/
public function testAuthFailNoToken()
public function testAuthFailNoToken(): void
{
$response = $this->json('get', route('apiV4.customers.show', [
'serviceCustomer' => Str::uuid()
@ -147,17 +147,17 @@ class ApiTest extends ApiBase
}
/**
* Test Auth fail when unknown token
* Test Auth fail when unknown token.
*
* @return void
*/
public function testAuthFailUnknownToken()
public function testAuthFailUnknownToken(): void
{
$response = $this->json('get', route('apiV4.customers.show', [
'serviceCustomer' => Str::uuid()
]), [
'bearer_token' => 'qsdqsdqsd',
'timestamp' => \gmdate('Y-m-d H:i:s', \time())
'timestamp' => \gmdate('Y-m-d H:i:s', \time())
]);
$json = $response->decodeResponseJson();
$this->assertApiResponseStatusIs($json, ApiStatus::KO);
@ -165,19 +165,19 @@ class ApiTest extends ApiBase
}
/**
* Test Auth fail when wrong signature
* Test Auth fail when wrong signature.
*
* @return void
*/
public function testAuthFailWrongSignature()
public function testAuthFailWrongSignature(): void
{
$service = Service::query()->firstOrFail();
$response = $this->json('get', route('apiV4.customers.show', [
'serviceCustomer' => Str::uuid()
]), [
'bearer_token' => $service->bearer_token,
'timestamp' => \gmdate('Y-m-d H:i:s', \time()),
'signature' => 'sdqdqsdqd'
'timestamp' => \gmdate('Y-m-d H:i:s', \time()),
'signature' => 'sdqdqsdqd'
]);
$json = $response->decodeResponseJson();
$this->assertApiResponseStatusIs($json, ApiStatus::KO);

View file

@ -19,27 +19,27 @@ class ArcadiaTest extends ApiBase
*
* @return void
*/
public function testArcadiaSendOrderDefault()
public function testArcadiaSendOrderDefault(): void
{
extract($this->getCustomer());
$data = [
'deliver' => [
'email' => $customer->email,
'email' => $customer->email,
'firstname' => $info->firstname,
'lastname' => $info->lastname,
'phone' => $info->phone,
'address' => $info->address,
'address2' => $info->address2,
'city' => $info->city,
'postcode' => $info->postcode,
'lastname' => $info->lastname,
'phone' => $info->phone,
'address' => $info->address,
'address2' => $info->address2,
'city' => $info->city,
'postcode' => $info->postcode,
],
'operation' => 16,
'label_type_support' => 'Send Departaimants',
'order_date' => \date('Y/m/d H:i:s'),
'state_order' => ArcadiaOrderType::cb->value,
'support_code' => 1,
'label_type_support' => 'Fond carte Aimanté',
'order_num' => 23,
'operation' => 16,
'label_type_support' => 'Send Departaimants',
'order_date' => \date('Y/m/d H:i:s'),
'state_order' => ArcadiaOrderType::cb->value,
'support_code' => 1,
'label_type_support' => 'Fond carte Aimanté',
'order_num' => 23,
'package_unit_weight' => 0,
];
$response = $this->callApiWithToken($service, 'post', route(
@ -56,26 +56,26 @@ class ArcadiaTest extends ApiBase
*
* @return void
*/
public function testArcadiaSendOrderGame()
public function testArcadiaSendOrderGame(): void
{
extract($this->getCustomer());
$data = [
'deliver' => [
'email' => $customer->email,
'deliver' => [
'email' => $customer->email,
'firstname' => $info->firstname,
'lastname' => $info->lastname,
'phone' => $info->phone,
'address' => $info->address,
'address2' => $info->address2,
'city' => $info->city,
'postcode' => $info->postcode,
'lastname' => $info->lastname,
'phone' => $info->phone,
'address' => $info->address,
'address2' => $info->address2,
'city' => $info->city,
'postcode' => $info->postcode,
],
'operation' => 16,
'order_date' => date('Y/m/d H:i:s'),
'support_code' => 32,
'operation' => 16,
'order_date' => date('Y/m/d H:i:s'),
'support_code' => 32,
'label_type_support' => 'Jeux Reghalal',
'code_unique' => \strtoupper(\str_replace('-', '', (string)Str::uuid())),
'code_on_pack' => '2563547'
'code_unique' => \strtoupper(\str_replace('-', '', (string)Str::uuid())),
'code_on_pack' => '2563547'
];
$response = $this->callApiWithToken($service, 'post', route(
'apiV4.arcadia.outgoingMailGame',

View file

@ -25,7 +25,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testCustomerRelations()
public function testCustomerRelations(): void
{
extract($this->getCustomer());
$infos = $customer->infos;
@ -46,7 +46,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiAuthenticateCustomerShouldWork()
public function testApiAuthenticateCustomerShouldWork(): void
{
extract($this->getCustomer(true));
@ -58,7 +58,7 @@ class CustomerTest extends ApiBase
'post',
route('apiV4.customers.authenticate', []),
[
'email' => $customer->email,
'email' => $customer->email,
'password' => 'testPassword'
]
);
@ -84,7 +84,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiAuthenticateCustomerShouldFailIfWrongPassword()
public function testApiAuthenticateCustomerShouldFailIfWrongPassword(): void
{
extract($this->getCustomer());
$response = $this->callApiWithToken(
@ -92,7 +92,7 @@ class CustomerTest extends ApiBase
'post',
route('apiV4.customers.authenticate', []),
[
'email' => $customer->email,
'email' => $customer->email,
'password' => 'azdqdqdazd'
]
);
@ -113,7 +113,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiAuthenticateCustomerShouldFailIfWrongEmail()
public function testApiAuthenticateCustomerShouldFailIfWrongEmail(): void
{
extract($this->getCustomer());
$response = $this->callApiWithToken(
@ -121,7 +121,7 @@ class CustomerTest extends ApiBase
'post',
route('apiV4.customers.authenticate', []),
[
'email' => 'wrongemail@hotmail.fr',
'email' => 'wrongemail@hotmail.fr',
'password' => 'azdqdqdazd'
]
);
@ -142,7 +142,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiAuthenticateCustomerShouldFailIfCustomerNotActivated()
public function testApiAuthenticateCustomerShouldFailIfCustomerNotActivated(): void
{
$login = CustomerLogin::query()->where('status', false)->firstOrFail();
/** @var \App\Models\Brand $brand */
@ -177,7 +177,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiStoreCustomerOk()
public function testApiStoreCustomerOk(): void
{
extract($this->getCustomer());
@ -230,22 +230,22 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiStoreCustomerShouldFailIfCustomerAlreadyExists()
public function testApiStoreCustomerShouldFailIfCustomerAlreadyExists(): void
{
extract($this->getCustomer());
$data = [
'firstname' => 'Jean',
'lastname' => 'Bond',
'firstname' => 'Jean',
'lastname' => 'Bond',
'birth_date' => \date('1992-03-08'),
'address' => '10 rue des toto',
'email' => 'newcustomer@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
'address' => '10 rue des toto',
'email' => 'newcustomer@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
];
$this->createNewCustomer($data, $brand);
@ -264,21 +264,21 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiStoreCustomerValidationFailures()
public function testApiStoreCustomerValidationFailures(): void
{
extract($this->getCustomer());
$data = [
'firstname' => 'Jean',
'lastname' => 'Bond',
'firstname' => 'Jean',
'lastname' => 'Bond',
'birth_date' => \date('1992-03-08'),
'address' => '10 rue des toto',
'email' => 'newcustomer.failures@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
'address' => '10 rue des toto',
'email' => 'newcustomer.failures@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value(),
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
];
$sendData = $data;
@ -343,12 +343,12 @@ class CustomerTest extends ApiBase
}
/**
* Test activate customer ok
* Test activate customer ok.
* route: apiV4.customers.activate
*
* @return void
*/
public function testActivateCustomerOk()
public function testActivateCustomerOk(): void
{
extract($this->getCustomer(false));
@ -364,12 +364,12 @@ class CustomerTest extends ApiBase
}
/**
* Test activate customer already activated
* Test activate customer already activated.
* route: apiV4.customers.activate
*
* @return void
*/
public function testActivateCustomerAlreadyActivated()
public function testActivateCustomerAlreadyActivated(): void
{
extract($this->getCustomer(true));
@ -387,40 +387,40 @@ class CustomerTest extends ApiBase
}
/**
* Test customer update ok
* Test customer update ok.
* route: apiV4.customers.update
*
* @return void
*/
public function testApiUpdateCustomerOk()
public function testApiUpdateCustomerOk(): void
{
extract($this->getCustomer());
$data = [
'firstname' => 'Jean2',
'lastname' => 'Bond2',
'firstname' => 'Jean2',
'lastname' => 'Bond2',
'birth_date' => \date('1992-03-09'),
'address' => '10 rue des toto',
'email' => 'newcustomertoupdate@hotmail.fr',
'password' => '123.Mot.De.P4sseNew',
'phone' => '+33654821563',
'country' => Country::luxembourg->value(),
'city' => 'Connerré2',
'postcode' => '72161',
'opt_in' => 0
'address' => '10 rue des toto',
'email' => 'newcustomertoupdate@hotmail.fr',
'password' => '123.Mot.De.P4sseNew',
'phone' => '+33654821563',
'country' => Country::luxembourg->value(),
'city' => 'Connerré2',
'postcode' => '72161',
'opt_in' => 0
];
$newdata = [
'firstname' => 'Jean3',
'lastname' => 'Bond3',
'firstname' => 'Jean3',
'lastname' => 'Bond3',
'birth_date' => \date('1992-03-07'),
'address' => '10 rue des toto3',
'email' => 'newcustomertoupdate3@hotmail.fr',
'password' => '123.Mot.De.P4sseNew3',
'phone' => '+33654821564',
'country' => Country::france->value(),
'city' => 'Connerré3',
'postcode' => '72163',
'opt_in' => 1
'address' => '10 rue des toto3',
'email' => 'newcustomertoupdate3@hotmail.fr',
'password' => '123.Mot.De.P4sseNew3',
'phone' => '+33654821564',
'country' => Country::france->value(),
'city' => 'Connerré3',
'postcode' => '72163',
'opt_in' => 1
];
$this->createNewCustomer($data, $brand);
@ -460,26 +460,26 @@ class CustomerTest extends ApiBase
}
/**
* Test customer update should fail if no changes are provided
* Test customer update should fail if no changes are provided.
* route: apiV4.customers.update
*
* @return void
*/
public function testApiUpdateCustomerShouldFailWhenNothingChanges()
public function testApiUpdateCustomerShouldFailWhenNothingChanges(): void
{
extract($this->getCustomer());
$data = [
'firstname' => 'Jean2',
'lastname' => 'Bond2',
'firstname' => 'Jean2',
'lastname' => 'Bond2',
'birth_date' => \date('1992-03-09'),
'address' => '10 rue des toto',
'email' => 'anewcustomertoupdate@hotmail.fr',
'password' => '123.Mot.De.P4sseNew',
'phone' => '+33654821563',
'country' => Country::luxembourg->value(),
'city' => 'Connerré2',
'postcode' => '72161',
'opt_in' => 0
'address' => '10 rue des toto',
'email' => 'anewcustomertoupdate@hotmail.fr',
'password' => '123.Mot.De.P4sseNew',
'phone' => '+33654821563',
'country' => Country::luxembourg->value(),
'city' => 'Connerré2',
'postcode' => '72161',
'opt_in' => 0
];
$this->createNewCustomer($data, $brand);
@ -494,12 +494,12 @@ class CustomerTest extends ApiBase
}
/**
* Test customer show ok
* Test customer show ok.
* route: apiV4.customers.show
*
* @return void
*/
public function testApiGetCustomerOk()
public function testApiGetCustomerOk(): void
{
extract($this->getCustomer());
@ -522,12 +522,12 @@ class CustomerTest extends ApiBase
}
/**
* Test customer show using email ok
* Test customer show using email ok.
* route: apiV4.customers.show
*
* @return void
*/
public function testApiGetCustomerByEmailOk()
public function testApiGetCustomerByEmailOk(): void
{
extract($this->getCustomer());
@ -550,12 +550,12 @@ class CustomerTest extends ApiBase
}
/**
* Test customer show not found
* Test customer show not found.
* route: apiV4.customers.show
*
* @return void
*/
public function testApiGetCustomerNotFound()
public function testApiGetCustomerNotFound(): void
{
extract($this->getCustomer());
$csClassName = \array_slice(explode('\\', get_class($customer)), -1)[0];
@ -587,7 +587,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiDestroyCustomer()
public function testApiDestroyCustomer(): void
{
extract($this->getCustomer());
$csClassName = \array_slice(explode('\\', get_class($customer)), -1)[0];
@ -620,7 +620,7 @@ class CustomerTest extends ApiBase
*
* @return void
*/
public function testApiCompletelyDestroyCustomer()
public function testApiCompletelyDestroyCustomer(): void
{
$customer = Customer::whereHas('logins', null, '>', 1)->firstOrFail();
@ -672,13 +672,13 @@ class CustomerTest extends ApiBase
}
/**
* Make sute a customer exists and contains data
* Make sute a customer exists and contains data.
*
* @param array $data
* @param \App\Models\Brand $brand
* @return void
*/
private function createNewCustomer(array $data, Brand $brand)
private function createNewCustomer(array $data, Brand $brand): void
{
$customer = Customer::whereEmail($data['email'])
->whereHas('brands', function ($q) use ($brand) {

View file

@ -16,7 +16,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionIndex()
public function testQuestionIndex(): void
{
extract($this->getCustomer());
@ -66,7 +66,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionIndexWithAnswers()
public function testQuestionIndexWithAnswers(): void
{
extract($this->getCustomer(true, false));
@ -141,7 +141,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionIndexWithAnswersWhenCustomerNotFound()
public function testQuestionIndexWithAnswersWhenCustomerNotFound(): void
{
extract($this->getCustomer(true, false));
$service = Service::whereHas('brand', function ($q) use ($brand) {
@ -162,7 +162,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testCustomerUnAnsweredIndex()
public function testCustomerUnAnsweredIndex(): void
{
extract($this->getCustomer(true, false));
@ -237,7 +237,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testUnAnsweredIndexWhenCustomerNotFound()
public function testUnAnsweredIndexWhenCustomerNotFound(): void
{
extract($this->getCustomer(true, false));
$service = Service::whereHas('brand', function ($q) use ($brand) {
@ -258,7 +258,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionSetAnswer()
public function testQuestionSetAnswer(): void
{
extract($this->getCustomer(true, false));
$question = Question::whereHas('brand', function ($q) use ($brand) {
@ -275,7 +275,7 @@ class QuestionTest extends ApiBase
['serviceCustomer' => $info->hashcode]
), [
'question' => $question->id,
'answers' => [$answer->id]
'answers' => [$answer->id]
]);
$json = $response->decodeResponseJson();
$this->assertApiResponseStatusIs($json, ApiStatus::OK);
@ -293,7 +293,7 @@ class QuestionTest extends ApiBase
*
* @return void
*/
public function testQuestionSetAnswerWhenCustomerNotFound()
public function testQuestionSetAnswerWhenCustomerNotFound(): void
{
extract($this->getCustomer(true, false));
$service = Service::whereHas('brand', function ($q) use ($brand) {

View file

@ -16,17 +16,17 @@ class SingleOptinTest extends ApiBase
use DatabaseTransactions;
/**
* Test set single optin on
* Test set single optin on.
* route: apiV4.optin
*
* @return void
*/
public function testSetSingleOptinOn()
public function testSetSingleOptinOn(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'post', route('apiV4.optin'), [
'email' => 'singleoptin@hotmail.fr',
'email' => 'singleoptin@hotmail.fr',
'opt_in' => 1
]);
$json = $response->decodeResponseJson();
@ -38,17 +38,17 @@ class SingleOptinTest extends ApiBase
}
/**
* Test set single optin off
* Test set single optin off.
* route: apiV4.optin
*
* @return void
*/
public function testSetSingleOptinOff()
public function testSetSingleOptinOff(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'post', route('apiV4.optin'), [
'email' => 'singleoptin@hotmail.fr',
'email' => 'singleoptin@hotmail.fr',
'opt_in' => 0
]);
$json = $response->decodeResponseJson();
@ -65,7 +65,7 @@ class SingleOptinTest extends ApiBase
*
* @return void
*/
public function testSingleOptinShouldFailIfCustomerExists()
public function testSingleOptinShouldFailIfCustomerExists(): void
{
$service = Service::firstOrFail();
$this->storeCustomer($service);
@ -77,7 +77,7 @@ class SingleOptinTest extends ApiBase
$singleOptin->saveOrFail();
$response = $this->callApiWithToken($service, 'post', route('apiV4.optin'), [
'email' => 'singleoptin@hotmail.fr',
'email' => 'singleoptin@hotmail.fr',
'opt_in' => 1
]);
@ -88,12 +88,12 @@ class SingleOptinTest extends ApiBase
}
/**
* Test set single optin off using hashcode
* Test set single optin off using hashcode.
* route: apiV4.optout-hashcode
*
* @return void
*/
public function testSetSingleOptoutWithHashcode()
public function testSetSingleOptoutWithHashcode(): void
{
$service = Service::firstOrFail();
@ -116,12 +116,12 @@ class SingleOptinTest extends ApiBase
}
/**
* Test set single optin off using hashcode fails if does not exists
* Test set single optin off using hashcode fails if does not exists.
* route: apiV4.optout-hashcode
*
* @return void
*/
public function testSetSingleOptoutWithHashcodeFailsIfDoesNotExists()
public function testSetSingleOptoutWithHashcodeFailsIfDoesNotExists(): void
{
$service = Service::firstOrFail();
@ -144,25 +144,25 @@ class SingleOptinTest extends ApiBase
}
/**
* Store a customer in DB
* Store a customer in DB.
*
* @param \App\Models\Service $service
* @return void
*/
private function storeCustomer(Service $service)
private function storeCustomer(Service $service): void
{
$data = [
'firstname' => 'Jean',
'lastname' => 'Bond',
'firstname' => 'Jean',
'lastname' => 'Bond',
'birth_date' => \date('1992-03-08'),
'address' => '10 rue des totos',
'email' => 'singleoptin@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value,
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
'address' => '10 rue des totos',
'email' => 'singleoptin@hotmail.fr',
'password' => '123.Mot.De.P4sse',
'phone' => '+33654821562',
'country' => Country::france->value,
'city' => 'Connerré',
'postcode' => '72160',
'opt_in' => true
];
$this->callApiWithToken($service, 'post', route('apiV4.customers.store'), $data);
}

View file

@ -23,13 +23,13 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByBrand()
public function testStatsByBrand(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV4.stats.brandStats'), [
'start' => Carbon::now()->subMonths(3)->isoFormat('YYYY-MM-DD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -57,13 +57,13 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByBrandShouldFailWithInvalidDate()
public function testStatsByBrandShouldFailWithInvalidDate(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV4.stats.brandStats'), [
'start' => Carbon::now()->subMonths(3)->subDay()->isoFormat('YYYY-MM-DD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -77,13 +77,13 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByBrandShouldFailWithInvalidDateFormat()
public function testStatsByBrandShouldFailWithInvalidDateFormat(): void
{
$service = Service::firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV4.stats.brandStats'), [
'start' => Carbon::now()->subMonths(3)->subDay()->isoFormat('YYYY-MM-DD HH:mmDD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -97,7 +97,7 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByQuestion()
public function testStatsByQuestion(): void
{
$service = Service::firstOrFail();
$question = Question::whereBrandId($service->brand->id)->firstOrFail();
@ -116,7 +116,7 @@ class StatsTest extends ApiBase
$response = $this->callApiWithToken($service, 'get', route('apiV4.stats.questionStats', $question), [
'start' => $start->isoFormat('YYYY-MM-DD'),
'end' => $end->isoFormat('YYYY-MM-DD')
'end' => $end->isoFormat('YYYY-MM-DD')
]);
$datesIndexes = [];
@ -139,7 +139,7 @@ class StatsTest extends ApiBase
'answer'
]
],
'stats' => $datesIndexes
'stats' => $datesIndexes
]
]);
}
@ -150,14 +150,14 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByQuestionShouldFailWithInvalidQuestion()
public function testStatsByQuestionShouldFailWithInvalidQuestion(): void
{
$service = Service::firstOrFail();
$question = Question::where('brand_id', '!=', $service->brand->id)->firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV4.stats.questionStats', $question), [
'start' => Carbon::now()->subMonths(3)->subDay()->isoFormat('YYYY-MM-DD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -171,14 +171,14 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByQuestionShouldFailWithInvalidDate()
public function testStatsByQuestionShouldFailWithInvalidDate(): void
{
$service = Service::firstOrFail();
$question = Question::whereBrandId($service->brand->id)->firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV4.stats.questionStats', $question), [
'start' => Carbon::now()->subMonths(3)->subDay()->isoFormat('YYYY-MM-DD'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();
@ -192,14 +192,14 @@ class StatsTest extends ApiBase
*
* @return void
*/
public function testStatsByQuestionShouldFailWithInvalidDateFormat()
public function testStatsByQuestionShouldFailWithInvalidDateFormat(): void
{
$service = Service::firstOrFail();
$question = Question::whereBrandId($service->brand->id)->firstOrFail();
$response = $this->callApiWithToken($service, 'get', route('apiV4.stats.questionStats', $question), [
'start' => Carbon::now()->subMonths(3)->isoFormat('YYYY-MM Ddh'),
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
'end' => Carbon::now()->isoFormat('YYYY-MM-DD')
]);
$json = $response->decodeResponseJson();

View file

@ -11,7 +11,7 @@ trait CreatesApplication
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
public function createApplication(): \Illuminate\Foundation\Application
{
$app = require __DIR__ . '/../bootstrap/app.php';

View file

@ -54,7 +54,7 @@ class RunMultipleRequestsTest extends TestCase
*
* @return void
*/
public function testSpamSingleOptin()
public function testSpamSingleOptin(): void
{
for ($i = 35; $i >= 0; $i--) {
$this->assertTrue(SingleOptin::setStatus('singleoptinteststress@gmail.com', (bool)rand(0, 1)));
@ -66,7 +66,7 @@ class RunMultipleRequestsTest extends TestCase
*
* @return void
*/
public function testSpamCustomerGet()
public function testSpamCustomerGet(): void
{
for ($i = 35; $i >= 0; $i--) {
$this->assertIsObject(Customer::find(self::$info->hashcode));
@ -78,7 +78,7 @@ class RunMultipleRequestsTest extends TestCase
*
* @return void
*/
public function testSpamQuestionsGet()
public function testSpamQuestionsGet(): void
{
for ($i = 35; $i >= 0; $i--) {
$this->assertIsArray(Question::all());
@ -90,7 +90,7 @@ class RunMultipleRequestsTest extends TestCase
*
* @return void
*/
public function testSpamCustomerGets()
public function testSpamCustomerGets(): void
{
for ($i = 35; $i >= 0; $i--) {
$this->assertIsObject(Customer::findWithEmail(self::$customer->email));
@ -98,10 +98,12 @@ class RunMultipleRequestsTest extends TestCase
}
/**
* Get a customer.
*
* @param boolean $status
* @return array
*/
protected static function getCustomer(bool $status = true)
protected static function getCustomer(bool $status = true): array
{
/** @var \App\Models\Costumer $customer */
$customer = ModelsCustomer::whereHas('logins', function ($q) use ($status) {