Remove crm v1 - issue Closes #20

This commit is contained in:
Alexis Gousseau 2023-09-04 13:03:34 +02:00 • committed by Jérémy Munsch
parent 74aec7bf9f
commit e4b5eed7e4
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC
15 changed files with 7 additions and 2236 deletions

View file

@ -5,6 +5,7 @@ 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');

View file

@ -1,363 +0,0 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Resources\StatusResource;
use App\Mail\CourrierArcadiaError;
use App\Models\Customer;
use DOMDocument;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
/**
* @codeCoverageIgnore
*/
class ArcadiaController extends Controller
{
/**
* @param \Illuminate\Http\Request $request
* @return \App\Http\Resources\StatusResource
*/
public function outgoingMail(Request $request)
{
$validator = Validator::make($request->all(), [
'crm_id' => 'required',
'fields' => 'required|json',
'type' => 'required',
'shipping' => 'required_if:type,default|json'
]);
if ($validator->fails()) {
return new StatusResource([
'status' => 'KO',
'code' => 201,
'message' => 'Error on required fields.',
'errors' => $validator->errors()
]);
}
$brandId = $request->brand_id;
$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) {
return new StatusResource(['status' => 'KO', 'code' => 202, 'message' => 'User not found.']);
}
$CustomerInfo = $customer->infos()->where('brand_id', $brandId)->first();
if (!$CustomerInfo) {
return new StatusResource(['status' => 'KO', 'code' => 202, 'message' => 'User not found.']);
}
$check = $this->checkRequiredFields($fields, $type);
if ($check['status'] !== 'OK') {
return new StatusResource($check);
}
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") . microtime(true) . ".xml", $xml);
return new StatusResource(['status' => 'OK']);
} catch (\Exception $e) {
Log::critical("ARCADIA XML CREATION FAILED : " . $e->getMessage());
Mail::to(config('mail.MAIL_ADMIN'))->send(new CourrierArcadiaError(
"ARCADIA XML CREATION FAILED",
"Une erreur est survenue lors de la création du fichier XML : " . $e->getMessage(),
$xml ?: ''
));
return new StatusResource(['status' => 'KO', 'code' => 204, 'message' => 'Arcadia XML Creation failed.']);
}
}
/**
* @param mixed $fields
* @return array
*/
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'];
}
/**
*
* @param mixed $fields
* @param mixed $type
* @return array
*/
// phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh, Squiz.Commenting.FunctionComment.Missing
private function checkRequiredFields($fields, $type): array
{
$errors = [];
$key = array_search('operation', array_column($fields->root, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'operation', 'error' => 'required'];
}
$key = array_search('support_code', array_column($fields->orderLine, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'support_code', 'error' => 'required'];
}
$key = array_search('label_type_support', array_column($fields->orderLine, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'label_type_support', 'error' => 'required'];
}
$key = array_search('order_date', array_column($fields->root, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'order_date', 'error' => 'required'];
}
$regex = join('', [
'/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|',
'((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))',
'|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]',
'|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/'
]);
if (!preg_match($regex, $fields->root[$key]->fieldValue)) {
$errors[] = ['field' => 'order_date', 'error' => 'format must be DD/MM/YYYY'];
}
if ($type === 'default') {
$key = array_search('order_num', array_column($fields->root, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'order_num', 'error' => 'required for default type'];
}
if (!is_numeric($fields->root[$key]->fieldValue) || strlen($fields->root[$key]->fieldValue) !== 9) {
$errors[] = ['field' => 'order_num', 'error' => 'format must be 9 numeric characters'];
}
$key = array_search('state_order_cb', array_column($fields->root, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'state_order_cb', 'error' => 'required for default type'];
}
if ($fields->root[$key]->fieldValue !== 1 && $fields->root[$key]->fieldValue !== 'Null') {
$errors[] = ['field' => 'state_order_cb', 'error' => 'value must be 1 or Null (Yes Null not NULL)'];
}
$orderCB = $fields->root[$key]->fieldValue;
$key = array_search('state_order_check', array_column($fields->root, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'state_order_check', 'error' => 'required for default type'];
}
if ($fields->root[$key]->fieldValue !== 1 && $fields->root[$key]->fieldValue !== 'Null') {
$errors[] = ['field' => 'state_order_check', 'error' => 'value must be 1 or Null (Yes Null not NULL)'];
}
$orderCheck = $fields->root[$key]->fieldValue;
if ($orderCB === $orderCheck) {
$errors[] = [
'field' => 'state_order',
'error' => 'state_order_cb and state_order_check values must be different'
];
}
$key = array_search('package_unit_weight', array_column($fields->orderLine, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'package_unit_weight', 'error' => 'required for default type'];
}
} elseif ($type === 'game') {
$key = array_search('code_unique', array_column($fields->orderLine, 'fieldName'));
if ($key === false) {
$errors[] = ['field' => 'code_unique', 'error' => 'required for game type'];
}
}//end if
if (!empty($errors)) {
return ['status' => 'KO', 'code' => 203, 'message' => $errors];
}
return ['status' => 'OK'];
}
/**
* @param mixed $fields
* @param mixed $type
* @param mixed $customer
* @param mixed $customerInfos
* @param mixed $shipping
* @return string|false
*/
// phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh, Squiz.Commenting.FunctionComment.Missing
private function makeXml($fields, $type, $customer, $customerInfos, $shipping)
{
$pivot = [
'order_num' => 'Num_Commande',
// Required if type = default - format 9 numeric characters.
'order_date' => 'Date_Commande',
// Required - format : DD/MM/YYYY .
'operation' => 'Operation',
// Required.
'support_code' => 'Code_Support',
// Required.
'label_type_support' => 'Libelle_Type_Support',
// Required.
'package_unit_weight' => 'Poids_Unitaire_Colis',
// Required if type = default.
'qty' => 'Quantite',
'code_on_pack' => 'Code_on_Pack',
'code_unique' => 'Code_Unique',
// Required if type = game.
// Required if type = default - format 1 ou Null (oui Null et pas NULL).
'state_order_cb' => 'Etat_Commande_CB',
// Required if type = default - format 1 ou Null (oui Null et pas NULL).
'state_order_check' => 'Etat_Commande_Cheque',
];
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$root = $dom->createElement('export_arcadia');
$dom->appendChild($root);
$order = $root->appendChild($dom->createElement('Commande'));
$key = array_search('order_num', array_column($fields->root, 'fieldName'));
if ($key === false) {
$order->appendChild($dom->createElement('Num_Commande'));
} else {
$order->appendChild($dom->createElement('Num_Commande', $fields->root[$key]->fieldValue));
}
foreach ($fields->root as $value) {
// phpcs:ignore PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace
if (
isset($pivot[$value->fieldName]) && $value->fieldName !== 'state_order_cb' &&
$value->fieldName !== 'state_order_check' && $value->fieldName !== 'order_num'
) {
$order->appendChild($dom->createElement($pivot[$value->fieldName], $value->fieldValue));
}
}
if ($type === 'default') {
$key = array_search('state_order_cb', array_column($fields->root, 'fieldName'));
if ($key) {
$order->appendChild($dom->createElement('Etat_Commande_CB', $fields->root[$key]->fieldValue));
}
$key = array_search('state_order_check', array_column($fields->root, 'fieldName'));
if ($key) {
$order->appendChild($dom->createElement('Etat_Commande_Cheque', $fields->root[$key]->fieldValue));
}
}
$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"));
}//end if
$orderLine = $order->appendChild($dom->createElement('Ligne_de_Commande'));
$key = array_search('qty', array_column($fields->orderLine, 'fieldName'));
if ($key === false) {
$orderLine->appendChild($dom->createElement('Quantite', '1'));
}
$key = array_search('package_unit_weight', array_column($fields->orderLine, 'fieldName'));
if ($key === false) {
$orderLine->appendChild($dom->createElement('Poids_Unitaire_Colis'));
}
foreach ($fields->orderLine as $value) {
// phpcs:ignore PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace
if (
isset($pivot[$value->fieldName]) &&
$value->fieldName !== 'code_on_pack' &&
$value->fieldName !== 'code_unique'
) {
$orderLine->appendChild($dom->createElement($pivot[$value->fieldName], $value->fieldValue));
}
}
if ($type === 'game') {
$key = array_search('code_on_pack', array_column($fields->orderLine, 'fieldName'));
if ($key !== false) {
$orderLine->appendChild(
$dom->createElement('Code_on_Pack')
)->appendChild($dom->createCDATASection($fields->orderLine[$key]->fieldValue));
}
$key = array_search('code_unique', array_column($fields->orderLine, 'fieldName'));
if ($key !== false) {
$orderLine->appendChild(
$dom->createElement('Code_Unique')
)->appendChild($dom->createCDATASection($fields->orderLine[$key]->fieldValue));
}
}
return $dom->saveXML();
}
}

View file

@ -1,574 +0,0 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Enums\Country;
use App\Http\Controllers\Controller;
use App\Http\Resources\CustomerResource;
use App\Http\Resources\StatusResource;
use App\Models\Customer;
use App\Models\CustomerInfo;
use App\Models\CustomerLogin;
use App\Models\CustomerOptInHistory;
use App\Models\SingleOptin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
/**
* @codeCoverageIgnore
*/
class CustomerController extends Controller
{
/**
* Store a newly created resource in storage
* @param \Illuminate\Http\Request $request
* @return \App\Http\Resources\CustomerResource|\App\Http\Resources\StatusResource
*/
// phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh, Squiz.Commenting.FunctionComment.Missing
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
'firstname' => 'required',
'lastname' => 'required',
'opt_in' => 'required',
'birth_date' => 'date_format:Y-m-d'
]);
if ($validator->fails()) {
return new StatusResource([
'status' => 'KO', 'code' => 102,
'message' => 'Error on required fields.', 'errors' => $validator->errors()
]);
}
$brandId = $request->brand_id;
$email = strtolower(filter_var($request->email, FILTER_SANITIZE_EMAIL));
$firstname = filter_var($request->firstname, FILTER_SANITIZE_STRING);
$lastname = filter_var($request->lastname, FILTER_SANITIZE_STRING);
$optIn = filter_var($request->opt_in, FILTER_SANITIZE_STRING);
$hashcode = Str::uuid();
// Récupère le customer s'il existe déjà.
$customer = Customer::where('email', $email)->first();
// Si le customer n'existe pas déjà.
if (!$customer) {
$customer = new Customer();
$customer->email = $email;
$customer->save();
$singleOptin = SingleOptin::query()->where([
['email', $email], ['brand_id', $brandId]
])->first();
if ($singleOptin) {
$singleOptin->delete();
}
} else {
// Récupère les infos s'ils existent déjà.
$CustomerInfo = CustomerInfo::query()->where([
['customer_id', $customer->id], ['brand_id', $brandId]
])->first();
if ($CustomerInfo) {
return new StatusResource([
'status' => 'KO', 'code' => 103,
'message' => 'User already registered on this site.'
]);
}
}//end if
$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;
try {
$customerInfos->country = Country::make(filter_var($request->country, FILTER_SANITIZE_STRING));
} catch (\Exception $e) {
$customerInfos->country = Country::france();
}
$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($customerInfos);
// Création du login pour cet utilisateur sur ce service.
$customerLogin = new CustomerLogin();
$customerLogin->customer_id = $customer->id;
$customerLogin->password = Hash::make(trim($request->password));
$customerLogin->last_connection = now();
$customerLogin->brand_id = $brandId;
$customerLogin->status = 0;
$customer->logins()->save($customerLogin);
// Ajout dans la table d'historique des opt-in de la nouvelle valeur.
$optInHistory = new CustomerOptInHistory();
$optInHistory->customer_id = $customer->id;
$optInHistory->brand_id = $brandId;
$optInHistory->new_value = $optIn;
$optInHistory->save();
return new CustomerResource($customer, $brandId);
}
/**
* Display the specified resource.
*
* @param \Illuminate\Http\Request $request
* @param mixed $type
* @param mixed $value
* @return \App\Http\Resources\CustomerResource|\App\Http\Resources\StatusResource
*/
public function show(Request $request, $type, $value)
{
$brandId = $request->brand_id;
if ($type === 'id') {
$customer = Customer::find($value);
if (!$customer) {
return new StatusResource(['status' => 'KO', 'code' => 101, 'message' => 'User not found.']);
}
} elseif ($type === 'email') {
$customer = Customer::where('email', $value)->first();
if (!$customer) {
return new StatusResource(['status' => 'KO', 'code' => 101, 'message' => 'User not found.']);
}
$CustomerInfo = $customer->infos()->where('brand_id', $brandId)->first();
if (!$CustomerInfo) {
return new StatusResource(['status' => 'KO', 'code' => 101, 'message' => 'User not found.']);
}
} else {
return new StatusResource(['status' => 'KO', 'code' => 101, 'message' => 'User not found.']);
}
return new CustomerResource($customer, $brandId);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param integer $id
* @return \App\Http\Resources\CustomerResource|\App\Http\Resources\StatusResource
*/
// phpcs:ignore Generic.Metrics.CyclomaticComplexity.MaxExceeded, Squiz.Commenting.FunctionComment.Missing
public function update(Request $request, $id)
{
$validator = Validator::make($request->all(), [
'birth_date' => 'date_format:Y-m-d'
]);
if ($validator->fails()) {
return new StatusResource([
'status' => 'KO', 'code' => 104,
'message' => 'Error on required fields.', 'errors' => $validator->errors()
]);
}
$brandId = $request->brand_id;
$customer = Customer::find($id);
if (!$customer) {
return new StatusResource(['status' => 'KO', 'code' => 105, 'message' => 'User not found.']);
}
$CustomerInfo = $customer->infos()->where('brand_id', $brandId)->first();
if (!$CustomerInfo) {
return new StatusResource(['status' => 'KO', 'code' => 105, 'message' => 'User not found.']);
}
if ($request->has('firstname')) {
$CustomerInfo->firstname = filter_var($request->firstname, FILTER_SANITIZE_STRING);
}
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 ($request->has('address')) {
if (!empty($request->address)) {
$CustomerInfo->address = filter_var($request->address, FILTER_SANITIZE_STRING);
} else {
$CustomerInfo->address = null;
}
}
if ($request->has('address2')) {
if (!empty($request->address2)) {
$CustomerInfo->address2 = filter_var($request->address2, FILTER_SANITIZE_STRING);
} else {
$CustomerInfo->address2 = null;
}
}
if ($request->has('phone')) {
if (!empty($request->phone)) {
$CustomerInfo->phone = filter_var($request->phone, FILTER_SANITIZE_STRING);
} else {
$CustomerInfo->phone = null;
}
}
if ($request->has('country')) {
try {
$CustomerInfo->country = Country::make(filter_var($request->country, FILTER_SANITIZE_STRING));
} catch (\Exception $e) {
$CustomerInfo->country = Country::france();
}
}
if ($request->has('city')) {
if (!empty($request->city)) {
$CustomerInfo->city = filter_var($request->city, FILTER_SANITIZE_STRING);
} else {
$CustomerInfo->city = null;
}
}
if ($request->has('postcode')) {
if (!empty($request->postcode)) {
$CustomerInfo->postcode = filter_var($request->postcode, FILTER_SANITIZE_STRING);
} else {
$CustomerInfo->postcode = null;
}
}
if ($request->has('opt_in')) {
$optIn = filter_var($request->opt_in, FILTER_SANITIZE_STRING);
if ($CustomerInfo->opt_in != $optIn) {
// Ajout dans la table d'historique des opt-in de la nouvelle valeur.
$optInHistory = new CustomerOptInHistory();
$optInHistory->customer_id = $customer->id;
$optInHistory->brand_id = $brandId;
$optInHistory->new_value = $optIn;
$optInHistory->save();
}
$CustomerInfo->opt_in = $optIn;
}
$CustomerInfo->save();
return new CustomerResource($customer, $brandId);
}
/**
* Authenticate the user
* @param \Illuminate\Http\Request $request
* @return \App\Http\Resources\CustomerResource|\App\Http\Resources\StatusResource
*/
public function authenticate(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return new StatusResource([
'status' => 'KO', 'code' => 115,
'message' => 'Error on required fields.', 'errors' => $validator->errors()
]);
}
$brandId = $request->brand_id;
$email = filter_var($request->email, FILTER_SANITIZE_EMAIL);
$password = trim($request->password);
$customer = Customer::where('email', $email)->first();
if ($customer) {
$login = $customer->logins()->where('brand_id', $brandId)->first();
if ($login) {
if (Hash::check($password, $login->password)) {
if ($login->status === false) {
$infos = $customer->infos()->where('brand_id', $brandId)->first();
// "Le compte de l'utilisateur n'est pas activé"
return new StatusResource(
[
'status' => 'KO',
'code' => 116,
'message' => 'Account not activated.',
'user' => [
'crm_id' => $customer->id,
'firstname' => $infos->firstname,
'lastname' => $infos->lastname,
'email' => $customer->email,
'birth_date' => $infos->birth_date,
'address' => $infos->address,
'address2' => $infos->address2,
'phone' => $infos->phone,
'country' => $infos->country->label,
'city' => $infos->city,
'postcode' => $infos->postcode,
'opt_in' => $infos->opt_in,
'hashcode' => $infos->hashcode,
'status' => $login->status,
]
]
);
} //end if
$login->last_connection = now();
$customer->logins()->save($login);
return new CustomerResource($customer, $brandId);
} //end if
// "Mot de passe incorrect"
return new StatusResource(['status' => 'KO', 'code' => 117, 'message' => 'Authentication failed.']);
} else {
// "Ce compte n'est pas enregistré pour cette marque"
return new StatusResource(['status' => 'KO', 'code' => 118, 'message' => 'User not found.']);
} //end if
} else {
// "Ce compte n'existe pas dans la CRM"
return new StatusResource(['status' => 'KO', 'code' => 119, 'message' => 'User not found.']);
} //end if
}
/**
* Change the password of the user for the brand
* @param \Illuminate\Http\Request $request
* @param mixed $id
* @return \App\Http\Resources\StatusResource
*/
public function changePassword(Request $request, $id)
{
$validator = Validator::make($request->all(), [
'password' => 'required',
]);
if ($validator->fails()) {
return new StatusResource([
'status' => 'KO', 'code' => 107,
'message' => 'Error on required fields.', 'errors' => $validator->errors()
]);
}
$brandId = $request->brand_id;
$customer = Customer::find($id);
$password = trim($request->password);
if ($customer) {
$customerLogin = $customer->logins()->where('brand_id', $brandId)->first();
if ($customerLogin) {
// Check if same password.
if (Hash::check($password, $customerLogin->password)) {
return new StatusResource(['status' => 'KO', 'code' => 123, 'message' => 'Same password.']);
}
$customerLogin->password = Hash::make($password);
$customerLogin->save();
} else {
// "Ce compte n'est pas enregistré pour cette marque"
return new StatusResource(['status' => 'KO', 'code' => 108, 'message' => 'User not found.']);
}
} else {
// "Ce compte n'existe pas"
return new StatusResource(['status' => 'KO', 'code' => 109, 'message' => 'User not found.']);
}
return new StatusResource(['status' => 'OK', 'message' => 'Update complete.']);
}
/**
* Activate the account of the user
* @param \Illuminate\Http\Request $request
* @param mixed $id
* @return \App\Http\Resources\StatusResource
*/
public function activateAccount(Request $request, $id)
{
$brandId = $request->brand_id;
$customer = Customer::find($id);
if ($customer) {
$login = $customer->logins()->where('brand_id', $brandId)->first();
if ($login) {
if ($login->status === false) {
$login->status = true;
$login->save();
// "Le compte a bien été activé"
return new StatusResource(['status' => 'OK', 'message' => 'Update complete.']);
} else {
// "Ce compte est déjà activé"
return new StatusResource(['status' => 'KO', 'code' => 110, 'message' => 'User already active.']);
}
} else {
// "Ce compte n'est pas enregistré pour cette marque"
return new StatusResource(['status' => 'KO', 'code' => 111, 'message' => 'User not found.']);
}
} else {
// "Cet utilisateur n'existe pas dans la CRM"
return new StatusResource(['status' => 'KO', 'code' => 112, 'message' => 'User not found.']);
}
}
/**
* Delete the user account for the brand
* @param \Illuminate\Http\Request $request
* @param mixed $id
*/
// phpcs:disable Squiz.PHP.NonExecutableCode.Unreachable, Squiz.Commenting.FunctionComment.Missing
public function delete(Request $request, $id)
{
die("Not implemented yet");
// TODO : Gestion avec mesBR.
$brandId = $request->brand_id;
$customer = Customer::find($id);
if ($customer) {
$customer->infos()->where('brand_id', $brandId)->first()->delete();
$customer->logins()->where('brand_id', $brandId)->first()->delete();
if (count($customer->infos) === 0 && count($customer->logins) === 0) {
$customer->optInHistory()->delete();
$customer->delete();
// Suppression du compte de la CRM terminée.
return new StatusResource(['status' => 'OK', 'message' => 'Deletion complete.']);
} else {
// Suppression des informations du compte pour la marque terminée.
return new StatusResource(['status' => 'OK', 'message' => 'Deletion complete.']);
}
} else {
return new StatusResource(['status' => 'KO', 'code' => 106, 'message' => 'User not found.']);
}
// phpcs:enable Squiz.PHP.NonExecutableCode.Unreachable, Squiz.Commenting.FunctionComment.Missing
}
/**
* Change the status of the opt-in for the customer on this brand
* @param \Illuminate\Http\Request $request
* @param mixed $id
* @return \App\Http\Resources\StatusResource
*/
public function toggleOptin(Request $request, $id)
{
// TODO : Liaison des opt-in avec MailJet.
$brandId = $request->brand_id;
$customer = Customer::find($id);
if ($customer) {
$infos = $customer->infos()->where('brand_id', $brandId)->first();
if ($infos) {
$infos->opt_in = $infos->opt_in === 0 ? 1 : 0;
// On enregistre l'historique du changement d'optin.
$optinHistory = new CustomerOptInHistory();
$optinHistory->customer_id = $customer->id;
$optinHistory->new_value = $infos->opt_in;
$optinHistory->brand_id = $brandId;
$optinHistory->save();
$infos->save();
// "Changement effectué"
return new StatusResource(['status' => 'OK', 'message' => 'Update complete.']);
} else {
// "Ce compte n'a pas d'information liés à cette marque"
return new StatusResource(['status' => 'KO', 'code' => 113, 'message' => 'User not found.']);
}
} else {
// "Cet utilisateur n'existe pas dans la CRM"
return new StatusResource(['status' => 'KO', 'code' => 114, 'message' => 'User not found.']);
} //end if
}
/**
* Remove opt-in for the customer on this brand
* @param \Illuminate\Http\Request $request
* @param mixed $hashcode
* @return \App\Http\Resources\StatusResource
*/
public function removeOptin(Request $request, $hashcode)
{
// TODO : Liaison des opt-in avec MailJet.
$brandId = $request->brand_id;
$infos = CustomerInfo::where([
['brand_id', $brandId],
['hashcode', $hashcode]
])->first();
if ($infos) {
$infos->opt_in = 0;
// On enregistre l'historique du changement d'optin.
$optinHistory = new CustomerOptInHistory();
$optinHistory->customer_id = $infos->customer_id;
$optinHistory->new_value = 0;
$optinHistory->brand_id = $brandId;
$optinHistory->save();
$infos->save();
// "Changement effectué"
return new StatusResource(['status' => 'OK', 'message' => 'Update complete.']);
} else {
// "Ce compte n'a pas d'information liés à cette marque"
return new StatusResource(['status' => 'KO', 'code' => 122, 'message' => 'User not found.']);
}
}
/**
* @param \Illuminate\Http\Request $request
* @return void
*/
// phpcs:ignore Squiz.PHP.NonExecutableCode.Unreachable, Squiz.Commenting.FunctionComment.Missing
public function addSingleOptin(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return new StatusResource([
'status' => 'KO', 'code' => 120,
'message' => 'Error on required fields.', 'errors' => $validator->errors()
]);
}
$brandId = $request->brand_id;
$email = filter_var($request->email, FILTER_SANITIZE_EMAIL);
// Check si le customer ou l'optin simple existe avant de l'ajouter en optin simple.
if (
!SingleOptin::query()->where([['email', $email], ['brand_id', $brandId]])->exists() &&
!CustomerInfo::join("customers", "customer_infos.customer_id", "=", "customers.id")->where([
['brand_id', $brandId], ['email', $email]
])->exists()
) {
$singleOptin = new SingleOptin();
$singleOptin->email = $email;
$singleOptin->brand_id = $brandId;
$singleOptin->save();
} else {
// "Cet utilisateur est déjà inscrit à la newsletter pour cette marque"
return new StatusResource([
'status' => 'KO', 'code' => 121,
'message' => 'This user is already subscribed to the newsletter for this brand.'
]);
}
return new StatusResource(['status' => 'OK', 'message' => 'Optin added.']);
}
}

View file

@ -35,19 +35,6 @@ class ApiResponse
// Set no cache header.
$response->header('Cache-Control', 'No-Store');
if (Helper::isRequestForApiV1($request)) {
// @codeCoverageIgnoreStart
try {
$bearerToken = Helper::getBearerTokenFromRequest($request) ?? $request->api_token ?? '';
$service = Service::getFromBearerToken($bearerToken);
$service->incrementStat();
} catch (ModelNotFoundException $e) {
Log::error(sprintf('Could not increment stats %s', $e->getMessage()));
}
return $response;
// @codeCoverageIgnoreEnd
}
/** @var \App\Models\Service|null */
if (\optional($service = app(Service::class))->id) {
$service->incrementStat();

View file

@ -24,23 +24,11 @@ class Authenticate extends Middleware
*/
public function handle($request, Closure $next, ...$guards)
{
if (Helper::isRequestForApiV1($request)) {
// @codeCoverageIgnoreStart
// Use patched v1 Auth mecanism (without bearer reimplementation).
$bearerToken = Helper::getBearerTokenFromRequest($request) ?? $request->api_token ?? '';
$service = Service::getFromBearerToken($bearerToken);
$request->request->add(['brand_id' => $service->brand->id]);
$response = $next($request);
// @codeCoverageIgnoreEnd
} else {
// Use Laravel auth check mecanism.
$response = \call_user_func_array(
[$this, 'parent::' . __FUNCTION__],
array_merge([$request, $next], $guards)
);
}
return $response;
// Use Laravel auth check mecanism.
return \call_user_func_array(
[$this, 'parent::' . __FUNCTION__],
array_merge([$request, $next], $guards)
);
}
/**
* Get the path the user should be redirected to when they are not authenticated.

View file

@ -2,7 +2,6 @@
namespace App\Http\Middleware;
use App\Lib\Helper;
use Illuminate\Http\Request;
class JsonOnly
@ -16,9 +15,7 @@ class JsonOnly
*/
public function handle(Request $request, \Closure $next)
{
// TODO remove condition v1 check when dropped.
if (
!Helper::isRequestForApiV1($request) and
(!$request->isJson() or
!$request->expectsJson() or
is_null(json_decode($request->getContent())))

View file

@ -35,20 +35,6 @@ class Helper
return strpos($routeName, 'apiV2.') === 0;
}
/**
* Tells if the request is within apiV1 routes
*
* @param \Illuminate\Http\Request $request
* @return boolean
*/
public static function isRequestForApiV1(Request $request): bool
{
// * Small hack to ensure to know if route is From APIv1.
$routePrefix = (strpos(static::getRoutePrefix($request), 'api/v1') ? 'v1' : null) ??
(strpos($request->path(), 'api/v1') === 0 ? 'v1' : null) ?? 'none';
return strpos($routePrefix, 'v1') === 0;
}
/**
* Try to get current route name
*

View file

@ -27,8 +27,7 @@ class AppServiceProvider extends ServiceProvider
return Limit::perMinute(60)->by(2);
});
// ! Important pourra etre retiré quand la V1 sera supprimé
// empeche l'encapsulation dans data
// Empêche l'encapsulation dans data.
JsonResource::withoutWrapping();
// * LOCAL HTTPS FIX.

View file

@ -1,183 +0,0 @@
<?php
namespace LDCCRM;
class ApiV1
{
private $endpoint;
private $api_key;
public function __construct($endpoint, $api_key)
{
$this->endpoint = $endpoint;
$this->api_key = $api_key;
}
public function getCustomer($id)
{
return $this->callAPI('GET', "/customer/id/$id");
}
public function getCustomerByEmail($email)
{
return $this->callAPI('GET', "/customer/email/$email");
}
public function createCustomer($email, $password, $firstname, $lastname, $optin, $birthdate = null, $phone = null, $address = null, $address2 = null, $city = null, $postcode = null, $country = null)
{
$user = [
'email' => $email,
'password' => $password,
'firstname' => $firstname,
'lastname' => $lastname,
'opt_in' => $optin,
'birth_date' => $birthdate,
'phone' => $phone,
'address' => $address,
'address2' => $address2,
'city' => $city,
'postcode' => $postcode,
'country' => $country
];
return $this->callAPI('POST', '/customer/create', $user);
}
public function updateCustomer($crmId, $firstname = null, $lastname = null, $optin = null, $birthdate = null, $phone = null, $address = null, $address2 = null, $city = null, $postcode = null, $country = null)
{
$user = [];
if ($firstname !== null)
$user['firstname'] = $firstname;
if ($lastname !== null)
$user['lastname'] = $lastname;
if ($optin !== null)
$user['opt_in'] = $optin;
if ($birthdate !== null)
$user['birth_date'] = $birthdate;
if ($phone !== null)
$user['phone'] = $phone;
if ($address !== null)
$user['address'] = $address;
if ($address2 !== null)
$user['address2'] = $address2;
if ($city !== null)
$user['city'] = $city;
if ($postcode !== null)
$user['postcode'] = $postcode;
if ($country !== null)
$user['country'] = $country;
return $this->callAPI('PUT', "/customer/$crmId", $user);
}
public function deleteCustomer($id)
{
return $this->callAPI('DELETE', "/customer/$id");
}
public function changePwdCustomer($id, $password)
{
return $this->callAPI('POST', "/customer/$id/change-password", ['password' => $password]);
}
public function activateCustomer($id)
{
return $this->callAPI('POST', "/customer/$id/activate");
}
public function toggleOptInCustomer($id)
{
return $this->callAPI('POST', "/customer/$id/toggle-optin");
}
public function removeOptInCustomer($hashcode)
{
return $this->callAPI('POST', "/customer/$hashcode/remove-optin");
}
public function loginCustomer($email, $password)
{
return $this->callAPI('POST', "/customer/login", ['email' => $email, 'password' => $password]);
}
public function createSingleOptin($email)
{
return $this->callAPI('POST', '/single-optin', ['email' => $email]);
}
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)
{
if (strpos($this->endpoint, "dev")) {
if ($data !== false) {
$data = array_merge($data, ['api_token' => $this->api_key]);
} else {
$data = ['api_token' => $this->api_key];
}
}
$url = $this->endpoint . '/api/v1' . $url;
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
if (!strpos($this->endpoint, "dev")) {
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Authorization: Bearer ' . $this->api_key
));
}
$result = curl_exec($curl);
if (!curl_errno($curl)) {
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if (!in_array($http_code, [200, 201]))
return (object) ['status' => 'KO', 'code' => 500, 'message' => 'Connection to API failed - Code HTTP : ' . $http_code];
} else {
return (object) ['status' => 'KO', 'code' => 500, 'message' => 'Connection to API failed : ' . curl_error($curl)];
}
curl_close($curl);
return json_decode($result);
}
}

View file

@ -1,352 +0,0 @@
<?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;
// phpcs:ignore Squiz.PHP.CommentedOutCode.Found
// 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
* 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
{
/** @var LDCCRM\WPCrm $sessionKey */
private static $sessionKey = 'LDC_CRM_USER';
/** @var DCCRM\WPCrm $sessionDestroyed */
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') {
// phpcs:ignore Squiz.PHP.DiscouragedFunctions.Found
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') {
// phpcs:ignore Squiz.PHP.DiscouragedFunctions.Found
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
*
* @return object|null
*/
public static function getUserToTable()
{
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::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()
{
// phpcs:ignore Squiz.PHP.GlobalKeyword.NotAllowed
global $wpdb;
return $wpdb;
}
}

View file

@ -1,148 +0,0 @@
<?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
* 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 integer $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 integer|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

@ -1,8 +1,6 @@
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\V1\CustomerController;
use App\Http\Controllers\Api\V1\ArcadiaController;
use App\Http\Controllers\Api\V2\ApiController as V2ApiController;
use App\Http\Controllers\Api\V2\ArcadiaController as V2ArcadiaController;
use App\Http\Controllers\Api\V2\CustomerController as V2CustomerController;
@ -22,25 +20,6 @@ use App\Http\Controllers\Api\V2\StatsController as V2StatsController;
|
*/
Route::prefix('v1')->middleware(['auth:api', 'check-brand'])->group(function () {
// * Clients
Route::prefix('customer')->group(function () {
Route::get('/{type}/{value}', [CustomerController::class, 'show']);
Route::post('/create', [CustomerController::class, 'store']);
Route::put('/{id}', [CustomerController::class, 'update']);
Route::delete('/{id}', [CustomerController::class, 'delete']);
Route::post('/{id}/change-password', [CustomerController::class, 'changePassword']);
Route::post('/{id}/activate', [CustomerController::class, 'activateAccount']);
Route::post('/{id}/toggle-optin', [CustomerController::class, 'toggleOptin']);
Route::post('/{hashcode}/remove-optin', [CustomerController::class, 'removeOptin']);
Route::post('/login', [CustomerController::class, 'authenticate']);
});
// * Optin simple
Route::post('/single-optin', [CustomerController::class, 'addSingleOptin']);
// * Arcadia
Route::post('/arcadia/outgoing-mail', [ArcadiaController::class, 'outgoingMail']);
});
Route::prefix('v2')->name('apiV2.')->group(function () {
// * PUBLIC

View file

@ -6,16 +6,12 @@ use App\Models\Customer;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use LDC\LDCCRM\CrmApiV2;
use LDCCRM\ApiV1;
use Tests\CreatesApplication;
abstract class CrmClientTester extends BaseTestCase
{
use CreatesApplication;
/** @var \LDCCRM\ApiV1 */
protected static $apiV1;
/** @var \App\Models\Customer */
protected static $customer;
@ -54,7 +50,6 @@ abstract class CrmClientTester extends BaseTestCase
self::$service->bearer_token,
Crypt::decryptString(self::$service->bearer_pwd)
);
static::$apiV1 = new ApiV1(config('app.url'), self::$service->bearer_token);
}
/**

View file

@ -1,530 +0,0 @@
<?php
namespace Tests\Client;
use App\Models\Customer as ModelsCustomer;
use LDC\LDCCRM\Enums\Country;
class CrmClientV1CustomerTest extends CrmClientTester
{
/**
* Get customer by ID
*
* @return void
*/
public function testGetCustomerById()
{
$reponse = static::$apiV1->getCustomer(static::$customer->id);
$this->assertEquals($reponse->status, 'OK');
$this->assertEquals($reponse->user->crm_id, static::$customer->id);
$this->assertEquals($reponse->user->email, static::$customer->email);
$this->assertEquals($reponse->user->firstname, static::$info->firstname);
$this->assertEquals($reponse->user->lastname, static::$info->lastname);
$this->assertEquals($reponse->user->birth_date, static::$info->birth_date);
$this->assertEquals($reponse->user->address, static::$info->address);
$this->assertEquals($reponse->user->address2, static::$info->address2);
$this->assertEquals($reponse->user->phone, static::$info->phone);
$this->assertEquals($reponse->user->country, static::$info->country->label);
$this->assertEquals($reponse->user->city, static::$info->city);
$this->assertEquals($reponse->user->opt_in, static::$info->opt_in);
$this->assertEquals($reponse->user->hashcode, static::$info->hashcode);
$this->assertEquals($reponse->user->status, static::$login->status);
}
/**
* Get customer by id should fail if not found
*
* @return void
*/
public function testGetCustomerByIdShouldFail()
{
$reponse = static::$apiV1->getCustomer(9999999);
$this->assertEquals($reponse->status, 'KO');
$this->assertEquals($reponse->code, 101);
}
/**
* Get customer by email.
*
* @return void
*/
public function testGetCustomerByEmail()
{
$reponse = static::$apiV1->getCustomerByEmail(static::$customer->email);
$this->assertEquals($reponse->status, 'OK');
$this->assertEquals($reponse->user->crm_id, static::$customer->id);
$this->assertEquals($reponse->user->email, static::$customer->email);
$this->assertEquals($reponse->user->firstname, static::$info->firstname);
$this->assertEquals($reponse->user->lastname, static::$info->lastname);
$this->assertEquals($reponse->user->birth_date, static::$info->birth_date);
$this->assertEquals($reponse->user->address, static::$info->address);
$this->assertEquals($reponse->user->address2, static::$info->address2);
$this->assertEquals($reponse->user->phone, static::$info->phone);
$this->assertEquals($reponse->user->country, static::$info->country->label);
$this->assertEquals($reponse->user->city, static::$info->city);
$this->assertEquals($reponse->user->opt_in, static::$info->opt_in);
$this->assertEquals($reponse->user->hashcode, static::$info->hashcode);
$this->assertEquals($reponse->user->status, static::$login->status);
}
/**
* Get customer by email should fail if not found.
*
* @return void
*/
public function testGetCustomerByEmailShouldFail()
{
$reponse = static::$apiV1->getCustomer('totoo@toto.fr');
$this->assertEquals($reponse->status, 'KO');
$this->assertEquals($reponse->code, 101);
}
/**
* Create customer
*
* @return void
*/
public function testCustomerStoreProps()
{
$reponse = static::$apiV1->createCustomer(
'v1toto.delarogerie@gmail.com',
'Complic4tEd!P4assW0rd',
'toto',
'delarogerie',
true,
'1992-03-08',
'0673891160',
'rue des totos',
'',
'Toto ville',
'72160',
Country::france()->label
);
$this->assertEquals($reponse->status, 'OK');
$this->assertNotEmpty($reponse->user->crm_id);
$this->assertNotEmpty($reponse->user->hashcode);
$this->assertEquals($reponse->user->email, 'v1toto.delarogerie@gmail.com');
$this->assertEquals($reponse->user->firstname, 'Toto');
$this->assertEquals($reponse->user->lastname, 'Delarogerie');
$this->assertEquals($reponse->user->birth_date, '1992-03-08');
$this->assertEquals($reponse->user->address, 'rue des totos');
$this->assertEquals($reponse->user->address2, '');
$this->assertEquals($reponse->user->phone, '0673891160');
$this->assertEquals($reponse->user->country, Country::france()->label);
$this->assertEquals($reponse->user->city, 'Toto ville');
$this->assertEquals($reponse->user->opt_in, true);
$this->assertEquals($reponse->user->status, false);
}
/**
* Create customer should fail if exists.
*
* @return void
*/
public function testCustomerStorePropsShouldFailBecauseAlreadyExist()
{
$reponse = static::$apiV1->createCustomer(
'v1toto.delarogerie@gmail.com',
'Complic4tEd!P4assW0rd',
'toto',
'delarogerie',
true,
'1992-03-08',
'0673891160',
'rue des totos',
'',
'Toto ville',
'72160',
Country::france()->label
);
$this->assertEquals($reponse->status, 'KO');
$this->assertEquals($reponse->code, 103);
}
/**
* Should fail if invalid data is passed.
*
* @return void
*/
public function testCustomerStorePropsShouldFail()
{
$reponse = static::$apiV1->createCustomer(
'v1bistoto.delarogerie@gmail.com',
'123456',
'toto bis',
'delarogerie',
true,
'1992-08',
'0673891160',
'rue des totos',
'',
'Toto ville',
'72160',
Country::france()->label
);
$this->assertEquals($reponse->status, 'KO');
$this->assertEquals($reponse->code, 102);
}
/**
* Customer update
*
* @return void
*/
public function testCustomerUpdateProps()
{
$reponse = static::$apiV1->updateCustomer(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')->firstOrFail()->id,
'toto new',
'delarogerie',
true,
'1992-03-08',
'0673891160',
'rue des totos',
'',
'Toto ville',
'72160',
Country::france()->label
);
$this->assertEquals($reponse->status, 'OK');
$this->assertNotEmpty($reponse->user->crm_id);
$this->assertNotEmpty($reponse->user->hashcode);
$this->assertEquals($reponse->user->email, 'v1toto.delarogerie@gmail.com');
$this->assertEquals($reponse->user->firstname, 'toto new');
$this->assertEquals($reponse->user->lastname, 'delarogerie');
$this->assertEquals($reponse->user->birth_date, '1992-03-08');
$this->assertEquals($reponse->user->address, 'rue des totos');
$this->assertEquals($reponse->user->address2, '');
$this->assertEquals($reponse->user->phone, '0673891160');
$this->assertEquals($reponse->user->country, Country::france()->label);
$this->assertEquals($reponse->user->city, 'Toto ville');
$this->assertEquals($reponse->user->opt_in, true);
$this->assertEquals($reponse->user->status, false);
}
/**
* Customer update should fail if dont exists.
*
* @return void
*/
public function testCustomerLoginShouldFailDontExists()
{
$reponse = static::$apiV1->loginCustomer('v1totso.delarogerie@gmail.com', 'Complic4tEd!P4assW0rd');
$this->assertEquals('KO', $reponse->status);
$this->assertEquals(119, $reponse->code);
}
/**
* Customer update should fail if account is not activated.
*
* @return void
*/
public function testCustomerLoginShouldFailNotActivated()
{
$reponse = static::$apiV1->loginCustomer('v1toto.delarogerie@gmail.com', 'Complic4tEd!P4assW0rd');
$this->assertEquals('KO', $reponse->status);
$this->assertEquals(116, $reponse->code);
}
/**
* Customer activate
*
* @return void
*/
public function testCustomerActivate()
{
$reponse = static::$apiV1->activateCustomer(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')->firstOrFail()->id
);
$this->assertEquals('OK', $reponse->status);
}
/**
* Customer login
*
* @return void
*/
public function testCustomerLogin()
{
$reponse = static::$apiV1->loginCustomer('v1toto.delarogerie@gmail.com', 'Complic4tEd!P4assW0rd');
$this->assertEquals('OK', $reponse->status);
}
/**
* Customer activation should fail if already exists.
*
* @return void
*/
public function testCustomerActivateShouldFail()
{
$reponse = static::$apiV1->activateCustomer(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')->firstOrFail()->id
);
$this->assertEquals('KO', $reponse->status);
$this->assertEquals(110, $reponse->code);
}
/**
* Customer toggle optin
*
* @return void
*/
public function testCustomerToggleOptin()
{
$reponse = static::$apiV1->toggleOptInCustomer(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')->firstOrFail()->id
);
$this->assertEquals('OK', $reponse->status);
$reponse = static::$apiV1->toggleOptInCustomer(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')->firstOrFail()->id
);
$this->assertEquals('OK', $reponse->status);
$reponse = static::$apiV1->toggleOptInCustomer(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')->firstOrFail()->id
);
$this->assertEquals('OK', $reponse->status);
}
/**
* Customer remove optin
*
* @return void
*/
public function testCustomerRemoveOptin()
{
$hashcode = static::$apiV1->getCustomerByEmail('v1toto.delarogerie@gmail.com')->user->hashcode;
$reponse = static::$apiV1->removeOptInCustomer($hashcode);
$this->assertEquals('OK', $reponse->status);
}
/**
* Customer Delete
*
* @return void
*/
public function testCustomerDelete()
{
$reponse = static::$apiV1->deleteCustomer(ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')
->firstOrFail()->id);
$this->assertNull($reponse);
}
/**
* Create single optin
*
* @return void
*/
public function testCreateSingleOptin()
{
$reponse = static::$apiV1->createSingleOptin('singlev1toto.delarogerie@gmail.com');
$this->assertEquals('OK', $reponse->status);
}
/**
* Create single optin already exists.
*
* @return void
*/
public function testCreateSingleOptinShouldFail()
{
$reponse = static::$apiV1->createSingleOptin('singlev1toto.delarogerie@gmail.com');
$this->assertEquals('KO', $reponse->status);
$this->assertEquals(121, $reponse->code);
}
/**
* Send arcadia outgoing mail.
*
* @return void
*/
public function testCreateArcadiaOutgoingMail()
{
$reponse = static::$apiV1->ArcadiaOutgoingMail(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')
->firstOrFail()->id,
[
'root' => [
[
'fieldName' => 'order_num',
// Format 9 numeric characters.
'fieldValue' => str_pad(12, 9, '0', \STR_PAD_LEFT),
],
[
'fieldName' => 'order_date',
// Format : DD/MM/YYYY .
'fieldValue' => '12/05/1992',
],
[
'fieldName' => 'state_order_cb',
// Format 1 ou Null (oui Null et pas NULL).
'fieldValue' => 1,
],
[
'fieldName' => 'state_order_check',
// Format 1 ou Null (oui Null et pas NULL).
'fieldValue' => 'Null'
],
[
'fieldName' => 'operation',
// Mettre valeur dans .env .
'fieldValue' => 16
]
],
'orderLine' => [
[
'fieldName' => 'package_unit_weight',
'fieldValue' => 200
],
[
'fieldName' => 'qty',
// Forced to 1 faire un appel par produit et pour chaque quantité.
'fieldValue' => '1'
],
[
'fieldName' => 'support_code',
'fieldValue' => 2
],
[
'fieldName' => 'label_type_support',
'fieldValue' => 'label supoport'
]
]
],
'default',
[
"firstname" => 'toto',
"lastname" => 'delarogerie',
"address" => 'rue des toto',
"city" => 'toto ville',
"postcode" => '72000',
"phone" => '0673891160'
]
);
$this->assertEquals('OK', $reponse->status);
}
/**
* Send arcadia outgoing mail game.
*
* @return void
*/
public function testCreateArcadiaOutgoingMailGameWithEan()
{
$reponse = static::$apiV1->ArcadiaOutgoingMail(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')
->firstOrFail()->id,
[
'root' => [
[
'fieldName' => 'order_date',
'fieldValue' => date('d/m/Y')
],
[
'fieldName' => 'operation',
'fieldValue' => '32'
]
],
'orderLine' => [
[
'fieldName' => 'code_unique',
'fieldValue' => '2A5B416325414232'
],
[
'fieldName' => 'code_on_pack',
'fieldValue' => '2541632541423'
],
[
'fieldName' => 'support_code',
'fieldValue' => '16'
],
[
'fieldName' => 'label_type_support',
'fieldValue' => 'Gain du lot : ballon de foot en métal type "fracture"'
]
]
],
'game',
[
"firstname" => 'toto',
"lastname" => 'delarogerie',
"address" => 'rue des toto',
"city" => 'toto ville',
"postcode" => '72000',
"phone" => '0673891160'
]
);
$this->assertEquals('OK', $reponse->status);
}
/**
* Send arcadia mail without ean.
*
* @return void
*/
public function testCreateArcadiaOutgoingMailGameWithoutEan()
{
$reponse = static::$apiV1->ArcadiaOutgoingMail(
ModelsCustomer::where('email', 'v1toto.delarogerie@gmail.com')
->firstOrFail()->id,
[
'root' => [
[
'fieldName' => 'order_date',
'fieldValue' => date('d/m/Y')
],
[
'fieldName' => 'operation',
'fieldValue' => '32'
]
],
'orderLine' => [
[
'fieldName' => 'code_unique',
'fieldValue' => '25416325414232'
],
[
'fieldName' => 'support_code',
'fieldValue' => '16'
],
[
'fieldName' => 'label_type_support',
'fieldValue' => 'Gain du lot : ballon de foot en métal type "fracture"'
]
]
],
'game',
[
"firstname" => 'toto',
"lastname" => 'delarogerie',
"address" => 'rue des toto',
"city" => 'toto ville',
"postcode" => '72000',
"phone" => '0673891160'
]
);
$this->assertEquals('OK', $reponse->status);
}
}

View file

@ -45,17 +45,6 @@ class HelperTest extends TestCase
$this->assertEquals($request->route()->getName(), Helper::getRouteName($request));
}
/**
* Helper::isRequestForApiV1 test
*
* @return void
*/
public function testIsRequestForApiV1()
{
$request = $this->makeRequest('App\Http\Controllers\Api\V1\CustomerController@activateAccount');
$this->assertTrue(Helper::isRequestForApiV1($request));
}
/**
* Helper::isRequestForApiV2 test
*