Merge branch 'develop' into trunk

This commit is contained in:
Jérémy Munsch 2023-12-18 12:53:39 +01:00
commit 8acecfb9a5
No known key found for this signature in database
GPG key ID: 18361AF3BFEC0FEC
69 changed files with 967 additions and 581 deletions

View file

@ -15,11 +15,10 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\ValidationException as IlluminateValidationException;
use LDC\LDCCRM\Enums\ApiError;
use LDC\LDCCRM\Enums\Country;
use LDC\LDCCRM\Exceptions\ApiErrorException;
use LDC\LDCCRM\Exceptions\ValidationException as ExceptionsValidationException;
use LDC\LDCCRM\Exceptions\ValidationException as CrmValidationException;
use LDC\LDCCRM\Models\Customer as CrmCustomer;
class RegisterController extends Controller
@ -53,7 +52,7 @@ class RegisterController extends Controller
*/
public function showRegistrationForm()
{
$staticPageModel = StaticPage::query()->where('type', StaticPageType::klub_register)->first();
$staticPageModel = StaticPage::query()->where('type', StaticPageType::klub_register)->firstOrFail();
return view('fo.auth.register', compact('staticPageModel'));
}
@ -62,34 +61,20 @@ class RegisterController extends Controller
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
* @throws \Illuminate\Validation\ValidationException If data is incorrect.
* @throws IlluminateValidationException If data is incorrect.
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClass
*/
protected function validator(array $data): ValidationValidator
{
$data['ok_cgv'] = \request()->boolean('ok_cgv');
$data['phone'] = $data['phone'] ?? null;
$data['opt_in'] = ($data['opt_in'] ?? false) ? true : false;
$request = new CreateAccountRequest();
$validateData = Validator::make(
$data,
// phpcs:enable
$request = CreateAccountRequest::capture();
$request->prepareForValidation();
return Validator::make(
$request->validationData(),
$request->rules(),
$request->messages(),
$request->attributes()
);
if ($validateData) {
return $validateData;
} else {
try {
(new CrmCustomer())->fill($this->getOnlyCrmData($data));
} catch (ExceptionsValidationException $e) {
throw ValidationException::withMessages([
'error' => $e->getMessage()
]);
}
}
}
/**
@ -97,22 +82,29 @@ class RegisterController extends Controller
*
* @param array $data
* @return \App\Models\Customer
* @throws \Illuminate\Validation\ValidationException If there are validation errors.
* @throws IlluminateValidationException If there are validation errors.
* @throws \RuntimeException On unhandled api Error.
*/
protected function create(array $data): Customer
{
$data['country'] = Country::france();
$data['ok_cgv'] = \request()->boolean('ok_cgv');
$data['phone'] = $data['phone'] ?? null;
$data['opt_in'] = ($data['opt_in'] ?? false) ? true : false;
$data['ok_cgv'] = \request()->boolean('ok_cgv');
$data['opt_in'] = \request()->boolean('opt_in');
$data['phone'] = Arr::get($data, 'phone');
// * This field is not standard in crm
$data['postcode'] = Arr::get($data, 'postal_code');
Arr::forget($data, 'postal_code');
try {
return DB::transaction(function () use ($data) {
$crmCustomer = new CrmCustomer($this->getOnlyCrmData($data));
$crmCustomer = new CrmCustomer(Arr::only(
$data,
[
'firstname', 'lastname', 'birth_date', 'address',
'address2', 'postcode', 'country', 'city', 'phone',
'email', 'password', 'opt_in',
]
));
// * Country Is forced to france
$crmCustomer->country = Country::france();
$crmCustomer->save();
// * Enregistrement du Hashcode
@ -133,20 +125,20 @@ class RegisterController extends Controller
});
} catch (ApiErrorException $e) {
if ($e->getApiError()->equals(ApiError::customerExists())) {
throw ValidationException::withMessages([
'error' => 'Un compte est déjà associé à cette adresse email.'
throw IlluminateValidationException::withMessages([
'error' => trans('Un compte est déjà associé à cette adresse email.')
]);
}
if ($e->getApiError()->equals(ApiError::validationFailed())) {
throw ValidationException::withMessages([
throw IlluminateValidationException::withMessages([
'error' => $e->getMessage()
]);
}
report($e);
Log::error(__CLASS__ . '::create reached end of possibilities.');
throw new \RuntimeException(__CLASS__ . '::create reached end of possibilities.');
} catch (ExceptionsValidationException $e) {
throw ValidationException::withMessages([
} catch (CrmValidationException $e) {
throw IlluminateValidationException::withMessages([
'error' => $e->getMessage()
]);
} //end try
@ -161,30 +153,4 @@ class RegisterController extends Controller
{
return $this->authLoggedRedirectPath();
}
/**
* Get only data used in crm
*
* @param array $data
* @return array
*/
private function getOnlyCrmData(array $data): array
{
return \array_intersect_key(
$data,
[
'firstname' => '',
'lastname' => '',
'birth_date' => '',
'address' => '',
'postcode' => '',
'country' => '',
'city' => '',
'phone' => '',
'email' => '',
'password' => '',
'opt_in' => '',
]
);
}
}

View file

@ -68,7 +68,7 @@ class ResetPasswordController extends Controller
*/
protected function resetPassword(mixed $customer, mixed $password): void
{
/** @var \App\Models\Customer\Customer $user */
/** @var \App\Models\Customer $customer */
/** @var string $password */
/** @var \LDC\LDCCRM\CrmApiV2 */
@ -77,7 +77,7 @@ class ResetPasswordController extends Controller
try {
if (!($crmCustomer = $crm->getCustomer($customer->hashcode))) {
throw ValidationException::withMessages([
'error' => 'Changement impossible, compte inexistant.'
'error' => trans('Changement impossible, compte inexistant.')
]);
}
$crmCustomer->password = $password;
@ -85,11 +85,11 @@ class ResetPasswordController extends Controller
} catch (\TypeError | CrmException | ApiErrorException $e) {
report($e);
throw ValidationException::withMessages([
'error' => 'Une erreur est survenue, merci de réessayer ultérieurement.'
'error' => trans('Une erreur est survenue, merci de réessayer ultérieurement.')
]);
} catch (ExceptionsValidationException $e) {
throw ValidationException::withMessages([
'error' => $e->getMessage()
'password' => $e->getMessage()
]);
}

View file

@ -18,10 +18,13 @@ class HomeController extends Controller
*/
public function index(): \Illuminate\Contracts\View\View
{
$rangeModels = Range::all();
$klubBloc = KlubBloc::first();
$rangeModels = Range::query()->limit(3)->inRandomOrder()->get();
$newsModels = News::query()->where('published', true)->orderBy('created_at', 'desc')->limit(6)->get();
$staticPageModel = StaticPage::query()->where('type', StaticPageType::home)->first();
$staticPageModel = StaticPage::query()->where('type', StaticPageType::home)->firstOrFail();
$klubBloc = KlubBloc::first();
\throw_if(empty($klubBloc), 'empty klubBloc');
return view('fo.pages.home', compact('staticPageModel', 'rangeModels', 'klubBloc', 'newsModels'));
}
}

View file

@ -4,9 +4,15 @@ namespace App\Http\Controllers\Fo\Klub;
use App\Http\Controllers\Controller;
use App\Http\Requests\Fo\MesBr\PrintCouponsRequest;
use App\Models\Customer;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use LDC\LDCCRM\Enums\ApiError;
use LDC\LDCCRM\Exceptions\ApiErrorException;
use LDC\LDCCRM\Exceptions\CrmException;
use Symfony\Component\HttpFoundation\StreamedResponse;
class MesBrController extends Controller
@ -68,33 +74,81 @@ class MesBrController extends Controller
* @param \App\Models\Customer $customer
* @param array $coupons
* @return string|null
* @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
*/
private function fetchBrPdfFromMesBr(\App\Models\Customer $customer, array $coupons): string|null
private function fetchBrPdfFromMesBr(Customer $customer, array $coupons): string|null
{
/** @var \LDCWEB\MesBR */
$mesBr = app('mesbr');
$message = null;
// phpcs:enable
// * Phase - 1 Recupération des informations CRM
/** @var \LDC\LDCCRM\Models\Customer*/
$crmUser = $this->fetchCrmCustomer($customer);
// * Phase - 2 Mise à jour du coupon dans MesBr
try {
$res = $mesBr->printCoupons($customer->hashcode, $coupons);
if (!$res) {
$message = "ERROR MesBR API : printCoupons on api failed {$customer->hashcode}";
} elseif (Arr::get((array)$res, 'status') === 'KO') {
$message = Arr::get(
(array)$res,
'message',
"ERROR MesBR API : printCoupons on api failed (no message) {$customer->hashcode}"
);
/** @var \LDC\MESBR\MesBr */
$mesBr = app('mesBrAPI');
// * MaJ Customer
/** @var integer */
retry(3, function () use ($mesBr, $crmUser) {
/**
* Parce que MesBr n'est pas fiable il faut retenter pour avoir
* l'id client, des fois cet id sera dans hashcode...
*
* Id est necessaire pour update panier..
*/
$result = $mesBr->updateCustomer($crmUser->hashcode, $crmUser->email, $crmUser->country);
if (optional($result)->status !== "OK") {
throw new \RuntimeException(
\sprintf(
'MESBR : Une erreur est survenue. Code : %s Message : %s',
$result->code ?? 'Undefined',
$result->message ?? 'Undefined'
)
);
}
/** @var object|null */
$crm_customer = optional($result)->customer;
if (empty(optional($crm_customer)->id)) {
throw new \RuntimeException(
'MESBR : Une erreur est survenue. Update Customer n\'as pas retourné le customer id'
);
}
return intval($crm_customer->id);
}, 100);
// * Maj Panier
$result = $mesBr->printCoupons($crmUser->hashcode, $coupons);
$result = \is_object($result) ? (array)$result : $result;
if (Arr::get($result, 'status') !== "OK") {
report(new \RuntimeException(
\sprintf(
'MESBR : Une erreur est survenue. Code : %s Message : %s',
Arr::get($result, 'code') ?? 'Undefined',
Arr::get($result, 'message') ?? 'Undefined',
)
));
return null;
}
if ($message === null) {
return \base64_decode(strval(optional($res)->pdf));
// * La réponse est conforme ?
$needed_fields = ['pdf'];
if (!Arr::has($result, $needed_fields)) {
report(new \RuntimeException(sprintf(
'MESBR : Il manques des champs dans la réponse, attendu => %s, donné => %s',
json_encode($needed_fields),
json_encode($result),
)));
return null;
}
report(new \RuntimeException($message));
return null;
} catch (\Exception $e) {
// * Tout est OK
return \base64_decode(Arr::get($result, 'pdf')) ?: null;
} catch (\RuntimeException $e) {
report($e);
// * Retenter ?
return null;
} //end try
}
@ -130,8 +184,8 @@ class MesBrController extends Controller
return null;
}
/** @var \LDCWEB\MesBR */
$mesBr = app('mesbr');
/** @var \LDC\MESBR\MesBR */
$mesBr = app('mesBrAPI');
$message = null;
@ -171,8 +225,8 @@ class MesBrController extends Controller
private function createOrUpdateMesBrCustomer(\LDC\LDCCRM\Models\Customer $customer): bool
{
// * Ajout du customer sur mes BR
/** @var \LDCWEB\MesBR */
$mesBr = app('mesbr');
/** @var \LDC\MESBR\MesBR */
$mesBr = app('mesBrAPI');
$message = null;
@ -205,6 +259,49 @@ class MesBrController extends Controller
} //end try
}
/**
* Fetch Crm Customer
*
* @param \App\Models\Customer $customer
* @return \LDC\LDCCRM\Models\Customer
* @throws \Illuminate\Http\Exceptions\HttpResponseException In case of failure or customer not activated.
*/
private function fetchCrmCustomer(Customer $customer): \LDC\LDCCRM\Models\Customer
{
try {
$crmUser = $customer->api_data;
// ? Le compte est vérifié ?
if (!$crmUser->status) {
// * Doit avoir un compte vérifié pour imprimer.
response()->redirectToRoute('fo.verification.notice')
->with('error', trans('Votre compte doit être activé'))
->throwResponse();
}
return $crmUser;
} catch (ApiErrorException $e) {
// * Customer is not found.
if ($e->getApiError()->equals(ApiError::modelNotFound())) {
// * Déconnexion immédiate et retour maison.
auth('frontend')->logout();
response()->redirectToRoute('fo.homepage')
->with('error', trans('Une erreur est survenue, compte introuvable.'))
->throwResponse();
}
report($e);
Log::error('Unhandled response ' . $e->getApiError()->label);
// * Retenter ?
back()->with('error', trans('Une erreur est survenue, veuillez réssayer.'))->throwResponse();
} catch (HttpResponseException $e) {
// * continue this
throw $e;
} catch (CrmException | \Exception $e) {
report($e);
// * Retenter ?
back()->with('error', trans('Une erreur est survenue, veuillez réssayer.'))->throwResponse();
} //end try
}
// * STATIC Fetch BR
/**
@ -216,8 +313,8 @@ class MesBrController extends Controller
*/
public static function getStaticBr(): object|null
{
/** @var \LDCWEB\MesBR */
$mesBr = app('mesbr');
/** @var \LDC\MESBR\MesBR */
$mesBr = app('mesBrAPI');
$message = null;

View file

@ -47,7 +47,7 @@ class StaticPageController extends Controller
->orderBy('created_at', 'desc')
->limit(6)
->get();
$rangeModels = Range::all();
$rangeModels = Range::query()->limit(3)->inRandomOrder()->get();
$milestoneModels = HistoricalMilestone::orderBy('year', 'asc')->where('published', true)->get();
$staticPageModel = StaticPage::query()->where('type', StaticPageType::history)->first();
return view('fo.pages.history', compact('staticPageModel', 'newsModels', 'rangeModels', 'milestoneModels'));

View file

@ -26,8 +26,7 @@ class CrmMiddlewareQuestions
$user = \auth('frontend')->user() and
$user->last_connection !== null
) {
/** @var \LDC\LDCCRM\Models\Customer */
$crmCustomer = $user->apiData;
$crmCustomer = $user->api_data;
$questions = Customer::cacheCrm(
$user->hashcode,
'questions',

View file

@ -53,14 +53,21 @@ class SecureHeaders
"default-src 'none';",
"manifest-src 'self';",
// * CKEDITOR Specific https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/csp.html
"connect-src 'self' " . implode(' ', [
"connect-src 'self' blob: " . implode(' ', [
// * VITE DEV
config('app.debug') ? "wss://{$host}:4443" : '',
config('app.debug') ? "https://{$host}:4443" : '',
'https://yl.s-web.fr'
]) . ';',
"img-src * data: blob:;",
'frame-src ' . implode(' ', [
"img-src 'self' data: blob: " . implode(' ', [
// * VITE DEV
config('app.debug') ? "https://{$host}:4443" : '',
// * MESBR
'https://dev.mesbr.eu',
'https://www.mesbr.eu'
]) . ';',
"object-src 'self' " . implode(' ', []) . ';',
"frame-src 'self' " . implode(' ', [
'https://www.google.com/recaptcha/',
'https://recaptcha.google.com/recaptcha/',
'https://www.google.com/maps/'

View file

@ -10,6 +10,8 @@ class TrustProxies extends Middleware
/**
* The trusted proxies for this application.
*
* ! Added * as tmp Fix for #13
*
* @var array<int, string>|string|null
*/
protected $proxies = '*';

View file

@ -3,6 +3,7 @@
namespace App\Http\Requests\Bo\StaticPages;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
class UpdateStaticPageRequest extends FormRequest
@ -12,9 +13,9 @@ class UpdateStaticPageRequest extends FormRequest
*
* @return boolean
*/
public function authorize(): bool
public function authorize()
{
return auth('backend')->check();
return Gate::check('update', $this->route('static_page'));
}
/**
@ -25,7 +26,7 @@ class UpdateStaticPageRequest extends FormRequest
public function prepareForValidation(): void
{
$this->merge([
'content' => Str::of($this->post('content'))->value()
'content' => (string)Str::of($this->input('content'))
]);
}
@ -55,7 +56,7 @@ class UpdateStaticPageRequest extends FormRequest
'seo_title' => trans('validation.custom.seo_title'),
'seo_description' => trans('validation.custom.seo_description'),
'title' => trans('validation.attributes.title'),
'content' => trans('validation.custom.content'),
'content' => trans('validation.attributes.content'),
];
}
}

View file

@ -24,7 +24,7 @@ class UpdateChangeOrderRequest extends FormRequest
protected function prepareForValidation(): void
{
$this->merge([
'direction' => $this->direction === 'up' ? true : false
'direction' => $this->string('direction') === 'up' ? true : false
]);
}

View file

@ -3,7 +3,9 @@
namespace App\Http\Requests\Bo\Users;
use App\Enums\Users\RoleEnum;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rules\Enum;
use Illuminate\Validation\Rules\Password;
@ -14,9 +16,9 @@ class StoreUserRequest extends FormRequest
*
* @return boolean
*/
public function authorize(): bool
public function authorize()
{
return auth('backend')->check();
return Gate::check('create', User::class);
}
/**
@ -27,7 +29,7 @@ class StoreUserRequest extends FormRequest
protected function prepareForValidation()
{
$this->merge([
'published' => $this->published ? true : false
'published' => $this->boolean('published')
]);
}
@ -40,9 +42,9 @@ class StoreUserRequest extends FormRequest
{
return [
'first_name' => 'required|string|min:3|max:255',
'last_name' => 'required|string|min:3|max:255',
'email' => 'required|email:rfc,strict,dns,spoof,filter|unique:users,email',
'password' => [
'last_name' => 'required|string|min:3|max:255',
'email' => 'required|email:rfc,strict,dns,spoof,filter|unique:users,email',
'password' => [
'required', 'required_with:password_confirmation', 'confirmed', 'max:255', Password::min(8)
->letters()
->mixedCase()
@ -50,8 +52,8 @@ class StoreUserRequest extends FormRequest
->symbols()
->uncompromised()
],
'role' => ['required', new Enum(RoleEnum::class)],
'published' => 'required|boolean',
'role' => ['required', new Enum(RoleEnum::class)],
'published' => 'required|boolean',
];
}

View file

@ -2,10 +2,22 @@
namespace App\Http\Requests\Bo\Users;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
class UpdateUserRequest extends StoreUserRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize()
{
return Gate::check('update', $this->route('user'));
}
/**
* Prepare the data for validation.
*
@ -14,10 +26,10 @@ class UpdateUserRequest extends StoreUserRequest
protected function prepareForValidation()
{
$this->merge([
'published' => $this->published ? true : false,
'password' => $this->password ? $this->password : $this->route('user')->password,
'password_confirmation' => $this->password_confirmation ?
$this->password_confirmation :
'published' => $this->boolean('published'),
'password' => $this->input('password') ??
$this->route('user')->password,
'password_confirmation' => $this->input('password_confirmation') ??
$this->route('user')->password
]);
}
@ -30,10 +42,10 @@ class UpdateUserRequest extends StoreUserRequest
public function rules(): array
{
return array_merge(parent::rules(), [
'email' => [
'email' => [
'required',
'email:rfc,strict,dns,spoof,filter',
'unique:users,email,' . $this->route('user')->id . ',id',
Rule::unique('users', 'email')->ignore($this->route('user')->getRouteKey())
],
'password' => [
'required', 'required_with:password_confirmation', 'confirmed', 'max:255', Password::min(8)

View file

@ -2,10 +2,11 @@
namespace App\Http\Requests\Fo\Customers;
use App\Rules\IsAdult;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Kwaadpepper\Enum\Rules\EnumIsValidRule;
use LDC\LDCCRM\Enums\Country;
use LDC\LDCCRM\Models\Customer as CrmCustomer;
@ -29,8 +30,9 @@ class CreateAccountRequest extends FormRequest
public function prepareForValidation()
{
$this->merge([
'phone' => $this->phone,
'opt_in' => $this->opt_in ? true : false
'phone' => $this->input('phone'),
'opt_in' => $this->boolean('opt_in'),
'ok_cgv' => $this->boolean('ok_cgv')
]);
}
@ -42,14 +44,19 @@ class CreateAccountRequest extends FormRequest
public function rules()
{
return [
'lastname' => 'required|string|max:255',
'firstname' => 'required|string|max:255',
'phone' => 'nullable|max:255|phone:FR',
'address' => 'required|string|min:1|max:255',
'postcode' => 'required|string|min:1|postal_code:FR',
'city' => 'required|string|min:1|max:255',
'birth_date' => ['required', new IsAdult(trans('Vous devez être majeur pour vous inscrire.'))],
'email' => [
'lastname' => 'required|string|max:255',
'firstname' => 'required|string|max:255',
'phone' => 'nullable|max:255|phone:FR',
'address' => 'required|string|min:1|max:255',
'address2' => 'nullable|string|min:1|max:255',
'postal_code' => 'required|string|min:1|postal_code:FR',
'city' => 'required|string|min:2|max:255',
'birth_date' => 'required|date',
'country' => [
'required', new EnumIsValidRule(Country::class),
Rule::in(Country::getValidCountries())
],
'email' => [
'required', 'email:rfc,dns,spoof', 'max:255',
// * Does email already exists in CRM ?
// phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundInExtendedClassBeforeLastUsed
@ -60,11 +67,12 @@ class CreateAccountRequest extends FormRequest
},
'unique:customers,email',
],
'password' => [
'required', 'confirmed', Password::min(8)->mixedCase()->numbers()->symbols()
'password' => [
'required', 'confirmed', Password::min(8)->mixedCase()
->numbers()->symbols()->uncompromised()
],
'ok_cgv' => 'accepted',
'opt_in' => 'required|boolean',
'ok_cgv' => 'accepted',
'opt_in' => 'required|boolean',
];
}
@ -76,17 +84,20 @@ class CreateAccountRequest extends FormRequest
public function attributes()
{
return [
'lastname' => trans('nom'),
'firstname' => trans('prénom'),
'phone' => trans('téléphone'),
'address' => trans('adresse'),
'postcode' => trans('code postal'),
'city' => trans('ville'),
'birth_date' => trans('date de naissance'),
'email' => trans('email'),
'password' => trans('mot de passe'),
'ok_cgv' => trans('conditions d\'utilisation'),
'opt_in' => trans('newsletter'),
'lastname' => trans('validation.attributes.first_name'),
'firstname' => trans('validation.attributes.first_name'),
'phone' => trans('validation.attributes.phone'),
'address' => trans('validation.attributes.line_address_1'),
'address2' => trans('validation.attributes.line_address_2'),
'country' => trans('validation.attributes.country'),
'postal_code' => trans('validation.attributes.postal_code'),
'city' => trans('validation.attributes.city'),
'birth_date' => trans('validation.attributes.date_of_birth'),
'email' => trans('validation.attributes.email'),
'password' => trans('validation.attributes.password'),
'password_confirmation' => trans('validation.attributes.password_confirmation'),
'ok_cgv' => trans('conditions d\'utilisation'),
'opt_in' => trans('newsletter'),
];
}
@ -98,11 +109,13 @@ class CreateAccountRequest extends FormRequest
public function messages()
{
return [
'postal_code' => trans('validation.custom.postal_code', [
'countries' => Country::france()->label, 'examples' => 72000
'postal_code' => trans('validation.postal_code', [
'countries' => \implode(', ', Country::getValidCountriesLabel()), 'examples' => 72000
]),
'phone.phone' => trans('validation.custom.phone'),
'email.unique' => trans('Un compte existe déjà avec cette adresse.'),
'phone.phone' => trans('validation.phone', [
'countries' => \implode(', ', Country::getValidCountriesLabel())
]),
'email.unique' => trans('Un compte existe déjà avec cette adresse.'),
'ok_cgv.accepted' => trans('Vous devez accepter les conditions d\'utilisation du site pour continuer.')
];
}

View file

@ -2,20 +2,20 @@
namespace App\Http\Requests\Fo\Customers;
use App\Rules\IsAdult;
class UpdateAccountRequest extends CreateAccountRequest
{
/** @var array */
private static $skeleton = [
'lastname',
'firstname',
'birth_date',
'phone',
'address',
'address2',
'postcode',
'city',
'country',
'opt_in',
'birth_date'
];
/**
@ -29,13 +29,7 @@ class UpdateAccountRequest extends CreateAccountRequest
\array_intersect_key(
parent::rules(),
\array_flip(self::$skeleton)
),
[
'birth_date' => [
'required',
new IsAdult(trans('Vous devez être majeur pour utiliser le site.'))
],
]
)
);
}
}

View file

@ -19,9 +19,9 @@ class GamesStatusUpdate
*/
public function handle()
{
/** @var \Illuminate\Database\Eloquent\Collection<array-key, \App\Models\News> */
/** @var \Illuminate\Database\Eloquent\Collection<array-key,\App\Models\News> */
$gamesListToUnPublish = Game::query()
->where('unpublish_at', '<=', Carbon::now()->toDateTime())
->where('unpublish_at', '<=', Carbon::now())
->whereNotNull('unpublish_at')
->where('published', true)->get();
Log::debug(__CLASS__ . " games to unpublish " . $gamesListToUnPublish->count());
@ -31,18 +31,19 @@ class GamesStatusUpdate
$game->published = false;
$game->saveOrFail();
}
/** @var \Illuminate\Database\Eloquent\Collection<array-key, \App\Models\> */
/** @var \Illuminate\Database\Eloquent\Collection<array-key,\App\Models\Game> */
$gamesListToPublish = Game::query()
->where('publish_at', '<=', Carbon::now()->toDateTime())
->where('publish_at', '<=', Carbon::now())
->whereNotNull('publish_at')
->where('published', false)->get();
Log::debug(__CLASS__ . " games to publish " . $gamesListToPublish->count());
// Unpublish all game with no date because only 1 game can be published.
if ($gamesListToPublish->count()) {
Game::query()->where('published', true)->each(function (Game $game) {
$game->published = false;
$game->saveOrFail();
});
Game::query()->where('published', true)
->each(function (Game $game) {
$game->published = false;
$game->saveOrFail();
});
}
foreach ($gamesListToPublish as $game) {
$game->publish_at = null;

View file

@ -19,9 +19,9 @@ class NewsStatusUpdate
*/
public function handle()
{
/** @var \Illuminate\Database\Eloquent\Collection<array-key, \App\Models\News> */
/** @var \Illuminate\Database\Eloquent\Collection<array-key,\App\Models\News> */
$newsListToPublish = News::query()
->where('publish_at', '<=', Carbon::now()->toDateTime())
->where('publish_at', '<=', Carbon::now())
->whereNotNull('publish_at')
->where('published', false)->get();
Log::debug(__CLASS__ . " news to publish " . $newsListToPublish->count());
@ -30,9 +30,9 @@ class NewsStatusUpdate
$news->published = true;
$news->saveOrFail();
}
/** @var \Illuminate\Database\Eloquent\Collection<array-key, \App\Models\News> */
/** @var \Illuminate\Database\Eloquent\Collection<array-key,\App\Models\News> */
$newsListToUnPublish = News::query()
->where('unpublish_at', '<=', Carbon::now()->toDateTime())
->where('unpublish_at', '<=', Carbon::now())
->whereNotNull('unpublish_at')
->where('published', true)->get();
Log::debug(__CLASS__ . " news to unpublish " . $newsListToPublish->count());

View file

@ -30,6 +30,20 @@ use Illuminate\Support\Str;
*/
class FileStorageHelper
{
/**
* Remove all files from string attribute html that are stored in public
*
* @param string $publicStorageFilePath The file path from public directory.
* @return string The local storage path.
*/
public static function getFileFullPath(string $publicStorageFilePath): string
{
/** @var \Illuminate\Filesystem\FilesystemAdapter */
$disk = Storage::disk('uploads');
$path = ToolboxHelper::mbReplace('storage/', '', \ltrim(\urldecode($publicStorageFilePath), '/'));
return $disk->path($path);
}
/**
* Destroy the file associate with the attribute.
*
@ -451,22 +465,4 @@ class FileStorageHelper
$filename = trim($filename, '.-');
return $filename;
}
/**
* Remove all model files for the given Model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public static function removeModelFiles(Model $model): void
{
$tableName = $model::query()->getModel()->getTable();
if (!empty(Storage::disk('public')->allFiles("modelfiles/{$tableName}"))) {
Storage::disk('public')->deleteDirectory("modelfiles/{$tableName}");
}
if (!empty(Storage::disk('private')->allFiles("modelfiles/{$tableName}"))) {
Storage::disk('private')->deleteDirectory("modelfiles/{$tableName}");
}
}
}

View file

@ -1,73 +0,0 @@
<?php
namespace LDCWEB;
class MesBR
{
private $endpoint;
private $refCamp;
public function __construct($endpoint, $refCamp)
{
$this->endpoint = $endpoint;
$this->refCamp = $refCamp;
}
public function createCustomer(string $hashcode, string $email, string $country)
{
return $this->callAPI("POST", '/customer', ['hashcode' => $hashcode, 'email' => $email, 'country' => $country]);
}
public function updateCustomer(string $hashcode, string $email, string $country)
{
return $this->callAPI("POST", '/customer', ['hashcode' => $hashcode, 'email' => $email, 'country' => $country]);
}
public function getMurCustomer(string $hashcode)
{
return $this->callAPI("GET", '/customer/mur', ['refcamp' => $this->refCamp, 'hashcode' => $hashcode]);
}
public function getMur()
{
return $this->callAPI("GET", '/mur', ['refcamp' => $this->refCamp]);
}
public function printCoupons(string $hashcode, array $coupons)
{
return $this->callAPI("GET", '/coupons/print', ['refcamp' => $this->refCamp, 'hashcode' => $hashcode, 'coupons' => implode(",", $coupons)]);
}
private function callAPI($method, $url, $data = [])
{
$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":
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
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);
$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);
}
}

150
app/Lib/vendor/LDCWEB/MesBr.php vendored Normal file
View file

@ -0,0 +1,150 @@
<?php
namespace LDC\MESBR;
use LDC\LDCCRM\Enums\Country;
use LDC\LDCCRM\Models\Customer;
class MesBr
{
private $endpoint;
private $refCamp;
public function __construct($endpoint, $refCamp)
{
$this->endpoint = $endpoint;
$this->refCamp = $refCamp;
}
public function createCustomer(string $hashcode, string $email, string $country)
{
return $this->callApi("POST", '/customer', ['hashcode' => $hashcode, 'email' => $email, 'country' => $country]);
}
public function updateCustomer(string $hashcode, string $email, string $country)
{
return $this->callApi("POST", '/customer', ['hashcode' => $hashcode, 'email' => $email, 'country' => $country]);
}
public function getMurCustomer(string $hashcode)
{
return $this->callApi("GET", '/customer/mur', ['refcamp' => $this->refCamp, 'hashcode' => $hashcode]);
}
public function getMur()
{
return $this->callApi("GET", '/mur', ['refcamp' => $this->refCamp]);
}
public function printCoupons(string $hashcode, array $coupons)
{
return $this->callApi("GET", '/coupons/print', [
'refcamp' => $this->refCamp, 'hashcode' => $hashcode, 'coupons' => implode(",", $coupons)
]);
}
private function callApi($method, $url, $data = [], $path = '/api/v1')
{
$url = $this->endpoint . $path . $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":
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
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);
$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);
}
// * Added METHODS
/** .
* Update panier
*
* @param \LDC\LDCCRM\Models\Customer $crm_customer
* @param integer $crm_customer_id
* @param string $ref_site
* @param string $coupon_id
* @param integer $quantity
* @return array<string,string>
* 'status' => 'OK',
* 'link' => URL,
* 'verif' => URL,
* 'basketId' => 'ID'
*/
public function updatePanier(
Customer $crm_customer,
int $crm_customer_id,
string $ref_site,
string $coupon_id,
int $quantity = 1
): array {
$res = $this->callAPI("GET", "/updatebasket", [
'refsite' => $ref_site,
'refcamp' => $this->refCamp,
'refadherent' => $crm_customer_id,
'nom' => $crm_customer->lastname,
'prenom' => $crm_customer->firstname,
'email' => $crm_customer->email,
'code_postal' => $crm_customer->postcode,
'commune' => $crm_customer->city,
'pays' => $this->getCountry($crm_customer->country),
'panier' => "({$quantity}){$coupon_id}"
], '');
if (!$res) {
error_log("MESBR - CODE : 999 - MESSAGE : Cannot read API Response (non json)");
return ['status' => 'KO', 'code' => 999, 'message' => 'Cannot read API Response (non json)'];
}
if ($res->Statut === 'KO') {
error_log("MESBR - CODE : $res->Code - MESSAGE : $res->Message");
return ['status' => 'KO', 'code' => $res->Code, 'message' => $res->Message];
}
$panierVerification = $this->endpoint . '/showbasket?basketid=' . $res->Panier->Panier;
$panier_link = $this->endpoint . '/?basketid=' . $res->Panier->Panier;
return ['status' => 'OK', 'link' => $panier_link, 'verif' => $panierVerification, 'basketId' => $res->Panier->Panier];
}
/**
* Translate country to MesBr Country
*
* @param \LDC\LDCCRM\Enums\Country $country
* @return inteager
*/
private function getCountry(Country $country): int
{
return match ($country) {
Country::belgium() => 56,
Country::luxembourg() => 442,
// * France
default => 250
};
}
}

View file

@ -1,24 +0,0 @@
<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Verified;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class LogVerifiedUser
{
/**
* Handle the given event.
*
* @param \Illuminate\Auth\Events\Verified $event
* @return void
*/
public function handle(Verified $event)
{
/** @var \App\Models\Customer */
$customer = $event->user;
Auth::guard('frontend')->login($customer);
Session::flash('success', trans('Votre compte à bien été validé, vous êtes à présent connecté.'));
}
}

View file

@ -10,11 +10,11 @@ use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Schema;
/**
* @property string $model Target model.
* @property string $model_id Id of the target model.
* @property string $event Event of this activity (ActivityLogsEventEnum).
* @property string $data Changes.
* @property-read \Carbon\Carbon $created_at Created date.
* @property string $model Target model.
* @property string $model_id Id of the target model.
* @property string $event Event of this activity (ActivityLogsEventEnum).
* @property string $data Changes.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
*
* @property-read \App\Models\User $user User BelongsTo relation.
*/
@ -122,7 +122,7 @@ class ActivityLog extends Model
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(User::class);
}

View file

@ -4,6 +4,7 @@ namespace App\Models;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\IsCachedAsCollection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
@ -34,6 +35,7 @@ use Illuminate\Support\Str;
*/
class Range extends Model
{
use IsCachedAsCollection;
use HasFactory;
/**
@ -71,10 +73,12 @@ class Range extends Model
static::creating(function () {
throw new \RuntimeException("Creating a new range is not authorized");
});
static::created(fn () => self::removeCached());
static::updating(function (self $model) {
self::manageFields($model);
});
static::updated(function (self $model) {
self::removeCached();
FileStorageHelper::removeOldFile($model, 'picture');
FileStorageHelper::removeOldFile($model, 'picture_ambiance');
FileStorageHelper::removeOldFile($model, 'picto1_picture');
@ -83,6 +87,7 @@ class Range extends Model
static::deleting(function () {
throw new \RuntimeException('Deleting a range is not authorized');
});
static::deleted(fn () => self::removeCached());
}
// * METHODS

View file

@ -10,14 +10,14 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
/**
* @property \App\Enums\StaticPageType $type Page type (StaticPageEnum).
* @property string $seo_title Seo title about 70 chars as recommended.
* @property string $seo_description Seo description about 160 chars as recommended.
* @property string $title Title for the page.
* @property string $slug Slug of the title for the page.
* @property string $content WYSIWYG text content using ckeditor.
* @property-read \Carbon\Carbon $created_at Created date.
* @property-read \Carbon\Carbon $updated_at Updated date.
* @property \App\Enums\StaticPageType $type Page type (StaticPageEnum).
* @property string $seo_title Seo title about 70 chars as recommended.
* @property string $seo_description Seo description about 160 chars as recommended.
* @property string $title Title for the page.
* @property string $slug Slug of the title for the page.
* @property string $content WYSIWYG text content using ckeditor.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*/
class StaticPage extends Model
{
@ -67,6 +67,32 @@ class StaticPage extends Model
});
}
// * ROUTABLE
/**
* Get the value of the model's route key.
*
* @return mixed
*/
public function getRouteKey()
{
/** @var \App\Enums\StaticPageType */
$enum = $this->getAttribute($this->getRouteKeyName());
return $enum->value();
}
/**
* Get the route key for the model.
*
* ! Type is the routable parameter
*
* @return string
*/
public function getRouteKeyName(): string
{
return 'type';
}
// * METHODS
/**

View file

@ -4,21 +4,22 @@ namespace App\Models;
use App\Enums\Users\RoleEnum;
use App\Traits\Models\ActivityLog;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
/**
* @property string $first_name Prénom.
* @property string $last_name Nom.
* @property string $email Email.
* @property string $password Mot de passe.
* @property \App\Enums\Users\RoleEnum $role Rôle.
* @property \Carbon\Carbon $published État de publication.
* @property \Carbon\Carbon $published_at Date de mise à jour de l'état de publication.
* @property-read \Carbon\Carbon $created_at Created date.
* @property-read \Carbon\Carbon $updated_at Updated date.
* @property string $first_name Prénom.
* @property string $last_name Nom.
* @property string $email Email.
* @property string $password Mot de passe.
* @property \App\Enums\Users\RoleEnum $role Rôle.
* @property \Illuminate\Support\Carbon $published État de publication.
* @property \Illuminate\Support\Carbon $published_at Date de mise à jour de l'état de publication.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*
* @property-read \App\Models\ActivityLog $activityLogs Activities logs One-to-many relationship.
*/

View file

@ -2,11 +2,9 @@
namespace App\Providers;
use App\Listeners\LogVerifiedUser;
use App\Listeners\PasswordHasReset;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Events\Verified;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
@ -21,9 +19,6 @@ class EventServiceProvider extends ServiceProvider
Registered::class => [
SendEmailVerificationNotification::class,
],
Verified::class => [
LogVerifiedUser::class
],
PasswordReset::class => [
PasswordHasReset::class
],

View file

@ -4,9 +4,9 @@ namespace App\Providers;
use Illuminate\Support\Facades\App;
use Illuminate\Support\ServiceProvider;
use LDCWEB\MesBR;
use LDC\MESBR\MesBr;
class MesBrServiceProvider extends ServiceProvider
class MesBrApiServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
@ -15,8 +15,8 @@ class MesBrServiceProvider extends ServiceProvider
*/
public function boot()
{
App::singleton('mesbr', function () {
return new MesBR(
App::singleton('mesBrAPI', function () {
return new MesBr(
config('mesbr.endpoint'),
config('mesbr.camp')
);

View file

@ -45,7 +45,7 @@ class ViewServiceProvider extends ServiceProvider
if (!app()->runningInConsole()) {
// Shares this data with all views.
if (Schema::hasTable('ranges')) {
View::share('allRanges', Range::query()->get());
View::share('allRanges', Range::getCached());
}
// * FORCE BOOTSTRAP PAGINATOR (or custom if in front)

View file

@ -1,105 +0,0 @@
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Carbon;
class IsAdult implements ValidationRule
{
/**
* Error message
*
* @var string|null
*/
private $error_message;
/**
* Create a new rule instance.
*
* @param null|string $message
* @return void
*/
public function __construct(?string $message = null)
{
$this->error_message = $message ?? trans('Vous devez être majeur.');
}
/**
* Run the validation rule.
*
* @param string $attribute
* @param mixed $value
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
* @return void
* @throws \RuntimeException If date cannot be parsed.
* @phpcs:disable Squiz.Commenting.FunctionComment.IncorrectTypeHint
*/
public function validate(string $attribute, mixed $value, \Closure $fail): void
{
//@phpcs:enable
$MJ = Carbon::now()->subYears(18);
if ($this->isIsoFormat($value)) {
$d = Carbon::parse($value);
}
if ($this->isSqlDate($value)) {
$d = Carbon::createFromFormat('Y-m-d', $value);
}
if ($this->isFormDate($value)) {
$d = Carbon::createFromFormat('d/m/Y', $value);
}
// * Could not parse date.
if (!$d) {
throw new \RuntimeException("Could not parse date {$value} for attribute '{$attribute}'.");
}
if (!$d->lessThanOrEqualTo($MJ)) {
$fail($this->error_message);
}
}
/**
* Check if provided string is formatted for mysql
*
* @param string $date
* @return boolean
*/
private function isSqlDate(string $date)
{
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)) {
return true;
}
return false;
}
/**
* Check if provided string is formatted DD/MM/AAAA
*
* @param string $date
* @return boolean
*/
private function isFormDate(string $date)
{
if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}$/", $date)) {
return true;
}
return false;
}
/**
* Check if provided string is iso format
*
* * https://www.w3.org/TR/NOTE-datetime
*
* @param string $date
* @return boolean
*/
private function isIsoFormat(string $date)
{
// phpcs:ignore Generic.Files.LineLength.TooLong
if (preg_match("/^(\d{4})(?:-?W(\d+)(?:-?(\d+)D?)?|(?:-(\d+))?-(\d+))(?:[T ](\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?)?(?:Z(-?\d*))?$/", $date)) {
return true;
}
return false;
}
}

View file

@ -51,7 +51,7 @@
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/",
"LDCWEB\\": "app/Lib/vendor/LDCWEB"
"LDC\\MESBR\\": "app/Lib/vendor/LDCWEB"
}
},
"scripts": {

View file

@ -197,7 +197,7 @@ return [
App\Providers\TranslationServiceProvider::class,
App\Providers\ViewServiceProvider::class,
App\Providers\CrmApiServiceProvider::class,
App\Providers\MesBrServiceProvider::class,
App\Providers\MesBrApiServiceProvider::class,
],
/*

View file

@ -51,9 +51,9 @@ class ProductFactory extends Factory
],
];
$label = fake()->text(15);
$label = fake()->unique()->slug(3);
return [
'label' => $label,
'label' => Str::of($label)->replace('-', ' ')->title(),
'slug' => Str::slug($label),
'seo_title' => fake()->sentence(),
'seo_description' => fake()->sentence(),

View file

@ -2,7 +2,6 @@
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
@ -29,9 +28,6 @@ return new class extends Migration
$table->timestamps();
});
Artisan::call('db:seed', [
'class' => 'StaticPageSeeder'
]);
}
/**

View file

@ -0,0 +1,30 @@
<?php
use Database\Seeders\MandatorySeeder;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Artisan;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up(): void
{
Artisan::call('db:seed', [
'class' => MandatorySeeder::class
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down(): void
{
// Do nothing.
}
};

View file

@ -14,17 +14,9 @@ class DatabaseSeeder extends Seeder
public function run()
{
$this->call([
UserSeeder::class,
PictoSeeder::class,
CommitmentPageSeeder::class,
GameSeeder::class,
HistoricalMilestoneSeeder::class,
KlubBlocSeeder::class,
LocalCommitmentSeeder::class,
NewsSeeder::class,
RangeSeeder::class,
ProductSeeder::class,
ReductionSeeder::class,
MandatorySeeder::class,
DevelopmentSeeder::class,
UserSeeder::class
]);
}
}

View file

@ -1,10 +1,12 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Development;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\Game;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class GameSeeder extends Seeder
{
@ -15,7 +17,8 @@ class GameSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new Game());
DB::table((new Game())->getTable())->truncate();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new Game())->getTable()));
$publish_at = now()->addMonth();
$unpublish_at = $publish_at->copy()->addDays(rand(10, 20));

View file

@ -1,10 +1,12 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Development;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\HistoricalMilestone;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class HistoricalMilestoneSeeder extends Seeder
{
@ -15,7 +17,8 @@ class HistoricalMilestoneSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new HistoricalMilestone());
DB::table((new HistoricalMilestone())->getTable())->truncate();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new HistoricalMilestone())->getTable()));
HistoricalMilestone::factory(7)->make()->each(function (HistoricalMilestone $historicalMilestone) {
$historicalMilestone->picture1 = FileStorageHelper::storeFile(

View file

@ -1,10 +1,12 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Development;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\LocalCommitment;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class LocalCommitmentSeeder extends Seeder
{
@ -15,7 +17,8 @@ class LocalCommitmentSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new LocalCommitment());
DB::table((new LocalCommitment())->getTable())->truncate();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new LocalCommitment())->getTable()));
LocalCommitment::factory(7)->make()->each(function (LocalCommitment $localCommitment) {
$localCommitment->picture1 = FileStorageHelper::storeFile(

View file

@ -1,10 +1,12 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Development;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\News;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class NewsSeeder extends Seeder
{
@ -15,7 +17,8 @@ class NewsSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new News());
DB::table((new News())->getTable())->truncate();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new News())->getTable()));
News::factory(20)->make()->each(function (News $news) {
$news->picture = FileStorageHelper::storeFile(

View file

@ -1,11 +1,14 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Development;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\Picto;
use App\Models\Product;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
class ProductSeeder extends Seeder
{
@ -16,7 +19,11 @@ class ProductSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new Product());
Schema::disableForeignKeyConstraints();
DB::table((new Product())->getTable())->truncate();
Schema::enableForeignKeyConstraints();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new Product())->getTable()));
Product::factory(12)->make()->each(function (Product $product) {
$product->picture = FileStorageHelper::storeFile(

View file

@ -1,10 +1,12 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Development;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\Reduction;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class ReductionSeeder extends Seeder
{
@ -15,7 +17,8 @@ class ReductionSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new Reduction());
DB::table((new Reduction())->getTable())->truncate();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new Reduction())->getTable()));
Reduction::factory(10)->make()->each(function (Reduction $reduction) {
$reduction->picture_packshot = FileStorageHelper::storeFile(

View file

@ -0,0 +1,31 @@
<?php
namespace Database\Seeders;
use Database\Seeders\Development\GameSeeder;
use Database\Seeders\Development\HistoricalMilestoneSeeder;
use Database\Seeders\Development\LocalCommitmentSeeder;
use Database\Seeders\Development\NewsSeeder;
use Database\Seeders\Development\ProductSeeder;
use Database\Seeders\Development\ReductionSeeder;
use Illuminate\Database\Seeder;
class DevelopmentSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{
$this->call([
GameSeeder::class,
HistoricalMilestoneSeeder::class,
LocalCommitmentSeeder::class,
NewsSeeder::class,
ProductSeeder::class,
ReductionSeeder::class,
]);
}
}

View file

@ -1,10 +1,13 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Mandatory;
use App\Models\CommitmentPage;
use App\Models\Picto;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
class CommitmentPageSeeder extends Seeder
{
@ -15,6 +18,12 @@ class CommitmentPageSeeder extends Seeder
*/
public function run()
{
Schema::disableForeignKeyConstraints();
DB::table((new CommitmentPage())->getTable())->truncate();
Schema::enableForeignKeyConstraints();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new Picto())->getTable()));
CommitmentPage::factory(1)->createQuietly();
$pictos = Picto::query()->get();

View file

@ -1,10 +1,12 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Mandatory;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\KlubBloc;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class KlubBlocSeeder extends Seeder
{
@ -15,7 +17,9 @@ class KlubBlocSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new KlubBloc());
DB::table((new KlubBloc())->getTable())->truncate();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new KlubBloc())->getTable()));
KlubBloc::factory(1)->make()->each(function (KlubBloc $klubBloc) {
$klubBloc->picture = FileStorageHelper::storeFile(
new KlubBloc(),

View file

@ -1,10 +1,13 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Mandatory;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\Picto;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
class PictoSeeder extends Seeder
{
@ -15,7 +18,11 @@ class PictoSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new Picto());
Schema::disableForeignKeyConstraints();
DB::table((new Picto())->getTable())->truncate();
Schema::enableForeignKeyConstraints();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new Picto())->getTable()));
Picto::factory(10)->make()->each(function (Picto $picto) {
$picto->picture = FileStorageHelper::storeFile(

View file

@ -1,10 +1,13 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Mandatory;
use App\Lib\Helpers\FileStorageHelper;
use App\Models\Range;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
class RangeSeeder extends Seeder
{
@ -15,7 +18,11 @@ class RangeSeeder extends Seeder
*/
public function run()
{
FileStorageHelper::removeModelFiles(new Range());
Schema::disableForeignKeyConstraints();
DB::table((new Range())->getTable())->truncate();
Schema::enableForeignKeyConstraints();
File::deleteDirectory(\storage_path('app/public/modelfiles/' . (new Range())->getTable()));
Range::factory(3)->make()->each(function (Range $range) {
$range->picture = FileStorageHelper::storeFile(

View file

@ -1,10 +1,11 @@
<?php
namespace Database\Seeders;
namespace Database\Seeders\Mandatory;
use App\Enums\StaticPageType;
use App\Models\StaticPage;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class StaticPageSeeder extends Seeder
@ -16,6 +17,8 @@ class StaticPageSeeder extends Seeder
*/
public function run()
{
DB::table((new StaticPage())->getTable())->truncate();
StaticPage::query()->make(
[
'seo_title' => 'Seo title pour la page contactez nous',
@ -23,7 +26,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Contactez-nous',
'slug' => Str::slug('Contactez-nous'),
'type' => StaticPageType::contact,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -33,7 +36,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Mentions légales',
'slug' => Str::slug('Mentions légales'),
'type' => StaticPageType::legals,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -43,7 +46,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Charte de confidentialité',
'slug' => Str::slug('Charte de confidentialité'),
'type' => StaticPageType::confidentiality,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -53,7 +56,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Accueil',
'slug' => Str::slug('Accueil'),
'type' => StaticPageType::home,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -63,7 +66,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Nos gammes',
'slug' => Str::slug('Nos gammes'),
'type' => StaticPageType::ranges,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -73,7 +76,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Une Gamme',
'slug' => Str::slug('Une Gamme'),
'type' => StaticPageType::range,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -83,7 +86,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Actualités',
'slug' => Str::slug('Actualités'),
'type' => StaticPageType::news,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -93,7 +96,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Le Klub',
'slug' => Str::slug('Le Klub'),
'type' => StaticPageType::klub,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -103,7 +106,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Le Klub - Inscription',
'slug' => Str::slug('Le Klub - Inscription'),
'type' => StaticPageType::klub_register,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(
@ -113,7 +116,7 @@ class StaticPageSeeder extends Seeder
'title' => 'Notre Histoire',
'slug' => Str::slug('Notre Histoire'),
'type' => StaticPageType::history,
'content' => \clean(\fake()->randomHtml(6, 7)),
'content' => \clean(\fake()->randomHtml(2, 3)),
]
)->saveQuietly();
StaticPage::query()->make(

View file

@ -0,0 +1,29 @@
<?php
namespace Database\Seeders;
use Database\Seeders\Mandatory\CommitmentPageSeeder;
use Database\Seeders\Mandatory\KlubBlocSeeder;
use Database\Seeders\Mandatory\PictoSeeder;
use Database\Seeders\Mandatory\RangeSeeder;
use Database\Seeders\Mandatory\StaticPageSeeder;
use Illuminate\Database\Seeder;
class MandatorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run(): void
{
$this->call([
StaticPageSeeder::class,
PictoSeeder::class,
CommitmentPageSeeder::class,
RangeSeeder::class,
KlubBlocSeeder::class
]);
}
}

View file

@ -3,10 +3,13 @@
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class UserSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Run the database seeds.
*
@ -14,6 +17,6 @@ class UserSeeder extends Seeder
*/
public function run()
{
User::factory(20)->createQuietly();
User::factory(20)->create();
}
}

View file

@ -217,6 +217,12 @@ return [
'username' => 'nom d\'utilisateur',
'year' => 'année',
],
'postal_code' => 'le champ :attribute accepte les codes postaux des pays suivants
:countries comme par exemple :examples',
'phone' => 'Le champ :attribute n\'est pas un numéro de téléphone valide, il accepte les
numéros des pays suivants :countries.',
'custom' => [
'of_the' => [
'male' => 'du ',

View file

@ -9,6 +9,7 @@
v-model="ipt_value"
:autocomplete="String(ipt_autocomplete)"
:required="Boolean(ipt_required)"
:aria-label="__(ipt_placeholder)"
@focus="startEditing"
@change="changed"
>

View file

@ -1,17 +1,18 @@
<div class="row">
{{-- ROLE --}}
{{-- TYPE --}}
<div class="col-12 col-md-6 mb-3">
<fieldset class="h-100 border p-3">
<legend>{{ Str::ucfirst(__('validation.custom.static_page_type')) }}</legend>
<div class="row">
<div class="col-12">
@include('bo.partials.inputs.tinyint-enum', [
'id' => 'userRole',
'label' => __('Associer un rôle'),
'name' => 'role',
'id' => 'staticPageType',
'label' => __('Type de page'),
'name' => 'type',
'model' => $staticPageModel ?? null,
'required' => false,
'disabled' => true,
'value' => optional(optional($staticPageModel ?? null)->type)->value(),
'associatedModels' => \App\Enums\StaticPageType::toArray(),
'helper' => '',
])

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -17,15 +18,18 @@
@endif
<select
id="{{ $id }}"
class="form-select @if($errors->has($name)) is-invalid @endif"
@class([
'form-select',
'is-invalid' => $errors->has($name)
])
name="{{ $name }}"
@if(!empty($size))
size="{{ $size }}"
@endif
aria-describedby="{{ $id }}Help"
@if(!empty($required))
required
@endif>
@disabled(!empty($disabled))
@readonly(!empty($readonly))
@required(!empty($required))>
@foreach ($associatedModels as $associatedModel)
<option
value="{{ $associatedModel->id }}"
@ -38,6 +42,6 @@
</select>
@include('modules.input-error', [
'inputName' => $name,
'helperId' => "{{ $id }}Help",
'helperId' => "{$id}Help",
'helper' => $helper
])

View file

@ -0,0 +1,71 @@
{{-- blade-formatter-disable --}}
@if(!empty($label))
<label for="{{ $id }}" class="col-form-label">
<b>{{ $label }} {{ $required ? '*' : '' }}</b>
</label>
@endif
@if(isset($appendText))
<div class="input-group">
@endif
<input
id="{{ $id }}"
name="{{ $name }}"
type="text"
data-jscolor=""
class="form-control"
aria-describedby="{{ $id }}Help"
value="{{ old($name, $model->{$name} ?? $value ?? '') }}"
@if(!empty($disabled))disabled @endif
@if(!empty($readonly))readonly @endif
@if(!empty($required))required @endif>
@if(isset($appendText))
<label class="input-group-text">{{ $appendText }}</label>
</div>
@endif
@include('modules.input-error', [
'inputName' => $name,
'helperId' => "{$id}Help",
'helper' => $helper
])
@push('scripts')
<script @if(isset($nonce) and is_string($nonce)) nonce="{{ $nonce }}" @endif>
window.addEventListener("DOMContentLoaded", (event) => {
// https://stackoverflow.com/a/35970186/4355295
let __invertColor = function(hex, bw) {
if (hex.indexOf('#') === 0) {
hex = hex.slice(1);
}
// convert 3-digit hex to 6-digits.
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (hex.length !== 6) {
throw new Error('Invalid HEX color.');
}
var r = parseInt(hex.slice(0, 2), 16),
g = parseInt(hex.slice(2, 4), 16),
b = parseInt(hex.slice(4, 6), 16);
if (bw) {
// https://stackoverflow.com/a/3943023/112731
return (r * 0.299 + g * 0.587 + b * 0.114) > 186
? '#000000'
: '#FFFFFF';
}
// invert color components
r = (255 - r).toString(16);
g = (255 - g).toString(16);
b = (255 - b).toString(16);
// pad each with zeros and return
return "#" + r.padStart(1, '0') + g.padStart(1, '0') + b.padStart(1, '0');
}
let colorSpans = document.getElementsByClassName('colorize');
if(colorSpans.length) {
for(let colorSpan of colorSpans) {
colorSpan.style.color = __invertColor(colorSpan.textContent, true);
colorSpan.style.backgroundColor = colorSpan.textContent;
}
}
});
</script>
@endpush

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -28,7 +29,10 @@
name="{{ $name }}"
type="number"
value="{{ Str::replace(',', '.', strval(old($name, $value ?? $model->{$name} ?? 0))) }}"
class="form-control @if($errors->has($name)) is-invalid @endif"
@class([
'form-control',
'is-invalid' => $errors->has($name)
])
aria-describedby="{{ $id }}Help"
@if(!empty($step))
step="{{ Str::replace(',', '.', strval($step)) }}"
@ -43,15 +47,15 @@
@else
min="{{ !empty($unsigned) ? '0' : '-2147483648' }}"
@endif
@if(!empty($required))
required
@endif>
@disabled(!empty($disabled))
@readonly(!empty($readonly))
@required(!empty($required))>
@if(isset($appendText))
<label class="input-group-text">{{ $appendText }}</label>
</div>
@endif
@include('modules.input-error', [
'inputName' => $name,
'helperId' => '{{ $id }}Help',
'helperId' => "{$id}Help",
'helper' => $helper
])

View file

@ -13,7 +13,7 @@
@php
$data = [
'name' => $name,
'value' => old($name) ?? ($model->{$name} ?? []) ?? [],
'value' => Arr::wrap(old($name) ?? ($model->{$name} ?? [])),
'placeholder' => $placeholder,
'itemsList' => $itemsList,
'itemLimit' => $itemLimit ?? null,

View file

@ -1,16 +1,16 @@
@php
$data = [
"name" => $name,
"label" => $label,
"value" => $value ?? [],
"placeholder" => $placeholder,
"itemsSelected" => $itemsSelected,
"itemsList" => $itemsList,
"itemLimit" => $itemLimit,
"showSpecificItem" => $showSpecificItem ?? null,
"errors" => $errors->getBag("default")->getMessages() ?? [],
'helper' => $helper,
'require' => $require
];
$data = [
'name' => $name,
'label' => $label,
'value' => $value ?? [],
'placeholder' => $placeholder,
'itemsSelected' => $itemsSelected,
'itemsList' => $itemsList,
'itemLimit' => $itemLimit,
'showSpecificItem' => $showSpecificItem ?? null,
'errors' => $errors->getBag('default')->getMessages() ?? [],
'helper' => $helper,
'require' => $require,
];
@endphp
<div class="select-multiple-enum" data-json='@json($data)'></div>

View file

@ -10,23 +10,27 @@
$model || The model we're creating/editing || Model class || OPTIONNAL || null
--}}
@if(!empty($label))
<label for="{{ $id }}" class="col-form-label">
<b>{{ $label }} {{ $required ?? false ? '*' : '' }}</b>
</label>
@if (!empty($label))
<label class="col-form-label" for="{{ $id }}">
<b>{{ $label }} {{ $required ?? false ? '*' : '' }}</b>
</label>
@endif
@php
$data = [
'name' => $name,
'text' => old($name, $model->{$name} ?? $value ?? '')
];
$data = [
'name' => $name,
'text' => old($name, $model->{$name} ?? ($value ?? '')),
];
@endphp
<div class="ck-editor" data-json='@json($data)'></div>
@include('modules.input-error', [
'inputName' => $name,
'helperId' => "{$id}Help",
'helper' => $helper ?? __('crud.minicrud.text_warning') . '. ' . __('validation.min.string', [
'attribute' => $input['label'],
'min' => 15
]),
'helper' =>
$helper ??
__('crud.minicrud.text_warning') .
'. ' .
__('validation.min.string', [
'attribute' => $input['label'],
'min' => 15,
]),
])

View file

@ -1,7 +1,7 @@
<div class="container p-0 m-0">
<div class="container m-0 p-0">
<div class="row">
<div class="col">
<label for="{{ $name }}" class="col-form-label">
<label class="col-form-label" for="{{ $name }}">
<b>{{ $label }} {{ $required ? '*' : '' }}</b>
</label>
</div>
@ -9,16 +9,16 @@
<div class="row">
<div class="col">
@php
$data = [
'itemList' => old($name, $model->{$name} ?? []) ?? [],
'itemColumns' => $itemColumns,
'itemType' => $itemType,
'itemLimit' => $itemLimit ?? [],
'inputName' => $name,
'inputPlaceholder' => $inputPlaceholder,
'header' => $header ?? false,
'errors' => $errors->getBag('default')->getMessages() ?? []
];
$data = [
'itemList' => old($name, $model->{$name} ?? []) ?? [],
'itemColumns' => $itemColumns,
'itemType' => $itemType,
'itemLimit' => $itemLimit ?? [],
'inputName' => $name,
'inputPlaceholder' => $inputPlaceholder,
'header' => $header ?? false,
'errors' => $errors->getBag('default')->getMessages() ?? [],
];
@endphp
<div class="list-item" data-json='@json($data)'></div>
@include('modules.input-error', [

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -16,8 +17,11 @@
<b>{{ $label }} {{ $required ?? false ? '*' : '' }}</b>
</label>
@endif
<input class="form-control @if ($errors->has($name)) is-invalid @endif" id="{{ $id }}" name="{{ $name }}"
data-form-type="date" type="{{ $type ?? 'datetime-local' }}"
<input id="{{ $id }}"
name="{{ $name }}"
class="form-control @if ($errors->has($name)) is-invalid @endif"
type="{{ $type ?? 'datetime-local' }}"
data-form-type="date"
value="{{ old($name, (isset($model) and $model->{$name}) ? $model->{$name}->format($format ?? 'Y-m-d\TH:i') ?? '' : '') }}"
aria-describedby="{{ "{$id}Help" }}">
@include('modules.input-error', [

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -9,7 +10,7 @@
--}}
<div class="form-check form-switch ms-2">
<label class="col-form-label p-0" type="button" for="{{ $id }}"><b>{{ $label }}</b></label>
<label class="col-form-label p-0" for="{{ $id }}"><b>{{ $label }}</b></label>
<input
id="{{ $id }}"
aria-describedby="{{ $id }}Help"
@ -17,13 +18,13 @@
type="checkbox"
class="ml-2 form-check-input"
value="1"
@if(!empty($disabled))
disabled
@endif
@if(old($name, (old('_token') ? false : ($model->{$name} ?? false)))) checked @endif>
@disabled(!empty($disabled))
@readonly(!empty($readonly))
@required(!empty($required))
@checked(old($name, (old('_token') ? false : ($model->{$name} ?? false))))>
</div>
@include('modules.input-error', [
'inputName' => $name,
'helperId' => '{{ $id }}Help' ,
'helperId' => "{$id}Help",
'helper' => $helper
])

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -17,7 +18,10 @@
@endif
<select
id="{{ $name }}"
class="form-select @if($errors->has($name)) is-invalid @endif"
@class([
'form-select',
'is-invalid' => $errors->has($name)
])
name="{{ $name }}"
aria-describedby="{{ $id }}Help"
@if(!empty($disabled))
@ -39,6 +43,6 @@
</select>
@include('modules.input-error', [
'inputName' => $name,
'helperId' => "{{ $id }}Help",
'helperId' => "{$id}Help",
'helper' => $helper
])

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -10,8 +11,8 @@
$model || The model we're creating/editing || Model class || OPTIONNAL || null
--}}
@if(!empty($label))
<label for="{{ $id }}" class="col-form-label">
@if (!empty($label))
<label class="col-form-label" for="{{ $id }}">
<b>{{ $label }} {{ $required ?? false ? '*' : '' }}</b>
</label>
@endif
@ -19,15 +20,15 @@
name="{{ $name }}"
type="email"
value="{{ old($name, $model->{$name} ?? '') }}"
class="form-control @if($errors->has($name)) is-invalid @endif"
class="form-control @if ($errors->has($name)) is-invalid @endif"
id="{{ $id }}"
aria-describedby="{{ $id }}Help"
placeholder="{{ $placeholder ?? __('aaa.bbb@example.com') }}"
@if(!empty($required))
required
@endif>
@disabled(!empty($disabled))
@readonly(!empty($readonly))
@required(!empty($required))>
@include('modules.input-error', [
'inputName' => $name,
'helperId' => '{{ $id }}Help',
'helper' => $helper
'helperId' => "{$id}Help",
'helper' => $helper,
])

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -35,6 +36,32 @@
data-bs-toggle="tooltip">
{{ basename($model->{$name}) }}
</a>
@php
$removeBtnId = 'remove-btn-id-' . uniqid();
@endphp
<button class="btn btn-danger" id="{{ $removeBtnId }}" data-bs-toggle="tooltip"
title="{{ __('Supprimer le fichier :type', ['type' => $file ?? '.pdf']) }}">
<i class="fa fa-trash"></i>
</button>
@push('scripts')
<script nonce="{{ $nonce }}">
document.addEventListener('DOMContentLoaded', function() {
const removeBtn = document.getElementById('{{ $removeBtnId }}'),
input = removeBtn.parentElement.querySelector('input'),
link = removeBtn.parentElement.querySelector('a');
input.addEventListener('change', () => {
removeBtn.classList.remove('d-none');
link.classList.add('d-none');
});
removeBtn.addEventListener('click', (e) => {
e.preventDefault();
input.value = "";
removeBtn.classList.add('d-none');
link.classList.add('d-none');
});
});
</script>
@endpush
@endif
</div>
@include('modules.input-error', [

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -24,14 +25,18 @@
name="{{ $name }}"
type="password"
value="{{ old($name, $model->{$name} ?? '') }}"
class="form-control @if($errors->has($name)) is-invalid @endif @if(!empty($hasWordCounter ?? false)) need-word-counter-password @endif"
@class([
'form-control',
'is-invalid' => $errors->has($name),
'need-word-counter-password' => !empty($hasWordCounter ?? false)
])
id="{{ $id }}"
aria-describedby="{{ $id }}Help"
placeholder="{{ $placeholder ?? __('Un beau mot de passe') }}"
autocomplete="current-password"
@if(!empty($required))
required
@endif>
@disabled(!empty($disabled))
@readonly(!empty($readonly))
@required(!empty($required))>
@php $dataPassword = ['inputId' => $id]; @endphp
<span class="btn btn-primary password-visibility w-fit d-flex justify-content-center align-items-center p-0 @if(!empty($hasWordCounter ?? false)) need-word-counter-password-btn @endif"
data-json='@json($dataPassword)'>
@ -39,6 +44,6 @@
</div>
@include('modules.input-error', [
'inputName' => $name,
'helperId' => $id . 'Help',
'helperId' => "{$id}Help",
'helper' => $helper
])

View file

@ -15,17 +15,17 @@
--}}
@php
$data = [
'id' => $id,
'name' => $name,
'helper' => $helper,
'width' => $width,
'height' => $height,
'value' => $model->{$name} ?? $value ?? '',
'preview' => $preview ?? false,
'browseEvent' => $browseEvent ?? false,
'required' => $required ?? false,
];
$data = [
'id' => $id,
'name' => $name,
'helper' => $helper,
'width' => $width,
'height' => $height,
'value' => $model->{$name} ?? ($value ?? ''),
'preview' => $preview ?? false,
'browseEvent' => $browseEvent ?? false,
'required' => $required ?? false,
];
@endphp
<div class="image-input" data-json='@json($data)'></div>
@include('modules.input-error', ['inputName' => $name, 'helper' => null])

View file

@ -1,3 +1,4 @@
{{-- blade-formatter-disable --}}
{{--
VARIABLE || COMMENT || TYPE || REQUIRED || DEFAULT
@ -24,12 +25,16 @@
type="text"
value="{{ old($name, $model->{$name} ?? $value ?? '') }}"
class="form-control @if($errors->has($name)) is-invalid @endif"
@class([
'form-control',
'is-invalid' => $errors->has($name)
])
id="{{ $id }}"
aria-describedby="{{ $id }}Help"
placeholder="{{ $placeholder ?? __('A beautiful title') }}"
@if(!empty($required))
required
@endif>
@disabled(!empty($disabled))
@readonly(!empty($readonly))
@required(!empty($required))>
@include('modules.input-error', [
'inputName' => $name,
'helperId' => $id.'Help',

View file

@ -19,13 +19,13 @@
{{ __('Code postal :') }} __{{ $data->postal_code }}__
@if ($data->product)
{{ __('Produit concerné :') }} __{{ $data->product->label }}__
{{ __('Produit concerné :') }} __{{ $data->product->label }}__<br>
@endif
@if ($data->expiration_date)
{{ __('DCR :') }} __{{ $data->expiration_date->isoFormat('LLLL') }}__
{{ __('DCR :') }} __{{ $data->expiration_date->isoFormat('LLLL') }}__<br>
@endif
@if ($data->batch_number)
{{ __('Numéro de lot :') }} __{{ $data->batch_number }}__
{{ __('Numéro de lot :') }} __{{ $data->batch_number }}__<br>
@endif
{{ __('Message :') }}

View file

@ -14,20 +14,21 @@
<h1 class="fs-1 text-primary text-center">{{ __('Le Klub') }} <span class="text-tertiary">{{ config('app.name') }} !</span></h1>
<img class="img-fluid flex-shrink-1 mb-3 flex-grow-0"
src="{{ Vite::asset('resources/assets/images/global/underline-yellow.svg') }}" alt="{{ __('Trait souligné') }}">
<span class="d-block text-primary">{{ __('Inscrivez vous au Klub Tre Galette') }}</span>
<form method="POST" action="{{ route('fo.register') }}">
@csrf
<fieldset class="container-fluid p-md-5 pt-md-1">
<legend class="d-block text-primary fs-5">{{ __('Inscrivez vous au Klub Tre Galette') }}</legend>
@include('fo.pages.klub.customer-form')
<div class="row justify-content-center">
<div class="col col-md-8 text-primary lh-sm px-0 py-2">
<div class="form-check text-start">
<input class="form-check-input @if ($errors->has('opt_in')) is-invalid @endif me-1" id="checkOptin"
name="opt_in" type="checkbox">
<label class="form-check-label w-fit" for="checkOptin" role="button">
<input class="form-check-input @if ($errors->has('opt_in')) is-invalid @endif me-1" id="check-optin"
name="opt_in" type="checkbox" @checked(old('opt_in'))>
<label class="form-check-label w-fit" for="check-optin" role="button">
{{ __('Je souhaite m\'inscrire à la newsletter') }} {{ Config::get('theme.site_name') }}
</label>
</div>
@ -39,9 +40,9 @@
<div class="row justify-content-center mb-3">
<div class="col col-md-8 text-primary lh-sm px-0 py-2">
<div class="form-check">
<input class="form-check-input @if ($errors->has('ok_cgv')) is-invalid @endif me-1" id="checkCGV"
<input class="form-check-input @if ($errors->has('ok_cgv')) is-invalid @endif me-1" id="check-cgv"
name="ok_cgv" type="checkbox" required />
<label class="form-check-label w-fit" for="checkCGV" role="button">
<label class="form-check-label w-fit" for="check-cgv" role="button">
J'ai lu et accepte les <a class="text-primary" href="{{ route('fo.policies.show') }}" target="_blank">
{{ __('conditions générales d\'utilisation du site Tre Galette et du Klub Tre Galette') }}</a>.
</label>

View file

@ -2,7 +2,7 @@
<div class="col col-md-10 col-lg-8 py-2">
<input class="form-control @if ($errors->has('lastname')) is-invalid @endif mx-auto" name="lastname" type="text"
value="{{ old('lastname', $crmCustomer->lastname ?? null) }}" aria-label="{{ __('Nom') }}" placeholder="{{ __('Nom') }}*"
autocomplete="given-name" required />
autocomplete="family-name" required />
@foreach ($errors->get('lastname') as $message)
<div class="invalid-feedback">{{ $message }}</div>
@endforeach
@ -13,7 +13,7 @@
<div class="col col-md-10 col-lg-8 py-2">
<input class="form-control @if ($errors->has('firstname')) is-invalid @endif mx-auto" name="firstname" type="text"
value="{{ old('firstname', $crmCustomer->firstname ?? null) }}" aria-label="{{ __('Prénom') }}"
placeholder="{{ __('Prénom') }}*" autocomplete="family-name" required />
placeholder="{{ __('Prénom') }}*" autocomplete="given-name" required />
@foreach ($errors->get('firstname') as $message)
<div class="invalid-feedback">{{ $message }}</div>
@endforeach
@ -65,20 +65,30 @@
<div class="row justify-content-center">
<div class="col col-md-10 col-lg-8 py-2">
<input class="form-control @if ($errors->has('address')) is-invalid @endif mx-auto" name="address" type="text"
value="{{ old('address', $crmCustomer->address ?? null) }}" aria-label="{{ __('Adresse') }}"
placeholder="{{ __('Adresse') }}*" autocomplete="street-address" required />
value="{{ old('address', $crmCustomer->address ?? null) }}" aria-label="{{ __('validation.attributes.line_address_1') }}"
placeholder="{{ Str::ucfirst(__('validation.attributes.line_address_1')) }}*" autocomplete="address-line1" required />
@foreach ($errors->get('address') as $message)
<div class="invalid-feedback">{{ $message }}</div>
@endforeach
</div>
</div>
<div class="row justify-content-center">
<div class="col col-md-10 col-lg-8 py-2">
<input class="form-control @if ($errors->has('address2')) is-invalid @endif mx-auto" name="address2" type="text"
value="{{ old('address2', $crmCustomer->address2 ?? null) }}" aria-label="{{ __('validation.attributes.line_address_2') }}"
placeholder="{{ Str::ucfirst(__('validation.attributes.line_address_2')) }}" autocomplete="address-line2" />
@foreach ($errors->get('address2') as $message)
<div class="invalid-feedback">{{ $message }}</div>
@endforeach
</div>
</div>
<div class="row justify-content-center">
<div class="col col-md-10 col-lg-8 py-2">
<input class="form-control @if ($errors->has('postcode')) is-invalid @endif mx-auto" name="postcode" type="text"
value="{{ old('postcode', $crmCustomer->postcode ?? null) }}" aria-label="{{ __('Code postal') }}"
<input class="form-control @if ($errors->has('postal_code')) is-invalid @endif mx-auto" name="postal_code" type="text"
value="{{ old('postal_code', $crmCustomer->postcode ?? null) }}" aria-label="{{ __('Code postal') }}"
placeholder="{{ __('Code postal') }}*" autocomplete="postal-code" required />
@foreach ($errors->get('postcode') as $message)
@foreach ($errors->get('postal_code') as $message)
<div class="invalid-feedback">{{ $message }}</div>
@endforeach
</div>
@ -95,6 +105,42 @@
</div>
</div>
<div class="row justify-content-center">
<div class="col col-md-10 col-lg-8 py-2">
@php
// * Avoir les DROM-COM + France
$franceCountries = collect(\LDC\LDCCRM\Enums\Country::getValidCountries())->filter(fn($enum) => !in_array($enum, [LDC\LDCCRM\Enums\Country::belgium(), LDC\LDCCRM\Enums\Country::luxembourg()]));
$countries = collect(\LDC\LDCCRM\Enums\Country::getValidCountries())->filter(fn($enum) => !$franceCountries->contains($enum));
$old_country = old('country', optional($crmCustomer->country ?? null)->value ?: null);
@endphp
<select id="country" name="country" aria-label="{{ Str::ucfirst(__('validation.attributes.country')) }}"
@class([
'form-select',
'mx-auto',
'is-invalid' => $errors->has('country'),
]) @readonly(!empty($readonly)) @disabled(!empty($disabled)) @required(!empty($required))>
<option @selected(!$old_country) disabled>
{{ __('Votre :attribute', [
'attribute' => __('validation.attributes.country'),
]) }}
</option>
@foreach ($franceCountries as $countryEnum)
<option value="{{ $countryEnum->value }}" @selected($old_country == $countryEnum->value)>
{{ Str::ucfirst($countryEnum->label) }}
</option>
@endforeach
@foreach ($countries as $countryEnum)
<option value="{{ $countryEnum->value }}" @selected($old_country == $countryEnum->value)>
{{ Str::ucfirst($countryEnum->label) }}
</option>
@endforeach
</select>
@foreach ($errors->get('country') as $message)
<div class="invalid-feedback">{{ $message }}</div>
@endforeach
</div>
</div>
@if (empty($displayEdit))
<div class="row justify-content-center">
<div class="col col-md-10 col-lg-8 input-group d-flex justify-content-center py-2">