Permalink
Browse files

Use save event to auto-attach invoices and time entries

  • Loading branch information...
lovett committed Dec 14, 2016
1 parent 62e4ce5 commit 3d2bf0a644c2a15950ec0f04b914b7229bf9b0a3
Showing with 55 additions and 1 deletion.
  1. +15 −0 app/Invoice.php
  2. +12 −0 app/Providers/EventServiceProvider.php
  3. +27 −0 app/Time.php
  4. +1 −1 database/seeds/FakeSeeder.php
View
@@ -10,6 +10,8 @@
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use App\Traits\Search;
use App\Time;
use Illuminate\Support\Facades\DB;
/**
* Eloquent model for the invoices table.
@@ -119,5 +121,18 @@ public function client()
return $this->project()->with('client');
}
public function attachTime()
{
DB::beginTransaction();
$this->times()->update(['invoice_id' => null]);
$times = Time::whereBetween('start', [$this->start, $this->end]);
$times->where('project_id', $this->project_id);
$times->whereNull('invoice_id');
$times->update(['invoice_id' => $this->getKey()]);
DB::commit();
}
}
@@ -5,6 +5,8 @@
use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider
as ServiceProvider;
use App\Invoice;
use App\Time;
/**
* Standard Laravel event service provider class.
@@ -28,5 +30,15 @@ class EventServiceProvider extends ServiceProvider
public function boot(DispatcherContract $events)
{
parent::boot($events);
Time::saved(function ($model) {
$model->attachInvoice();
return true;
});
Invoice::saved(function ($model) {
$model->attachTime();
return true;
});
}
}
View
@@ -9,6 +9,7 @@
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Traits\Search;
use App\Invoice;
/**
* Eloquent model for the times table.
@@ -99,6 +100,17 @@ public function project()
return $this->belongsTo('App\Project');
}
/**
* Invoice associated with the time entry.
*
* @return HasOne
*/
public function invoice()
{
return $this->belongsTo('App\Invoice');
}
/**
* Custom accessor to set default value for start date.
*
@@ -234,4 +246,19 @@ function ($accumulator, $item) {
return $result;
}
public function attachInvoice()
{
DB::beginTransaction();
$this->invoice()->dissociate();
$invoice = Invoice::where('start', '>=', $this->start);
$invoice->where('end', '<=', $this->start);
$invoice->where('project_id', $this->project_id);
$this->invoice()->associate($invoice->first());
DB::commit();
}
}
@@ -24,7 +24,7 @@ class FakeSeeder extends Seeder
public function run()
{
$faker = FakerFactory::create();
$maxUserId = 10;
$maxUserId = 3;
Model::unguard();

0 comments on commit 3d2bf0a

Please sign in to comment.