1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-09-21 00:41:34 +02:00
invoiceninja/app/Ninja/Repositories/AccountRepository.php

711 lines
22 KiB
PHP
Raw Normal View History

2017-01-30 20:40:43 +01:00
<?php
2015-03-16 22:45:25 +01:00
2017-01-30 20:40:43 +01:00
namespace App\Ninja\Repositories;
use App\Models\Account;
2017-03-31 17:02:56 +02:00
use App\Models\AccountEmailSettings;
2015-03-31 11:38:24 +02:00
use App\Models\AccountGateway;
2017-01-30 20:40:43 +01:00
use App\Models\AccountToken;
use App\Models\Client;
use App\Models\Company;
use App\Models\Contact;
use App\Models\Credit;
2015-03-31 11:38:24 +02:00
use App\Models\Invitation;
use App\Models\Invoice;
use App\Models\InvoiceItem;
2015-04-05 21:15:37 +02:00
use App\Models\Language;
2015-03-24 08:35:20 +01:00
use App\Models\User;
2015-06-16 21:35:35 +02:00
use App\Models\UserAccount;
2017-01-30 20:40:43 +01:00
use Auth;
use Input;
use Request;
use Schema;
use Session;
use stdClass;
use URL;
use Utils;
use Validator;
2015-03-24 08:35:20 +01:00
2015-03-16 22:45:25 +01:00
class AccountRepository
{
2017-03-24 12:51:24 +01:00
public function create($firstName = '', $lastName = '', $email = '', $password = '', $company = false)
2015-03-16 22:45:25 +01:00
{
2017-03-24 12:51:24 +01:00
if (! $company) {
$company = new Company();
$company->utm_source = Input::get('utm_source');
$company->utm_medium = Input::get('utm_medium');
$company->utm_campaign = Input::get('utm_campaign');
$company->utm_term = Input::get('utm_term');
$company->utm_content = Input::get('utm_content');
$company->save();
}
2016-05-13 11:23:13 +02:00
2015-03-16 22:45:25 +01:00
$account = new Account();
$account->ip = Request::getClientIp();
2017-04-02 19:46:01 +02:00
$account->account_key = strtolower(str_random(RANDOM_KEY_LENGTH));
$account->company_id = $company->id;
2015-03-16 22:45:25 +01:00
// Track referal code
if ($referralCode = Session::get(SESSION_REFERRAL_CODE)) {
if ($user = User::whereReferralCode($referralCode)->first()) {
$account->referral_user_id = $user->id;
}
}
if ($locale = Session::get(SESSION_LOCALE)) {
2015-03-16 22:45:25 +01:00
if ($language = Language::whereLocale($locale)->first()) {
$account->language_id = $language->id;
}
}
$account->save();
$user = new User();
2017-01-30 20:40:43 +01:00
if (! $firstName && ! $lastName && ! $email && ! $password) {
2017-04-02 19:46:01 +02:00
$user->password = strtolower(str_random(RANDOM_KEY_LENGTH));
$user->username = strtolower(str_random(RANDOM_KEY_LENGTH));
2015-03-29 14:37:42 +02:00
} else {
$user->first_name = $firstName;
$user->last_name = $lastName;
$user->email = $user->username = $email;
2017-01-30 20:40:43 +01:00
if (! $password) {
2017-04-02 19:46:01 +02:00
$password = strtolower(str_random(RANDOM_KEY_LENGTH));
2015-10-11 16:41:09 +02:00
}
2015-03-29 14:37:42 +02:00
$user->password = bcrypt($password);
}
2017-01-30 20:40:43 +01:00
$user->confirmed = ! Utils::isNinja();
$user->registered = ! Utils::isNinja() || $email;
2015-03-29 14:37:42 +02:00
2017-01-30 20:40:43 +01:00
if (! $user->confirmed) {
2017-04-02 19:46:01 +02:00
$user->confirmation_code = strtolower(str_random(RANDOM_KEY_LENGTH));
2015-04-05 21:15:37 +02:00
}
2015-03-29 14:37:42 +02:00
$account->users()->save($user);
2015-03-16 22:45:25 +01:00
2017-03-31 17:02:56 +02:00
$emailSettings = new AccountEmailSettings();
$account->account_email_settings()->save($emailSettings);
2015-03-16 22:45:25 +01:00
return $account;
}
2016-05-08 20:29:49 +02:00
public function getSearchData($user)
2015-03-16 22:45:25 +01:00
{
2016-05-08 20:29:49 +02:00
$data = $this->getAccountSearchData($user);
2016-02-22 22:23:28 +01:00
2016-05-08 20:29:49 +02:00
$data['navigation'] = $user->is_admin ? $this->getNavigationSearchData() : [];
2016-02-22 22:23:28 +01:00
return $data;
}
2016-05-08 20:29:49 +02:00
private function getAccountSearchData($user)
2015-03-16 22:45:25 +01:00
{
2016-05-08 20:29:49 +02:00
$account = $user->account;
2016-05-13 11:23:13 +02:00
2016-02-25 22:33:48 +01:00
$data = [
2016-02-28 21:43:43 +01:00
'clients' => [],
'contacts' => [],
'invoices' => [],
'quotes' => [],
2016-02-25 22:33:48 +01:00
];
// include custom client fields in search
if ($account->custom_client_label1) {
$data[$account->custom_client_label1] = [];
}
if ($account->custom_client_label2) {
$data[$account->custom_client_label2] = [];
}
2016-05-13 11:23:13 +02:00
2016-05-08 20:29:49 +02:00
if ($user->hasPermission('view_all')) {
$clients = Client::scope()
->with('contacts', 'invoices')
->get();
} else {
$clients = Client::scope()
->where('user_id', '=', $user->id)
2017-01-30 17:05:31 +01:00
->with(['contacts', 'invoices' => function ($query) use ($user) {
2016-05-08 20:29:49 +02:00
$query->where('user_id', '=', $user->id);
}])->get();
}
2016-05-13 11:23:13 +02:00
2016-02-25 22:33:48 +01:00
foreach ($clients as $client) {
if ($client->name) {
2016-02-28 21:43:43 +01:00
$data['clients'][] = [
2017-02-28 19:24:30 +01:00
'value' => ($account->clientNumbersEnabled() && $client->id_number ? $client->id_number . ': ' : '') . $client->name,
'tokens' => implode(',', [$client->name, $client->id_number, $client->vat_number, $client->work_phone]),
2016-02-25 22:33:48 +01:00
'url' => $client->present()->url,
];
2016-05-13 11:23:13 +02:00
}
if ($client->custom_value1) {
$data[$account->custom_client_label1][] = [
'value' => "{$client->custom_value1}: " . $client->getDisplayName(),
'tokens' => $client->custom_value1,
2016-05-13 11:23:13 +02:00
'url' => $client->present()->url,
];
2016-05-13 11:23:13 +02:00
}
if ($client->custom_value2) {
$data[$account->custom_client_label2][] = [
'value' => "{$client->custom_value2}: " . $client->getDisplayName(),
'tokens' => $client->custom_value2,
2016-05-13 11:23:13 +02:00
'url' => $client->present()->url,
];
2015-03-16 22:45:25 +01:00
}
2016-02-25 22:33:48 +01:00
foreach ($client->contacts as $contact) {
$data['contacts'][] = [
'value' => $contact->getDisplayName(),
'tokens' => implode(',', [$contact->first_name, $contact->last_name, $contact->email, $contact->phone]),
'url' => $client->present()->url,
];
2015-03-16 22:45:25 +01:00
}
2016-02-25 22:33:48 +01:00
foreach ($client->invoices as $invoice) {
$entityType = $invoice->getEntityType();
2016-02-28 21:43:43 +01:00
$data["{$entityType}s"][] = [
2016-02-25 22:33:48 +01:00
'value' => $invoice->getDisplayName() . ': ' . $client->getDisplayName(),
'tokens' => implode(',', [$invoice->invoice_number, $invoice->po_number]),
2016-02-25 22:33:48 +01:00
'url' => $invoice->present()->url,
];
2015-03-16 22:45:25 +01:00
}
2016-02-22 22:23:28 +01:00
}
return $data;
}
2015-03-16 22:45:25 +01:00
2016-02-22 22:23:28 +01:00
private function getNavigationSearchData()
{
$entityTypes = [
ENTITY_INVOICE,
ENTITY_CLIENT,
ENTITY_QUOTE,
ENTITY_TASK,
ENTITY_EXPENSE,
2016-07-06 20:35:16 +02:00
ENTITY_EXPENSE_CATEGORY,
2016-05-05 09:28:23 +02:00
ENTITY_VENDOR,
2016-02-22 22:23:28 +01:00
ENTITY_RECURRING_INVOICE,
ENTITY_PAYMENT,
2016-11-29 18:47:26 +01:00
ENTITY_CREDIT,
ENTITY_PROJECT,
2016-02-22 22:23:28 +01:00
];
foreach ($entityTypes as $entityType) {
$features[] = [
"new_{$entityType}",
2017-01-30 20:40:43 +01:00
Utils::pluralizeEntityType($entityType) . '/create',
2016-02-22 22:23:28 +01:00
];
$features[] = [
2016-07-06 20:35:16 +02:00
'list_' . Utils::pluralizeEntityType($entityType),
2017-01-30 20:40:43 +01:00
Utils::pluralizeEntityType($entityType),
2016-02-22 22:23:28 +01:00
];
}
2016-05-05 21:31:11 +02:00
$features = array_merge($features, [
['dashboard', '/dashboard'],
2017-01-22 11:09:29 +01:00
['reports', '/reports'],
2016-05-05 21:31:11 +02:00
['customize_design', '/settings/customize_design'],
['new_tax_rate', '/tax_rates/create'],
['new_product', '/products/create'],
['new_user', '/users/create'],
['custom_fields', '/settings/invoice_settings'],
['invoice_number', '/settings/invoice_settings'],
2016-09-05 20:40:02 +02:00
['buy_now_buttons', '/settings/client_portal#buy_now'],
2016-09-05 14:28:59 +02:00
['invoice_fields', '/settings/invoice_design#invoice_fields'],
2016-05-05 21:31:11 +02:00
]);
2016-02-24 21:58:42 +01:00
2016-02-22 22:23:28 +01:00
$settings = array_merge(Account::$basicSettings, Account::$advancedSettings);
2017-01-30 17:05:31 +01:00
if (! Utils::isNinjaProd()) {
2016-05-05 09:28:23 +02:00
$settings[] = ACCOUNT_SYSTEM_SETTINGS;
}
2016-02-22 22:23:28 +01:00
foreach ($settings as $setting) {
$features[] = [
$setting,
"/settings/{$setting}",
];
}
foreach ($features as $feature) {
$data[] = [
'value' => trans('texts.' . $feature[0]),
'tokens' => trans('texts.' . $feature[0]),
2017-01-30 20:40:43 +01:00
'url' => URL::to($feature[1]),
2015-03-16 22:45:25 +01:00
];
}
return $data;
}
2016-07-14 11:46:00 +02:00
public function enablePlan($plan, $credit = 0)
2015-03-16 22:45:25 +01:00
{
2016-02-29 12:25:32 +01:00
$account = Auth::user()->account;
$client = $this->getNinjaClient($account);
2016-07-14 11:46:00 +02:00
$invitation = $this->createNinjaInvoice($client, $account, $plan, $credit);
2015-03-16 22:45:25 +01:00
return $invitation;
}
2016-07-14 21:58:48 +02:00
public function createNinjaCredit($client, $amount)
{
$account = $this->getNinjaAccount();
$lastCredit = Credit::withTrashed()->whereAccountId($account->id)->orderBy('public_id', 'DESC')->first();
$publicId = $lastCredit ? ($lastCredit->public_id + 1) : 1;
$credit = new Credit();
$credit->public_id = $publicId;
$credit->account_id = $account->id;
$credit->user_id = $account->users()->first()->id;
$credit->client_id = $client->id;
$credit->amount = $amount;
$credit->save();
return $credit;
}
2016-07-14 11:46:00 +02:00
public function createNinjaInvoice($client, $clientAccount, $plan, $credit = 0)
2015-03-16 22:45:25 +01:00
{
2016-07-11 19:08:43 +02:00
$term = $plan['term'];
$plan_cost = $plan['price'];
$num_users = $plan['num_users'];
$plan = $plan['plan'];
2016-04-17 00:34:39 +02:00
if ($credit < 0) {
$credit = 0;
}
2016-05-13 11:23:13 +02:00
2015-05-08 10:21:29 +02:00
$account = $this->getNinjaAccount();
$lastInvoice = Invoice::withTrashed()->whereAccountId($account->id)->orderBy('public_id', 'DESC')->first();
2016-12-15 11:52:10 +01:00
$renewalDate = $clientAccount->getRenewalDate();
2015-05-08 10:21:29 +02:00
$publicId = $lastInvoice ? ($lastInvoice->public_id + 1) : 1;
2016-12-15 11:52:10 +01:00
2015-03-16 22:45:25 +01:00
$invoice = new Invoice();
$invoice->is_public = true;
2015-03-16 22:45:25 +01:00
$invoice->account_id = $account->id;
$invoice->user_id = $account->users()->first()->id;
$invoice->public_id = $publicId;
$invoice->client_id = $client->id;
2017-01-04 09:11:32 +01:00
$invoice->invoice_number = $account->getNextNumber($invoice);
2016-12-15 11:52:10 +01:00
$invoice->invoice_date = $renewalDate->format('Y-m-d');
2016-04-17 00:34:39 +02:00
$invoice->amount = $invoice->balance = $plan_cost - $credit;
2016-08-25 16:32:26 +02:00
$invoice->invoice_type_id = INVOICE_TYPE_STANDARD;
2016-12-14 15:19:16 +01:00
// check for promo/discount
$clientCompany = $clientAccount->company;
2016-12-15 11:52:10 +01:00
if ($clientCompany->hasActivePromo() || $clientCompany->hasActiveDiscount($renewalDate)) {
2016-12-14 15:19:16 +01:00
$discount = $invoice->amount * $clientCompany->discount;
$invoice->discount = $clientCompany->discount * 100;
$invoice->amount -= $discount;
$invoice->balance -= $discount;
}
2015-03-16 22:45:25 +01:00
$invoice->save();
2016-04-17 00:34:39 +02:00
if ($credit) {
$credit_item = InvoiceItem::createNew($invoice);
$credit_item->qty = 1;
$credit_item->cost = -$credit;
$credit_item->notes = trans('texts.plan_credit_description');
$credit_item->product_key = trans('texts.plan_credit_product');
$invoice->invoice_items()->save($credit_item);
}
2016-05-13 11:23:13 +02:00
2016-04-17 00:34:39 +02:00
$item = InvoiceItem::createNew($invoice);
2015-03-16 22:45:25 +01:00
$item->qty = 1;
2016-04-17 00:34:39 +02:00
$item->cost = $plan_cost;
$item->notes = trans("texts.{$plan}_plan_{$term}_description");
2016-05-13 11:23:13 +02:00
2016-07-11 19:08:43 +02:00
if ($plan == PLAN_ENTERPRISE) {
$min = Utils::getMinNumUsers($num_users);
$item->notes .= "\n\n###" . trans('texts.min_to_max_users', ['min' => $min, 'max' => $num_users]);
}
2016-04-17 00:34:39 +02:00
// Don't change this without updating the regex in PaymentService->createPayment()
$item->product_key = 'Plan - '.ucfirst($plan).' ('.ucfirst($term).')';
2015-03-16 22:45:25 +01:00
$invoice->invoice_items()->save($item);
2016-05-13 11:23:13 +02:00
2015-03-16 22:45:25 +01:00
$invitation = new Invitation();
$invitation->account_id = $account->id;
$invitation->user_id = $account->users()->first()->id;
$invitation->public_id = $publicId;
$invitation->invoice_id = $invoice->id;
$invitation->contact_id = $client->contacts()->first()->id;
2017-04-02 19:46:01 +02:00
$invitation->invitation_key = strtolower(str_random(RANDOM_KEY_LENGTH));
2015-03-16 22:45:25 +01:00
$invitation->save();
return $invitation;
}
public function getNinjaAccount()
{
$account = Account::whereAccountKey(NINJA_ACCOUNT_KEY)->first();
if ($account) {
return $account;
} else {
$company = new Company();
$company->save();
2015-03-16 22:45:25 +01:00
$account = new Account();
$account->name = 'Invoice Ninja';
$account->work_email = 'contact@invoiceninja.com';
$account->work_phone = '(800) 763-1948';
$account->account_key = NINJA_ACCOUNT_KEY;
$account->company_id = $company->id;
2015-03-16 22:45:25 +01:00
$account->save();
2017-04-16 16:22:07 +02:00
$emailSettings = new AccountEmailSettings();
$account->account_email_settings()->save($emailSettings);
2015-03-16 22:45:25 +01:00
$user = new User();
$user->registered = true;
$user->confirmed = true;
2017-05-01 14:17:52 +02:00
$user->email = NINJA_ACCOUNT_EMAIL;
$user->username = NINJA_ACCOUNT_EMAIL;
$user->password = strtolower(str_random(RANDOM_KEY_LENGTH));
2015-03-16 22:45:25 +01:00
$user->first_name = 'Invoice';
$user->last_name = 'Ninja';
$user->notify_sent = true;
$user->notify_paid = true;
$account->users()->save($user);
2016-05-13 11:23:13 +02:00
if ($config = env(NINJA_GATEWAY_CONFIG)) {
$accountGateway = new AccountGateway();
$accountGateway->user_id = $user->id;
$accountGateway->gateway_id = NINJA_GATEWAY_ID;
$accountGateway->public_id = 1;
$accountGateway->setConfig(json_decode($config));
$account->account_gateways()->save($accountGateway);
}
2015-03-16 22:45:25 +01:00
}
return $account;
}
2015-05-08 10:21:29 +02:00
public function getNinjaClient($account)
2015-03-16 22:45:25 +01:00
{
2015-05-08 10:21:29 +02:00
$account->load('users');
$ninjaAccount = $this->getNinjaAccount();
2016-05-08 14:37:32 +02:00
$ninjaUser = $ninjaAccount->getPrimaryUser();
$client = Client::whereAccountId($ninjaAccount->id)
->wherePublicId($account->id)
->first();
$clientExists = $client ? true : false;
2015-03-16 22:45:25 +01:00
2017-01-30 20:40:43 +01:00
if (! $client) {
2015-03-16 22:45:25 +01:00
$client = new Client();
2015-05-08 10:21:29 +02:00
$client->public_id = $account->id;
2016-05-08 14:37:32 +02:00
$client->account_id = $ninjaAccount->id;
$client->user_id = $ninjaUser->id;
2015-03-16 22:45:25 +01:00
$client->currency_id = 1;
2016-05-08 14:37:32 +02:00
}
2016-05-13 11:23:13 +02:00
2016-05-08 14:37:32 +02:00
foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone', 'language_id', 'vat_number'] as $field) {
$client->$field = $account->$field;
}
2016-05-13 11:23:13 +02:00
2016-05-08 14:37:32 +02:00
$client->save();
2015-03-16 22:45:25 +01:00
2016-05-08 14:37:32 +02:00
if ($clientExists) {
$contact = $client->getPrimaryContact();
} else {
2015-03-16 22:45:25 +01:00
$contact = new Contact();
2016-05-08 14:37:32 +02:00
$contact->user_id = $ninjaUser->id;
2015-03-16 22:45:25 +01:00
$contact->account_id = $ninjaAccount->id;
2015-05-08 10:21:29 +02:00
$contact->public_id = $account->id;
2015-03-16 22:45:25 +01:00
$contact->is_primary = true;
}
2016-05-13 11:23:13 +02:00
2016-05-08 14:37:32 +02:00
$user = $account->getPrimaryUser();
foreach (['first_name', 'last_name', 'email', 'phone'] as $field) {
$contact->$field = $user->$field;
}
$client->contacts()->save($contact);
2015-03-16 22:45:25 +01:00
return $client;
}
2015-11-03 20:03:24 +01:00
public function findByKey($key)
{
$account = Account::whereAccountKey($key)
->with('clients.invoices.invoice_items', 'clients.contacts')
->firstOrFail();
return $account;
}
2015-10-11 16:41:09 +02:00
public function unlinkUserFromOauth($user)
{
$user->oauth_provider_id = null;
$user->oauth_user_id = null;
$user->save();
}
public function updateUserFromOauth($user, $firstName, $lastName, $email, $providerId, $oauthUserId)
{
2017-01-30 20:40:43 +01:00
if (! $user->registered) {
2015-10-11 16:41:09 +02:00
$rules = ['email' => 'email|required|unique:users,email,'.$user->id.',id'];
$validator = Validator::make(['email' => $email], $rules);
2015-10-11 16:41:09 +02:00
if ($validator->fails()) {
$messages = $validator->messages();
return $messages->first('email');
}
if (! \App\Models\LookupUser::validateEmail($email, $user)) {
return trans('texts.email_taken');
}
2015-10-11 16:41:09 +02:00
$user->email = $email;
$user->first_name = $firstName;
$user->last_name = $lastName;
$user->registered = true;
2016-04-19 16:28:27 +02:00
$user->account->startTrial(PLAN_PRO);
2015-10-11 16:41:09 +02:00
}
$user->oauth_provider_id = $providerId;
$user->oauth_user_id = $oauthUserId;
$user->save();
return true;
}
public function registerNinjaUser($user)
2015-03-16 22:45:25 +01:00
{
2015-09-25 11:57:40 +02:00
if ($user->email == TEST_USERNAME) {
return false;
}
$url = (Utils::isNinjaDev() ? SITE_URL : NINJA_APP_URL) . '/signup/register';
2015-03-16 22:45:25 +01:00
$data = '';
$fields = [
2015-05-08 10:21:29 +02:00
'first_name' => urlencode($user->first_name),
'last_name' => urlencode($user->last_name),
'email' => urlencode($user->email),
];
2015-03-16 22:45:25 +01:00
foreach ($fields as $key => $value) {
$data .= $key.'='.$value.'&';
}
rtrim($data, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
2015-09-25 11:57:40 +02:00
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2015-03-16 22:45:25 +01:00
curl_exec($ch);
curl_close($ch);
}
2015-06-16 21:35:35 +02:00
2015-10-11 16:41:09 +02:00
public function findUserByOauth($providerId, $oauthUserId)
{
return User::where('oauth_user_id', $oauthUserId)
->where('oauth_provider_id', $providerId)
->first();
}
2015-11-03 20:03:24 +01:00
public function findUsers($user, $with = null)
{
$accounts = $this->findUserAccounts($user->id);
if ($accounts) {
return $this->getUserAccounts($accounts, $with);
} else {
return [$user];
}
}
public function findUser($user, $accountKey)
{
$users = $this->findUsers($user, 'account');
foreach ($users as $user) {
if ($accountKey && hash_equals($user->account->account_key, $accountKey)) {
return $user;
}
}
return false;
}
2015-06-16 21:35:35 +02:00
public function findUserAccounts($userId1, $userId2 = false)
{
2017-01-30 20:40:43 +01:00
if (! Schema::hasTable('user_accounts')) {
2015-08-03 21:08:07 +02:00
return false;
}
2015-06-16 21:35:35 +02:00
$query = UserAccount::where('user_id1', '=', $userId1)
->orWhere('user_id2', '=', $userId1)
->orWhere('user_id3', '=', $userId1)
->orWhere('user_id4', '=', $userId1)
->orWhere('user_id5', '=', $userId1);
if ($userId2) {
$query->orWhere('user_id1', '=', $userId2)
->orWhere('user_id2', '=', $userId2)
->orWhere('user_id3', '=', $userId2)
->orWhere('user_id4', '=', $userId2)
->orWhere('user_id5', '=', $userId2);
}
return $query->first(['id', 'user_id1', 'user_id2', 'user_id3', 'user_id4', 'user_id5']);
}
2015-11-03 20:03:24 +01:00
public function getUserAccounts($record, $with = null)
{
2017-01-30 20:40:43 +01:00
if (! $record) {
2015-06-16 21:35:35 +02:00
return false;
}
$userIds = [];
2017-01-30 20:40:43 +01:00
for ($i = 1; $i <= 5; $i++) {
2015-06-16 21:35:35 +02:00
$field = "user_id$i";
if ($record->$field) {
$userIds[] = $record->$field;
}
}
$users = User::with('account')
2015-11-03 20:03:24 +01:00
->whereIn('id', $userIds);
if ($with) {
$users->with($with);
}
2016-05-13 11:23:13 +02:00
2015-11-03 20:03:24 +01:00
return $users->get();
}
public function prepareUsersData($record)
{
2017-01-30 20:40:43 +01:00
if (! $record) {
return false;
}
2015-11-03 20:03:24 +01:00
$users = $this->getUserAccounts($record);
2015-06-16 21:35:35 +02:00
$data = [];
foreach ($users as $user) {
$item = new stdClass();
$item->id = $record->id;
$item->user_id = $user->id;
$item->public_id = $user->public_id;
2015-06-16 21:35:35 +02:00
$item->user_name = $user->getDisplayName();
$item->account_id = $user->account->id;
$item->account_name = $user->account->getDisplayName();
$item->logo_url = $user->account->hasLogo() ? $user->account->getLogoUrl() : null;
2015-06-16 21:35:35 +02:00
$data[] = $item;
}
return $data;
}
2017-01-30 17:05:31 +01:00
public function loadAccounts($userId)
{
2015-06-16 21:35:35 +02:00
$record = self::findUserAccounts($userId);
2017-01-30 20:40:43 +01:00
2015-06-16 21:35:35 +02:00
return self::prepareUsersData($record);
}
2017-01-30 17:05:31 +01:00
public function associateAccounts($userId1, $userId2)
{
2015-06-16 21:35:35 +02:00
$record = self::findUserAccounts($userId1, $userId2);
if ($record) {
foreach ([$userId1, $userId2] as $userId) {
2017-01-30 20:40:43 +01:00
if (! $record->hasUserId($userId)) {
2015-06-16 21:35:35 +02:00
$record->setUserId($userId);
}
}
} else {
$record = new UserAccount();
$record->user_id1 = $userId1;
$record->user_id2 = $userId2;
}
$record->save();
2017-03-24 12:51:24 +01:00
return $this->loadAccounts($userId1);
2015-06-16 21:35:35 +02:00
}
2017-01-30 17:05:31 +01:00
public function unlinkAccount($account)
{
2015-07-07 22:08:16 +02:00
foreach ($account->users as $user) {
if ($userAccount = self::findUserAccounts($user->id)) {
$userAccount->removeUserId($user->id);
$userAccount->save();
}
}
}
2015-06-16 21:35:35 +02:00
2017-01-30 17:05:31 +01:00
public function unlinkUser($userAccountId, $userId)
{
2015-07-07 22:08:16 +02:00
$userAccount = UserAccount::whereId($userAccountId)->first();
if ($userAccount->hasUserId($userId)) {
2015-06-16 21:35:35 +02:00
$userAccount->removeUserId($userId);
$userAccount->save();
}
2016-05-13 11:23:13 +02:00
$user = User::whereId($userId)->first();
2016-05-13 11:23:13 +02:00
2017-01-30 20:40:43 +01:00
if (! $user->public_id && $user->account->hasMultipleAccounts()) {
$company = Company::create();
$company->save();
$user->account->company_id = $company->id;
$user->account->save();
}
2015-06-16 21:35:35 +02:00
}
2015-09-17 21:01:06 +02:00
public function findWithReminders()
{
return Account::whereRaw('enable_reminder1 = 1 OR enable_reminder2 = 1 OR enable_reminder3 = 1')->get();
}
2015-09-20 23:05:02 +02:00
public function getReferralCode()
{
do {
$code = strtoupper(str_random(8));
$match = User::whereReferralCode($code)
->withTrashed()
->first();
} while ($match);
2016-05-13 11:23:13 +02:00
2015-09-20 23:05:02 +02:00
return $code;
}
2015-11-01 23:10:20 +01:00
2016-07-21 14:35:23 +02:00
public function createTokens($user, $name)
2015-11-01 23:10:20 +01:00
{
2015-11-02 19:43:22 +01:00
$name = trim($name) ?: 'TOKEN';
2015-11-03 20:03:24 +01:00
$users = $this->findUsers($user);
2016-05-13 11:23:13 +02:00
2015-11-03 20:03:24 +01:00
foreach ($users as $user) {
if ($token = AccountToken::whereUserId($user->id)->whereName($name)->first()) {
continue;
}
2015-11-01 23:10:20 +01:00
2015-11-03 20:03:24 +01:00
$token = AccountToken::createNew($user);
$token->name = $name;
2017-04-02 19:46:01 +02:00
$token->token = strtolower(str_random(RANDOM_KEY_LENGTH));
2015-11-03 20:03:24 +01:00
$token->save();
}
2015-11-01 23:10:20 +01:00
}
2015-11-12 21:36:28 +01:00
2016-07-21 14:35:23 +02:00
public function getUserAccountId($account)
2015-11-12 21:36:28 +01:00
{
$user = $account->users()->first();
$userAccount = $this->findUserAccounts($user->id);
return $userAccount ? $userAccount->id : false;
}
2016-02-03 13:41:40 +01:00
2016-07-21 14:35:23 +02:00
public function save($data, $account)
2016-02-03 13:41:40 +01:00
{
$account->fill($data);
$account->save();
}
2015-03-16 22:45:25 +01:00
}