Merge branch 'develop' into v2

This commit is contained in:
Jérémy Munsch 2021-07-22 14:44:54 +02:00
commit 6324606e44
22 changed files with 1699 additions and 85 deletions

View file

@ -14,6 +14,15 @@ 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=file
QUEUE_CONNECTION=sync

4
.gitignore vendored
View file

@ -14,3 +14,7 @@ Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
storage/crm_migration.csv
MIG/errors_sql.txt
public/js
public/css

View file

@ -0,0 +1,69 @@
<?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));
}
}

96
MIG/Db.php Normal file
View file

@ -0,0 +1,96 @@
<?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);
}
}
}

90
MIG/export.php Normal file
View file

@ -0,0 +1,90 @@
<?php
ini_set("memory_limit", "-1");
set_time_limit(0);
error_reporting(E_ALL);
require_once 'Db.php';
require_once 'CPlatosChiffrement.class.php';
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);
}

9
MIG/make_tmp_table.sql Normal file
View file

@ -0,0 +1,9 @@
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;

80
MIG/migrate.php Normal file
View file

@ -0,0 +1,80 @@
<?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);
}
}

89
MIG/pwd.php Normal file
View file

@ -0,0 +1,89 @@
<?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

@ -0,0 +1,77 @@
<?php
namespace App\Console\Commands;
use App\Lib\MigrateOldData;
use App\Models\Brand;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
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 int
*/
public function handle()
{
try {
$date = null;
// $table = $this->ask('What is the tmp table name with users data ?');
$table = 'legaulois_migration';
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::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;
}
return 0;
}
}

View file

@ -0,0 +1,14 @@
<?php
namespace App\Exceptions;
use Exception;
/**
* 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 Exception
{
}

View file

@ -21,6 +21,7 @@ class ArcadiaController extends Controller
'crm_id' => 'required',
'fields' => 'required|json',
'type' => 'required',
'shipping' => 'required_if:type,default|json'
]);
if ($validator->fails()) {
@ -33,9 +34,10 @@ class ArcadiaController extends Controller
}
$brandId = $request->brand_id;
$crmId = $request->crm_id;
$fields = json_decode($request->fields);
$type = $request->type;
$crmId = $request->crm_id;
$fields = json_decode($request->fields);
$type = $request->type;
$shipping = $type === 'default' ? json_decode($request->shipping) : false;
$customer = Customer::where('id', $crmId)->first();
if (!$customer) {
@ -53,10 +55,16 @@ class ArcadiaController extends Controller
return new StatusResource($check);
}
$xml = $this->makeXml($fields, $type, $customer, $CustomerInfo);
if ($type === 'default') {
$check = $this->checkShippingRequiredFields($shipping);
if ($check['status'] !== 'OK')
return new StatusResource($check);
}
$xml = $this->makeXML($fields, $type, $customer, $CustomerInfo, $shipping);
try {
Storage::disk('arcadia')->put(date("Ymd_His") . ".xml", $xml);
Storage::disk('arcadia')->put(date ("Ymd_His") . microtime(true) . ".xml", $xml);
return new StatusResource(['status' => 'OK']);
} catch (\Exception $e) {
Log::critical("ARCADIA XML CREATION FAILED : " . $e->getMessage());
@ -69,7 +77,28 @@ class ArcadiaController extends Controller
}
}
private function checkShippingRequiredFields($fields)
{
$test = [
'firstname',
'lastname',
'address',
'city',
'postcode'
];
foreach ($test as $t) {
if (!array_key_exists($t, $fields)){
$errors[] = ['field' => $t, 'error' => 'required'];
}
}
if (!empty($errors))
return ['status' => 'KO', 'code' => 203, 'message' => $errors];
return ['status' => 'OK'];
}
private function checkRequiredFields($fields, $type)
{
@ -155,14 +184,13 @@ class ArcadiaController extends Controller
}
}
if (!empty($errors)) {
return ['status' => 'NOK', 'code' => 203, 'message' => $errors];
}
if (!empty($errors))
return ['status' => 'KO', 'code' => 203, 'message' => $errors];
return ['status' => 'OK'];
}
private function makeXml($fields, $type, $customer, $CustomerInfo)
private function makeXML($fields, $type, $customer, $customerInfos, $shipping)
{
$pivot = [
'order_num' => 'Num_Commande', // required if type = default - format 9 numeric characters
@ -217,33 +245,30 @@ class ArcadiaController extends Controller
}
}
$order->appendChild(
$dom->createElement('Email_conso')
)->appendChild($dom->createCDATASection("$customer->email"));
$order->appendChild(
$dom->createElement('Civilite')
);
$order->appendChild(
$dom->createElement('Nom')
)->appendChild($dom->createCDATASection("$CustomerInfo->lastname"));
$order->appendChild(
$dom->createElement('Prenom')
)->appendChild($dom->createCDATASection("$CustomerInfo->firstname"));
$order->appendChild(
$dom->createElement('Adresse')
)->appendChild($dom->createCDATASection("$CustomerInfo->address"));
$order->appendChild(
$dom->createElement('Adresse_Complementaire')
)->appendChild($dom->createCDATASection("$CustomerInfo->address2"));
$order->appendChild(
$dom->createElement('CP')
)->appendChild($dom->createCDATASection("$CustomerInfo->postcode"));
$order->appendChild(
$dom->createElement('Ville')
)->appendChild($dom->createCDATASection("$CustomerInfo->city"));
$order->appendChild(
$dom->createElement('Telephone')
)->appendChild($dom->createCDATASection("$CustomerInfo->phone"));
$order->appendChild($dom->createElement('Email_conso'))->appendChild($dom->createCDATASection( "$customer->email"));
$order->appendChild($dom->createElement('Civilite'));
if ($type === 'default') {
$order->appendChild($dom->createElement('Nom'))->appendChild($dom->createCDATASection("$shipping->lastname"));
$order->appendChild($dom->createElement('Prenom'))->appendChild($dom->createCDATASection("$shipping->firstname"));
$order->appendChild($dom->createElement('Adresse'))->appendChild($dom->createCDATASection("$shipping->address"));
$order->appendChild($dom->createElement('Adresse_Complementaire'));
$order->appendChild($dom->createElement('CP'))->appendChild($dom->createCDATASection("$shipping->postcode"));
$order->appendChild($dom->createElement('Ville'))->appendChild($dom->createCDATASection("$shipping->city"));
if (isset($shipping->phone) && !empty($shipping->phone)) {
$order->appendChild($dom->createElement('Telephone'))->appendChild($dom->createCDATASection("$shipping->phone"));
}else{
$order->appendChild($dom->createElement('Telephone'));
}
} else {
$order->appendChild($dom->createElement('Nom'))->appendChild($dom->createCDATASection( "$customerInfos->lastname"));
$order->appendChild($dom->createElement('Prenom'))->appendChild($dom->createCDATASection( "$customerInfos->firstname"));
$order->appendChild($dom->createElement('Adresse'))->appendChild($dom->createCDATASection( "$customerInfos->address"));
$order->appendChild($dom->createElement('Adresse_Complementaire'))->appendChild($dom->createCDATASection( "$customerInfos->address2"));
$order->appendChild($dom->createElement('CP'))->appendChild($dom->createCDATASection( "$customerInfos->postcode"));
$order->appendChild($dom->createElement('Ville'))->appendChild($dom->createCDATASection( "$customerInfos->city"));
$order->appendChild($dom->createElement('Telephone'))->appendChild($dom->createCDATASection( "$customerInfos->phone"));
}
$orderLine = $order->appendChild($dom->createElement('Ligne_de_Commande'));

View file

@ -54,8 +54,8 @@ class CustomerController extends Controller
// Si le customer n'existe pas déjà
if (!$customer) {
$customer = new Customer();
$customer->email = $email;
$customer = new Customer();
$customer->email = strtolower($email);
$customer->save();
$singleOptin = SingleOptin::where([['email', $email], ['brand_id', $brandId]])->first();
if ($singleOptin) {
@ -72,22 +72,22 @@ class CustomerController extends Controller
}
}
$CustomerInfo = new CustomerInfo();
$CustomerInfo->firstname = $firstname;
$CustomerInfo->lastname = $lastname;
$CustomerInfo->birth_date = !empty($request->birth_date) ? filter_var($request->birth_date, FILTER_SANITIZE_STRING) : null;
$CustomerInfo->address = !empty($request->address) ? filter_var($request->address, FILTER_SANITIZE_STRING) : null;
$CustomerInfo->address2 = !empty($request->address2) ? filter_var($request->address2, FILTER_SANITIZE_STRING) : null;
$CustomerInfo->phone = !empty($request->phone) ? filter_var($request->phone, FILTER_SANITIZE_STRING) : null;
$CustomerInfo->country = !empty($request->country) ? filter_var($request->country, FILTER_SANITIZE_STRING) : null;
$CustomerInfo->city = !empty($request->city) ? filter_var($request->city, FILTER_SANITIZE_STRING) : null;
$CustomerInfo->postcode = !empty($request->postcode) ? filter_var($request->postcode, FILTER_SANITIZE_STRING) : null;
$CustomerInfo->opt_in = $optIn;
$CustomerInfo->hashcode = $hashcode;
$CustomerInfo->brand_id = $brandId;
$CustomerInfo->customer_id = $customer->id;
$customerInfos = new CustomerInfo();
$customerInfos->firstname = ucfirst(strtolower($firstname));
$customerInfos->lastname = ucfirst(strtolower($lastname));
$customerInfos->birth_date = !empty($request->birth_date) ? filter_var($request->birth_date, FILTER_SANITIZE_STRING) : null;
$customerInfos->address = !empty($request->address) ? filter_var($request->address, FILTER_SANITIZE_STRING) : null;
$customerInfos->address2 = !empty($request->address2) ? filter_var($request->address2, FILTER_SANITIZE_STRING) : null;
$customerInfos->phone = !empty($request->phone) ? filter_var($request->phone, FILTER_SANITIZE_STRING) : null;
$customerInfos->country = !empty($request->country) ? filter_var($request->country, FILTER_SANITIZE_STRING) : null;
$customerInfos->city = !empty($request->city) ? filter_var($request->city, FILTER_SANITIZE_STRING) : null;
$customerInfos->postcode = !empty($request->postcode) ? filter_var($request->postcode, FILTER_SANITIZE_STRING) : null;
$customerInfos->opt_in = $optIn;
$customerInfos->hashcode = $hashcode;
$customerInfos->brand_id = $brandId;
$customerInfos->customer_id = $customer->id;
$customer->infos()->save($CustomerInfo);
$customer->infos()->save($customerInfos);
// Création du login pour cet utilisateur sur ce service
$customerLogin = new CustomerLogin();
@ -176,43 +176,69 @@ class CustomerController extends Controller
return new StatusResource(['status' => 'KO', 'code' => 105, 'message' => 'User not found.']);
}
if (isset($request->firstname)) {
if ($request->has('firstname'))
$CustomerInfo->firstname = filter_var($request->firstname, FILTER_SANITIZE_STRING);
}
if (isset($request->lastname)) {
if ($request->has('lastname'))
$CustomerInfo->lastname = filter_var($request->lastname, FILTER_SANITIZE_STRING);
if ($request->has('birth_date')) {
if (!empty($request->birth_date)){
$CustomerInfo->birth_date = filter_var($request->birth_date, FILTER_SANITIZE_STRING);
}else{
$CustomerInfo->birth_date = null;
}
}
if (isset($request->birth_date)) {
$CustomerInfo->birth_date = filter_var($request->birth_date, FILTER_SANITIZE_STRING);
if ($request->has('address')) {
if (!empty($request->address)){
$CustomerInfo->address = filter_var($request->address, FILTER_SANITIZE_STRING);
}else{
$CustomerInfo->address = null;
}
}
if (isset($request->address)) {
$CustomerInfo->address = filter_var($request->address, FILTER_SANITIZE_STRING);
if ($request->has('address2')) {
if (!empty($request->address2)){
$CustomerInfo->address2 = filter_var($request->address2, FILTER_SANITIZE_STRING);
}else{
$CustomerInfo->address2 = null;
}
}
if (isset($request->address2)) {
$CustomerInfo->address2 = filter_var($request->address2, FILTER_SANITIZE_STRING);
if ($request->has('phone')) {
if (!empty($request->phone)){
$CustomerInfo->phone = filter_var($request->phone, FILTER_SANITIZE_STRING);
}else{
$CustomerInfo->phone = null;
}
}
if (isset($request->phone)) {
$CustomerInfo->phone = filter_var($request->phone, FILTER_SANITIZE_STRING);
if ($request->has('country')) {
if (!empty($request->country)){
$CustomerInfo->country = filter_var($request->country, FILTER_SANITIZE_STRING);
}else{
$CustomerInfo->country = null;
}
}
if (isset($request->country)) {
$CustomerInfo->country = filter_var($request->country, FILTER_SANITIZE_STRING);
if ($request->has('city')) {
if (!empty($request->city)){
$CustomerInfo->city = filter_var($request->city, FILTER_SANITIZE_STRING);
}else{
$CustomerInfo->city = null;
}
}
if (isset($request->city)) {
$CustomerInfo->city = filter_var($request->city, FILTER_SANITIZE_STRING);
if ($request->has('postcode')) {
if (!empty($request->postcode)){
$CustomerInfo->postcode = filter_var($request->postcode, FILTER_SANITIZE_STRING);
}else{
$CustomerInfo->postcode = null;
}
}
if (isset($request->postcode)) {
$CustomerInfo->postcode = filter_var($request->postcode, FILTER_SANITIZE_STRING);
}
if (isset($request->opt_in)) {
if ($request->has('opt_in')) {
$optIn = filter_var($request->opt_in, FILTER_SANITIZE_STRING);
if ($CustomerInfo->opt_in != $optIn) {
@ -271,6 +297,7 @@ class CustomerController extends Controller
'crm_id' => $customer->id,
'firstname' => $infos->firstname,
'lastname' => $infos->lastname,
'email' => $customer->email,
'birth_date' => $infos->birth_date,
'address' => $infos->address,
'address2' => $infos->address2,

211
app/Lib/MigrateOldData.php Normal file
View file

@ -0,0 +1,211 @@
<?php
namespace App\Lib;
use App\Exceptions\AbortRowImportException;
use App\Models\Brand;
use App\Models\Customer;
use App\Models\CustomerInfos;
use App\Models\CustomerLogin;
use App\Models\SingleOptin;
use Carbon\Exceptions\InvalidFormatException;
use Database\migrations\LeGaulois2016Migration;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class MigrateOldData extends LeGaulois2016Migration
{
/** @var Brand */
private $brand;
public function runMigration(Brand $brand, string $table)
{
$this->table = $table;
$this->brand = $brand;
$this->instruct();
$this->up();
}
public function instruct(): array
{
$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::where('email', strtolower($email))
->where('brand_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 = null;
}
if ($birth_date === '0000-00-00') {
$birth_date = null;
}
$city = !empty($city) ? $city : null;
$postcode = !empty($postcode) ? $postcode : null;
$address = !empty($address) ? $address : null;
$address2 = !empty($address2) ? $address2 : null;
$cInfo = new CustomerInfos();
$cInfo->hashcode = Str::uuid();
$cInfo->firstname = ucfirst(strtolower($first_name));
$cInfo->lastname = ucfirst(strtolower($last_name));
$cInfo->birth_date = strlen($birth_date) ? $birth_date : null;
$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
]
);
}
throw new AbortRowImportException();
},
'name' => [
'user_id',
'firstname',
'lastname',
'birthdate',
'address',
'address2',
'city',
'postcode',
'optin',
'email',
'pwd',
'created_at',
'updated_at',
'last_cnx'
]
],
]
],
];
}
public function initFile()
{
File::put(storage_path('crm_migration.csv'), sprintf('new;old;hashcode;created_at;updated_at') . PHP_EOL);
}
public function write(array $data)
{
foreach ($data as &$d) {
$d = sprintf('"%s"', $d);
}
File::append(storage_path('crm_migration.csv'), implode(';', $data) . PHP_EOL);
}
}

View file

@ -104,8 +104,12 @@ class ApiV1
return $this->callAPI('POST', '/single-optin', ['email' => $email]);
}
public function ArcadiaOutgoingMail($crm_id, $fields, $type){
return $this->callAPI('POST', '/arcadia/outgoing-mail', ['crm_id' => $crm_id, 'fields' => json_encode($fields), 'type' => $type]);
public function ArcadiaOutgoingMail($crm_id, $fields, $type, $shipping = false){
if ($shipping !== false && $type === 'default') {
return $this->callAPI('POST', '/arcadia/outgoing-mail', ['crm_id' => $crm_id, 'fields' => json_encode($fields), 'type' => $type, 'shipping' => json_encode($shipping)]);
}else{
return $this->callAPI('POST', '/arcadia/outgoing-mail', ['crm_id' => $crm_id, 'fields' => json_encode($fields), 'type' => $type]);
}
}
private function callAPI($method, $url, $data = false){

351
clients/WPCrm.php Normal file
View file

@ -0,0 +1,351 @@
<?php
/**
* LDCCRM For Wordpress usage
* php version 5
*
* @category API
* @package None
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
* @license MIT https://opensource.org/licenses/MIT
* @version GIT: 0.0.1
* @link /
*/
namespace LDCCRM;
use Exception;
// TABLE LDC CUSTOMERS
// CREATE TABLE `ldc_wp_customers` (
// `crm_id` BIGINT NOT NULL COMMENT 'Le CRM ID',
// `hashcode` VARCHAR(36) NOT NULL DEFAULT '' COMMENT 'Le hashcode (UUID)',
// `email` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Le customer email',
// PRIMARY KEY (`crm_id`),
// UNIQUE INDEX `hashcode` (`hashcode`)
// )
// COMMENT='Les customers sur un WP liées à la CRM'
// COLLATE='utf8mb4_unicode_ci';
/**
* Class de gestion des users en session avec Wordpress (ce truc immonde)
* Compatible avec php5
*
* @category API
* @package None
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
* @license MIT https://opensource.org/licenses/MIT
* @link /
*/
class WPCrm extends ApiV1
{
private static $_sessionKey = 'LDC_CRM_USER';
private static $_sessionDestroyed = false;
/**
* The user object
*
* @var \LDCCRM\ApiV1
*/
protected static $api = null;
/**
* The user object
*
* @var \LDCCRM\WPCrmUser
*/
protected static $user = null;
/**
* Try to login with CRM API
* return api response code if an error occurs
*
* @param string $email The customer email
* @param string $password The customer password
*
* @return \LDCCRM\WPCrmUser|int
*/
public static function login($email, $password)
{
self::_bootSessionIfNeeded();
return self::_loginUserWithApi($email, $password);
}
/**
* Get the current user
* return null if the user is not logged in
*
* @return \LDCCRM\WPCrmUser|null
*/
public static function getUser()
{
self::_bootSessionIfNeeded();
return self::$user;
}
/**
* Get the current user
* return api response code if an error occurs
*
* @param string $email The customer email
*
* @return \LDCCRM\WPCrmUser|int
*/
public static function getUserFromApi($email)
{
self::_initLDCApi();
/**
* Object response
*
* @var object
*/
$response = self::$api->getCustomerByEmail($email);
if ($response->status === 'KO') {
error_log(
sprintf(
'LDC CRM: returned KO from CRM => %s',
$response->message
)
);
return $response->code;
}
self::_setUser(
$response->user->crm_id,
$response->user->hashcode,
$response->user->email,
$response
);
return self::$user;
}
/**
* Get the current user
* return null if the user is not logged in
*
* @param string $email The customer email
* @param string $password The customer password
*
* @return \LDCCRM\WPCrmUser|int
*/
private static function _loginUserWithApi($email, $password)
{
self::_initLDCApi();
/**
* Object response
*
* @var object
*/
$response = self::$api->loginCustomer($email, $password);
if ($response->status === 'KO') {
error_log(
sprintf(
'LDC CRM: returned KO from CRM => %s',
$response->message
)
);
return $response->code;
}
self::_setUser(
$response->user->crm_id,
$response->user->hashcode,
$response->user->email,
$response
);
self::_saveOrUpdateUserToTable();
return self::$user;
}
/**
* Destroy the customer from session
* and therefore logout
*
* @return void
*/
public static function logout()
{
self::_bootSessionIfNeeded();
unset($_SESSION[self::$_sessionKey]);
session_destroy();
self::$_sessionDestroyed = true;
}
/**
* Check if the user is Authenticated
*
* @return bool
*/
public static function check()
{
self::_bootSessionIfNeeded();
return (bool) self::getUser();
}
/**
* Create a user
* stores it to the session
* and finally saves it to the database if it does not exists
*
* @param int $crm_id The crm id
* @param string $hashcode The customer hashcode (UUID)
* @param string $email The customer email
* @param object $response The crm API response
*
* @return void
*/
private static function _setUser($crm_id, $hashcode, $email, $response)
{
self::_bootSessionIfNeeded();
if (!self::$user) {
self::$user = new WPCrmUser($crm_id, $hashcode, $email);
}
self::$user->setInfo($response->user);
$_SESSION[self::$_sessionKey] = json_encode(self::$user);
}
/**
* Get the initialized API object
*
* @return \LDCCRM\ApiV1
*/
private static function _initLDCApi()
{
if (!self::$api) {
if (!extension_loaded('curl')) {
throw new Exception(
'LDC CRM require php extension curl'
);
}
$endpoint = getenv('CRM_ENDPOINT');
$api_key = getenv('CRM_API_TOKEN');
if ($endpoint === false or $api_key === false) {
throw new Exception(
'LDC CRM require .env to have CRM_ENDPOINT and CRM_API_TOKEN'
);
}
self::$api = new ApiV1($endpoint, $api_key);
}
return self::$api;
}
/**
* Boot the php session if needed
*
* @return void
*/
private static function _bootSessionIfNeeded()
{
if (!session_id() && !self::$_sessionDestroyed) {
session_start();
}
if (!self::$user and array_key_exists(self::$_sessionKey, $_SESSION)) {
/**
* The user object
*
* @var \LDCCRM\WPCrmUser
*/
self::$user = WPCrmUser::parseFromJson(
$_SESSION[self::$_sessionKey] ?? null
);
}
}
/**
* Get a customer from table
*
* @param int $crm_id The customer crm id
*
* @return object|null
*/
public static function getUserFromTable($crm_id)
{
return self::_getWpDB()->get_row(
'SELECT * FROM `ldc_wp_customers` WHERE `crm_id` = ' . $crm_id
);
}
/**
* Get a customer from table by an email
*
* @param int $email The customer email
*
* @return object|null
*/
public static function getUserFromTableByEmail($email)
{
return self::_getWpDB()->get_row(
'SELECT * FROM `ldc_wp_customers` WHERE `email` = "' . $email . '"'
);
}
/**
* Get a customer from table
*
* @param int $crm_id The customer crm id
*
* @return object|null
*/
public static function getUserToTable($crm_id)
{
return self::_getWpDB()->get_row(
'SELECT * FROM `ldc_wp_customers` WHERE `crm_id` = ' .
self::$user->crm_id
);
}
/**
* Save or update the user to the table
*
* @return void
*/
private static function _saveOrUpdateUserToTable()
{
if (self::getUserToTable(self::$user->crm_id)) {
self::_query(
'UPDATE `ldc_wp_customers` SET `hashcode` = %d, `email` = %d' .
' WHERE `crm_id` = %d',
[
'crm_id' => self::$user->crm_id,
'hashcode' => self::$user->hashcode,
'email' => self::$user->email,
]
);
} else {
self::_query(
'INSERT INTO `ldc_wp_customers` VALUES (%d, %s, %s)',
[
'crm_id' => self::$user->crm_id,
'hashcode' => self::$user->hashcode,
'email' => self::$user->email,
]
);
}
}
/**
* Query in DB
*
* @param string $query La request avec les variables en points d'interrogation
* @param array $params Les paramètres des la requète
*
* @return object Containing the row columns
*/
private static function _query($query, array $params = [])
{
return self::_getWpDB()->query(
self::_getWpDB()->prepare($query, $params)
);
}
/**
* Get WP 'pdo instance'
*
* @return object The $wpdb variable
*/
private static function _getWpDB()
{
global $wpdb;
return $wpdb;
}
}

148
clients/WPCrmUser.php Normal file
View file

@ -0,0 +1,148 @@
<?php
/**
* LDCCRM For Wordpress usage
* php version 5
*
* @category API
* @package None
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
* @license MIT https://opensource.org/licenses/MIT
* @version GIT: 0.0.1
* @link /
*/
namespace LDCCRM;
use Exception;
use JsonSerializable;
/**
* Class de gestion des users en session avec Wordpress (ce truc immonde)
* Compatible avec php5
*
* @category API
* @package None
* @author Jérémy Munsch <jeremy.munsch@ldc.fr>
* @license MIT https://opensource.org/licenses/MIT
* @link /
*/
class WPCrmUser implements JsonSerializable
{
/**
* The CRM ID
*
* @var int
*/
protected $crm_id = null;
/**
* The CRM hashcode (UUID)
*
* @var string
*/
protected $hashcode = null;
/**
* The CRM customer email
*
* @var string
*/
protected $email = null;
/**
* The CRM customer info (the api response)
*
* @var object
*/
protected $info = null;
/**
* WPCrmUser construct
*
* @param int $crm_id The crm id
* @param string $hashcode The customer hashcode (UUID)
* @param string $email The customer email
*/
public function __construct($crm_id, $hashcode, $email)
{
$this->crm_id = $crm_id;
$this->hashcode = $hashcode;
$this->email = $email;
}
/**
* Magic getter
*
* @param string $prop The prop to get
*
* @return int|string
*/
public function __get($prop)
{
if (is_null($this->info)) {
/**
* Object response
*
* @var object
*/
WPCrm::getUserFromApi($this->email);
}
if (!array_key_exists($prop, (array)$this->info)) {
throw new Exception('This value does not exists');
}
return $this->info->{$prop};
}
/**
* Set the customer info
* with api response
*
* @param object $info The Api object reponse (user)
*
* @return void
*/
public function setInfo($info)
{
if (is_null($info) or is_null($info->email)) {
throw new Exception('Info cannot be null');
}
$this->info = $info;
$this->crm_id = $info->crm_id;
$this->email = $info->email;
$this->hashcode = $info->hashcode;
}
/**
* Generate a user from session data
*
* @param string $string The json data stored in session
*
* @return \LDCCRM\WPCrmUser
*/
public static function parseFromJson($string)
{
$a = json_decode($string, true);
return new self(
$a['crm_id'],
$a['hashcode'],
$a['email'],
$a['info']
);
}
/**
* Serialize this object to an array
*
* @return array
*/
public function jsonSerialize()
{
return [
'crm_id' => $this->crm_id,
'hashcode' => $this->hashcode,
'email' => $this->email,
'info' => $this->info
];
}
}

View file

@ -48,6 +48,7 @@
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\migrations\\": "database/migrations/",
"Database\\Seeders\\": "database/seeders/"
}
},

View file

@ -33,6 +33,9 @@ return [
|
*/
'oldDB' => 'oldcrm',
'newDB' => 'mysql',
'connections' => [
'sqlite' => [
@ -63,6 +66,26 @@ 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,293 @@
<?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;
}
}

8
public/css/app.css vendored

File diff suppressed because one or more lines are too long

2
public/js/app.js vendored

File diff suppressed because one or more lines are too long

View file

@ -53,7 +53,11 @@
</tr>
<tr>
<td><b>Date de la dernière modification de l'abonnement</b></td>
@if($customerInfos->customer->optInHistory()->orderBy('created_at', 'DESC')->exists())
<td>{{ \Carbon\Carbon::parse($customerInfos->customer->optInHistory()->orderBy('created_at', 'DESC')->first()->created_at)->format('d/m/Y à H:i') }}</td>
@else
<td></td>
@endif
</tr>
<tr>
<td><b>Dernière connexion</b></td>