File: D:/HostingSpaces/SBogers85/equichecker.com/app/KommaApp/Customers/CustomerService.php
<?php
namespace KommaApp\Customers;
use KommaApp\Customers\Customer;
use KommaApp\Site\Checkout\CheckoutSession\CheckoutSession;
use KommaApp\Site\FormValidation\UpdateCustomerForm;
use KommaApp\Orders\Models\Order;
use KommaApp\Site\FormValidation\CustomerForm;
use KommaApp\Site\FormValidation\FullCustomerForm;
use KommaApp\Site\FormValidation\LoginForm;
use KommaApp\Site\Mailers\CustomerMailer;
use TijsVerkoyen\CssToInlineStyles\Exception;
class CustomerService
{
/**
* @var FullCustomerForm
*/
private $fullCustomerForm;
/**
* @var CustomerForm
*/
private $customerForm;
/**
* @var Customer
*/
private $customer;
/**
* @var CheckoutSession
*/
private $checkoutSession;
/**
* @var LoginForm
*/
private $loginForm;
private $customerMailer;
/**
* @param Customer $customer
* @param FullCustomerForm $fullCustomerForm
* @param UpdateCustomerForm $updateCustomerForm
* @param CustomerForm $customerForm
* @param LoginForm $loginForm
* @param CheckoutSession $checkoutSession
* @param CustomerMailer $customerMailer
*/
public function __construct(
Customer $customer,
FullCustomerForm $fullCustomerForm,
UpdateCustomerForm $updateCustomerForm,
CustomerForm $customerForm,
LoginForm $loginForm,
CheckoutSession $checkoutSession,
CustomerMailer $customerMailer
)
{
$this->fullCustomerForm = $fullCustomerForm;
$this->updateCustomerForm = $updateCustomerForm;
$this->customerForm = $customerForm;
$this->customer = $customer;
$this->checkoutSession = $checkoutSession;
$this->loginForm = $loginForm;
$this->customerMailer = $customerMailer;
}
public function updateCustomer(array $input)
{
//todo: this is not the way to go, the lang should be set in the contruct
//Translate the messages
$this->updateCustomerForm->translateMessages();
//Not logged in so new customer
if (!$currentCustomer = $this->getLoggedInCustomer()) return $this->storeNewCustomer($input);
// Validate the form
if (!$this->updateCustomerForm->isValid($input))
return \Redirect::back()
->withInput()
->withErrors($this->updateCustomerForm->errorMessages());
if (!$currentCustomer = $this->getLoggedInCustomer())
throw new \Exception('Update failed: Can\'t find current user.');
// Prepare input data for update
$input['username'] = $input['email'];
if ($input['company'] == '') $input['company_vat'] = '';
$input['title'] == 'mr' ? $input['gender'] = 'male' : $input['female'] = 'male';
if ($input['password'] == '') {
unset($input['password']);
} else {
$input['password'] = \Hash::make($input['password']);
}
// Save the customer
$currentCustomer->fill($input);
$currentCustomer->save();
return \Redirect::to(\Site::getPageService()->page('customer')->route);
}
public function storeNewCustomerFromToken($orderToken, $password)
{
$order = Order::where('order_token', $orderToken)->first();
$data = [
'username' => $order->invoice_email,
'email' => $order->invoice_email,
'password' => $password,
'password_confirmation' => $password,
'gender' => $order->invoice_gender,
'title' => $order->invoice_title,
'first_name' => $order->invoice_first_name,
'last_name' => $order->invoice_last_name,
'name_insertion' => $order->invoice_name_insertion,
'company' => $order->invoice_company,
'company_vat' => $order->invoice_company_vat,
'postal' => $order->invoice_postal,
'city' => $order->invoice_city,
'street' => $order->invoice_street,
'house_number' => $order->invoice_house_number,
'house_number_suffix' => $order->invoice_house_number_suffix,
'country' => $order->invoice_country,
'order_id' => $order->id,
];
return $this->storeNewCustomer($data);
}
/**
* @param array $input
*/
public function storeNewCustomer(array $input)
{
$input['username'] = $input['email'];
if (isset($input['company_vat'])) {
$input['company_vat'] = strtoupper($input['company_vat']);
$input['company_vat'] = preg_replace("/[^a-zA-Z0-9]/", "", $input['company_vat']);
}
//todo: this is not the wat to, the lang should be set in the contruct
//Translate the messages
$this->fullCustomerForm->translateMessages();
// Validate the form
if (!$this->fullCustomerForm->isValid($input)) {
return \Redirect::back()
->withInput()
->withErrors($this->fullCustomerForm->errorMessages());
}
//TODO: Als een klant registreert, niet activeert, registreert activeert, kan hij meerdere accounts de hetzelfde email hebben
if ($currentCustomer = Customer::where('email', $input['email'])->where('site_id', \Site::getId())->first()) {
if ($this->customer->active == 1) {
return \Lang::get('customer/create.error_user_exists');
}
$this->customer = $currentCustomer;
}
$input['site_id'] = \Site::getId();
$input['password'] = \Hash::make($input['password']);
$input['title'] == 'mr' ? $input['gender'] = 'male' : $input['female'] = 'male';
do { // Ensure that validate_token is unique
$input['validate_token'] = str_random(32);
} while (!$this->customer->where('validate_token', $input['validate_token'])->get());
$input['customer_number'] = Customer::getNewCustomerNumber();
// Create Customer
if (!$this->customer
->fill($input)
->save()
) {
// Todo: With error / flash message
return \Redirect::back()
->withInput();
};
if (isset($input['order_id'])) {
$order = Order::find($input['order_id']);
$order->customer()->associate($this->customer);
$order->save();
}
try {
$this->customerMailer->sendCustomerValidation($input);
} catch (\Exception $e) {
// Todo: With error / flash message
return \Redirect::back();
}
return \View::make('customers.sendValidation', ['email' => $input['email']]);
}
/**
* Duplicate of store new customer,
* I don't want to change the flow a week befor live
* Todo: fix this and make it in one function
*
* @param $input
* @return mixed
*
*/
public function streamLinedStoreNewCustomer($input)
{
//Clean up the VAt if it is set
if (isset($input['company_vat'])) {
$input['company_vat'] = strtoupper($input['company_vat']);
$input['company_vat'] = preg_replace("/[^a-zA-Z0-9]/", "", $input['company_vat']);
}
$input['site_id'] = \Site::getId();
$input['password'] = \Hash::make($input['password']);
$input['title'] == 'mr' ? $input['gender'] = 'male' : $input['female'] = 'male';
do { // Ensure that validate_token is unique
$input['validate_token'] = str_random(32);
} while (!$this->customer->where('validate_token', $input['validate_token'])->get());
$input['customer_number'] = Customer::getNewCustomerNumber();
if (!isset($input['username'])) {
$input['username'] = $input['customer_number'];
}
// Create Customer
if (!$this->customer
->fill($input)
->save()
) {
return false;
};
return $this->customer;
}
public function activateCustomer($token)
{
if ($this->customer->where('validate_token', $token)->first() && $this->customer->where('validate_token', $token)->first()->active == 1) {
return \View::make('customers.invalidLink');
}
if (!($customer = $this->customer->where('validate_token', $token)->first())) {
return \View::make('customers.invalidLink');
}
$customer->active = 1;
$customer->validate_token = null;
$customer->save();
return \View::make('customers.activated');
}
/**
* @param $input
*/
public function store($input)
{
if (isset($input['company_vat'])) {
$input['company_vat'] = strtoupper($input['company_vat']);
$input['company_vat'] = preg_replace("/[^a-zA-Z0-9]/", "", $input['company_vat']);
}
// Validate the form
if (!$this->customerForm->isValid($input)) {
return \Redirect::back()
->withErrors($this->customerForm->errorMessages());
}
// Create data array
$data = [];
// check for unique email
if ($currentCustomer = Customer::where('email', $input['email'])->where('site_id', \Site::getId())->first()) {
if ($this->customer->active == 1) {
return \Lang::get('customer/create.error_user_exists');
}
$this->customer = $currentCustomer;
}
// Get user data from the checkoutSession
/*
foreach($this->checkoutSession->customer()->get() as $invoiceField => $value)
{
$dbKey = str_replace('invoice-','',$invoiceField);
$dbKey = str_replace('-','_',$dbKey);
$data[$dbKey] = $value;
}
*/
// Other data
$data['site_id'] = \Site::getId();
$data['username'] = $data['email'];
$data['customer_number'] = Customer::getNewCustomerNumber();
// Set password
$this->customer->password = \Hash::make($input['password']);
$this->customer->remember_token = $data['remember_token'];
// Set validation token
do { // Ensure that validate_token is unique
$input['validate_token'] = str_random(32);
} while (!$this->customer->where('validate_token', $input['validate_token'])->get());
$data['validate_token'] = $this->customer->validate_token = $input['validate_token'];
// Mass assign data and save order
if (!$this->customer
->fill($data)
->save()
) {
// Todo message
// Bevestigings mail
return \Redirect::back();
};
if (isset($input['order_id'])) {
$order = Order::find(\Input::get('order_id'));
$order->customer()->associate($this->customer);
$order->save();
}
try {
$this->customerMailer->sendCustomerValidation($input);
} catch (\Exception $e) {
// Todo: With error / flash message
return \Redirect::back();
}
return \View::make('customers.sendValidation', ['email' => $input['email']]);
}
public function isLoggedIn()
{
return \Auth::customer()->check();
}
public function authorizeLogin($input, $pageSlug = 'customer')
{
// Is the form valid
$messages = [
'email.exists' => \Lang::get('customer/login.email_exists'),
'email.activated' => \Lang::get('customer/login.email_activated'),
];
$this->loginForm->setMessages($messages);
if (!$this->loginForm->isValid($input)) {
return \Redirect::back()
->withErrors($this->loginForm->errorMessages());
}
$input['active'] = 1;
$input['site_id'] = \Site::getId();
// Does the user exists
if (!\Auth::customer()->attempt($input)) {
return \Redirect::back()
->withErrors(['wrongPassword' => \Lang::get('customer/login.wrong_password')]);
// Todo errors
}
// Redirect to checkout data
$this->checkoutSession->customer()->fillAfterLogin();
return \Redirect::to(\Site::getPageService()->page($pageSlug)->route);
}
public function getLoggedInCustomer()
{
if (!$this->isLoggedIn()) {
return null;
}
return \Auth::customer()->get();
}
public function checkEmailAddress($email)
{
$customer = $this->customer
->where('email', $email)
->where('site_id', \Site::getId())
->where('active', 1)
->first();
if ($customer == null) return false;
return true;
}
public function getReminderService()
{
return $this->reminderService;
}
public function getCustomerByEmail($email)
{
$customer = Customer::
where('email', '=', $email)
->where('site_id', '=', \Site::getId())
->where('active', '=', 1)
->first();
return $customer;
}
/**
* In this Method we will activate the account based on an order token
* We'll check if there is an customer for the order and link this
* We are going to activate this account and set token to null
*
* @param $orderToken
* @param $password
* @return array|bool
*
*/
public function LinkAccountFromOrder($orderToken, $password)
{
//Load order by Token
if (!$order = \App::make('KommaApp\Orders\OrderService')->getOrderByToken($orderToken)) {
//No order found, return with error message
}
//load customer from order
if (!$customer = $order->customer) {
//No customer found, this is normaly not possible todo: create customer from token?
return ['error' => 'Oops Something went wrong'];
}
//Set password
$customer->password = \Hash::make($password);
//Set username, use the customer email (is our default)
$customer->username = $customer->email;
//set account active
$customer->active = 1;
//Set validate_token to null
$customer->validate_token = null;
//save the customer
$customer->save();
return true;
}
}