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

616 lines
19 KiB
PHP
Raw Normal View History

<?php namespace App\Ninja\Repositories;
2015-03-16 22:45:25 +01:00
use Auth;
2015-03-24 08:35:20 +01:00
use Request;
use Session;
2015-03-16 22:45:25 +01:00
use Utils;
2015-06-16 21:35:35 +02:00
use DB;
2016-02-22 22:23:28 +01:00
use URL;
2015-06-16 21:35:35 +02:00
use stdClass;
2015-10-11 16:41:09 +02:00
use Validator;
2015-08-03 21:08:07 +02:00
use Schema;
2015-03-31 11:38:24 +02:00
use App\Models\AccountGateway;
use App\Models\Invitation;
use App\Models\Invoice;
use App\Models\InvoiceItem;
2015-03-24 08:35:20 +01:00
use App\Models\Client;
2015-04-05 21:15:37 +02:00
use App\Models\Language;
2015-03-24 08:35:20 +01:00
use App\Models\Contact;
use App\Models\Account;
use App\Models\User;
2015-06-16 21:35:35 +02:00
use App\Models\UserAccount;
2015-11-01 23:10:20 +01:00
use App\Models\AccountToken;
2015-03-24 08:35:20 +01:00
2015-03-16 22:45:25 +01:00
class AccountRepository
{
2015-03-29 14:37:42 +02:00
public function create($firstName = '', $lastName = '', $email = '', $password = '')
2015-03-16 22:45:25 +01:00
{
$account = new Account();
$account->ip = Request::getClientIp();
$account->account_key = str_random(RANDOM_KEY_LENGTH);
// 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();
2015-03-29 14:37:42 +02:00
if (!$firstName && !$lastName && !$email && !$password) {
$user->password = str_random(RANDOM_KEY_LENGTH);
2015-05-09 20:25:16 +02:00
$user->username = 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;
2015-10-11 16:41:09 +02:00
if (!$password) {
$password = str_random(RANDOM_KEY_LENGTH);
}
2015-03-29 14:37:42 +02:00
$user->password = bcrypt($password);
}
2015-03-16 22:45:25 +01:00
$user->confirmed = !Utils::isNinja();
2016-03-08 22:34:59 +01:00
$user->registered = !Utils::isNinja() || $email;
2015-03-29 14:37:42 +02:00
2015-04-05 21:15:37 +02:00
if (!$user->confirmed) {
$user->confirmation_code = str_random(RANDOM_KEY_LENGTH);
}
2015-03-29 14:37:42 +02:00
$account->users()->save($user);
2015-03-16 22:45:25 +01:00
return $account;
}
public function getSearchData($account)
2015-03-16 22:45:25 +01:00
{
$data = $this->getAccountSearchData($account);
2016-02-22 22:23:28 +01:00
2016-02-28 21:43:43 +01:00
$data['navigation'] = $this->getNavigationSearchData();
2016-02-22 22:23:28 +01:00
return $data;
}
private function getAccountSearchData($account)
2015-03-16 22:45:25 +01: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-02-25 22:33:48 +01:00
$clients = Client::scope()
->with('contacts', 'invoices')
->get();
foreach ($clients as $client) {
if ($client->name) {
2016-02-28 21:43:43 +01:00
$data['clients'][] = [
2016-02-25 22:33:48 +01:00
'value' => $client->name,
'tokens' => $client->name,
2016-02-25 22:33:48 +01:00
'url' => $client->present()->url,
];
}
if ($client->custom_value1) {
$data[$account->custom_client_label1][] = [
'value' => "{$client->custom_value1}: " . $client->getDisplayName(),
'tokens' => $client->custom_value1,
'url' => $client->present()->url,
];
}
if ($client->custom_value2) {
$data[$account->custom_client_label2][] = [
'value' => "{$client->custom_value2}: " . $client->getDisplayName(),
'tokens' => $client->custom_value2,
'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) {
2016-02-28 21:43:43 +01:00
if ($contact->getFullName()) {
$data['contacts'][] = [
'value' => $contact->getDisplayName(),
'tokens' => $contact->getDisplayName(),
2016-02-28 21:43:43 +01:00
'url' => $client->present()->url,
];
}
if ($contact->email) {
$data['contacts'][] = [
2016-02-28 21:43:43 +01:00
'value' => $contact->email,
'tokens' => $contact->email,
2016-02-28 21:43:43 +01:00
'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' => $invoice->getDisplayName() . ': ' . $client->getDisplayName(),
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,
ENTITY_RECURRING_INVOICE,
ENTITY_PAYMENT,
ENTITY_CREDIT
];
foreach ($entityTypes as $entityType) {
$features[] = [
"new_{$entityType}",
"/{$entityType}s/create",
];
$features[] = [
"list_{$entityType}s",
"/{$entityType}s",
];
}
2016-02-24 21:58:42 +01:00
$features[] = ['dashboard', '/dashboard'];
$features[] = ['customize_design', '/settings/customize_design'];
$features[] = ['new_tax_rate', '/tax_rates/create'];
$features[] = ['new_product', '/products/create'];
$features[] = ['new_user', '/users/create'];
$features[] = ['custom_fields', '/settings/invoice_settings'];
2016-02-24 21:58:42 +01:00
2016-02-22 22:23:28 +01:00
$settings = array_merge(Account::$basicSettings, Account::$advancedSettings);
foreach ($settings as $setting) {
$features[] = [
$setting,
"/settings/{$setting}",
];
}
foreach ($features as $feature) {
$data[] = [
'value' => trans('texts.' . $feature[0]),
'tokens' => trans('texts.' . $feature[0]),
2016-02-22 22:23:28 +01:00
'url' => URL::to($feature[1])
2015-03-16 22:45:25 +01:00
];
}
return $data;
}
public function enableProPlan()
{
if (Auth::user()->isPro() && ! Auth::user()->isTrial()) {
2015-03-16 22:45:25 +01:00
return false;
}
2015-05-08 10:21:29 +02:00
2016-02-29 12:25:32 +01:00
$account = Auth::user()->account;
$client = $this->getNinjaClient($account);
$invitation = $this->createNinjaInvoice($client, $account);
2015-03-16 22:45:25 +01:00
return $invitation;
}
2016-02-29 12:25:32 +01:00
public function createNinjaInvoice($client, $clientAccount)
2015-03-16 22:45:25 +01:00
{
2015-05-08 10:21:29 +02:00
$account = $this->getNinjaAccount();
$lastInvoice = Invoice::withTrashed()->whereAccountId($account->id)->orderBy('public_id', 'DESC')->first();
$publicId = $lastInvoice ? ($lastInvoice->public_id + 1) : 1;
2015-03-16 22:45:25 +01:00
$invoice = new Invoice();
$invoice->account_id = $account->id;
$invoice->user_id = $account->users()->first()->id;
$invoice->public_id = $publicId;
$invoice->client_id = $client->id;
2015-10-23 13:55:18 +02:00
$invoice->invoice_number = $account->getNextInvoiceNumber($invoice);
2016-02-29 12:25:32 +01:00
$invoice->invoice_date = $clientAccount->getRenewalDate();
2015-03-16 22:45:25 +01:00
$invoice->amount = PRO_PLAN_PRICE;
$invoice->balance = PRO_PLAN_PRICE;
$invoice->save();
$item = new InvoiceItem();
$item->account_id = $account->id;
$item->user_id = $account->users()->first()->id;
$item->public_id = $publicId;
$item->qty = 1;
$item->cost = PRO_PLAN_PRICE;
$item->notes = trans('texts.pro_plan_description');
$item->product_key = trans('texts.pro_plan_product');
$invoice->invoice_items()->save($item);
$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;
$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
$invitation->save();
return $invitation;
}
public function getNinjaAccount()
{
$account = Account::whereAccountKey(NINJA_ACCOUNT_KEY)->first();
if ($account) {
return $account;
} else {
$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->save();
$random = str_random(RANDOM_KEY_LENGTH);
$user = new User();
$user->registered = true;
$user->confirmed = true;
$user->email = 'contact@invoiceninja.com';
$user->password = $random;
$user->username = $random;
$user->first_name = 'Invoice';
$user->last_name = 'Ninja';
$user->notify_sent = true;
$user->notify_paid = true;
$account->users()->save($user);
$accountGateway = new AccountGateway();
$accountGateway->user_id = $user->id;
$accountGateway->gateway_id = NINJA_GATEWAY_ID;
$accountGateway->public_id = 1;
2015-11-01 19:21:11 +01:00
$accountGateway->setConfig(json_decode(env(NINJA_GATEWAY_CONFIG)));
2015-03-16 22:45:25 +01:00
$account->account_gateways()->save($accountGateway);
}
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();
$client = Client::whereAccountId($ninjaAccount->id)->wherePublicId($account->id)->first();
2015-03-16 22:45:25 +01:00
if (!$client) {
$client = new Client();
2015-05-08 10:21:29 +02:00
$client->public_id = $account->id;
2015-03-16 22:45:25 +01:00
$client->user_id = $ninjaAccount->users()->first()->id;
$client->currency_id = 1;
foreach (['name', 'address1', 'address2', 'city', 'state', 'postal_code', 'country_id', 'work_phone', 'language_id'] as $field) {
2015-05-08 10:21:29 +02:00
$client->$field = $account->$field;
2015-03-16 22:45:25 +01:00
}
$ninjaAccount->clients()->save($client);
$contact = new Contact();
$contact->user_id = $ninjaAccount->users()->first()->id;
$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;
foreach (['first_name', 'last_name', 'email', 'phone'] as $field) {
2015-05-08 10:21:29 +02:00
$contact->$field = $account->users()->first()->$field;
2015-03-16 22:45:25 +01:00
}
$client->contacts()->save($contact);
}
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)
{
if (!$user->registered) {
$rules = ['email' => 'email|required|unique:users,email,'.$user->id.',id'];
$validator = Validator::make(['email' => $email], $rules);
if ($validator->fails()) {
$messages = $validator->messages();
return $messages->first('email');
}
$user->email = $email;
$user->first_name = $firstName;
$user->last_name = $lastName;
$user->registered = true;
$user->account->startTrial();
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];
}
}
2015-06-16 21:35:35 +02:00
public function findUserAccounts($userId1, $userId2 = false)
{
2015-08-03 21:08:07 +02:00
if (!Schema::hasTable('user_accounts')) {
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)
{
2015-06-16 21:35:35 +02:00
if (!$record) {
return false;
}
$userIds = [];
for ($i=1; $i<=5; $i++) {
$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);
}
return $users->get();
}
public function prepareUsersData($record)
{
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->user_name = $user->getDisplayName();
$item->account_id = $user->account->id;
$item->account_name = $user->account->getDisplayName();
$item->pro_plan_paid = $user->account->pro_plan_paid;
2016-01-18 15:09:06 +01:00
$item->logo_path = $user->account->hasLogo() ? $user->account->getLogoPath() : null;
2015-06-16 21:35:35 +02:00
$data[] = $item;
}
return $data;
}
public function loadAccounts($userId) {
$record = self::findUserAccounts($userId);
return self::prepareUsersData($record);
}
public function syncAccounts($userId, $proPlanPaid) {
$users = self::loadAccounts($userId);
self::syncUserAccounts($users, $proPlanPaid);
}
public function syncUserAccounts($users, $proPlanPaid = false) {
2015-08-04 13:38:48 +02:00
if (!$users) {
return;
}
2015-06-16 21:35:35 +02:00
if (!$proPlanPaid) {
foreach ($users as $user) {
if ($user->pro_plan_paid && $user->pro_plan_paid != '0000-00-00') {
$proPlanPaid = $user->pro_plan_paid;
break;
}
}
}
if (!$proPlanPaid) {
return;
}
$accountIds = [];
foreach ($users as $user) {
if ($user->pro_plan_paid != $proPlanPaid) {
$accountIds[] = $user->account_id;
}
}
if (count($accountIds)) {
DB::table('accounts')
->whereIn('id', $accountIds)
->update(['pro_plan_paid' => $proPlanPaid]);
}
}
public function associateAccounts($userId1, $userId2) {
$record = self::findUserAccounts($userId1, $userId2);
if ($record) {
foreach ([$userId1, $userId2] as $userId) {
if (!$record->hasUserId($userId)) {
$record->setUserId($userId);
}
}
} else {
$record = new UserAccount();
$record->user_id1 = $userId1;
$record->user_id2 = $userId2;
}
$record->save();
$users = self::prepareUsersData($record);
self::syncUserAccounts($users);
return $users;
}
2015-07-07 22:08:16 +02:00
public function unlinkAccount($account) {
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
2015-07-07 22:08:16 +02:00
public function unlinkUser($userAccountId, $userId) {
$userAccount = UserAccount::whereId($userAccountId)->first();
if ($userAccount->hasUserId($userId)) {
2015-06-16 21:35:35 +02:00
$userAccount->removeUserId($userId);
$userAccount->save();
}
}
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);
return $code;
}
2015-11-01 23:10:20 +01:00
2015-11-03 20:03:24 +01: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);
2015-11-02 19:43:22 +01: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;
$token->token = str_random(RANDOM_KEY_LENGTH);
$token->save();
}
2015-11-01 23:10:20 +01:00
}
2015-11-12 21:36:28 +01:00
public function getUserAccountId($account)
{
$user = $account->users()->first();
$userAccount = $this->findUserAccounts($user->id);
return $userAccount ? $userAccount->id : false;
}
2016-02-03 13:41:40 +01:00
public function save($data, $account)
{
$account->fill($data);
$account->save();
}
2015-03-16 22:45:25 +01:00
}