1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-08 12:12:48 +01:00

Refactored to events

This commit is contained in:
Hillel Coren 2015-10-28 21:22:07 +02:00
parent 5ac0cfdb99
commit 404435a145
122 changed files with 3516 additions and 1692 deletions

View File

@ -1,7 +1,6 @@
<?php namespace App\Commands; <?php namespace app\Commands;
abstract class Command { abstract class Command
{
//
} }

View File

@ -98,7 +98,7 @@ class CheckData extends Command {
$activities = DB::table('activities') $activities = DB::table('activities')
->where('client_id', '=', $client->id) ->where('client_id', '=', $client->id)
->orderBy('activities.id') ->orderBy('activities.id')
->get(['activities.id', 'activities.created_at', 'activities.activity_type_id', 'activities.message', 'activities.adjustment', 'activities.balance', 'activities.invoice_id']); ->get(['activities.id', 'activities.created_at', 'activities.activity_type_id', 'activities.adjustment', 'activities.balance', 'activities.invoice_id']);
//$this->info(var_dump($activities)); //$this->info(var_dump($activities));
foreach ($activities as $activity) { foreach ($activities as $activity) {
@ -235,7 +235,6 @@ class CheckData extends Command {
'updated_at' => new Carbon, 'updated_at' => new Carbon,
'account_id' => $client->account_id, 'account_id' => $client->account_id,
'client_id' => $client->id, 'client_id' => $client->id,
'message' => 'Corrected client balance',
'adjustment' => $client->actual_balance - $activity->balance, 'adjustment' => $client->actual_balance - $activity->balance,
'balance' => $client->actual_balance, 'balance' => $client->actual_balance,
]); ]);

View File

@ -1,88 +0,0 @@
<?php namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class CreateRandomData extends Command {
protected $name = 'ninja:create-data';
protected $description = 'Create random data';
public function fire()
{
$this->info(date('Y-m-d') . ' Running CreateRandomData...');
$user = User::first();
if (!$user) {
$this->error("Error: please create user account by logging in");
return;
}
$productNames = ['Arkansas', 'New York', 'Arizona', 'California', 'Colorado', 'Alabama', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'Alaska', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];
$clientNames = ['IBM', 'Nestle', 'Mitsubishi UFJ Financial', 'Vodafone', 'Eni', 'Procter & Gamble', 'Johnson & Johnson', 'American International Group', 'Banco Santander', 'BHP Billiton', 'Pfizer', 'Itaú Unibanco Holding', 'Ford Motor', 'BMW Group', 'Commonwealth Bank', 'EDF', 'Statoil', 'Google', 'Siemens', 'Novartis', 'Royal Bank of Canada', 'Sumitomo Mitsui Financial', 'Comcast', 'Sberbank', 'Goldman Sachs Group', 'Westpac Banking Group', 'Nippon Telegraph & Tel', 'Ping An Insurance Group', 'Banco Bradesco', 'Anheuser-Busch InBev', 'Bank of Communications', 'China Life Insurance', 'General Motors', 'Telefónica', 'MetLife', 'Honda Motor', 'Enel', 'BASF', 'Softbank', 'National Australia Bank', 'ANZ', 'ConocoPhillips', 'TD Bank Group', 'Intel', 'UBS', 'Hewlett-Packard', 'Coca-Cola', 'Cisco Systems', 'UnitedHealth Group', 'Boeing', 'Zurich Insurance Group', 'Hyundai Motor', 'Sanofi', 'Credit Agricole', 'United Technologies', 'Roche Holding', 'Munich Re', 'PepsiCo', 'Oracle', 'Bank of Nova Scotia'];
foreach ($productNames as $i => $value) {
$product = Product::createNew($user);
$product->id = $i+1;
$product->product_key = $value;
$product->save();
}
foreach ($clientNames as $i => $value) {
$client = Client::createNew($user);
$client->name = $value;
$client->save();
$contact = Contact::createNew($user);
$contact->email = "client@aol.com";
$contact->is_primary = 1;
$client->contacts()->save($contact);
$numInvoices = rand(1, 25);
if ($numInvoices == 4 || $numInvoices == 10 || $numInvoices == 25) {
// leave these
} else if ($numInvoices % 3 == 0) {
$numInvoices = 1;
} else if ($numInvoices > 10) {
$numInvoices = $numInvoices % 2;
}
$paidUp = rand(0, 1) == 1;
for ($j=1; $j<=$numInvoices; $j++) {
$price = rand(10, 1000);
if ($price < 900) {
$price = rand(10, 150);
}
$invoice = Invoice::createNew($user);
$invoice->invoice_number = $user->account->getNextInvoiceNumber($invoice);
$invoice->amount = $invoice->balance = $price;
$invoice->created_at = date('Y-m-d', strtotime(date("Y-m-d") . ' - ' . rand(1, 100) . ' days'));
$client->invoices()->save($invoice);
$productId = rand(0, 40);
if ($productId > 20) {
$productId = ($productId % 2) + rand(0, 2);
}
$invoiceItem = InvoiceItem::createNew($user);
$invoiceItem->product_id = $productId+1;
$invoiceItem->product_key = $productNames[$invoiceItem->product_id];
$invoiceItem->cost = $invoice->amount;
$invoiceItem->qty = 1;
$invoice->invoice_items()->save($invoiceItem);
if ($paidUp || rand(0,2) > 1) {
$payment = Payment::createNew($user);
$payment->invoice_id = $invoice->id;
$payment->amount = $invoice->amount;
$client->payments()->save($payment);
}
}
}
}
}

View File

@ -13,7 +13,6 @@ class Kernel extends ConsoleKernel
*/ */
protected $commands = [ protected $commands = [
'App\Console\Commands\SendRecurringInvoices', 'App\Console\Commands\SendRecurringInvoices',
'App\Console\Commands\CreateRandomData',
'App\Console\Commands\ResetData', 'App\Console\Commands\ResetData',
'App\Console\Commands\CheckData', 'App\Console\Commands\CheckData',
'App\Console\Commands\SendRenewalInvoices', 'App\Console\Commands\SendRenewalInvoices',

View File

@ -0,0 +1,21 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class ClientWasArchived extends Event
{
use SerializesModels;
public $client;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($client)
{
$this->client = $client;
}
}

View File

@ -0,0 +1,21 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class ClientWasCreated extends Event
{
use SerializesModels;
public $client;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($client)
{
$this->client = $client;
}
}

View File

@ -0,0 +1,21 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class ClientWasDeleted extends Event
{
use SerializesModels;
public $client;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($client)
{
$this->client = $client;
}
}

View File

@ -0,0 +1,21 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class ClientWasRestored extends Event
{
use SerializesModels;
public $client;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($client)
{
$this->client = $client;
}
}

View File

@ -0,0 +1,21 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class ClientWasUpdated extends Event
{
use SerializesModels;
public $client;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($client)
{
$this->client = $client;
}
}

View File

@ -0,0 +1,23 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class CreditWasArchived extends Event {
use SerializesModels;
public $credit;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($credit)
{
$this->credit = $credit;
}
}

View File

@ -0,0 +1,23 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class CreditWasCreated extends Event {
use SerializesModels;
public $credit;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($credit)
{
$this->credit = $credit;
}
}

View File

@ -0,0 +1,23 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class CreditWasDeleted extends Event {
use SerializesModels;
public $credit;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($credit)
{
$this->credit = $credit;
}
}

View File

@ -0,0 +1,23 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class CreditWasRestored extends Event {
use SerializesModels;
public $credit;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($credit)
{
$this->credit = $credit;
}
}

View File

@ -0,0 +1,25 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class InvoiceInvitationWasEmailed extends Event {
use SerializesModels;
public $invoice;
public $invitation;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($invoice, $invitation)
{
$this->invoice = $invoice;
$this->invitation = $invitation;
}
}

View File

@ -0,0 +1,25 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class InvoiceInvitationWasViewed extends Event {
use SerializesModels;
public $invoice;
public $invitation;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($invoice, $invitation)
{
$this->invoice = $invoice;
$this->invitation = $invitation;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class InvoiceWasArchived extends Event {
use SerializesModels;
public $invoice;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($invoice)
{
$this->invoice = $invoice;
}
}

View File

@ -4,10 +4,9 @@ use App\Events\Event;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
class InvoiceSent extends Event { class InvoiceWasCreated extends Event {
use SerializesModels; use SerializesModels;
public $invoice; public $invoice;
/** /**

View File

@ -4,10 +4,9 @@ use App\Events\Event;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
class InvoiceViewed extends Event { class InvoiceWasDeleted extends Event {
use SerializesModels; use SerializesModels;
public $invoice; public $invoice;
/** /**
@ -15,9 +14,9 @@ class InvoiceViewed extends Event {
* *
* @return void * @return void
*/ */
public function __construct($invoice) public function __construct($invoice)
{ {
$this->invoice = $invoice; $this->invoice = $invoice;
} }
} }

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class InvoiceWasEmailed extends Event {
use SerializesModels;
public $invoice;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($invoice)
{
$this->invoice = $invoice;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class InvoiceWasRestored extends Event {
use SerializesModels;
public $invoice;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($invoice)
{
$this->invoice = $invoice;
}
}

View File

@ -4,10 +4,9 @@ use App\Events\Event;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
class QuoteApproved extends Event { class InvoiceWasUpdated extends Event {
use SerializesModels; use SerializesModels;
public $invoice; public $invoice;
/** /**

View File

@ -4,10 +4,9 @@ use App\Events\Event;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
class InvoicePaid extends Event { class PaymentWasArchived extends Event {
use SerializesModels; use SerializesModels;
public $payment; public $payment;
/** /**

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class PaymentWasCreated extends Event {
use SerializesModels;
public $payment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($payment)
{
$this->payment = $payment;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class PaymentWasDeleted extends Event {
use SerializesModels;
public $payment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($payment)
{
$this->payment = $payment;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class PaymentWasRestored extends Event {
use SerializesModels;
public $payment;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($payment)
{
$this->payment = $payment;
}
}

View File

@ -0,0 +1,25 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteInvitationWasApproved extends Event {
use SerializesModels;
public $quote;
public $invitation;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote, $invitation)
{
$this->quote = $quote;
$this->invitation = $invitation;
}
}

View File

@ -0,0 +1,25 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteInvitationWasEmailed extends Event {
use SerializesModels;
public $quote;
public $invitation;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote, $invitation)
{
$this->quote = $quote;
$this->invitation = $invitation;
}
}

View File

@ -0,0 +1,25 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteInvitationWasViewed extends Event {
use SerializesModels;
public $quote;
public $invitation;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote, $invitation)
{
$this->quote = $quote;
$this->invitation = $invitation;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteWasArchived extends Event {
use SerializesModels;
public $quote;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote)
{
$this->quote = $quote;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteWasCreated extends Event {
use SerializesModels;
public $quote;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote)
{
$this->quote = $quote;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteWasDeleted extends Event {
use SerializesModels;
public $quote;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote)
{
$this->quote = $quote;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteWasEmailed extends Event {
use SerializesModels;
public $quote;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote)
{
$this->quote = $quote;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteWasRestored extends Event {
use SerializesModels;
public $quote;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote)
{
$this->quote = $quote;
}
}

View File

@ -0,0 +1,22 @@
<?php namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
class QuoteWasUpdated extends Event {
use SerializesModels;
public $quote;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($quote)
{
$this->quote = $quote;
}
}

View File

@ -45,6 +45,8 @@ use App\Events\UserLoggedIn;
use App\Events\UserSettingsChanged; use App\Events\UserSettingsChanged;
use App\Services\AuthService; use App\Services\AuthService;
use App\Commands\CreateClient;
class AccountController extends BaseController class AccountController extends BaseController
{ {
protected $accountRepo; protected $accountRepo;
@ -637,49 +639,56 @@ class AccountController extends BaseController
continue; continue;
} }
$client = Client::createNew(); $data = [
$contact = Contact::createNew(); 'contacts' => [[]]
$contact->is_primary = true; ];
$contact->send_invoice = true;
$count++;
foreach ($row as $index => $value) { foreach ($row as $index => $value) {
$field = $map[$index]; $field = $map[$index];
$value = trim($value); if ( ! $value = trim($value)) {
continue;
}
if ($field == Client::$fieldName && !$client->name) { if ($field == Client::$fieldName) {
$client->name = $value; $data['name'] = $value;
} elseif ($field == Client::$fieldPhone && !$client->work_phone) { } elseif ($field == Client::$fieldPhone) {
$client->work_phone = $value; $data['work_phone'] = $value;
} elseif ($field == Client::$fieldAddress1 && !$client->address1) { } elseif ($field == Client::$fieldAddress1) {
$client->address1 = $value; $data['address1'] = $value;
} elseif ($field == Client::$fieldAddress2 && !$client->address2) { } elseif ($field == Client::$fieldAddress2) {
$client->address2 = $value; $data['address2'] = $value;
} elseif ($field == Client::$fieldCity && !$client->city) { } elseif ($field == Client::$fieldCity) {
$client->city = $value; $data['city'] = $value;
} elseif ($field == Client::$fieldState && !$client->state) { } elseif ($field == Client::$fieldState) {
$client->state = $value; $data['state'] = $value;
} elseif ($field == Client::$fieldPostalCode && !$client->postal_code) { } elseif ($field == Client::$fieldPostalCode) {
$client->postal_code = $value; $data['postal_code'] = $value;
} elseif ($field == Client::$fieldCountry && !$client->country_id) { } elseif ($field == Client::$fieldCountry) {
$value = strtolower($value); $value = strtolower($value);
$client->country_id = isset($countryMap[$value]) ? $countryMap[$value] : null; $data['country_id'] = isset($countryMap[$value]) ? $countryMap[$value] : null;
} elseif ($field == Client::$fieldNotes && !$client->private_notes) { } elseif ($field == Client::$fieldNotes) {
$client->private_notes = $value; $data['private_notes'] = $value;
} elseif ($field == Contact::$fieldFirstName && !$contact->first_name) { } elseif ($field == Contact::$fieldFirstName) {
$contact->first_name = $value; $data['contacts'][0]['first_name'] = $value;
} elseif ($field == Contact::$fieldLastName && !$contact->last_name) { } elseif ($field == Contact::$fieldLastName) {
$contact->last_name = $value; $data['contacts'][0]['last_name'] = $value;
} elseif ($field == Contact::$fieldPhone && !$contact->phone) { } elseif ($field == Contact::$fieldPhone) {
$contact->phone = $value; $data['contacts'][0]['phone'] = $value;
} elseif ($field == Contact::$fieldEmail && !$contact->email) { } elseif ($field == Contact::$fieldEmail) {
$contact->email = strtolower($value); $data['contacts'][0]['email'] = strtolower($value);
} }
} }
$client->save(); $rules = [
$client->contacts()->save($contact); 'contacts' => 'valid_contacts',
Activity::createClient($client, false); ];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
continue;
}
$this->dispatch(new CreateClient($data));
$count++;
} }
$message = Utils::pluralize('created_client', $count); $message = Utils::pluralize('created_client', $count);

View File

@ -5,20 +5,46 @@ use DB;
use Datatable; use Datatable;
use Utils; use Utils;
use View; use View;
use App\Models\Client;
use App\Models\Activity;
use App\Ninja\Repositories\ActivityRepository;
class ActivityController extends BaseController class ActivityController extends BaseController
{ {
protected $activityRepo;
public function __construct(ActivityRepository $activityRepo)
{
parent::__construct();
$this->activityRepo = $activityRepo;
}
public function getDatatable($clientPublicId) public function getDatatable($clientPublicId)
{ {
$query = DB::table('activities') $clientId = Client::getPrivateId($clientPublicId);
->join('clients', 'clients.id', '=', 'activities.client_id')
->where('clients.public_id', '=', $clientPublicId) if ( ! $clientId) {
->where('activities.account_id', '=', Auth::user()->account_id) app()->abort(404);
->select('activities.id', 'activities.message', 'activities.created_at', 'clients.currency_id', 'activities.balance', 'activities.adjustment'); }
$query = $this->activityRepo->findByClientId($clientId);
return Datatable::query($query) return Datatable::query($query)
->addColumn('activities.id', function ($model) { return Utils::timestampToDateTimeString(strtotime($model->created_at)); }) ->addColumn('activities.id', function ($model) { return Utils::timestampToDateTimeString(strtotime($model->created_at)); })
->addColumn('message', function ($model) { return Utils::decodeActivity($model->message); }) ->addColumn('activity_type_id', function ($model) {
$data = [
'client' => link_to('/clients/' . $model->client_public_id, Utils::getClientDisplayName($model)),
'user' => $model->is_system ? '<i>' . trans('texts.system') . '</i>' : Utils::getPersonDisplayName($model->user_first_name, $model->user_last_name, $model->user_email),
'invoice' => $model->invoice ? link_to('/invoices/' . $model->invoice_public_id, $model->is_recurring ? trans('texts.recurring_invoice') : $model->invoice) : null,
'quote' => $model->invoice ? link_to('/quotes/' . $model->invoice_public_id, $model->invoice) : null,
'contact' => $model->contact_id ? link_to('/clients/' . $model->client_public_id, Utils::getClientDisplayName($model)) : Utils::getPersonDisplayName($model->user_first_name, $model->user_last_name, $model->user_email),
'payment' => $model->payment ?: '',
'credit' => Utils::formatMoney($model->credit, $model->currency_id)
];
return trans("texts.activity_{$model->activity_type_id}", $data);
})
->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); }) ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); })
->addColumn('adjustment', function ($model) { return $model->adjustment != 0 ? Utils::wrapAdjustment($model->adjustment, $model->currency_id) : ''; }) ->addColumn('adjustment', function ($model) { return $model->adjustment != 0 ? Utils::wrapAdjustment($model->adjustment, $model->currency_id) : ''; })
->make(); ->make();

View File

@ -1,7 +1,11 @@
<?php namespace App\Http\Controllers; <?php namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesCommands;
class BaseController extends Controller class BaseController extends Controller
{ {
use DispatchesCommands;
/** /**
* Setup the layout used by the controller. * Setup the layout used by the controller.
* *

View File

@ -5,6 +5,7 @@ use Response;
use Input; use Input;
use App\Models\Client; use App\Models\Client;
use App\Ninja\Repositories\ClientRepository; use App\Ninja\Repositories\ClientRepository;
use App\Http\Requests\CreateClientRequest;
class ClientApiController extends Controller class ClientApiController extends Controller
{ {
@ -36,23 +37,15 @@ class ClientApiController extends Controller
return Response::make($response, 200, $headers); return Response::make($response, 200, $headers);
} }
public function store() public function store(CreateClientRequest $request)
{ {
$data = Input::all(); $client = $this->clientRepo->save($request->input());
$error = $this->clientRepo->getErrors($data);
if ($error) { $client = Client::scope($client->public_id)->with('country', 'contacts', 'industry', 'size', 'currency')->first();
$headers = Utils::getApiHeaders(); $client = Utils::remapPublicIds([$client]);
$response = json_encode($client, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
return Response::make($error, 500, $headers); return Response::make($response, 200, $headers);
} else {
$client = $this->clientRepo->save(isset($data['id']) ? $data['id'] : false, $data, false);
$client = Client::scope($client->public_id)->with('country', 'contacts', 'industry', 'size', 'currency')->first();
$client = Utils::remapPublicIds([$client]);
$response = json_encode($client, JSON_PRETTY_PRINT);
$headers = Utils::getApiHeaders();
return Response::make($response, 200, $headers);
}
} }
} }

View File

@ -21,18 +21,23 @@ use App\Models\Industry;
use App\Models\Currency; use App\Models\Currency;
use App\Models\Country; use App\Models\Country;
use App\Models\Task; use App\Models\Task;
use App\Ninja\Repositories\ClientRepository; use App\Ninja\Repositories\ClientRepository;
use App\Services\ClientService;
use App\Http\Requests\CreateClientRequest;
use App\Http\Requests\UpdateClientRequest;
class ClientController extends BaseController class ClientController extends BaseController
{ {
protected $clientService;
protected $clientRepo; protected $clientRepo;
public function __construct(ClientRepository $clientRepo) public function __construct(ClientRepository $clientRepo, ClientService $clientService)
{ {
parent::__construct(); parent::__construct();
$this->clientRepo = $clientRepo; $this->clientRepo = $clientRepo;
$this->clientService = $clientService;
} }
/** /**
@ -103,9 +108,13 @@ class ClientController extends BaseController
* *
* @return Response * @return Response
*/ */
public function store() public function store(CreateClientRequest $request)
{ {
return $this->save(); $client = $this->clientService->save($request->input());
Session::flash('message', trans('texts.created_client'));
return redirect()->to($client->getRoute());
} }
/** /**
@ -194,6 +203,7 @@ class ClientController extends BaseController
private static function getViewModel() private static function getViewModel()
{ {
return [ return [
'data' => Input::old('data'),
'account' => Auth::user()->account, 'account' => Auth::user()->account,
'sizes' => Cache::get('sizes'), 'sizes' => Cache::get('sizes'),
'paymentTerms' => Cache::get('paymentTerms'), 'paymentTerms' => Cache::get('paymentTerms'),
@ -212,105 +222,20 @@ class ClientController extends BaseController
* @param int $id * @param int $id
* @return Response * @return Response
*/ */
public function update($publicId) public function update(UpdateClientRequest $request)
{ {
return $this->save($publicId); $client = $this->clientService->save($request->input());
}
Session::flash('message', trans('texts.updated_client'));
private function save($publicId = null)
{ return redirect()->to($client->getRoute());
$rules = array(
'email' => 'email|required_without:first_name',
'first_name' => 'required_without:email',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
$url = $publicId ? 'clients/'.$publicId.'/edit' : 'clients/create';
return Redirect::to($url)
->withErrors($validator)
->withInput(Input::except('password'));
} else {
if ($publicId) {
$client = Client::scope($publicId)->firstOrFail();
} else {
$client = Client::createNew();
}
$client->name = trim(Input::get('name'));
$client->id_number = trim(Input::get('id_number'));
$client->vat_number = trim(Input::get('vat_number'));
$client->work_phone = trim(Input::get('work_phone'));
$client->custom_value1 = trim(Input::get('custom_value1'));
$client->custom_value2 = trim(Input::get('custom_value2'));
$client->address1 = trim(Input::get('address1'));
$client->address2 = trim(Input::get('address2'));
$client->city = trim(Input::get('city'));
$client->state = trim(Input::get('state'));
$client->postal_code = trim(Input::get('postal_code'));
$client->country_id = Input::get('country_id') ?: null;
$client->private_notes = trim(Input::get('private_notes'));
$client->size_id = Input::get('size_id') ?: null;
$client->industry_id = Input::get('industry_id') ?: null;
$client->currency_id = Input::get('currency_id') ?: null;
$client->language_id = Input::get('language_id') ?: null;
$client->payment_terms = Input::get('payment_terms') ?: 0;
$client->website = trim(Input::get('website'));
if (Input::has('invoice_number_counter')) {
$client->invoice_number_counter = (int) Input::get('invoice_number_counter');
}
if (Input::has('quote_number_counter')) {
$client->invoice_number_counter = (int) Input::get('quote_number_counter');
}
$client->save();
$data = json_decode(Input::get('data'));
$contactIds = [];
$isPrimary = true;
foreach ($data->contacts as $contact) {
if (isset($contact->public_id) && $contact->public_id) {
$record = Contact::scope($contact->public_id)->firstOrFail();
} else {
$record = Contact::createNew();
}
$record->email = trim($contact->email);
$record->first_name = trim($contact->first_name);
$record->last_name = trim($contact->last_name);
$record->phone = trim($contact->phone);
$record->is_primary = $isPrimary;
$isPrimary = false;
$client->contacts()->save($record);
$contactIds[] = $record->public_id;
}
foreach ($client->contacts as $contact) {
if (!in_array($contact->public_id, $contactIds)) {
$contact->delete();
}
}
if ($publicId) {
Session::flash('message', trans('texts.updated_client'));
} else {
Activity::createClient($client);
Session::flash('message', trans('texts.created_client'));
}
return Redirect::to('clients/'.$client->public_id);
}
} }
public function bulk() public function bulk()
{ {
$action = Input::get('action'); $action = Input::get('action');
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $ids = Input::get('public_id') ? Input::get('public_id') : Input::get('ids');
$count = $this->clientRepo->bulk($ids, $action); $count = $this->clientService->bulk($ids, $action);
$message = Utils::pluralize($action.'d_client', $count); $message = Utils::pluralize($action.'d_client', $count);
Session::flash('message', $message); Session::flash('message', $message);

View File

@ -8,18 +8,21 @@ use Utils;
use View; use View;
use Validator; use Validator;
use App\Models\Client; use App\Models\Client;
use App\Services\CreditService;
use App\Ninja\Repositories\CreditRepository; use App\Ninja\Repositories\CreditRepository;
use App\Http\Requests\CreateCreditRequest;
class CreditController extends BaseController class CreditController extends BaseController
{ {
protected $creditRepo; protected $creditRepo;
protected $CreditService;
public function __construct(CreditRepository $creditRepo) public function __construct(CreditRepository $creditRepo, CreditService $creditService)
{ {
parent::__construct(); parent::__construct();
$this->creditRepo = $creditRepo; $this->creditRepo = $creditRepo;
$this->creditService = $creditService;
} }
/** /**
@ -106,46 +109,20 @@ class CreditController extends BaseController
return View::make('credit.edit', $data); return View::make('credit.edit', $data);
} }
public function store() public function store(CreateCreditRequest $request)
{ {
return $this->save(); $credit = $this->creditRepo->save($request->input());
}
Session::flash('message', trans('texts.created_credit'));
public function update($publicId)
{ return redirect()->to($credit->client->getRoute());
return $this->save($publicId);
}
private function save($publicId = null)
{
$rules = array(
'client' => 'required',
'amount' => 'required|positive',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
$url = $publicId ? 'credits/'.$publicId.'/edit' : 'credits/create';
return Redirect::to($url)
->withErrors($validator)
->withInput();
} else {
$this->creditRepo->save($publicId, Input::all());
$message = trans('texts.created_credit');
Session::flash('message', $message);
return Redirect::to('clients/'.Input::get('client'));
}
} }
public function bulk() public function bulk()
{ {
$action = Input::get('action'); $action = Input::get('action');
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $ids = Input::get('public_id') ? Input::get('public_id') : Input::get('ids');
$count = $this->creditRepo->bulk($ids, $action); $count = $this->creditService->bulk($ids, $action);
if ($count > 0) { if ($count > 0) {
$message = Utils::pluralize($action.'d_credit', $count); $message = Utils::pluralize($action.'d_credit', $count);

View File

@ -62,6 +62,7 @@ class DashboardController extends BaseController
->get(); ->get();
$activities = Activity::where('activities.account_id', '=', Auth::user()->account_id) $activities = Activity::where('activities.account_id', '=', Auth::user()->account_id)
->with('client.contacts', 'user', 'invoice', 'payment', 'credit')
->where('activity_type_id', '>', 0) ->where('activity_type_id', '>', 0)
->orderBy('created_at', 'desc') ->orderBy('created_at', 'desc')
->take(50) ->take(50)

View File

@ -58,7 +58,11 @@ class InvoiceApiController extends Controller
{ {
$data = Input::all(); $data = Input::all();
$error = null; $error = null;
if (isset($data['id']) || isset($data['public_id'])) {
die("We don't yet support updating invoices");
}
if (isset($data['email'])) { if (isset($data['email'])) {
$client = Client::scope()->whereHas('contacts', function($query) use ($data) { $client = Client::scope()->whereHas('contacts', function($query) use ($data) {
$query->where('email', '=', $data['email']); $query->where('email', '=', $data['email']);
@ -78,7 +82,7 @@ class InvoiceApiController extends Controller
} }
$error = $this->clientRepo->getErrors($clientData); $error = $this->clientRepo->getErrors($clientData);
if (!$error) { if (!$error) {
$client = $this->clientRepo->save(false, $clientData, false); $client = $this->clientRepo->save($clientData);
} }
} }
} else if (isset($data['client_id'])) { } else if (isset($data['client_id'])) {
@ -108,7 +112,7 @@ class InvoiceApiController extends Controller
} else { } else {
$data = self::prepareData($data, $client); $data = self::prepareData($data, $client);
$data['client_id'] = $client->id; $data['client_id'] = $client->id;
$invoice = $this->invoiceRepo->save(false, $data, false); $invoice = $this->invoiceRepo->save($data);
if (!isset($data['id'])) { if (!isset($data['id'])) {
$invitation = Invitation::createNew(); $invitation = Invitation::createNew();

View File

@ -14,7 +14,6 @@ use Datatable;
use Request; use Request;
use DropdownButton; use DropdownButton;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\Invitation;
use App\Models\Client; use App\Models\Client;
use App\Models\Account; use App\Models\Account;
use App\Models\Product; use App\Models\Product;
@ -31,21 +30,27 @@ use App\Models\Gateway;
use App\Ninja\Mailers\ContactMailer as Mailer; use App\Ninja\Mailers\ContactMailer as Mailer;
use App\Ninja\Repositories\InvoiceRepository; use App\Ninja\Repositories\InvoiceRepository;
use App\Ninja\Repositories\ClientRepository; use App\Ninja\Repositories\ClientRepository;
use App\Events\InvoiceViewed; use App\Events\InvoiceInvitationWasViewed;
use App\Events\QuoteInvitationWasViewed;
use App\Services\InvoiceService;
use App\Http\Requests\SaveInvoiceRequest;
class InvoiceController extends BaseController class InvoiceController extends BaseController
{ {
protected $mailer; protected $mailer;
protected $invoiceRepo; protected $invoiceRepo;
protected $clientRepo; protected $clientRepo;
protected $invoiceService;
public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo) public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, InvoiceService $invoiceService)
{ {
parent::__construct(); parent::__construct();
$this->mailer = $mailer; $this->mailer = $mailer;
$this->invoiceRepo = $invoiceRepo; $this->invoiceRepo = $invoiceRepo;
$this->clientRepo = $clientRepo; $this->clientRepo = $clientRepo;
$this->invoiceService = $invoiceService;
} }
public function index() public function index()
@ -147,12 +152,15 @@ class InvoiceController extends BaseController
} }
if (!Input::has('phantomjs') && !Session::has($invitationKey) && (!Auth::check() || Auth::user()->account_id != $invoice->account_id)) { if (!Input::has('phantomjs') && !Session::has($invitationKey) && (!Auth::check() || Auth::user()->account_id != $invoice->account_id)) {
Activity::viewInvoice($invitation); if ($invoice->is_quote) {
Event::fire(new InvoiceViewed($invoice)); event(new QuoteInvitationWasViewed($invoice, $invitation));
} else {
event(new InvoiceInvitationWasViewed($invoice, $invitation));
}
} }
Session::set($invitationKey, true); // track this invitation has been seen Session::put($invitationKey, true); // track this invitation has been seen
Session::set('invitation_key', $invitationKey); // track current invitation Session::put('invitation_key', $invitationKey); // track current invitation
$account->loadLocalizationSettings($client); $account->loadLocalizationSettings($client);
@ -245,7 +253,7 @@ class InvoiceController extends BaseController
->select('contacts.public_id')->lists('public_id'); ->select('contacts.public_id')->lists('public_id');
if ($clone) { if ($clone) {
$invoice->id = null; $invoice->id = $invoice->public_id = null;
$invoice->invoice_number = $account->getNextInvoiceNumber($invoice); $invoice->invoice_number = $account->getNextInvoiceNumber($invoice);
$invoice->balance = $invoice->amount; $invoice->balance = $invoice->amount;
$invoice->invoice_status_id = 0; $invoice->invoice_status_id = 0;
@ -347,13 +355,16 @@ class InvoiceController extends BaseController
public function create($clientPublicId = 0, $isRecurring = false) public function create($clientPublicId = 0, $isRecurring = false)
{ {
$account = Auth::user()->account; $account = Auth::user()->account;
$entityType = $isRecurring ? ENTITY_RECURRING_INVOICE : ENTITY_INVOICE;
$clientId = null; $clientId = null;
if ($clientPublicId) { if ($clientPublicId) {
$clientId = Client::getPrivateId($clientPublicId); $clientId = Client::getPrivateId($clientPublicId);
} }
$entityType = $isRecurring ? ENTITY_RECURRING_INVOICE : ENTITY_INVOICE;
$invoice = $account->createInvoice($entityType, $clientId);
$invoice = $account->createInvoice($entityType, $clientId);
$invoice->public_id = 0;
$data = [ $data = [
'entityType' => $invoice->getEntityType(), 'entityType' => $invoice->getEntityType(),
'invoice' => $invoice, 'invoice' => $invoice,
@ -418,50 +429,62 @@ class InvoiceController extends BaseController
* *
* @return Response * @return Response
*/ */
public function store() public function store(SaveInvoiceRequest $request)
{
return InvoiceController::save();
}
private function save($publicId = null)
{ {
$action = Input::get('action'); $action = Input::get('action');
$entityType = Input::get('entityType'); $entityType = Input::get('entityType');
$input = json_decode(Input::get('data'));
if (in_array($action, ['archive', 'delete', 'mark', 'restore'])) { $invoice = $this->invoiceService->save($request->input());
return InvoiceController::bulk($entityType); $entityType = $invoice->getEntityType();
$message = trans("texts.created_{$entityType}");
// check if we created a new client with the invoice
// TODO: replace with HistoryListener
$input = $request->input();
$clientPublicId = isset($input['client']['public_id']) ? $input['client']['public_id'] : false;
if ($clientPublicId == '-1') {
$message = $message.' '.trans('texts.and_created_client');
$trackUrl = URL::to('clients/' . $invoice->client->public_id);
Utils::trackViewed($invoice->client->getDisplayName(), ENTITY_CLIENT, $trackUrl);
} }
if ($errors = $this->invoiceRepo->getErrors($input->invoice)) { Session::flash('message', $message);
Session::flash('error', trans('texts.invoice_error'));
$url = "{$entityType}s/" . ($publicId ?: 'create');
return Redirect::to($url)->withInput()->withErrors($errors);
} else {
$invoice = $this->saveInvoice($publicId, $input, $entityType);
$url = "{$entityType}s/".$invoice->public_id.'/edit';
$message = trans($publicId ? "texts.updated_{$entityType}" : "texts.created_{$entityType}");
// check if we created a new client with the invoice if ($action == 'email') {
if ($input->invoice->client->public_id == '-1') { return $this->emailInvoice($invoice, Input::get('pdfupload'));
$message = $message.' '.trans('texts.and_created_client');
$trackUrl = URL::to('clients/'.$invoice->client->public_id);
Utils::trackViewed($invoice->client->getDisplayName(), ENTITY_CLIENT, $trackUrl);
}
if ($action == 'clone') {
return $this->cloneInvoice($publicId);
} elseif ($action == 'convert') {
return $this->convertQuote($publicId);
} elseif ($action == 'email') {
return $this->emailInvoice($invoice, Input::get('pdfupload'));
}
Session::flash('message', $message);
return Redirect::to($url);
} }
return redirect()->to($invoice->getRoute());
} }
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update(SaveInvoiceRequest $request)
{
$action = Input::get('action');
$entityType = Input::get('entityType');
$invoice = $this->invoiceService->save($request->input());
$entityType = $invoice->getEntityType();
$message = trans("texts.updated_{$entityType}");
Session::flash('message', $message);
if ($action == 'clone') {
return $this->cloneInvoice($invoice->public_id);
} elseif ($action == 'convert') {
return $this->convertQuote($invoice->public_id);
} elseif ($action == 'email') {
return $this->emailInvoice($invoice, Input::get('pdfupload'));
}
return redirect()->to($invoice->getRoute());
}
private function emailInvoice($invoice, $pdfUpload) private function emailInvoice($invoice, $pdfUpload)
{ {
$entityType = $invoice->getEntityType(); $entityType = $invoice->getEntityType();
@ -512,43 +535,6 @@ class InvoiceController extends BaseController
} }
} }
private function saveInvoice($publicId, $input, $entityType)
{
$invoice = $input->invoice;
$clientData = (array) $invoice->client;
$client = $this->clientRepo->save($invoice->client->public_id, $clientData);
$invoiceData = (array) $invoice;
$invoiceData['client_id'] = $client->id;
$invoice = $this->invoiceRepo->save($publicId, $invoiceData, $entityType);
$client->load('contacts');
$sendInvoiceIds = [];
foreach ($client->contacts as $contact) {
if ($contact->send_invoice || count($client->contacts) == 1) {
$sendInvoiceIds[] = $contact->id;
}
}
foreach ($client->contacts as $contact) {
$invitation = Invitation::scope()->whereContactId($contact->id)->whereInvoiceId($invoice->id)->first();
if (in_array($contact->id, $sendInvoiceIds) && !$invitation) {
$invitation = Invitation::createNew();
$invitation->invoice_id = $invoice->id;
$invitation->contact_id = $contact->id;
$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
$invitation->save();
} elseif (!in_array($contact->id, $sendInvoiceIds) && $invitation) {
$invitation->delete();
}
}
return $invoice;
}
/** /**
* Display the specified resource. * Display the specified resource.
* *
@ -562,17 +548,6 @@ class InvoiceController extends BaseController
return Redirect::to("invoices/{$publicId}/edit"); return Redirect::to("invoices/{$publicId}/edit");
} }
/**
* Update the specified resource in storage.
*
* @param int $id
* @return Response
*/
public function update($publicId)
{
return InvoiceController::save($publicId);
}
/** /**
* Remove the specified resource from storage. * Remove the specified resource from storage.
* *
@ -581,10 +556,10 @@ class InvoiceController extends BaseController
*/ */
public function bulk($entityType = ENTITY_INVOICE) public function bulk($entityType = ENTITY_INVOICE)
{ {
$action = Input::get('action'); $action = Input::get('bulk_action') ?: Input::get('action');;
$ids = Input::get('bulk_public_id') ?: (Input::get('public_id') ?: Input::get('ids'));
$statusId = Input::get('statusId', INVOICE_STATUS_SENT); $statusId = Input::get('statusId', INVOICE_STATUS_SENT);
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $count = $this->invoiceService->bulk($ids, $action, $statusId);
$count = $this->invoiceRepo->bulk($ids, $action, $statusId);
if ($count > 0) { if ($count > 0) {
$key = $action == 'mark' ? "updated_{$entityType}" : "{$action}d_{$entityType}"; $key = $action == 'mark' ? "updated_{$entityType}" : "{$action}d_{$entityType}";
@ -602,7 +577,7 @@ class InvoiceController extends BaseController
public function convertQuote($publicId) public function convertQuote($publicId)
{ {
$invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail(); $invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail();
$clone = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id); $clone = $this->invoiceService->approveQuote($invoice);
Session::flash('message', trans('texts.converted_to_invoice')); Session::flash('message', trans('texts.converted_to_invoice'));
return Redirect::to('invoices/'.$clone->public_id); return Redirect::to('invoices/'.$clone->public_id);
@ -610,15 +585,6 @@ class InvoiceController extends BaseController
public function cloneInvoice($publicId) public function cloneInvoice($publicId)
{ {
/*
$invoice = Invoice::with('invoice_items')->scope($publicId)->firstOrFail();
$clone = $this->invoiceRepo->cloneInvoice($invoice);
$entityType = $invoice->getEntityType();
Session::flash('message', trans('texts.cloned_invoice'));
return Redirect::to("{$entityType}s/" . $clone->public_id);
*/
return self::edit($publicId, true); return self::edit($publicId, true);
} }
@ -636,7 +602,7 @@ class InvoiceController extends BaseController
->where('activity_type_id', '=', $activityTypeId) ->where('activity_type_id', '=', $activityTypeId)
->where('invoice_id', '=', $invoice->id) ->where('invoice_id', '=', $invoice->id)
->orderBy('id', 'desc') ->orderBy('id', 'desc')
->get(['id', 'created_at', 'user_id', 'json_backup', 'message']); ->get(['id', 'created_at', 'user_id', 'json_backup']);
$versionsJson = []; $versionsJson = [];
$versionsSelect = []; $versionsSelect = [];
@ -651,7 +617,7 @@ class InvoiceController extends BaseController
$backup->account = $invoice->account->toArray(); $backup->account = $invoice->account->toArray();
$versionsJson[$activity->id] = $backup; $versionsJson[$activity->id] = $backup;
$key = Utils::timestampToDateTimeString(strtotime($activity->created_at)) . ' - ' . Utils::decodeActivity($activity->message); $key = Utils::timestampToDateTimeString(strtotime($activity->created_at)) . ' - ' . $activity->user->getDisplayName();
$versionsSelect[$lastId ? $lastId : 0] = $key; $versionsSelect[$lastId ? $lastId : 0] = $key;
$lastId = $activity->id; $lastId = $activity->id;
} }

View File

@ -60,7 +60,7 @@ class PaymentApiController extends Controller
} }
if (!$error) { if (!$error) {
$payment = $this->paymentRepo->save(false, $data); $payment = $this->paymentRepo->save($data);
$payment = Payment::scope($payment->public_id)->with('client', 'contact', 'user', 'invoice')->first(); $payment = Payment::scope($payment->public_id)->with('client', 'contact', 'user', 'invoice')->first();
$payment = Utils::remapPublicIds([$payment]); $payment = Utils::remapPublicIds([$payment]);

View File

@ -25,6 +25,9 @@ use App\Ninja\Repositories\AccountRepository;
use App\Ninja\Mailers\ContactMailer; use App\Ninja\Mailers\ContactMailer;
use App\Services\PaymentService; use App\Services\PaymentService;
use App\Http\Requests\CreatePaymentRequest;
use App\Http\Requests\UpdatePaymentRequest;
class PaymentController extends BaseController class PaymentController extends BaseController
{ {
public function __construct(PaymentRepository $paymentRepo, InvoiceRepository $invoiceRepo, AccountRepository $accountRepo, ContactMailer $contactMailer, PaymentService $paymentService) public function __construct(PaymentRepository $paymentRepo, InvoiceRepository $invoiceRepo, AccountRepository $accountRepo, ContactMailer $contactMailer, PaymentService $paymentService)
@ -540,49 +543,36 @@ class PaymentController extends BaseController
} }
} }
public function store() public function store(CreatePaymentRequest $request)
{ {
return $this->save(); $input = $request->input();
} $payment = $this->paymentRepo->save($input);
public function update($publicId) if (Input::get('email_receipt')) {
{ $this->contactMailer->sendPaymentConfirmation($payment);
return $this->save($publicId); Session::flash('message', trans('texts.created_payment_emailed_client'));
}
private function save($publicId = null)
{
if (!$publicId && $errors = $this->paymentRepo->getErrors(Input::all())) {
$url = $publicId ? 'payments/'.$publicId.'/edit' : 'payments/create';
return Redirect::to($url)
->withErrors($errors)
->withInput();
} else { } else {
$payment = $this->paymentRepo->save($publicId, Input::all()); Session::flash('message', trans('texts.created_payment'));
if ($publicId) {
Session::flash('message', trans('texts.updated_payment'));
return Redirect::to('payments/');
} else {
if (Input::get('email_receipt')) {
$this->contactMailer->sendPaymentConfirmation($payment);
Session::flash('message', trans('texts.created_payment_emailed_client'));
} else {
Session::flash('message', trans('texts.created_payment'));
}
return Redirect::to('clients/'.Input::get('client'));
}
} }
return redirect()->to($payment->client->getRoute());
}
public function update(UpdatePaymentRequest $request)
{
$input = $request->input();
$payment = $this->paymentRepo->save($input);
Session::flash('message', trans('texts.updated_payment'));
return redirect()->to($payment->getRoute());
} }
public function bulk() public function bulk()
{ {
$action = Input::get('action'); $action = Input::get('action');
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $ids = Input::get('public_id') ? Input::get('public_id') : Input::get('ids');
$count = $this->paymentRepo->bulk($ids, $action); $count = $this->paymentService->bulk($ids, $action);
if ($count > 0) { if ($count > 0) {
$message = Utils::pluralize($action.'d_payment', $count); $message = Utils::pluralize($action.'d_payment', $count);

View File

@ -8,16 +8,18 @@ use Datatable;
use App\Models\Invitation; use App\Models\Invitation;
use App\Ninja\Repositories\InvoiceRepository; use App\Ninja\Repositories\InvoiceRepository;
use App\Ninja\Repositories\PaymentRepository; use App\Ninja\Repositories\PaymentRepository;
use App\Ninja\Repositories\ActivityRepository;
class PublicClientController extends BaseController class PublicClientController extends BaseController
{ {
private $invoiceRepo; private $invoiceRepo;
private $paymentRepo; private $paymentRepo;
public function __construct(InvoiceRepository $invoiceRepo, PaymentRepository $paymentRepo) public function __construct(InvoiceRepository $invoiceRepo, PaymentRepository $paymentRepo, ActivityRepository $activityRepo)
{ {
$this->invoiceRepo = $invoiceRepo; $this->invoiceRepo = $invoiceRepo;
$this->paymentRepo = $paymentRepo; $this->paymentRepo = $paymentRepo;
$this->activityRepo = $activityRepo;
} }
public function dashboard() public function dashboard()
@ -47,15 +49,22 @@ class PublicClientController extends BaseController
} }
$invoice = $invitation->invoice; $invoice = $invitation->invoice;
$query = DB::table('activities') $query = $this->activityRepo->findByClientId($invoice->client_id);
->join('clients', 'clients.id', '=', 'activities.client_id') $query->where('activities.adjustment', '!=', 0);
->where('activities.client_id', '=', $invoice->client_id)
->where('activities.adjustment', '!=', 0)
->select('activities.id', 'activities.message', 'activities.created_at', 'clients.currency_id', 'activities.balance', 'activities.adjustment');
return Datatable::query($query) return Datatable::query($query)
->addColumn('activities.id', function ($model) { return Utils::timestampToDateTimeString(strtotime($model->created_at)); }) ->addColumn('activities.id', function ($model) { return Utils::timestampToDateTimeString(strtotime($model->created_at)); })
->addColumn('message', function ($model) { return strip_tags(Utils::decodeActivity($model->message)); }) ->addColumn('message', function ($model) {
$data = [
'client' => Utils::getClientDisplayName($model),
'user' => $model->is_system ? ('<i>' . trans('texts.system') . '</i>') : ($model->user_first_name . ' ' . $model->user_last_name),
'invoice' => trans('texts.invoice') . ' ' . $model->invoice,
'contact' => Utils::getClientDisplayName($model),
'payment' => trans('texts.payment') . ($model->payment ? ' ' . $model->payment : ''),
];
return trans("texts.activity_{$model->activity_type_id}", $data);
})
->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); }) ->addColumn('balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id); })
->addColumn('adjustment', function ($model) { return $model->adjustment != 0 ? Utils::wrapAdjustment($model->adjustment, $model->currency_id) : ''; }) ->addColumn('adjustment', function ($model) { return $model->adjustment != 0 ? Utils::wrapAdjustment($model->adjustment, $model->currency_id) : ''; })
->make(); ->make();

View File

@ -24,24 +24,24 @@ use App\Models\Invoice;
use App\Ninja\Mailers\ContactMailer as Mailer; use App\Ninja\Mailers\ContactMailer as Mailer;
use App\Ninja\Repositories\InvoiceRepository; use App\Ninja\Repositories\InvoiceRepository;
use App\Ninja\Repositories\ClientRepository; use App\Ninja\Repositories\ClientRepository;
use App\Ninja\Repositories\TaxRateRepository; use App\Events\QuoteInvitationWasApproved;
use App\Events\QuoteApproved; use App\Services\InvoiceService;
class QuoteController extends BaseController class QuoteController extends BaseController
{ {
protected $mailer; protected $mailer;
protected $invoiceRepo; protected $invoiceRepo;
protected $clientRepo; protected $clientRepo;
protected $taxRateRepo; protected $invoiceService;
public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, TaxRateRepository $taxRateRepo) public function __construct(Mailer $mailer, InvoiceRepository $invoiceRepo, ClientRepository $clientRepo, InvoiceService $invoiceService)
{ {
parent::__construct(); parent::__construct();
$this->mailer = $mailer; $this->mailer = $mailer;
$this->invoiceRepo = $invoiceRepo; $this->invoiceRepo = $invoiceRepo;
$this->clientRepo = $clientRepo; $this->clientRepo = $clientRepo;
$this->taxRateRepo = $taxRateRepo; $this->invoiceService = $invoiceService;
} }
public function index() public function index()
@ -87,7 +87,8 @@ class QuoteController extends BaseController
$clientId = Client::getPrivateId($clientPublicId); $clientId = Client::getPrivateId($clientPublicId);
} }
$invoice = $account->createInvoice(ENTITY_QUOTE, $clientId); $invoice = $account->createInvoice(ENTITY_QUOTE, $clientId);
$invoice->public_id = 0;
$data = [ $data = [
'entityType' => $invoice->getEntityType(), 'entityType' => $invoice->getEntityType(),
'invoice' => $invoice, 'invoice' => $invoice,
@ -123,19 +124,19 @@ class QuoteController extends BaseController
public function bulk() public function bulk()
{ {
$action = Input::get('action'); $action = Input::get('bulk_action') ?: Input::get('action');;
if ($action == 'convert') { if ($action == 'convert') {
$invoice = Invoice::with('invoice_items')->scope(Input::get('id'))->firstOrFail(); $invoice = Invoice::with('invoice_items')->scope(Input::get('id'))->firstOrFail();
$clone = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id); $clone = $this->invoiceService->approveQuote($invoice);
Session::flash('message', trans('texts.converted_to_invoice')); Session::flash('message', trans('texts.converted_to_invoice'));
return Redirect::to('invoices/'.$clone->public_id); return Redirect::to('invoices/'.$clone->public_id);
} }
$statusId = Input::get('statusId'); $statusId = Input::get('statusId');
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $ids = Input::get('bulk_public_id') ?: (Input::get('public_id') ?: Input::get('ids'));
$count = $this->invoiceRepo->bulk($ids, $action, $statusId); $count = $this->invoiceService->bulk($ids, $action, $statusId);
if ($count > 0) { if ($count > 0) {
$key = $action == 'mark' ? "updated_quote" : "{$action}d_quote"; $key = $action == 'mark' ? "updated_quote" : "{$action}d_quote";
@ -155,19 +156,8 @@ class QuoteController extends BaseController
$invitation = Invitation::with('invoice.invoice_items', 'invoice.invitations')->where('invitation_key', '=', $invitationKey)->firstOrFail(); $invitation = Invitation::with('invoice.invoice_items', 'invoice.invitations')->where('invitation_key', '=', $invitationKey)->firstOrFail();
$invoice = $invitation->invoice; $invoice = $invitation->invoice;
if ($invoice->is_quote && !$invoice->quote_invoice_id) { $invitationKey = $this->invoiceService->approveQuote($invoice, $invitation);
Event::fire(new QuoteApproved($invoice)); Session::flash('message', trans('texts.converted_to_invoice'));
Activity::approveQuote($invitation);
$invoice = $this->invoiceRepo->cloneInvoice($invoice, $invoice->id);
Session::flash('message', trans('texts.converted_to_invoice'));
foreach ($invoice->invitations as $invitationClone) {
if ($invitation->contact_id == $invitationClone->contact_id) {
$invitationKey = $invitationClone->invitation_key;
}
}
}
return Redirect::to("view/{$invitationKey}"); return Redirect::to("view/{$invitationKey}");
} }

View File

@ -156,7 +156,7 @@ class TaskController extends BaseController
*/ */
public function edit($publicId) public function edit($publicId)
{ {
$task = Task::scope($publicId)->with('client', 'invoice')->firstOrFail(); $task = Task::scope($publicId)->with('client', 'invoice')->withTrashed()->firstOrFail();
$actions = []; $actions = [];
if ($task->invoice) { if ($task->invoice) {
@ -240,7 +240,7 @@ class TaskController extends BaseController
public function bulk() public function bulk()
{ {
$action = Input::get('action'); $action = Input::get('action');
$ids = Input::get('id') ? Input::get('id') : Input::get('ids'); $ids = Input::get('public_id') ?: (Input::get('id') ?: Input::get('ids'));
if ($action == 'stop') { if ($action == 'stop') {
$this->taskRepo->save($ids, ['action' => $action]); $this->taskRepo->save($ids, ['action' => $action]);

View File

@ -0,0 +1,44 @@
<?php namespace app\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Factory;
class CreateClientRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'contacts' => 'valid_contacts',
];
}
public function validator($factory)
{
// support submiting the form with a single client record
$input = $this->input();
if (isset($input['contact'])) {
$input['contacts'] = [$input['contact']];
unset($input['contact']);
$this->replace($input);
}
return $factory->make(
$this->input(), $this->container->call([$this, 'rules']), $this->messages()
);
}
}

View File

@ -0,0 +1,30 @@
<?php namespace app\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Factory;
class CreateCreditRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'client' => 'required',
'amount' => 'required|positive',
];
}
}

View File

@ -0,0 +1,44 @@
<?php namespace app\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Factory;
use App\Models\Invoice;
class CreatePaymentRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$input = $this->input();
$rules = array(
'client' => 'required',
'invoice' => 'required',
'amount' => 'required',
);
if ($input['payment_type_id'] == PAYMENT_TYPE_CREDIT) {
$rules['payment_type_id'] = 'has_credit:'.$input['client'].','.$input['amount'];
}
if (isset($input['invoice']) && $input['invoice']) {
$invoice = Invoice::scope($input['invoice'])->firstOrFail();
$rules['amount'] .= "|less_than:{$invoice->balance}";
}
return $rules;
}
}

View File

@ -0,0 +1,44 @@
<?php namespace app\Http\Requests;
use Auth;
use App\Http\Requests\Request;
use Illuminate\Validation\Factory;
use App\Models\Invoice;
class SaveInvoiceRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$publicId = Request::get('public_id');
$invoiceId = $publicId ? Invoice::getPrivateId($publicId) : '';
$rules = [
'client.contacts' => 'valid_contacts',
'invoice_number' => 'required|unique:invoices,invoice_number,'.$invoiceId.',id,account_id,'.Auth::user()->account_id,
'discount' => 'positive',
];
/* There's a problem parsing the dates
if (Request::get('is_recurring') && Request::get('start_date') && Request::get('end_date')) {
$rules['end_date'] = 'after' . Request::get('start_date');
}
*/
return $rules;
}
}

View File

@ -0,0 +1,29 @@
<?php namespace app\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Factory;
class UpdateClientRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'contacts' => 'valid_contacts',
];
}
}

View File

@ -0,0 +1,28 @@
<?php namespace app\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Factory;
use App\Models\Invoice;
class UpdatePaymentRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [];
}
}

View File

@ -274,6 +274,9 @@ if (!defined('CONTACT_EMAIL')) {
define('ACCOUNT_API_TOKENS', 'api_tokens'); define('ACCOUNT_API_TOKENS', 'api_tokens');
define('ACCOUNT_CUSTOMIZE_DESIGN', 'customize_design'); define('ACCOUNT_CUSTOMIZE_DESIGN', 'customize_design');
define('ACTION_RESTORE', 'restore');
define('ACTION_ARCHIVE', 'archive');
define('ACTION_DELETE', 'delete');
define('ACTIVITY_TYPE_CREATE_CLIENT', 1); define('ACTIVITY_TYPE_CREATE_CLIENT', 1);
define('ACTIVITY_TYPE_ARCHIVE_CLIENT', 2); define('ACTIVITY_TYPE_ARCHIVE_CLIENT', 2);
@ -287,12 +290,12 @@ if (!defined('CONTACT_EMAIL')) {
define('ACTIVITY_TYPE_DELETE_INVOICE', 9); define('ACTIVITY_TYPE_DELETE_INVOICE', 9);
define('ACTIVITY_TYPE_CREATE_PAYMENT', 10); define('ACTIVITY_TYPE_CREATE_PAYMENT', 10);
define('ACTIVITY_TYPE_UPDATE_PAYMENT', 11); //define('ACTIVITY_TYPE_UPDATE_PAYMENT', 11);
define('ACTIVITY_TYPE_ARCHIVE_PAYMENT', 12); define('ACTIVITY_TYPE_ARCHIVE_PAYMENT', 12);
define('ACTIVITY_TYPE_DELETE_PAYMENT', 13); define('ACTIVITY_TYPE_DELETE_PAYMENT', 13);
define('ACTIVITY_TYPE_CREATE_CREDIT', 14); define('ACTIVITY_TYPE_CREATE_CREDIT', 14);
define('ACTIVITY_TYPE_UPDATE_CREDIT', 15); //define('ACTIVITY_TYPE_UPDATE_CREDIT', 15);
define('ACTIVITY_TYPE_ARCHIVE_CREDIT', 16); define('ACTIVITY_TYPE_ARCHIVE_CREDIT', 16);
define('ACTIVITY_TYPE_DELETE_CREDIT', 17); define('ACTIVITY_TYPE_DELETE_CREDIT', 17);

View File

@ -496,32 +496,15 @@ class Utils
} }
} }
public static function encodeActivity($person = null, $action, $entity = null, $otherPerson = null) public static function getPersonDisplayName($firstName, $lastName, $email)
{ {
$person = $person ? $person->getDisplayName() : '<i>System</i>'; if ($firstName || $lastName) {
$entity = $entity ? $entity->getActivityKey() : ''; return $firstName.' '.$lastName;
$otherPerson = $otherPerson ? 'to '.$otherPerson->getDisplayName() : ''; } elseif ($email) {
$token = Session::get('token_id') ? ' ('.trans('texts.token').')' : ''; return $email;
} else {
return trim("$person $token $action $entity $otherPerson"); return trans('texts.guest');
}
public static function decodeActivity($message)
{
$pattern = '/\[([\w]*):([\d]*):(.*)\]/i';
preg_match($pattern, $message, $matches);
if (count($matches) > 0) {
$match = $matches[0];
$type = $matches[1];
$publicId = $matches[2];
$name = $matches[3];
$link = link_to($type.'s/'.$publicId, $name);
$message = str_replace($match, "$type $link", $message);
} }
return $message;
} }
public static function generateLicense() public static function generateLicense()
@ -598,7 +581,7 @@ class Utils
foreach ($data as $key => $val) { foreach ($data as $key => $val) {
if (is_array($val)) { if (is_array($val)) {
if ($key == 'account' || isset($mapped[$key])) { if ($key == 'account' || isset($mapped[$key])) {
unset($data[$key]); // do nothing
} else { } else {
$mapped[$key] = true; $mapped[$key] = true;
$data[$key] = Utils::hideIds($val, $mapped); $data[$key] = Utils::hideIds($val, $mapped);
@ -795,4 +778,30 @@ class Utils
$adjustment = Utils::formatMoney($adjustment, $currencyId); $adjustment = Utils::formatMoney($adjustment, $currencyId);
return "<h4><div class=\"label label-{$class}\">$adjustment</div></h4>"; return "<h4><div class=\"label label-{$class}\">$adjustment</div></h4>";
} }
public static function copyContext($entity1, $entity2)
{
if (!$entity2) {
return $entity1;
}
$fields = [
'contact_id',
'payment_id',
'invoice_id',
'credit_id',
'invitation_id'
];
$fields1 = $entity1->getAttributes();
$fields2 = $entity2->getAttributes();
foreach ($fields as $field) {
if (isset($fields2[$field]) && $fields2[$field]) {
$entity1->$field = $entity2->$field;
}
}
return $entity1;
}
} }

View File

@ -0,0 +1,337 @@
<?php namespace app\Listeners;
use Auth;
use Utils;
use App\Models\Invoice;
use App\Events\ClientWasCreated;
use App\Events\ClientWasDeleted;
use App\Events\ClientWasArchived;
use App\Events\ClientWasRestored;
use App\Events\InvoiceWasCreated;
use App\Events\InvoiceWasUpdated;
use App\Events\InvoiceWasDeleted;
use App\Events\InvoiceWasArchived;
use App\Events\InvoiceWasRestored;
use App\Events\InvoiceInvitationWasEmailed;
use App\Events\InvoiceInvitationWasViewed;
use App\Events\QuoteWasCreated;
use App\Events\QuoteWasUpdated;
use App\Events\QuoteWasDeleted;
use App\Events\QuoteWasArchived;
use App\Events\QuoteWasRestored;
use App\Events\QuoteInvitationWasEmailed;
use App\Events\QuoteInvitationWasViewed;
use App\Events\QuoteInvitationWasApproved;
use App\Events\PaymentWasCreated;
use App\Events\PaymentWasDeleted;
use App\Events\PaymentWasArchived;
use App\Events\PaymentWasRestored;
use App\Events\CreditWasCreated;
use App\Events\CreditWasDeleted;
use App\Events\CreditWasArchived;
use App\Events\CreditWasRestored;
use App\Ninja\Repositories\ActivityRepository;
class ActivityListener
{
protected $activityRepo;
public function __construct(ActivityRepository $activityRepo)
{
$this->activityRepo = $activityRepo;
}
// Clients
public function createdClient(ClientWasCreated $event)
{
$this->activityRepo->create(
$event->client,
ACTIVITY_TYPE_CREATE_CLIENT
);
}
public function deletedClient(ClientWasDeleted $event)
{
$this->activityRepo->create(
$event->client,
ACTIVITY_TYPE_DELETE_CLIENT
);
}
public function archivedClient(ClientWasArchived $event)
{
if ($event->client->is_deleted) {
return;
}
$this->activityRepo->create(
$event->client,
ACTIVITY_TYPE_ARCHIVE_CLIENT
);
}
public function restoredClient(ClientWasRestored $event)
{
$this->activityRepo->create(
$event->client,
ACTIVITY_TYPE_RESTORE_CLIENT
);
}
// Invoices
public function createdInvoice(InvoiceWasCreated $event)
{
$this->activityRepo->create(
$event->invoice,
ACTIVITY_TYPE_CREATE_INVOICE,
$event->invoice->getAdjustment()
);
}
public function updatedInvoice(InvoiceWasUpdated $event)
{
if ( ! $event->invoice->isChanged()) {
return;
}
$backupInvoice = Invoice::with('invoice_items', 'client.account', 'client.contacts')->find($event->invoice->id);
$activity = $this->activityRepo->create(
$event->invoice,
ACTIVITY_TYPE_UPDATE_INVOICE,
$event->invoice->getAdjustment()
);
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
$activity->save();
}
public function deletedInvoice(InvoiceWasDeleted $event)
{
$this->activityRepo->create(
$event->invoice,
ACTIVITY_TYPE_DELETE_INVOICE,
$event->invoice->balance * -1,
$event->invoice->getAmountPaid() * -1
);
}
public function archivedInvoice(InvoiceWasArchived $event)
{
if ($event->invoice->is_deleted) {
return;
}
$this->activityRepo->create(
$event->invoice,
ACTIVITY_TYPE_ARCHIVE_INVOICE
);
}
public function restoredInvoice(InvoiceWasRestored $event)
{
$this->activityRepo->create(
$event->invoice,
ACTIVITY_TYPE_RESTORE_INVOICE
);
}
public function emailedInvoice(InvoiceInvitationWasEmailed $event)
{
$this->activityRepo->create(
$event->invoice,
ACTIVITY_TYPE_EMAIL_INVOICE,
false,
false,
$event->invitation
);
}
public function viewedInvoice(InvoiceInvitationWasViewed $event)
{
$this->activityRepo->create(
$event->invoice,
ACTIVITY_TYPE_VIEW_INVOICE,
false,
false,
$event->invitation
);
}
// Quotes
public function createdQuote(QuoteWasCreated $event)
{
$this->activityRepo->create(
$event->quote,
ACTIVITY_TYPE_CREATE_QUOTE
);
}
public function updatedQuote(QuoteWasUpdated $event)
{
if ( ! $event->quote->isChanged()) {
return;
}
$backupQuote = Invoice::with('invoice_items', 'client.account', 'client.contacts')->find($event->quote->id);
$activity = $this->activityRepo->create(
$event->quote,
ACTIVITY_TYPE_UPDATE_QUOTE,
$event->quote->getAdjustment()
);
$activity->json_backup = $backupQuote->hidePrivateFields()->toJSON();
$activity->save();
}
public function deletedQuote(QuoteWasDeleted $event)
{
$this->activityRepo->create(
$event->quote,
ACTIVITY_TYPE_DELETE_QUOTE
);
}
public function archivedQuote(QuoteWasArchived $event)
{
if ($event->quote->is_deleted) {
return;
}
$this->activityRepo->create(
$event->quote,
ACTIVITY_TYPE_ARCHIVE_QUOTE
);
}
public function restoredQuote(QuoteWasRestored $event)
{
$this->activityRepo->create(
$event->quote,
ACTIVITY_TYPE_RESTORE_QUOTE
);
}
public function emailedQuote(QuoteInvitationWasEmailed $event)
{
$this->activityRepo->create(
$event->quote,
ACTIVITY_TYPE_EMAIL_QUOTE,
false,
false,
$event->invitation
);
}
public function viewedQuote(QuoteInvitationWasViewed $event)
{
$this->activityRepo->create(
$event->quote,
ACTIVITY_TYPE_VIEW_QUOTE,
false,
false,
$event->invitation
);
}
public function approvedQuote(QuoteInvitationWasApproved $event)
{
$this->activityRepo->create(
$event->quote,
ACTIVITY_TYPE_APPROVE_QUOTE,
false,
false,
$event->invitation
);
}
// Credits
public function createdCredit(CreditWasCreated $event)
{
$this->activityRepo->create(
$event->credit,
ACTIVITY_TYPE_CREATE_CREDIT
);
}
public function deletedCredit(CreditWasDeleted $event)
{
$this->activityRepo->create(
$event->credit,
ACTIVITY_TYPE_DELETE_CREDIT
);
}
public function archivedCredit(CreditWasArchived $event)
{
if ($event->credit->is_deleted) {
return;
}
$this->activityRepo->create(
$event->credit,
ACTIVITY_TYPE_ARCHIVE_CREDIT
);
}
public function restoredCredit(CreditWasRestored $event)
{
$this->activityRepo->create(
$event->credit,
ACTIVITY_TYPE_RESTORE_CREDIT
);
}
// Payments
public function createdPayment(PaymentWasCreated $event)
{
$this->activityRepo->create(
$event->payment,
ACTIVITY_TYPE_CREATE_PAYMENT,
$event->payment->amount * -1,
$event->payment->amount
);
}
public function deletedPayment(PaymentWasDeleted $event)
{
$this->activityRepo->create(
$event->payment,
ACTIVITY_TYPE_DELETE_PAYMENT,
$event->payment->amount,
$event->payment->amount * -1
);
}
public function archivedPayment(PaymentWasArchived $event)
{
if ($event->payment->is_deleted) {
return;
}
$this->activityRepo->create(
$event->payment,
ACTIVITY_TYPE_ARCHIVE_PAYMENT
);
}
public function restoredPayment(PaymentWasRestored $event)
{
$this->activityRepo->create(
$event->payment,
ACTIVITY_TYPE_RESTORE_PAYMENT
);
}
}

View File

@ -0,0 +1,33 @@
<?php namespace app\Listeners;
use Carbon;
use App\Models\Credit;
use App\Events\PaymentWasDeleted;
use App\Ninja\Repositories\CreditRepository;
class CreditListener
{
protected $creditRepo;
public function __construct(CreditRepository $creditRepo)
{
$this->creditRepo = $creditRepo;
}
public function deletedPayment(PaymentWasDeleted $event)
{
$payment = $event->payment;
// if the payment was from a credit we need to refund the credit
if ($payment->payment_type_id != PAYMENT_TYPE_CREDIT) {
return;
}
$credit = Credit::createNew();
$credit->client_id = $payment->client_id;
$credit->credit_date = Carbon::now()->toDateTimeString();
$credit->balance = $credit->amount = $payment->amount;
$credit->private_notes = $payment->transaction_reference;
$credit->save();
}
}

View File

@ -1,48 +0,0 @@
<?php namespace App\Listeners;
use App\Events\InvoicePaid;
use App\Ninja\Mailers\UserMailer;
use App\Ninja\Mailers\ContactMailer;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class HandleInvoicePaid {
protected $userMailer;
protected $contactMailer;
/**
* Create the event handler.
*
* @return void
*/
public function __construct(UserMailer $userMailer, ContactMailer $contactMailer)
{
$this->userMailer = $userMailer;
$this->contactMailer = $contactMailer;
}
/**
* Handle the event.
*
* @param InvoicePaid $event
* @return void
*/
public function handle(InvoicePaid $event)
{
$payment = $event->payment;
$invoice = $payment->invoice;
$this->contactMailer->sendPaymentConfirmation($payment);
foreach ($invoice->account->users as $user)
{
if ($user->{'notify_paid'})
{
$this->userMailer->sendNotification($user, $invoice, 'paid', $payment);
}
}
}
}

View File

@ -1,42 +0,0 @@
<?php namespace App\Listeners;
use App\Events\InvoiceSent;
use App\Ninja\Mailers\UserMailer;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class HandleInvoiceSent {
protected $userMailer;
/**
* Create the event handler.
*
* @return void
*/
public function __construct(UserMailer $userMailer)
{
$this->userMailer = $userMailer;
}
/**
* Handle the event.
*
* @param InvoiceSent $event
* @return void
*/
public function handle(InvoiceSent $event)
{
$invoice = $event->invoice;
foreach ($invoice->account->users as $user)
{
if ($user->{'notify_sent'})
{
$this->userMailer->sendNotification($user, $invoice, 'sent');
}
}
}
}

View File

@ -1,42 +0,0 @@
<?php namespace App\Listeners;
use App\Events\InvoiceViewed;
use App\Ninja\Mailers\UserMailer;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class HandleInvoiceViewed {
protected $userMailer;
/**
* Create the event handler.
*
* @return void
*/
public function __construct(UserMailer $userMailer)
{
$this->userMailer = $userMailer;
}
/**
* Handle the event.
*
* @param InvoiceViewed $event
* @return void
*/
public function handle(InvoiceViewed $event)
{
$invoice = $event->invoice;
foreach ($invoice->account->users as $user)
{
if ($user->{'notify_viewed'})
{
$this->userMailer->sendNotification($user, $invoice, 'viewed');
}
}
}
}

View File

@ -1,42 +0,0 @@
<?php namespace App\Listeners;
use App\Events\QuoteApproved;
use App\Ninja\Mailers\UserMailer;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;
class HandleQuoteApproved {
protected $userMailer;
/**
* Create the event handler.
*
* @return void
*/
public function __construct(UserMailer $userMailer)
{
$this->userMailer = $userMailer;
}
/**
* Handle the event.
*
* @param QuoteApproved $event
* @return void
*/
public function handle(QuoteApproved $event)
{
$invoice = $event->invoice;
foreach ($invoice->account->users as $user)
{
if ($user->{'notify_approved'})
{
$this->userMailer->sendNotification($user, $invoice, 'approved');
}
}
}
}

View File

@ -41,12 +41,6 @@ class HandleUserSignedUp
$this->accountRepo->registerNinjaUser($user); $this->accountRepo->registerNinjaUser($user);
} }
$activities = Activity::scope()->get();
foreach ($activities as $activity) {
$activity->message = str_replace('Guest', $user->getFullName(), $activity->message);
$activity->save();
}
session([SESSION_COUNTER => -1]); session([SESSION_COUNTER => -1]);
} }
} }

View File

@ -0,0 +1,49 @@
<?php namespace app\Listeners;
use App\Events\InvoiceWasEmailed;
use App\Events\InvoiceWasUpdated;
use App\Events\PaymentWasCreated;
use App\Events\PaymentWasDeleted;
use App\Events\InvoiceInvitationWasViewed;
class InvoiceListener
{
public function createdPayment(PaymentWasCreated $event)
{
$payment = $event->payment;
$invoice = $payment->invoice;
$adjustment = $payment->amount * -1;
$partial = max(0, $invoice->partial - $payment->amount);
$invoice->updateBalances($adjustment, $partial);
$invoice->updatePaidStatus();
}
public function updatedInvoice(InvoiceWasUpdated $event)
{
$invoice = $event->invoice;
$invoice->updatePaidStatus();
}
public function emailedInvoice(InvoiceWasEmailed $event)
{
$invoice = $event->invoice;
$invoice->markSent();
}
public function viewedInvoice(InvoiceInvitationWasViewed $event)
{
$invitation = $event->invitation;
$invitation->markViewed();
}
public function deletedPayment(PaymentWasDeleted $event)
{
$payment = $event->payment;
$invoice = $payment->invoice;
$adjustment = $payment->amount;
$invoice->updateBalances($adjustment);
$invoice->updatePaidStatus();
}
}

View File

@ -0,0 +1,71 @@
<?php namespace app\Listeners;
use App\Ninja\Mailers\UserMailer;
use App\Ninja\Mailers\ContactMailer;
use App\Events\InvoiceWasEmailed;
use App\Events\QuoteWasEmailed;
use App\Events\InvoiceInvitationWasViewed;
use App\Events\QuoteInvitationWasViewed;
use App\Events\QuoteInvitationWasApproved;
use App\Events\PaymentWasCreated;
class NotificationListener
{
protected $userMailer;
protected $contactMailer;
public function __construct(UserMailer $userMailer, ContactMailer $contactMailer)
{
$this->userMailer = $userMailer;
$this->contactMailer = $contactMailer;
}
private function sendEmails($invoice, $type, $payment = null)
{
foreach ($invoice->account->users as $user)
{
if ($user->{"notify_{$type}"})
{
$this->userMailer->sendNotification($user, $invoice, $type, $payment);
}
}
}
public function emailedInvoice(InvoiceWasEmailed $event)
{
$this->sendEmails($event->invoice, 'sent');
}
public function emailedQuote(QuoteWasEmailed $event)
{
$this->sendEmails($event->quote, 'sent');
}
public function viewedInvoice(InvoiceInvitationWasViewed $event)
{
$this->sendEmails($event->invoice, 'viewed');
}
public function viewedQuote(QuoteInvitationWasViewed $event)
{
$this->sendEmails($event->quote, 'viewed');
}
public function approvedQuote(QuoteInvitationWasApproved $event)
{
$this->sendEmails($event->quote, 'approved');
}
public function createdPayment(PaymentWasCreated $event)
{
// only send emails for online payments
if ( ! $event->payment->account_gateway_id) {
return;
}
$this->contactMailer->sendPaymentConfirmation($event->payment);
$this->sendEmails($event->payment->invoice, 'paid', $event->payment);
}
}

View File

@ -0,0 +1,19 @@
<?php namespace app\Listeners;
use App\Events\QuoteWasEmailed;
use App\Events\QuoteInvitationWasViewed;
class QuoteListener
{
public function emailedQuote(QuoteWasEmailed $event)
{
$quote = $event->quote;
$quote->markSent();
}
public function viewedQuote(QuoteInvitationWasViewed $event)
{
$invitation = $event->invitation;
$invitation->markViewed();
}
}

View File

@ -0,0 +1,47 @@
<?php namespace app\Listeners;
use Auth;
use Utils;
use App\Events\ClientWasCreated;
use App\Events\QuoteWasCreated;
use App\Events\InvoiceWasCreated;
use App\Events\CreditWasCreated;
use App\Events\PaymentWasCreated;
class SubscriptionListener
{
public function createdClient(ClientWasCreated $event)
{
$this->checkSubscriptions(ACTIVITY_TYPE_CREATE_CLIENT, $event->client);
}
public function createdQuote(QuoteWasCreated $event)
{
$this->checkSubscriptions(ACTIVITY_TYPE_CREATE_QUOTE, $event->quote);
}
public function createdPayment(PaymentWasCreated $event)
{
$this->checkSubscriptions(ACTIVITY_TYPE_CREATE_PAYMENT, $event->payment);
}
public function createdCredit(CreditWasCreated $event)
{
$this->checkSubscriptions(ACTIVITY_TYPE_CREATE_CREDIT, $event->credit);
}
public function createdInvoice(InvoiceWasCreated $event)
{
$this->checkSubscriptions(ACTIVITY_TYPE_CREATE_INVOICE, $event->invoice);
}
private function checkSubscriptions($activityTypeId, $entity)
{
$subscription = $entity->account->getSubscription($activityTypeId);
if ($subscription) {
Utils::notifyZapier($subscription, $entity);
}
}
}

View File

@ -0,0 +1,14 @@
<?php namespace app\Listeners;
use App\Models\Task;
use App\Events\InvoiceWasDeleted;
class TaskListener
{
public function deletedInvoice(InvoiceWasDeleted $event)
{
// Release any tasks associated with the deleted invoice
Task::where('invoice_id', '=', $event->invoice->id)
->update(['invoice_id' => null]);
}
}

View File

@ -251,7 +251,7 @@ class Account extends Eloquent
$invoice->start_date = Utils::today(); $invoice->start_date = Utils::today();
$invoice->invoice_design_id = $this->invoice_design_id; $invoice->invoice_design_id = $this->invoice_design_id;
$invoice->client_id = $clientId; $invoice->client_id = $clientId;
if ($entityType === ENTITY_RECURRING_INVOICE) { if ($entityType === ENTITY_RECURRING_INVOICE) {
$invoice->invoice_number = microtime(true); $invoice->invoice_number = microtime(true);
$invoice->is_recurring = true; $invoice->is_recurring = true;
@ -316,7 +316,7 @@ class Account extends Eloquent
$pattern = str_replace($search, $replace, $pattern); $pattern = str_replace($search, $replace, $pattern);
if ($invoice->client->id) { if ($invoice->client_id) {
$pattern = $this->getClientInvoiceNumber($pattern, $invoice); $pattern = $this->getClientInvoiceNumber($pattern, $invoice);
} }
@ -330,13 +330,11 @@ class Account extends Eloquent
} }
$search = [ $search = [
//'{$clientId}',
'{$custom1}', '{$custom1}',
'{$custom2}', '{$custom2}',
]; ];
$replace = [ $replace = [
//str_pad($client->public_id, 3, '0', STR_PAD_LEFT),
$invoice->client->custom_value1, $invoice->client->custom_value1,
$invoice->client->custom_value2, $invoice->client->custom_value2,
]; ];
@ -344,17 +342,6 @@ class Account extends Eloquent
return str_replace($search, $replace, $pattern); return str_replace($search, $replace, $pattern);
} }
// if we're using a pattern we don't know the next number until a client
// is selected, to support this the default value is blank
public function getDefaultInvoiceNumber($invoice = false)
{
if ($this->hasClientNumberPattern($invoice)) {
return false;
}
return $this->getNextInvoiceNumber($invoice);
}
public function getCounter($isQuote) public function getCounter($isQuote)
{ {
return $isQuote && !$this->share_counter ? $this->quote_number_counter : $this->invoice_number_counter; return $isQuote && !$this->share_counter ? $this->quote_number_counter : $this->invoice_number_counter;
@ -372,7 +359,7 @@ class Account extends Eloquent
// confirm the invoice number isn't already taken // confirm the invoice number isn't already taken
do { do {
$number = $prefix.str_pad($counter, 4, "0", STR_PAD_LEFT); $number = $prefix.str_pad($counter, 4, '0', STR_PAD_LEFT);
$check = Invoice::scope(false, $this->id)->whereInvoiceNumber($number)->withTrashed()->first(); $check = Invoice::scope(false, $this->id)->whereInvoiceNumber($number)->withTrashed()->first();
$counter++; $counter++;
$counterOffset++; $counterOffset++;

View File

@ -23,480 +23,60 @@ class Activity extends Eloquent
public function user() public function user()
{ {
return $this->belongsTo('App\Models\User'); return $this->belongsTo('App\Models\User')->withTrashed();
} }
private static function getBlank($entity = false) public function contact()
{ {
$activity = new Activity(); return $this->belongsTo('App\Models\Contact')->withTrashed();
if ($entity) {
$activity->user_id = $entity instanceof User ? $entity->id : $entity->user_id;
$activity->account_id = $entity->account_id;
} elseif (Auth::check()) {
$activity->user_id = Auth::user()->id;
$activity->account_id = Auth::user()->account_id;
} else {
Utils::fatalError();
}
$activity->token_id = Session::get('token_id', null);
$activity->ip = Request::getClientIp();
return $activity;
} }
public static function createClient($client, $notify = true) public function client()
{ {
$activity = Activity::getBlank(); return $this->belongsTo('App\Models\Client')->withTrashed();
$activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_CREATE_CLIENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'created', $client);
$activity->save();
if ($notify) {
Activity::checkSubscriptions(EVENT_CREATE_CLIENT, $client);
}
} }
public static function updateClient($client) public function invoice()
{ {
if ($client->isBeingDeleted()) { return $this->belongsTo('App\Models\Invoice')->withTrashed();
$activity = Activity::getBlank();
$activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_DELETE_CLIENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted', $client);
$activity->balance = $client->balance;
$activity->save();
}
} }
public static function archiveClient($client) public function credit()
{ {
if (!$client->is_deleted) { return $this->belongsTo('App\Models\Credit')->withTrashed();
$activity = Activity::getBlank();
$activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CLIENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'archived', $client);
$activity->balance = $client->balance;
$activity->save();
}
} }
public static function restoreClient($client) public function payment()
{ {
$activity = Activity::getBlank(); return $this->belongsTo('App\Models\Payment')->withTrashed();
$activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_RESTORE_CLIENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored', $client);
$activity->balance = $client->balance;
$activity->save();
} }
public static function createInvoice($invoice) public static function calcMessage($activityTypeId, $client, $user, $invoice, $contactId, $payment, $credit, $isSystem)
{ {
if (Auth::check()) { $data = [
$message = Utils::encodeActivity(Auth::user(), 'created', $invoice); 'client' => link_to($client->getRoute(), $client->getDisplayName()),
} else { 'user' => $isSystem ? '<i>' . trans('texts.system') . '</i>' : $user->getDisplayName(),
$message = Utils::encodeActivity(null, 'created', $invoice); 'invoice' => $invoice ? link_to($invoice->getRoute(), $invoice->getDisplayName()) : null,
} 'quote' => $invoice ? link_to($invoice->getRoute(), $invoice->getDisplayName()) : null,
'contact' => $contactId ? $client->getDisplayName() : $user->getDisplayName(),
'payment' => $payment ? $payment->transaction_reference : null,
'credit' => $credit ? Utils::formatMoney($credit->amount, $client->currency_id) : null,
];
$adjustment = 0; return trans("texts.activity_{$activityTypeId}", $data);
$client = $invoice->client;
if (!$invoice->is_quote && !$invoice->is_recurring) {
$adjustment = $invoice->amount;
$client->balance = $client->balance + $adjustment;
$client->save();
}
$activity = Activity::getBlank($invoice);
$activity->invoice_id = $invoice->id;
$activity->client_id = $invoice->client_id;
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_CREATE_QUOTE : ACTIVITY_TYPE_CREATE_INVOICE;
$activity->message = $message;
$activity->balance = $client->balance;
$activity->adjustment = $adjustment;
$activity->save();
Activity::checkSubscriptions($invoice->is_quote ? EVENT_CREATE_QUOTE : EVENT_CREATE_INVOICE, $invoice);
} }
public static function archiveInvoice($invoice) public function getMessage()
{ {
if (!$invoice->is_deleted) { return static::calcMessage(
$activity = Activity::getBlank(); $this->activity_type_id,
$activity->invoice_id = $invoice->id; $this->client,
$activity->client_id = $invoice->client_id; $this->user,
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_ARCHIVE_QUOTE : ACTIVITY_TYPE_ARCHIVE_INVOICE; $this->invoice,
$activity->message = Utils::encodeActivity(Auth::user(), 'archived', $invoice); $this->contact_id,
$activity->balance = $invoice->client->balance; $this->payment,
$this->credit,
$activity->save(); $this->is_system
} );
}
public static function restoreInvoice($invoice)
{
$activity = Activity::getBlank();
$activity->invoice_id = $invoice->id;
$activity->client_id = $invoice->client_id;
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_RESTORE_QUOTE : ACTIVITY_TYPE_RESTORE_INVOICE;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored', $invoice);
$activity->balance = $invoice->client->balance;
$activity->save();
}
public static function emailInvoice($invitation)
{
$invoice = $invitation->invoice;
$client = $invoice->client;
if (!$invoice->isSent()) {
$invoice->invoice_status_id = INVOICE_STATUS_SENT;
$invoice->save();
}
$activity = Activity::getBlank($invitation);
$activity->client_id = $invitation->invoice->client_id;
$activity->invoice_id = $invitation->invoice_id;
$activity->contact_id = $invitation->contact_id;
$activity->activity_type_id = $invitation->invoice ? ACTIVITY_TYPE_EMAIL_QUOTE : ACTIVITY_TYPE_EMAIL_INVOICE;
$activity->message = Utils::encodeActivity(Auth::check() ? Auth::user() : null, 'emailed', $invitation->invoice, $invitation->contact);
$activity->balance = $client->balance;
$activity->save();
}
public static function updateInvoice($invoice)
{
$client = $invoice->client;
if ($invoice->isBeingDeleted()) {
$adjustment = 0;
if (!$invoice->is_quote && !$invoice->is_recurring) {
$adjustment = $invoice->balance * -1;
$client->balance = $client->balance - $invoice->balance;
$client->paid_to_date = $client->paid_to_date - ($invoice->amount - $invoice->balance);
$client->save();
}
$activity = Activity::getBlank();
$activity->client_id = $invoice->client_id;
$activity->invoice_id = $invoice->id;
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_DELETE_QUOTE : ACTIVITY_TYPE_DELETE_INVOICE;
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted', $invoice);
$activity->balance = $invoice->client->balance;
$activity->adjustment = $adjustment;
$activity->save();
// Release any tasks associated with the deleted invoice
Task::where('invoice_id', '=', $invoice->id)
->update(['invoice_id' => null]);
} else {
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
$fieldChanged = false;
foreach (['invoice_number', 'po_number', 'invoice_date', 'due_date', 'terms', 'public_notes', 'invoice_footer', 'partial'] as $field) {
if ($invoice->$field != $invoice->getOriginal($field)) {
$fieldChanged = true;
break;
}
}
if ($diff != 0 || $fieldChanged) {
$backupInvoice = Invoice::with('invoice_items', 'client.account', 'client.contacts')->find($invoice->id);
if ($diff != 0 && !$invoice->is_quote && !$invoice->is_recurring) {
$client->balance = $client->balance + $diff;
$client->save();
}
$activity = Activity::getBlank($invoice);
$activity->client_id = $invoice->client_id;
$activity->invoice_id = $invoice->id;
$activity->activity_type_id = $invoice->is_quote ? ACTIVITY_TYPE_UPDATE_QUOTE : ACTIVITY_TYPE_UPDATE_INVOICE;
$activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice);
$activity->balance = $client->balance;
$activity->adjustment = $invoice->is_quote || $invoice->is_recurring ? 0 : $diff;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
$activity->save();
if ($invoice->isPaid() && $invoice->balance > 0) {
$invoice->invoice_status_id = INVOICE_STATUS_PARTIAL;
} elseif ($invoice->invoice_status_id && $invoice->balance == 0) {
$invoice->invoice_status_id = INVOICE_STATUS_PAID;
}
}
}
}
public static function viewInvoice($invitation)
{
if (Session::get($invitation->invitation_key)) {
return;
}
Session::put($invitation->invitation_key, true);
$invoice = $invitation->invoice;
if (!$invoice->isViewed()) {
$invoice->invoice_status_id = INVOICE_STATUS_VIEWED;
$invoice->save();
}
$now = Carbon::now()->toDateTimeString();
$invitation->viewed_date = $now;
$invitation->save();
$client = $invoice->client;
$client->last_login = $now;
$client->save();
$activity = Activity::getBlank($invitation);
$activity->client_id = $invitation->invoice->client_id;
$activity->invitation_id = $invitation->id;
$activity->contact_id = $invitation->contact_id;
$activity->invoice_id = $invitation->invoice_id;
$activity->activity_type_id = $invitation->invoice->is_quote ? ACTIVITY_TYPE_VIEW_QUOTE : ACTIVITY_TYPE_VIEW_INVOICE;
$activity->message = Utils::encodeActivity($invitation->contact, 'viewed', $invitation->invoice);
$activity->balance = $invitation->invoice->client->balance;
$activity->save();
}
public static function approveQuote($invitation) {
$activity = Activity::getBlank($invitation);
$activity->client_id = $invitation->invoice->client_id;
$activity->invitation_id = $invitation->id;
$activity->contact_id = $invitation->contact_id;
$activity->invoice_id = $invitation->invoice_id;
$activity->activity_type_id = ACTIVITY_TYPE_APPROVE_QUOTE;
$activity->message = Utils::encodeActivity($invitation->contact, 'approved', $invitation->invoice);
$activity->balance = $invitation->invoice->client->balance;
$activity->save();
}
public static function createPayment($payment)
{
$client = $payment->client;
$client->balance = $client->balance - $payment->amount;
$client->paid_to_date = $client->paid_to_date + $payment->amount;
$client->save();
if ($payment->contact_id) {
$activity = Activity::getBlank($client);
$activity->contact_id = $payment->contact_id;
$activity->message = Utils::encodeActivity($payment->invitation->contact, 'entered '.$payment->getName().' for ', $payment->invoice);
} else {
$activity = Activity::getBlank($client);
$message = $payment->payment_type_id == PAYMENT_TYPE_CREDIT ? 'applied credit for ' : 'entered '.$payment->getName().' for ';
$activity->message = Utils::encodeActivity(Auth::user(), $message, $payment->invoice);
}
$activity->payment_id = $payment->id;
if ($payment->invoice_id) {
$activity->invoice_id = $payment->invoice_id;
$invoice = $payment->invoice;
$invoice->balance = $invoice->balance - $payment->amount;
$invoice->invoice_status_id = ($invoice->balance > 0) ? INVOICE_STATUS_PARTIAL : INVOICE_STATUS_PAID;
if ($invoice->partial > 0) {
$invoice->partial = max(0, $invoice->partial - $payment->amount);
}
$invoice->save();
}
$activity->payment_id = $payment->id;
$activity->client_id = $payment->client_id;
$activity->activity_type_id = ACTIVITY_TYPE_CREATE_PAYMENT;
$activity->balance = $client->balance;
$activity->adjustment = $payment->amount * -1;
$activity->save();
Activity::checkSubscriptions(EVENT_CREATE_PAYMENT, $payment);
}
public static function updatePayment($payment)
{
if ($payment->isBeingDeleted()) {
$client = $payment->client;
$client->balance = $client->balance + $payment->amount;
$client->paid_to_date = $client->paid_to_date - $payment->amount;
$client->save();
$invoice = $payment->invoice;
$invoice->balance = $invoice->balance + $payment->amount;
if ($invoice->isPaid() && $invoice->balance > 0) {
$invoice->invoice_status_id = ($invoice->balance == $invoice->amount ? INVOICE_STATUS_DRAFT : INVOICE_STATUS_PARTIAL);
}
$invoice->save();
// deleting a payment from credit creates a new credit
if ($payment->payment_type_id == PAYMENT_TYPE_CREDIT) {
$credit = Credit::createNew();
$credit->client_id = $client->id;
$credit->credit_date = Carbon::now()->toDateTimeString();
$credit->balance = $credit->amount = $payment->amount;
$credit->private_notes = $payment->transaction_reference;
$credit->save();
}
$activity = Activity::getBlank();
$activity->payment_id = $payment->id;
$activity->client_id = $invoice->client_id;
$activity->invoice_id = $invoice->id;
$activity->activity_type_id = ACTIVITY_TYPE_DELETE_PAYMENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted '.$payment->getName());
$activity->balance = $client->balance;
$activity->adjustment = $payment->amount;
$activity->save();
} else {
/*
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
if ($diff == 0)
{
return;
}
$client = $invoice->client;
$client->balance = $client->balance + $diff;
$client->save();
$activity = Activity::getBlank($invoice);
$activity->client_id = $invoice->client_id;
$activity->invoice_id = $invoice->id;
$activity->activity_type_id = ACTIVITY_TYPE_UPDATE_INVOICE;
$activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice);
$activity->balance = $client->balance;
$activity->adjustment = $diff;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
$activity->save();
*/
}
}
public static function archivePayment($payment)
{
if ($payment->is_deleted) {
return;
}
$client = $payment->client;
$invoice = $payment->invoice;
$activity = Activity::getBlank();
$activity->payment_id = $payment->id;
$activity->invoice_id = $invoice->id;
$activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_PAYMENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'archived '.$payment->getName());
$activity->balance = $client->balance;
$activity->adjustment = 0;
$activity->save();
}
public static function restorePayment($payment)
{
$client = $payment->client;
$invoice = $payment->invoice;
$activity = Activity::getBlank();
$activity->payment_id = $payment->id;
$activity->invoice_id = $invoice->id;
$activity->client_id = $client->id;
$activity->activity_type_id = ACTIVITY_TYPE_RESTORE_PAYMENT;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored '.$payment->getName());
$activity->balance = $client->balance;
$activity->adjustment = 0;
$activity->save();
}
public static function createCredit($credit)
{
$activity = Activity::getBlank();
$activity->message = Utils::encodeActivity(Auth::user(), 'entered '.Utils::formatMoney($credit->amount, $credit->client->getCurrencyId()).' credit');
$activity->credit_id = $credit->id;
$activity->client_id = $credit->client_id;
$activity->activity_type_id = ACTIVITY_TYPE_CREATE_CREDIT;
$activity->balance = $credit->client->balance;
$activity->save();
}
public static function updateCredit($credit)
{
if ($credit->isBeingDeleted()) {
$activity = Activity::getBlank();
$activity->credit_id = $credit->id;
$activity->client_id = $credit->client_id;
$activity->activity_type_id = ACTIVITY_TYPE_DELETE_CREDIT;
$activity->message = Utils::encodeActivity(Auth::user(), 'deleted '.Utils::formatMoney($credit->balance, $credit->client->getCurrencyId()).' credit');
$activity->balance = $credit->client->balance;
$activity->save();
} else {
/*
$diff = floatval($invoice->amount) - floatval($invoice->getOriginal('amount'));
if ($diff == 0)
{
return;
}
$client = $invoice->client;
$client->balance = $client->balance + $diff;
$client->save();
$activity = Activity::getBlank($invoice);
$activity->client_id = $invoice->client_id;
$activity->invoice_id = $invoice->id;
$activity->activity_type_id = ACTIVITY_TYPE_UPDATE_INVOICE;
$activity->message = Utils::encodeActivity(Auth::user(), 'updated', $invoice);
$activity->balance = $client->balance;
$activity->adjustment = $diff;
$activity->json_backup = $backupInvoice->hidePrivateFields()->toJSON();
$activity->save();
*/
}
}
public static function archiveCredit($credit)
{
if ($credit->is_deleted) {
return;
}
$activity = Activity::getBlank();
$activity->client_id = $credit->client_id;
$activity->credit_id = $credit->id;
$activity->activity_type_id = ACTIVITY_TYPE_ARCHIVE_CREDIT;
$activity->message = Utils::encodeActivity(Auth::user(), 'archived '.Utils::formatMoney($credit->balance, $credit->client->getCurrencyId()).' credit');
$activity->balance = $credit->client->balance;
$activity->save();
}
public static function restoreCredit($credit)
{
$activity = Activity::getBlank();
$activity->client_id = $credit->client_id;
$activity->credit_id = $credit->id;
$activity->activity_type_id = ACTIVITY_TYPE_RESTORE_CREDIT;
$activity->message = Utils::encodeActivity(Auth::user(), 'restored '.Utils::formatMoney($credit->balance, $credit->client->getCurrencyId()).' credit');
$activity->balance = $credit->client->balance;
$activity->save();
}
private static function checkSubscriptions($event, $data)
{
if (!Auth::check()) {
return;
}
$subscription = Auth::user()->account->getSubscription($event);
if ($subscription) {
Utils::notifyZapier($subscription, $data);
}
} }
} }

View File

@ -0,0 +1,6 @@
<?php namespace App\Models;
interface BalanceAffecting
{
public function getAdjustment();
}

View File

@ -2,7 +2,9 @@
use Utils; use Utils;
use DB; use DB;
use Carbon;
use App\Events\ClientWasCreated;
use App\Events\ClientWasUpdated;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
class Client extends EntityModel class Client extends EntityModel
@ -10,6 +12,28 @@ class Client extends EntityModel
use SoftDeletes; use SoftDeletes;
protected $dates = ['deleted_at']; protected $dates = ['deleted_at'];
protected $fillable = [
'name',
'id_number',
'vat_number',
'work_phone',
'custom_value1',
'custom_value2',
'address1',
'address2',
'city',
'state',
'postal_code',
'country_id',
'private_notes',
'size_id',
'industry_id',
'currency_id',
'language_id',
'payment_terms',
'website',
];
public static $fieldName = 'Client - Name'; public static $fieldName = 'Client - Name';
public static $fieldPhone = 'Client - Phone'; public static $fieldPhone = 'Client - Phone';
public static $fieldAddress1 = 'Client - Street'; public static $fieldAddress1 = 'Client - Street';
@ -70,6 +94,40 @@ class Client extends EntityModel
return $this->belongsTo('App\Models\Industry'); return $this->belongsTo('App\Models\Industry');
} }
public function addContact($data, $isPrimary = false)
{
$publicId = isset($data['public_id']) ? $data['public_id'] : false;
if ($publicId && $publicId != '-1') {
$contact = Contact::scope($publicId)->firstOrFail();
} else {
$contact = Contact::createNew();
$contact->send_invoice = true;
}
$contact->fill($data);
$contact->is_primary = $isPrimary;
return $this->contacts()->save($contact);
}
public function updateBalances($balanceAdjustment, $paidToDateAdjustment)
{
if ($balanceAdjustment === 0 && $paidToDateAdjustment === 0) {
return;
}
$this->balance = $this->balance + $balanceAdjustment;
$this->paid_to_date = $this->paid_to_date + $paidToDateAdjustment;
$this->save();
}
public function getRoute()
{
return "/clients/{$this->public_id}";
}
public function getTotalCredit() public function getTotalCredit()
{ {
return DB::table('credits') return DB::table('credits')
@ -89,8 +147,11 @@ class Client extends EntityModel
return $this->name; return $this->name;
} }
$contact = $this->contacts()->first(); if ( ! count($this->contacts)) {
return '';
}
$contact = $this->contacts[0];
return $contact->getDisplayName(); return $contact->getDisplayName();
} }
@ -178,24 +239,26 @@ class Client extends EntityModel
{ {
return $isQuote ? $this->quote_number_counter : $this->invoice_number_counter; return $isQuote ? $this->quote_number_counter : $this->invoice_number_counter;
} }
public function markLoggedIn()
{
$this->last_login = Carbon::now()->toDateTimeString();
$this->save();
}
} }
/* Client::creating(function ($client) {
Client::created(function($client) $client->setNullValues();
{ });
Activity::createClient($client);
Client::created(function ($client) {
event(new ClientWasCreated($client));
}); });
*/
Client::updating(function ($client) { Client::updating(function ($client) {
Activity::updateClient($client); $client->setNullValues();
}); });
Client::deleting(function ($client) { Client::updated(function ($client) {
Activity::archiveClient($client); event(new ClientWasUpdated($client));
}); });
/*Client::restoring(function ($client) {
Activity::restoreClient($client);
});
*/

View File

@ -9,6 +9,14 @@ class Contact extends EntityModel
use SoftDeletes; use SoftDeletes;
protected $dates = ['deleted_at']; protected $dates = ['deleted_at'];
protected $fillable = [
'first_name',
'last_name',
'email',
'phone',
'send_invoice',
];
public static $fieldFirstName = 'Contact - First Name'; public static $fieldFirstName = 'Contact - First Name';
public static $fieldLastName = 'Contact - Last Name'; public static $fieldLastName = 'Contact - Last Name';
public static $fieldEmail = 'Contact - Email'; public static $fieldEmail = 'Contact - Email';

View File

@ -1,12 +1,19 @@
<?php namespace App\Models; <?php namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use App\Events\CreditWasCreated;
class Credit extends EntityModel class Credit extends EntityModel
{ {
use SoftDeletes; use SoftDeletes;
protected $dates = ['deleted_at']; protected $dates = ['deleted_at'];
public function account()
{
return $this->belongsTo('App\Models\Account');
}
public function invoice() public function invoice()
{ {
return $this->belongsTo('App\Models\Invoice')->withTrashed(); return $this->belongsTo('App\Models\Invoice')->withTrashed();
@ -43,18 +50,10 @@ class Credit extends EntityModel
} }
} }
Credit::creating(function ($credit) {
});
Credit::created(function ($credit) { Credit::created(function ($credit) {
Activity::createCredit($credit); event(new CreditWasCreated($credit));
}); });
Credit::updating(function ($credit) {
Activity::updateCredit($credit);
});
Credit::deleting(function ($credit) {
Activity::archiveCredit($credit);
});
Credit::restoring(function ($credit) {
Activity::restoreCredit($credit);
});

View File

@ -39,7 +39,7 @@ class EntityModel extends Eloquent
{ {
$className = get_called_class(); $className = get_called_class();
return $className::scope($publicId)->pluck('id'); return $className::scope($publicId)->withTrashed()->pluck('id');
} }
public function getActivityKey() public function getActivityKey()
@ -112,8 +112,21 @@ class EntityModel extends Eloquent
return $data; return $data;
} }
public function isBeingDeleted() public function setNullValues()
{ {
return $this->is_deleted && !$this->getOriginal('is_deleted'); foreach ($this->fillable as $field) {
if (strstr($field, '_id') && !$this->$field) {
$this->$field = null;
}
}
}
// converts "App\Models\Client" to "client_id"
public function getKeyField()
{
$class = get_class($this);
$parts = explode('\\', $class);
$name = $parts[count($parts)-1];
return strtolower($name) . '_id';
} }
} }

View File

@ -1,6 +1,7 @@
<?php namespace App\Models; <?php namespace App\Models;
use Utils; use Utils;
use Carbon;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
class Invitation extends EntityModel class Invitation extends EntityModel
@ -72,4 +73,15 @@ class Invitation extends EntityModel
return $this->invitation_key; return $this->invitation_key;
} }
public function markViewed()
{
$invoice = $this->invoice;
$client = $invoice->client;
$this->viewed_date = Carbon::now()->toDateTimeString();
$this->save();
$invoice->markViewed();
$client->markLoggedIn();
}
} }

View File

@ -2,9 +2,15 @@
use Utils; use Utils;
use DateTime; use DateTime;
use App\Models\BalanceAffecting;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
class Invoice extends EntityModel use App\Events\QuoteWasCreated;
use App\Events\QuoteWasUpdated;
use App\Events\InvoiceWasCreated;
use App\Events\InvoiceWasUpdated;
class Invoice extends EntityModel implements BalanceAffecting
{ {
use SoftDeletes { use SoftDeletes {
SoftDeletes::trashed as parentTrashed; SoftDeletes::trashed as parentTrashed;
@ -26,6 +32,64 @@ class Invoice extends EntityModel
'year', 'year',
'date:', 'date:',
]; ];
public function getRoute()
{
$entityType = $this->getEntityType();
return "/{$entityType}s/{$this->public_id}/edit";
}
public function getDisplayName()
{
return $this->is_recurring ? trans('texts.recurring') : $this->invoice_number;
}
public function getAdjustment()
{
if ($this->is_quote || $this->is_recurring) {
return 0;
}
return $this->getRawAdjustment();
}
private function getRawAdjustment()
{
return floatval($this->amount) - floatval($this->getOriginal('amount'));
}
public function isChanged()
{
if ($this->getRawAdjustment() != 0) {
return true;
}
foreach ([
'invoice_number',
'po_number',
'invoice_date',
'due_date',
'terms',
'public_notes',
'invoice_footer',
'partial'
] as $field) {
if ($this->$field != $this->getOriginal($field)) {
return true;
}
}
return false;
}
public function getAmountPaid()
{
if ($this->is_quote || $this->is_recurring) {
return 0;
}
return ($this->amount - $this->balance);
}
public function trashed() public function trashed()
{ {
@ -81,6 +145,44 @@ class Invoice extends EntityModel
return $this->hasMany('App\Models\Invitation')->orderBy('invitations.contact_id'); return $this->hasMany('App\Models\Invitation')->orderBy('invitations.contact_id');
} }
public function markSent()
{
if (!$this->isSent()) {
$this->invoice_status_id = INVOICE_STATUS_SENT;
$this->save();
}
}
public function markViewed()
{
if (!$this->isViewed()) {
$this->invoice_status_id = INVOICE_STATUS_VIEWED;
$this->save();
}
}
public function updatePaidStatus()
{
if ($this->isPaid() && $this->balance > 0) {
$this->invoice_status_id = ($this->balance == $this->amount ? INVOICE_STATUS_SENT : INVOICE_STATUS_PARTIAL);
$this->save();
} elseif ($this->invoice_status_id && $this->amount && $this->balance == 0 && $this->invoice_status_id != INVOICE_STATUS_PAID) {
$this->invoice_status_id = INVOICE_STATUS_PAID;
$this->save();
}
}
public function updateBalances($balanceAdjustment, $partial = 0)
{
$this->balance = $this->balance + $balanceAdjustment;
if ($this->partial > 0) {
$this->partial = $partial;
}
$this->save();
}
public function getName() public function getName()
{ {
return $this->is_recurring ? trans('texts.recurring') : $this->invoice_number; return $this->is_recurring ? trans('texts.recurring') : $this->invoice_number;
@ -458,17 +560,17 @@ Invoice::creating(function ($invoice) {
}); });
Invoice::created(function ($invoice) { Invoice::created(function ($invoice) {
Activity::createInvoice($invoice); if ($invoice->is_quote) {
event(new QuoteWasCreated($invoice));
} else {
event(new InvoiceWasCreated($invoice));
}
}); });
Invoice::updating(function ($invoice) { Invoice::updating(function ($invoice) {
Activity::updateInvoice($invoice); if ($invoice->is_quote) {
}); event(new QuoteWasUpdated($invoice));
} else {
Invoice::deleting(function ($invoice) { event(new InvoiceWasUpdated($invoice));
Activity::archiveInvoice($invoice); }
});
Invoice::restoring(function ($invoice) {
Activity::restoreInvoice($invoice);
}); });

View File

@ -1,6 +1,7 @@
<?php namespace App\Models; <?php namespace App\Models;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use App\Events\PaymentWasCreated;
class Payment extends EntityModel class Payment extends EntityModel
{ {
@ -37,6 +38,11 @@ class Payment extends EntityModel
return $this->belongsTo('App\Models\Contact'); return $this->belongsTo('App\Models\Contact');
} }
public function getRoute()
{
return "/payments/{$this->public_id}/edit";
}
public function getAmount() public function getAmount()
{ {
return Utils::formatMoney($this->amount, $this->client->getCurrencyId()); return Utils::formatMoney($this->amount, $this->client->getCurrencyId());
@ -53,18 +59,10 @@ class Payment extends EntityModel
} }
} }
Payment::creating(function ($payment) {
});
Payment::created(function ($payment) { Payment::created(function ($payment) {
Activity::createPayment($payment); event(new PaymentWasCreated($payment));
}); });
Payment::updating(function ($payment) {
Activity::updatePayment($payment);
});
Payment::deleting(function ($payment) {
Activity::archivePayment($payment);
});
Payment::restoring(function ($payment) {
Activity::restorePayment($payment);
});

View File

@ -82,20 +82,4 @@ class Task extends EntityModel
{ {
return round($this->getDuration() / (60 * 60), 2); return round($this->getDuration() / (60 * 60), 2);
} }
} }
Task::created(function ($task) {
//Activity::createTask($task);
});
Task::updating(function ($task) {
//Activity::updateTask($task);
});
Task::deleting(function ($task) {
//Activity::archiveTask($task);
});
Task::restoring(function ($task) {
//Activity::restoreTask($task);
});

View File

@ -9,7 +9,12 @@ use App\Models\Invoice;
use App\Models\Payment; use App\Models\Payment;
use App\Models\Activity; use App\Models\Activity;
use App\Models\Gateway; use App\Models\Gateway;
use App\Events\InvoiceSent;
use App\Events\InvoiceWasEmailed;
use App\Events\InvoiceInvitationWasEmailed;
use App\Events\QuoteWasEmailed;
use App\Events\QuoteInvitationWasEmailed;
class ContactMailer extends Mailer class ContactMailer extends Mailer
{ {
@ -44,7 +49,11 @@ class ContactMailer extends Mailer
$account->loadLocalizationSettings(); $account->loadLocalizationSettings();
if ($sent === true) { if ($sent === true) {
Event::fire(new InvoiceSent($invoice)); if ($invoice->is_quote) {
event(new QuoteWasEmailed($invoice));
} else {
event(new InvoiceWasEmailed($invoice));
}
} }
return $sent ?: trans('texts.email_error'); return $sent ?: trans('texts.email_error');
@ -97,7 +106,12 @@ class ContactMailer extends Mailer
$response = $this->sendTo($invitation->contact->email, $fromEmail, $account->getDisplayName(), $subject, ENTITY_INVOICE, $data); $response = $this->sendTo($invitation->contact->email, $fromEmail, $account->getDisplayName(), $subject, ENTITY_INVOICE, $data);
if ($response === true) { if ($response === true) {
Activity::emailInvoice($invitation); if ($invoice->is_quote) {
event(new QuoteInvitationWasEmailed($invoice, $invitation));
} else {
event(new InvoiceInvitationWasEmailed($invoice, $invitation));
}
return true; return true;
} else { } else {
return false; return false;

View File

@ -0,0 +1,102 @@
<?php namespace App\Ninja\Repositories;
use DB;
use Auth;
use Utils;
use Request;
use App\Models\Activity;
use App\Models\Client;
class ActivityRepository
{
public function create($entity, $activityTypeId, $balanceChange = 0, $paidToDateChange = 0, $altEntity = null)
{
if ($entity instanceof Client) {
$client = $entity;
} elseif ($entity instanceof Invitation) {
$client = $entity->invoice->client;
} else {
$client = $entity->client;
}
// init activity and copy over context
$activity = self::getBlank($altEntity ?: $client);
$activity = Utils::copyContext($activity, $entity);
$activity = Utils::copyContext($activity, $altEntity);
$activity->client_id = $client->id;
$activity->activity_type_id = $activityTypeId;
$activity->adjustment = $balanceChange;
$activity->balance = $client->balance + $balanceChange;
$keyField = $entity->getKeyField();
$activity->$keyField = $entity->id;
$activity->ip = Request::getClientIp();
$activity->save();
$client->updateBalances($balanceChange, $paidToDateChange);
return $activity;
}
private function getBlank($entity)
{
$activity = new Activity();
if (Auth::check()) {
$activity->user_id = Auth::user()->id;
$activity->account_id = Auth::user()->account_id;
} else {
$activity->user_id = $entity->user_id;
$activity->account_id = $entity->account_id;
if ( ! $entity instanceof Invitation) {
$activity->is_system = true;
}
}
$activity->token_id = session('token_id');
return $activity;
}
public function findByClientId($clientId)
{
return DB::table('activities')
->join('users', 'users.id', '=', 'activities.user_id')
->join('clients', 'clients.id', '=', 'activities.client_id')
->leftJoin('contacts', 'contacts.client_id', '=', 'clients.id')
->leftJoin('invoices', 'invoices.id', '=', 'activities.invoice_id')
->leftJoin('payments', 'payments.id', '=', 'activities.payment_id')
->leftJoin('credits', 'credits.id', '=', 'activities.credit_id')
->where('activities.client_id', '=', $clientId)
->where('contacts.is_primary', '=', 1)
->whereNull('contacts.deleted_at')
->select(
'activities.id',
'activities.created_at',
'activities.contact_id',
'activities.activity_type_id',
'activities.is_system',
'clients.currency_id',
'activities.balance',
'activities.adjustment',
'users.first_name as user_first_name',
'users.last_name as user_last_name',
'users.email as user_email',
'invoices.invoice_number as invoice',
'invoices.public_id as invoice_public_id',
'invoices.is_recurring',
'clients.currency_id',
'clients.name as client_name',
'clients.public_id as client_public_id',
'contacts.id as contact',
'contacts.first_name as first_name',
'contacts.last_name as last_name',
'contacts.email as email',
'payments.transaction_reference as payment',
'credits.amount as credit');
}
}

View File

@ -0,0 +1,58 @@
<?php namespace App\Ninja\Repositories;
class BaseRepository
{
public function getClassName()
{
return null;
}
private function getInstance()
{
$className = $this->getClassName();
return new $className();
}
private function dispatchEvent($entity, $type)
{
$className = 'App\Events\\' . ucfirst($entity->getEntityType()) . 'Was' . $type;
event(new $className($entity));
}
public function archive($entity)
{
$entity->delete();
$this->dispatchEvent($entity, 'Archived');
}
public function restore($entity)
{
$entity->restore();
$entity->is_deleted = false;
$entity->save();
$this->dispatchEvent($entity, 'Restored');
}
public function delete($entity)
{
$entity->is_deleted = true;
$entity->save();
$entity->delete();
$this->dispatchEvent($entity, 'Deleted');
}
public function findByPublicIds($ids)
{
return $this->getInstance()->scope($ids)->get();
}
public function findByPublicIdsWithTrashed($ids)
{
return $this->getInstance()->scope($ids)->withTrashed()->get();
}
}

View File

@ -1,11 +1,17 @@
<?php namespace App\Ninja\Repositories; <?php namespace App\Ninja\Repositories;
use App\Ninja\Repositories\BaseRepository;
use App\Models\Client; use App\Models\Client;
use App\Models\Contact; use App\Models\Contact;
use App\Models\Activity; use App\Models\Activity;
class ClientRepository class ClientRepository extends BaseRepository
{ {
public function getClassName()
{
return 'App\Models\Client';
}
public function find($filter = null) public function find($filter = null)
{ {
$query = \DB::table('clients') $query = \DB::table('clients')
@ -30,179 +36,36 @@ class ClientRepository
return $query; return $query;
} }
public function getErrors($data) public function save($data)
{ {
$contact = isset($data['contacts']) ? (array) $data['contacts'][0] : (isset($data['contact']) ? $data['contact'] : []); $publicId = isset($data['public_id']) ? $data['public_id'] : false;
$validator = \Validator::make($contact, [
'email' => 'email|required_without:first_name',
'first_name' => 'required_without:email',
]);
if ($validator->fails()) {
return $validator->messages();
}
return false; if (!$publicId || $publicId == '-1') {
}
public function save($publicId, $data, $notify = true)
{
if (!$publicId || $publicId == "-1") {
$client = Client::createNew(); $client = Client::createNew();
$contact = Contact::createNew();
$contact->is_primary = true;
$contact->send_invoice = true;
} else { } else {
$client = Client::scope($publicId)->with('contacts')->firstOrFail(); $client = Client::scope($publicId)->with('contacts')->firstOrFail();
$contact = $client->contacts()->where('is_primary', '=', true)->firstOrFail();
}
if (isset($data['name'])) {
$client->name = trim($data['name']);
}
if (isset($data['id_number'])) {
$client->id_number = trim($data['id_number']);
}
if (isset($data['vat_number'])) {
$client->vat_number = trim($data['vat_number']);
}
if (isset($data['work_phone'])) {
$client->work_phone = trim($data['work_phone']);
}
if (isset($data['custom_value1'])) {
$client->custom_value1 = trim($data['custom_value1']);
}
if (isset($data['custom_value2'])) {
$client->custom_value2 = trim($data['custom_value2']);
}
if (isset($data['address1'])) {
$client->address1 = trim($data['address1']);
}
if (isset($data['address2'])) {
$client->address2 = trim($data['address2']);
}
if (isset($data['city'])) {
$client->city = trim($data['city']);
}
if (isset($data['state'])) {
$client->state = trim($data['state']);
}
if (isset($data['postal_code'])) {
$client->postal_code = trim($data['postal_code']);
}
if (isset($data['country_id'])) {
$client->country_id = $data['country_id'] ? $data['country_id'] : null;
}
if (isset($data['private_notes'])) {
$client->private_notes = trim($data['private_notes']);
}
if (isset($data['size_id'])) {
$client->size_id = $data['size_id'] ? $data['size_id'] : null;
}
if (isset($data['industry_id'])) {
$client->industry_id = $data['industry_id'] ? $data['industry_id'] : null;
}
if (isset($data['currency_id'])) {
$client->currency_id = $data['currency_id'] ? $data['currency_id'] : null;
}
if (isset($data['language_id'])) {
$client->language_id = $data['language_id'] ? $data['language_id'] : null;
}
if (isset($data['payment_terms'])) {
$client->payment_terms = $data['payment_terms'];
}
if (isset($data['website'])) {
$client->website = trim($data['website']);
} }
$client->fill($data);
$client->save(); $client->save();
$isPrimary = true; $first = true;
$contacts = isset($data['contact']) ? [$data['contact']] : $data['contacts'];
$contactIds = []; $contactIds = [];
if (isset($data['contact'])) { foreach ($data['contacts'] as $contact) {
$info = $data['contact']; $contact = $client->addContact($contact, $first);
if (isset($info['email'])) { $contactIds[] = $contact->public_id;
$contact->email = trim($info['email']); $first = false;
}
if (isset($info['first_name'])) {
$contact->first_name = trim($info['first_name']);
}
if (isset($info['last_name'])) {
$contact->last_name = trim($info['last_name']);
}
if (isset($info['phone'])) {
$contact->phone = trim($info['phone']);
}
$contact->is_primary = true;
$contact->send_invoice = true;
$client->contacts()->save($contact);
} else {
foreach ($data['contacts'] as $record) {
$record = (array) $record;
if ($publicId != "-1" && isset($record['public_id']) && $record['public_id']) {
$contact = Contact::scope($record['public_id'])->firstOrFail();
} else {
$contact = Contact::createNew();
}
if (isset($record['email'])) {
$contact->email = trim($record['email']);
}
if (isset($record['first_name'])) {
$contact->first_name = trim($record['first_name']);
}
if (isset($record['last_name'])) {
$contact->last_name = trim($record['last_name']);
}
if (isset($record['phone'])) {
$contact->phone = trim($record['phone']);
}
$contact->is_primary = $isPrimary;
$contact->send_invoice = isset($record['send_invoice']) ? $record['send_invoice'] : true;
$isPrimary = false;
$client->contacts()->save($contact);
$contactIds[] = $contact->public_id;
}
foreach ($client->contacts as $contact) {
if (!in_array($contact->public_id, $contactIds)) {
$contact->delete();
}
}
} }
$client->save(); foreach ($client->contacts as $contact) {
if (!in_array($contact->public_id, $contactIds)) {
if (!$publicId || $publicId == "-1") { $contact->delete();
Activity::createClient($client, $notify); }
} }
return $client; return $client;
} }
public function bulk($ids, $action)
{
$clients = Client::withTrashed()->scope($ids)->get();
foreach ($clients as $client) {
if ($action == 'restore') {
$client->restore();
$client->is_deleted = false;
$client->save();
} else {
if ($action == 'delete') {
$client->is_deleted = true;
$client->save();
}
$client->delete();
}
}
return count($clients);
}
} }

View File

@ -1,11 +1,17 @@
<?php namespace App\Ninja\Repositories; <?php namespace App\Ninja\Repositories;
use Utils;
use App\Models\Credit; use App\Models\Credit;
use App\Models\Client; use App\Models\Client;
use Utils; use App\Ninja\Repositories\BaseRepository;
class CreditRepository class CreditRepository extends BaseRepository
{ {
public function getClassName()
{
return 'App\Models\Credit';
}
public function find($clientPublicId = null, $filter = null) public function find($clientPublicId = null, $filter = null)
{ {
$query = \DB::table('credits') $query = \DB::table('credits')
@ -33,8 +39,10 @@ class CreditRepository
return $query; return $query;
} }
public function save($publicId = null, $input) public function save($input)
{ {
$publicId = isset($data['public_id']) ? $data['public_id'] : false;
if ($publicId) { if ($publicId) {
$credit = Credit::scope($publicId)->firstOrFail(); $credit = Credit::scope($publicId)->firstOrFail();
} else { } else {
@ -50,28 +58,4 @@ class CreditRepository
return $credit; return $credit;
} }
public function bulk($ids, $action)
{
if (!$ids) {
return 0;
}
$credits = Credit::withTrashed()->scope($ids)->get();
foreach ($credits as $credit) {
if ($action == 'restore') {
$credit->restore();
} else {
if ($action == 'delete') {
$credit->is_deleted = true;
$credit->save();
}
$credit->delete();
}
}
return count($credits);
}
} }

View File

@ -8,9 +8,15 @@ use App\Models\Invitation;
use App\Models\Product; use App\Models\Product;
use App\Models\Task; use App\Models\Task;
use App\Services\PaymentService; use App\Services\PaymentService;
use App\Ninja\Repositories\BaseRepository;
class InvoiceRepository class InvoiceRepository extends BaseRepository
{ {
public function getClassName()
{
return 'App\Models\Invoice';
}
public function __construct(PaymentService $paymentService) public function __construct(PaymentService $paymentService)
{ {
$this->paymentService = $paymentService; $this->paymentService = $paymentService;
@ -214,51 +220,24 @@ class InvoiceRepository
} }
return "<h4><div class=\"label label-{$class}\">$label</div></h4>"; return "<h4><div class=\"label label-{$class}\">$label</div></h4>";
} }
public function getErrors($input) public function save($data)
{
$contact = (array) $input->client->contacts[0];
$rules = [
'email' => 'email|required_without:first_name',
'first_name' => 'required_without:email',
];
$validator = \Validator::make($contact, $rules);
if ($validator->fails()) {
return $validator;
}
$invoice = (array) $input;
$invoiceId = isset($invoice['public_id']) && $invoice['public_id'] ? Invoice::getPrivateId($invoice['public_id']) : null;
$rules = [
'invoice_number' => 'required|unique:invoices,invoice_number,'.$invoiceId.',id,account_id,'.\Auth::user()->account_id,
'discount' => 'positive',
];
if ($invoice['is_recurring'] && $invoice['start_date'] && $invoice['end_date']) {
$rules['end_date'] = 'after:'.$invoice['start_date'];
}
$validator = \Validator::make($invoice, $rules);
if ($validator->fails()) {
return $validator;
}
return false;
}
public function save($publicId, $data, $entityType)
{ {
$account = \Auth::user()->account; $account = \Auth::user()->account;
$publicId = isset($data['public_id']) ? $data['public_id'] : false;
$isNew = !$publicId || $publicId == '-1';
if ($publicId) { if ($isNew) {
$invoice = Invoice::scope($publicId)->firstOrFail(); $entityType = ENTITY_INVOICE;
} else { if (isset($data['is_recurring']) && $data['is_recurring']) {
if ($data['is_recurring']) {
$entityType = ENTITY_RECURRING_INVOICE; $entityType = ENTITY_RECURRING_INVOICE;
} elseif (isset($data['is_quote']) && $data['is_quote']) {
$entityType = ENTITY_QUOTE;
} }
$invoice = $account->createInvoice($entityType, $data['client_id']); $invoice = $account->createInvoice($entityType, $data['client_id']);
} else {
$invoice = Invoice::scope($publicId)->firstOrFail();
} }
if ((isset($data['set_default_terms']) && $data['set_default_terms']) if ((isset($data['set_default_terms']) && $data['set_default_terms'])
@ -280,7 +259,7 @@ class InvoiceRepository
$invoice->is_amount_discount = $data['is_amount_discount'] ? true : false; $invoice->is_amount_discount = $data['is_amount_discount'] ? true : false;
$invoice->partial = round(Utils::parseFloat($data['partial']), 2); $invoice->partial = round(Utils::parseFloat($data['partial']), 2);
$invoice->invoice_date = isset($data['invoice_date_sql']) ? $data['invoice_date_sql'] : Utils::toSqlDate($data['invoice_date']); $invoice->invoice_date = isset($data['invoice_date_sql']) ? $data['invoice_date_sql'] : Utils::toSqlDate($data['invoice_date']);
$invoice->has_tasks = isset($data['has_tasks']) ? $data['has_tasks'] : false; $invoice->has_tasks = isset($data['has_tasks']) ? ($data['has_tasks'] ? true : false) : false;
if ($invoice->is_recurring) { if ($invoice->is_recurring) {
if ($invoice->start_date && $invoice->start_date != Utils::toSqlDate($data['start_date'])) { if ($invoice->start_date && $invoice->start_date != Utils::toSqlDate($data['start_date'])) {
@ -362,12 +341,20 @@ class InvoiceRepository
$total *= (100 - $invoice->discount) / 100; $total *= (100 - $invoice->discount) / 100;
} }
} }
$invoice->custom_value1 = round($data['custom_value1'], 2); if (isset($data['custom_value1'])) {
$invoice->custom_value2 = round($data['custom_value2'], 2); $invoice->custom_value1 = round($data['custom_value1'], 2);
$invoice->custom_taxes1 = $data['custom_taxes1'] ? true : false; if ($isNew) {
$invoice->custom_taxes2 = $data['custom_taxes2'] ? true : false; $invoice->custom_taxes1 = $account->custom_invoice_taxes1 ?: false;
}
}
if (isset($data['custom_value2'])) {
$invoice->custom_value2 = round($data['custom_value2'], 2);
if ($isNew) {
$invoice->custom_taxes2 = $account->custom_invoice_taxes2 ?: false;
}
}
if (isset($data['custom_text_value1'])) { if (isset($data['custom_text_value1'])) {
$invoice->custom_text_value1 = trim($data['custom_text_value1']); $invoice->custom_text_value1 = trim($data['custom_text_value1']);
} }
@ -543,31 +530,10 @@ class InvoiceRepository
return $clone; return $clone;
} }
public function bulk($ids, $action, $statusId = false) public function mark($invoice, $statusId)
{ {
if (!$ids) { $invoice->invoice_status_id = $statusId;
return 0; $invoice->save();
}
$invoices = Invoice::withTrashed()->scope($ids)->get();
foreach ($invoices as $invoice) {
if ($action == 'mark') {
$invoice->invoice_status_id = $statusId;
$invoice->save();
} elseif ($action == 'restore') {
$invoice->restore();
} else {
if ($action == 'delete') {
$invoice->is_deleted = true;
$invoice->save();
}
$invoice->delete();
}
}
return count($invoices);
} }
public function findInvoiceByInvitation($invitationKey) public function findInvoiceByInvitation($invitationKey)
@ -637,10 +603,10 @@ class InvoiceRepository
$invoice->tax_name = $recurInvoice->tax_name; $invoice->tax_name = $recurInvoice->tax_name;
$invoice->tax_rate = $recurInvoice->tax_rate; $invoice->tax_rate = $recurInvoice->tax_rate;
$invoice->invoice_design_id = $recurInvoice->invoice_design_id; $invoice->invoice_design_id = $recurInvoice->invoice_design_id;
$invoice->custom_value1 = $recurInvoice->custom_value1; $invoice->custom_value1 = $recurInvoice->custom_value1 ?: 0;
$invoice->custom_value2 = $recurInvoice->custom_value2; $invoice->custom_value2 = $recurInvoice->custom_value2 ?: 0;
$invoice->custom_taxes1 = $recurInvoice->custom_taxes1; $invoice->custom_taxes1 = $recurInvoice->custom_taxes1 ?: 0;
$invoice->custom_taxes2 = $recurInvoice->custom_taxes2; $invoice->custom_taxes2 = $recurInvoice->custom_taxes2 ?: 0;
$invoice->custom_text_value1 = $recurInvoice->custom_text_value1; $invoice->custom_text_value1 = $recurInvoice->custom_text_value1;
$invoice->custom_text_value2 = $recurInvoice->custom_text_value2; $invoice->custom_text_value2 = $recurInvoice->custom_text_value2;
$invoice->is_amount_discount = $recurInvoice->is_amount_discount; $invoice->is_amount_discount = $recurInvoice->is_amount_discount;

View File

@ -1,13 +1,19 @@
<?php namespace App\Ninja\Repositories; <?php namespace App\Ninja\Repositories;
use Utils;
use App\Models\Payment; use App\Models\Payment;
use App\Models\Credit; use App\Models\Credit;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\Client; use App\Models\Client;
use Utils; use App\Ninja\Repositories\BaseRepository;
class PaymentRepository class PaymentRepository extends BaseRepository
{ {
public function getClassName()
{
return 'App\Models\Payment';
}
public function find($clientPublicId = null, $filter = null) public function find($clientPublicId = null, $filter = null)
{ {
$query = \DB::table('payments') $query = \DB::table('payments')
@ -68,34 +74,10 @@ class PaymentRepository
return $query; return $query;
} }
public function getErrors($input) public function save($input)
{
$rules = array(
'client' => 'required',
'invoice' => 'required',
'amount' => 'required',
);
if ($input['payment_type_id'] == PAYMENT_TYPE_CREDIT) {
$rules['payment_type_id'] = 'has_credit:'.$input['client'].','.$input['amount'];
}
if (isset($input['invoice']) && $input['invoice']) {
$invoice = Invoice::scope($input['invoice'])->firstOrFail();
$rules['amount'] .= "|less_than:{$invoice->balance}";
}
$validator = \Validator::make($input, $rules);
if ($validator->fails()) {
return $validator;
}
return false;
}
public function save($publicId = null, $input)
{ {
$publicId = isset($input['public_id']) ? $input['public_id'] : false;
if ($publicId) { if ($publicId) {
$payment = Payment::scope($publicId)->firstOrFail(); $payment = Payment::scope($publicId)->firstOrFail();
} else { } else {
@ -145,28 +127,4 @@ class PaymentRepository
return $payment; return $payment;
} }
public function bulk($ids, $action)
{
if (!$ids) {
return 0;
}
$payments = Payment::withTrashed()->scope($ids)->get();
foreach ($payments as $payment) {
if ($action == 'restore') {
$payment->restore();
} else {
if ($action == 'delete') {
$payment->is_deleted = true;
$payment->save();
}
$payment->delete();
}
}
return count($payments);
}
} }

View File

@ -148,6 +148,19 @@ class AppServiceProvider extends ServiceProvider {
Validator::extend('has_counter', function($attribute, $value, $parameters) { Validator::extend('has_counter', function($attribute, $value, $parameters) {
return !$value || strstr($value, '{$counter}'); return !$value || strstr($value, '{$counter}');
}); });
Validator::extend('valid_contacts', function($attribute, $value, $parameters) {
foreach ($value as $contact) {
$validator = Validator::make($contact, [
'email' => 'email|required_without:first_name',
'first_name' => 'required_without:email',
]);
if ($validator->fails()) {
return false;
}
}
return true;
});
} }
/** /**

View File

@ -11,6 +11,123 @@ class EventServiceProvider extends ServiceProvider {
* @var array * @var array
*/ */
protected $listen = [ protected $listen = [
// Clients
'App\Events\ClientWasCreated' => [
'App\Listeners\ActivityListener@createdClient',
'App\Listeners\SubscriptionListener@createdClient',
],
'App\Events\ClientWasArchived' => [
'App\Listeners\ActivityListener@archivedClient',
],
'App\Events\ClientWasDeleted' => [
'App\Listeners\ActivityListener@deletedClient',
],
'App\Events\ClientWasRestored' => [
'App\Listeners\ActivityListener@restoredClient',
],
// Invoices
'App\Events\InvoiceWasCreated' => [
'App\Listeners\ActivityListener@createdInvoice',
'App\Listeners\SubscriptionListener@createdInvoice',
],
'App\Events\InvoiceWasUpdated' => [
'App\Listeners\ActivityListener@updatedInvoice',
'App\Listeners\InvoiceListener@updatedInvoice',
],
'App\Events\InvoiceWasArchived' => [
'App\Listeners\ActivityListener@archivedInvoice',
],
'App\Events\InvoiceWasDeleted' => [
'App\Listeners\ActivityListener@deletedInvoice',
'App\Listeners\TaskListener@deletedInvoice',
],
'App\Events\InvoiceWasRestored' => [
'App\Listeners\ActivityListener@restoredInvoice',
],
'App\Events\InvoiceWasEmailed' => [
'App\Listeners\NotificationListener@emailedInvoice',
'App\Listeners\InvoiceListener@emailedInvoice',
],
'App\Events\InvoiceInvitationWasEmailed' => [
'App\Listeners\ActivityListener@emailedInvoice',
],
'App\Events\InvoiceInvitationWasViewed' => [
'App\Listeners\ActivityListener@viewedInvoice',
'App\Listeners\NotificationListener@viewedInvoice',
'App\Listeners\InvoiceListener@viewedInvoice',
],
// Quotes
'App\Events\QuoteWasCreated' => [
'App\Listeners\ActivityListener@createdQuote',
'App\Listeners\SubscriptionListener@createdQuote',
],
'App\Events\QuoteWasUpdated' => [
'App\Listeners\ActivityListener@updatedQuote',
],
'App\Events\QuoteWasArchived' => [
'App\Listeners\ActivityListener@archivedQuote',
],
'App\Events\QuoteWasDeleted' => [
'App\Listeners\ActivityListener@deletedQuote',
],
'App\Events\QuoteWasRestored' => [
'App\Listeners\ActivityListener@restoredQuote',
],
'App\Events\QuoteWasEmailed' => [
'App\Listeners\QuoteListener@emailedQuote',
'App\Listeners\NotificationListener@emailedQuote',
],
'App\Events\QuoteInvitationWasEmailed' => [
'App\Listeners\ActivityListener@emailedQuote',
],
'App\Events\QuoteInvitationWasViewed' => [
'App\Listeners\ActivityListener@viewedQuote',
'App\Listeners\NotificationListener@viewedQuote',
'App\Listeners\QuoteListener@viewedQuote',
],
'App\Events\QuoteInvitationWasApproved' => [
'App\Listeners\ActivityListener@approvedQuote',
'App\Listeners\NotificationListener@approvedQuote',
],
// Payments
'App\Events\PaymentWasCreated' => [
'App\Listeners\ActivityListener@createdPayment',
'App\Listeners\SubscriptionListener@createdPayment',
'App\Listeners\InvoiceListener@createdPayment',
'App\Listeners\NotificationListener@createdPayment',
],
'App\Events\PaymentWasArchived' => [
'App\Listeners\ActivityListener@archivedPayment',
],
'App\Events\PaymentWasDeleted' => [
'App\Listeners\ActivityListener@deletedPayment',
'App\Listeners\InvoiceListener@deletedPayment',
'App\Listeners\CreditListener@deletedPayment',
],
'App\Events\PaymentWasRestored' => [
'App\Listeners\ActivityListener@restoredPayment',
],
// Credits
'App\Events\CreditWasCreated' => [
'App\Listeners\ActivityListener@createdCredit',
'App\Listeners\SubscriptionListener@createdCredit',
],
'App\Events\CreditWasArchived' => [
'App\Listeners\ActivityListener@archivedCredit',
],
'App\Events\CreditWasDeleted' => [
'App\Listeners\ActivityListener@deletedCredit',
],
'App\Events\CreditWasRestored' => [
'App\Listeners\ActivityListener@restoredCredit',
],
// User events
'App\Events\UserSignedUp' => [ 'App\Events\UserSignedUp' => [
'App\Listeners\HandleUserSignedUp', 'App\Listeners\HandleUserSignedUp',
], ],
@ -20,18 +137,7 @@ class EventServiceProvider extends ServiceProvider {
'App\Events\UserSettingsChanged' => [ 'App\Events\UserSettingsChanged' => [
'App\Listeners\HandleUserSettingsChanged', 'App\Listeners\HandleUserSettingsChanged',
], ],
'App\Events\InvoiceSent' => [
'App\Listeners\HandleInvoiceSent',
],
'App\Events\InvoiceViewed' => [
'App\Listeners\HandleInvoiceViewed',
],
'App\Events\InvoicePaid' => [
'App\Listeners\HandleInvoicePaid',
],
'App\Events\QuoteApproved' => [
'App\Listeners\HandleQuoteApproved',
],
]; ];
/** /**

View File

@ -0,0 +1,28 @@
<?php namespace App\Services;
use Illuminate\Foundation\Bus\DispatchesCommands;
class BaseService
{
use DispatchesCommands;
protected function getRepo()
{
return null;
}
public function bulk($ids, $action, $param = null)
{
if ( ! $ids) {
return 0;
}
$entities = $this->getRepo()->findByPublicIdsWithTrashed($ids);
foreach ($entities as $entity) {
$this->getRepo()->$action($entity, $param);
}
return count($entities);
}
}

View File

@ -0,0 +1,25 @@
<?php namespace App\Services;
use App\Services\BaseService;
use App\Ninja\Repositories\ClientRepository;
class ClientService extends BaseService
{
protected $clientRepo;
public function __construct(ClientRepository $clientRepo)
{
$this->clientRepo = $clientRepo;
}
protected function getRepo()
{
return $this->clientRepo;
}
public function save($data)
{
return $this->clientRepo->save($data);
}
}

View File

@ -0,0 +1,25 @@
<?php namespace App\Services;
use App\Services\BaseService;
use App\Ninja\Repositories\CreditRepository;
class CreditService extends BaseService
{
protected $creditRepo;
public function __construct(CreditRepository $creditRepo)
{
$this->creditRepo = $creditRepo;
}
protected function getRepo()
{
return $this->creditRepo;
}
public function save($data)
{
return $this->creditRepo->save($data);
}
}

View File

@ -0,0 +1,81 @@
<?php namespace App\Services;
use App\Services\BaseService;
use App\Ninja\Repositories\InvoiceRepository;
use App\Ninja\Repositories\ClientRepository;
use App\Events\QuoteInvitationWasApproved;
use App\Models\Invitation;
class InvoiceService extends BaseService
{
protected $clientRepo;
protected $invoiceRepo;
public function __construct(ClientRepository $clientRepo, InvoiceRepository $invoiceRepo)
{
$this->clientRepo = $clientRepo;
$this->invoiceRepo = $invoiceRepo;
}
protected function getRepo()
{
return $this->invoiceRepo;
}
public function save($data)
{
if (isset($data['client'])) {
$client = $this->clientRepo->save($data['client']);
$data['client_id'] = $client->id;
}
$invoice = $this->invoiceRepo->save($data);
$client = $invoice->client;
$client->load('contacts');
$sendInvoiceIds = [];
foreach ($client->contacts as $contact) {
if ($contact->send_invoice || count($client->contacts) == 1) {
$sendInvoiceIds[] = $contact->id;
}
}
foreach ($client->contacts as $contact) {
$invitation = Invitation::scope()->whereContactId($contact->id)->whereInvoiceId($invoice->id)->first();
if (in_array($contact->id, $sendInvoiceIds) && !$invitation) {
$invitation = Invitation::createNew();
$invitation->invoice_id = $invoice->id;
$invitation->contact_id = $contact->id;
$invitation->invitation_key = str_random(RANDOM_KEY_LENGTH);
$invitation->save();
} elseif (!in_array($contact->id, $sendInvoiceIds) && $invitation) {
$invitation->delete();
}
}
return $invoice;
}
public function approveQuote($quote, $invitation = null)
{
if (!$quote->is_quote || $quote->quote_invoice_id) {
return null;
}
$invoice = $this->invoiceRepo->cloneInvoice($quote, $quote->id);
if (!$invitation) {
return $invoice;
}
event(new QuoteInvitationWasApproved($invoice, $invitation));
foreach ($invoice->invitations as $invoiceInvitation) {
if ($invitation->contact_id == $invoiceInvitation->contact_id) {
return $invoiceInvitation->invitation_key;
}
}
}
}

View File

@ -10,18 +10,26 @@ use App\Models\Payment;
use App\Models\Account; use App\Models\Account;
use App\Models\Country; use App\Models\Country;
use App\Models\AccountGatewayToken; use App\Models\AccountGatewayToken;
use App\Ninja\Repositories\PaymentRepository;
use App\Ninja\Repositories\AccountRepository; use App\Ninja\Repositories\AccountRepository;
use App\Events\InvoicePaid; use App\Services\BaseService;
use App\Events\PaymentWasCreated;
class PaymentService {
class PaymentService extends BaseService
{
public $lastError; public $lastError;
public function __construct(AccountRepository $accountRepo) public function __construct(PaymentRepository $paymentRepo, AccountRepository $accountRepo)
{ {
$this->paymentRepo = $paymentRepo;
$this->accountRepo = $accountRepo; $this->accountRepo = $accountRepo;
} }
protected function getRepo()
{
return $this->paymentRepo;
}
public function createGateway($accountGateway) public function createGateway($accountGateway)
{ {
$gateway = Omnipay::create($accountGateway->gateway->provider); $gateway = Omnipay::create($accountGateway->gateway->provider);
@ -208,8 +216,6 @@ class PaymentService {
$payment->save(); $payment->save();
Event::fire(new InvoicePaid($payment));
return $payment; return $payment;
} }

View File

@ -0,0 +1,51 @@
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use App\Models\Activity;
class AddIsSystemToActivities extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('activities', function($table)
{
$table->boolean('is_system')->default(0);
});
$activities = Activity::where('message', 'like', '%<i>System</i>%')->get();
foreach ($activities as $activity) {
$activity->is_system = true;
$activity->save();
}
Schema::table('activities', function($table)
{
$table->dropColumn('message');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('activities', function($table)
{
$table->dropColumn('is_system');
});
Schema::table('activities', function($table)
{
$table->text('message')->nullable();
});
}
}

View File

@ -826,5 +826,62 @@
'no_longer_running' => 'This invoice is not scheduled to run', 'no_longer_running' => 'This invoice is not scheduled to run',
'general_settings' => 'General Settings', 'general_settings' => 'General Settings',
'customize' => 'Customize', 'customize' => 'Customize',
'oneclick_login_help' => 'Connect an account to login without a password',
'referral_code_help' => 'Earn money by sharing our app online',
'enable_with_stripe' => 'Enable | Requires Stripe',
'tax_settings' => 'Tax Settings',
'create_tax_rate' => 'Add Tax Rate',
'updated_tax_rate' => 'Successfully updated tax rate',
'created_tax_rate' => 'Successfully created tax rate',
'edit_tax_rate' => 'Edit tax rate',
'archive_tax_rate' => 'Archive tax rate',
'archived_tax_rate' => 'Successfully archived the tax rate',
'default_tax_rate_id' => 'Default Tax Rate',
'tax_rate' => 'Tax Rate',
'recurring_hour' => 'Recurring Hour',
'pattern' => 'Pattern',
'pattern_help_title' => 'Pattern Help',
'pattern_help_1' => 'Create custom invoice and quote numbers by specifying a pattern',
'pattern_help_2' => 'Available variables:',
'pattern_help_3' => 'For example, :example would be converted to :value',
'see_options' => 'See options',
'invoice_counter' => 'Invoice Counter',
'quote_counter' => 'Quote Counter',
'type' => 'Type',
'activity_1' => ':user created client :client',
'activity_2' => ':user archived client :client',
'activity_3' => ':user deleted client :client',
'activity_4' => ':user created invoice :invoice',
'activity_5' => ':user updated invoice :invoice',
'activity_6' => ':user emailed invoice :invoice to :contact',
'activity_7' => ':contact viewed invoice :invoice',
'activity_8' => ':user archived invoice :invoice',
'activity_9' => ':user deleted invoice :invoice',
'activity_10' => ':contact entered payment :payment for :invoice',
'activity_11' => ':user updated payment :payment',
'activity_12' => ':user archived payment :payment',
'activity_13' => ':user deleted payment :payment',
'activity_14' => ':user entered :credit credit',
'activity_15' => ':user updated :credit credit',
'activity_16' => ':user archived :credit credit',
'activity_17' => ':user deleted :credit credit',
'activity_18' => ':user created quote :quote',
'activity_19' => ':user updated quote :quote',
'activity_20' => ':user emailed quote :quote to :contact',
'activity_21' => ':contact viewed quote :quote',
'activity_22' => ':user archived quote :quote',
'activity_23' => ':user deleted quote :quote',
'activity_24' => ':user restored quote :quote',
'activity_25' => ':user restored invoice :invoice',
'activity_26' => ':user restored client :client',
'activity_27' => ':user restored payment :payment',
'activity_28' => ':user restored :credit credit',
'activity_29' => ':contact approved quote :quote',
'payment' => 'Payment',
'system' => 'System',
); );

View File

@ -841,4 +841,48 @@ return array(
'default_tax_rate_id' => 'Standard Steuersatz', 'default_tax_rate_id' => 'Standard Steuersatz',
'tax_rate' => 'Steuersatz', 'tax_rate' => 'Steuersatz',
'recurring_hour' => 'Recurring Hour',
'pattern' => 'Pattern',
'pattern_help_title' => 'Pattern Help',
'pattern_help_1' => 'Create custom invoice and quote numbers by specifying a pattern',
'pattern_help_2' => 'Available variables:',
'pattern_help_3' => 'For example, :example would be converted to :value',
'see_options' => 'See options',
'invoice_counter' => 'Invoice Counter',
'quote_counter' => 'Quote Counter',
'type' => 'Type',
'activity_1' => ':user created client :client',
'activity_2' => ':user archived client :client',
'activity_3' => ':user deleted client :client',
'activity_4' => ':user created invoice :invoice',
'activity_5' => ':user updated invoice :invoice',
'activity_6' => ':user emailed invoice :invoice to :contact',
'activity_7' => ':contact viewed invoice :invoice',
'activity_8' => ':user archived invoice :invoice',
'activity_9' => ':user deleted invoice :invoice',
'activity_10' => ':contact entered payment :payment for :invoice',
'activity_11' => ':user updated payment :payment',
'activity_12' => ':user archived payment :payment',
'activity_13' => ':user deleted payment :payment',
'activity_14' => ':user entered :credit credit',
'activity_15' => ':user updated :credit credit',
'activity_16' => ':user archived :credit credit',
'activity_17' => ':user deleted :credit credit',
'activity_18' => ':user created quote :quote',
'activity_19' => ':user updated quote :quote',
'activity_20' => ':user emailed quote :quote to :contact',
'activity_21' => ':contact viewed quote :quote',
'activity_22' => ':user archived quote :quote',
'activity_23' => ':user deleted quote :quote',
'activity_24' => ':user restored quote :quote',
'activity_25' => ':user restored invoice :invoice',
'activity_26' => ':user restored client :client',
'activity_27' => ':user restored payment :payment',
'activity_28' => ':user restored :credit credit',
'activity_29' => ':contact approved quote :quote',
'payment' => 'Payment',
'system' => 'System',
); );

View File

@ -852,4 +852,38 @@ return array(
'quote_counter' => 'Quote Counter', 'quote_counter' => 'Quote Counter',
'type' => 'Type', 'type' => 'Type',
'activity_1' => ':user created client :client',
'activity_2' => ':user archived client :client',
'activity_3' => ':user deleted client :client',
'activity_4' => ':user created invoice :invoice',
'activity_5' => ':user updated invoice :invoice',
'activity_6' => ':user emailed invoice :invoice to :contact',
'activity_7' => ':contact viewed invoice :invoice',
'activity_8' => ':user archived invoice :invoice',
'activity_9' => ':user deleted invoice :invoice',
'activity_10' => ':contact entered payment :payment for :invoice',
'activity_11' => ':user updated payment :payment',
'activity_12' => ':user archived payment :payment',
'activity_13' => ':user deleted payment :payment',
'activity_14' => ':user entered :credit credit',
'activity_15' => ':user updated :credit credit',
'activity_16' => ':user archived :credit credit',
'activity_17' => ':user deleted :credit credit',
'activity_18' => ':user created quote :quote',
'activity_19' => ':user updated quote :quote',
'activity_20' => ':user emailed quote :quote to :contact',
'activity_21' => ':contact viewed quote :quote',
'activity_22' => ':user archived quote :quote',
'activity_23' => ':user deleted quote :quote',
'activity_24' => ':user restored quote :quote',
'activity_25' => ':user restored invoice :invoice',
'activity_26' => ':user restored client :client',
'activity_27' => ':user restored payment :payment',
'activity_28' => ':user restored :credit credit',
'activity_29' => ':contact approved quote :quote',
'payment' => 'Payment',
'system' => 'System',
); );

View File

@ -74,6 +74,7 @@ return array(
"notmasked" => "The values are masked", "notmasked" => "The values are masked",
"less_than" => 'The :attribute must be less than :value', "less_than" => 'The :attribute must be less than :value',
"has_counter" => 'The value must contain {$counter}', "has_counter" => 'The value must contain {$counter}',
"valid_contacts" => 'All of the contacts must have either an email or name',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------

View File

@ -804,6 +804,62 @@ return array(
'no_longer_running' => 'This invoice is not scheduled to run', 'no_longer_running' => 'This invoice is not scheduled to run',
'general_settings' => 'General Settings', 'general_settings' => 'General Settings',
'customize' => 'Customize', 'customize' => 'Customize',
'oneclick_login_help' => 'Connect an account to login without a password',
'referral_code_help' => 'Earn money by sharing our app online',
'enable_with_stripe' => 'Enable | Requires Stripe',
'tax_settings' => 'Tax Settings',
'create_tax_rate' => 'Add Tax Rate',
'updated_tax_rate' => 'Successfully updated tax rate',
'created_tax_rate' => 'Successfully created tax rate',
'edit_tax_rate' => 'Edit tax rate',
'archive_tax_rate' => 'Archive tax rate',
'archived_tax_rate' => 'Successfully archived the tax rate',
'default_tax_rate_id' => 'Default Tax Rate',
'tax_rate' => 'Tax Rate',
'recurring_hour' => 'Recurring Hour',
'pattern' => 'Pattern',
'pattern_help_title' => 'Pattern Help',
'pattern_help_1' => 'Create custom invoice and quote numbers by specifying a pattern',
'pattern_help_2' => 'Available variables:',
'pattern_help_3' => 'For example, :example would be converted to :value',
'see_options' => 'See options',
'invoice_counter' => 'Invoice Counter',
'quote_counter' => 'Quote Counter',
'type' => 'Type',
'activity_1' => ':user created client :client',
'activity_2' => ':user archived client :client',
'activity_3' => ':user deleted client :client',
'activity_4' => ':user created invoice :invoice',
'activity_5' => ':user updated invoice :invoice',
'activity_6' => ':user emailed invoice :invoice to :contact',
'activity_7' => ':contact viewed invoice :invoice',
'activity_8' => ':user archived invoice :invoice',
'activity_9' => ':user deleted invoice :invoice',
'activity_10' => ':contact entered payment :payment for :invoice',
'activity_11' => ':user updated payment :payment',
'activity_12' => ':user archived payment :payment',
'activity_13' => ':user deleted payment :payment',
'activity_14' => ':user entered :credit credit',
'activity_15' => ':user updated :credit credit',
'activity_16' => ':user archived :credit credit',
'activity_17' => ':user deleted :credit credit',
'activity_18' => ':user created quote :quote',
'activity_19' => ':user updated quote :quote',
'activity_20' => ':user emailed quote :quote to :contact',
'activity_21' => ':contact viewed quote :quote',
'activity_22' => ':user archived quote :quote',
'activity_23' => ':user deleted quote :quote',
'activity_24' => ':user restored quote :quote',
'activity_25' => ':user restored invoice :invoice',
'activity_26' => ':user restored client :client',
'activity_27' => ':user restored payment :payment',
'activity_28' => ':user restored :credit credit',
'activity_29' => ':contact approved quote :quote',
'payment' => 'Payment',
'system' => 'System',
); );

View File

@ -825,5 +825,61 @@ return array(
'no_longer_running' => 'This invoice is not scheduled to run', 'no_longer_running' => 'This invoice is not scheduled to run',
'general_settings' => 'General Settings', 'general_settings' => 'General Settings',
'customize' => 'Customize', 'customize' => 'Customize',
'oneclick_login_help' => 'Connect an account to login without a password',
'referral_code_help' => 'Earn money by sharing our app online',
'enable_with_stripe' => 'Enable | Requires Stripe',
'tax_settings' => 'Tax Settings',
'create_tax_rate' => 'Add Tax Rate',
'updated_tax_rate' => 'Successfully updated tax rate',
'created_tax_rate' => 'Successfully created tax rate',
'edit_tax_rate' => 'Edit tax rate',
'archive_tax_rate' => 'Archive tax rate',
'archived_tax_rate' => 'Successfully archived the tax rate',
'default_tax_rate_id' => 'Default Tax Rate',
'tax_rate' => 'Tax Rate',
'recurring_hour' => 'Recurring Hour',
'pattern' => 'Pattern',
'pattern_help_title' => 'Pattern Help',
'pattern_help_1' => 'Create custom invoice and quote numbers by specifying a pattern',
'pattern_help_2' => 'Available variables:',
'pattern_help_3' => 'For example, :example would be converted to :value',
'see_options' => 'See options',
'invoice_counter' => 'Invoice Counter',
'quote_counter' => 'Quote Counter',
'type' => 'Type',
'activity_1' => ':user created client :client',
'activity_2' => ':user archived client :client',
'activity_3' => ':user deleted client :client',
'activity_4' => ':user created invoice :invoice',
'activity_5' => ':user updated invoice :invoice',
'activity_6' => ':user emailed invoice :invoice to :contact',
'activity_7' => ':contact viewed invoice :invoice',
'activity_8' => ':user archived invoice :invoice',
'activity_9' => ':user deleted invoice :invoice',
'activity_10' => ':contact entered payment :payment for :invoice',
'activity_11' => ':user updated payment :payment',
'activity_12' => ':user archived payment :payment',
'activity_13' => ':user deleted payment :payment',
'activity_14' => ':user entered :credit credit',
'activity_15' => ':user updated :credit credit',
'activity_16' => ':user archived :credit credit',
'activity_17' => ':user deleted :credit credit',
'activity_18' => ':user created quote :quote',
'activity_19' => ':user updated quote :quote',
'activity_20' => ':user emailed quote :quote to :contact',
'activity_21' => ':contact viewed quote :quote',
'activity_22' => ':user archived quote :quote',
'activity_23' => ':user deleted quote :quote',
'activity_24' => ':user restored quote :quote',
'activity_25' => ':user restored invoice :invoice',
'activity_26' => ':user restored client :client',
'activity_27' => ':user restored payment :payment',
'activity_28' => ':user restored :credit credit',
'activity_29' => ':contact approved quote :quote',
'payment' => 'Payment',
'system' => 'System',
); );

Some files were not shown because too many files have changed in this diff Show More