diff --git a/app/Invoice/Actions/MassStoreAction.php b/app/Invoice/Actions/MassStoreAction.php index dc0d2555..7176fc88 100644 --- a/app/Invoice/Actions/MassStoreAction.php +++ b/app/Invoice/Actions/MassStoreAction.php @@ -35,20 +35,12 @@ class MassStoreAction $memberGroup = Member::payable()->get() ->groupBy(fn ($member) => "{$member->bill_kind->value}{$member->lastname}{$member->address}{$member->zip}{$member->location}"); + foreach ($memberGroup as $members) { - $invoice = Invoice::createForMember($members->first()); - - foreach ($members as $member) { - foreach ($member->subscription->children as $child) { - $invoice->positions()->create([ - 'description' => str($child->name)->replace('{name}', $member->firstname . ' ' . $member->lastname)->replace('{year}', (string) $year), - 'price' => $child->amount, - 'member_id' => $member->id, - ]); - } - } - - $invoices->push($invoice); + $invoice = Invoice::createForMember($members->first(), $members, $year); + $invoice->save(); + $invoice->positions()->createMany($invoice->positions); + $invoices->push($invoice->fresh('positions')); } event(new InvoicesMassStored($year, $invoices)); diff --git a/app/Invoice/Models/Invoice.php b/app/Invoice/Models/Invoice.php index bec47aa3..3f731fd4 100644 --- a/app/Invoice/Models/Invoice.php +++ b/app/Invoice/Models/Invoice.php @@ -9,6 +9,7 @@ use App\Invoice\InvoiceDocument; use App\Invoice\RememberDocument; use App\Member\Member; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; @@ -40,9 +41,12 @@ class Invoice extends Model return $this->hasMany(InvoicePosition::class); } - public static function createForMember(Member $member): self + /** + * @param Collection $members + */ + public static function createForMember(Member $member, Collection $members, int $year): self { - return static::create([ + $invoice = new static([ 'to' => [ 'name' => 'Familie ' . $member->lastname, 'address' => $member->address, @@ -55,6 +59,20 @@ class Invoice extends Model 'usage' => 'Mitgliedsbeitrag für ' . $member->lastname, 'mail_email' => $member->email_parents ?: $member->email, ]); + + $positions = collect([]); + foreach ($members as $member) { + foreach ($member->subscription->children as $child) { + $positions->push([ + 'description' => str($child->name)->replace('{name}', $member->firstname . ' ' . $member->lastname)->replace('{year}', (string) $year), + 'price' => $child->amount, + 'member_id' => $member->id, + ]); + } + } + $invoice->setRelation('positions', $positions); + + return $invoice; } public static function booted(): void