12 Commits
Author SHA1 Message Date
th.guenther 91dca31c11 Prepared new version 2026-09-07 14:18:19 +02:00
th.guenther 40d5634764 Zahlungszwecke 2026-09-07 14:17:50 +02:00
th.guenther 350c8dd0d0 better handling payment purpose 2026-09-07 12:10:12 +02:00
th.guenther d07980dd1f Overview for refunds 2026-09-07 10:45:33 +02:00
th.guenther b9795f08f0 Besseres Handling Rückerstattungen 2026-09-06 20:11:50 +02:00
th.guenther e730d6db63 Korrektur Buchungstexte bei Auslagenerstattungen 2026-09-06 16:48:33 +02:00
th.guenther a6bddf9fa5 Merge pull request 'Dev 4.8.0' (#15) from dev-4.8.0 into main
Teili-Rechnungen
Teili-Rückerstattungen
EüR
2026-09-04 09:29:56 +02:00
th.guenther 749d8588da Prepared new versio 2026-09-04 09:28:13 +02:00
th.guenther 4bb64b0053 Code improvements 2026-09-04 09:27:48 +02:00
th.guenther d23e6c3914 Abrechnungsgrüne nun immer erforderlich 2026-09-04 02:11:43 +02:00
th.guenther 15690b1da9 Abrechnungsgründe nun immer erforderlich 2026-09-04 02:11:10 +02:00
th.guenther c1c1a4f143 Calculation errors for refunded amounts 2026-09-04 01:15:37 +02:00
127 changed files with 35766 additions and 416 deletions
+29010
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -23,7 +23,7 @@ class UserDetailGetController extends CommonController
return response()->json([ return response()->json([
'user' => $userData, 'user' => $userData,
'isOwnUser' => auth()->id() === $user->id, 'isOwnUser' => currentUser()?->id === $user->id,
'isLvTenant' => $this->tenant->slug === 'lv', 'isLvTenant' => $this->tenant->slug === 'lv',
'userRoles' => UserRole::all()->map(fn($role) => ['slug' => $role->slug, 'name' => $role->name]), 'userRoles' => UserRole::all()->map(fn($role) => ['slug' => $role->slug, 'name' => $role->name]),
'localGroups' => $this->adminTenants->getActiveLocalGroups()->map(fn($t) => ['slug' => $t->slug, 'name' => $t->name]), 'localGroups' => $this->adminTenants->getActiveLocalGroups()->map(fn($t) => ['slug' => $t->slug, 'name' => $t->name]),
@@ -16,7 +16,7 @@ class UserToggleActiveController extends CommonController
$action = new ToggleUserActiveAction(new ToggleUserActiveRequest( $action = new ToggleUserActiveAction(new ToggleUserActiveRequest(
user: $user, user: $user,
currentUserId: auth()->id(), currentUserId: currentUser()?->id,
)); ));
$response = $action->execute(); $response = $action->execute();
@@ -17,7 +17,7 @@ class UserUpdateController extends CommonController
$action = new UpdateUserAction(new UpdateUserRequest( $action = new UpdateUserAction(new UpdateUserRequest(
user: $user, user: $user,
data: $request->all(), data: $request->all(),
isOwnUser: auth()->id() === $user->id, isOwnUser: currentUser()?->id === $user->id,
isLvTenant: $this->tenant->slug === 'lv', isLvTenant: $this->tenant->slug === 'lv',
)); ));
@@ -25,7 +25,7 @@ class CreateEstimateAction {
if ($this->request->estimateId === 0) { if ($this->request->estimateId === 0) {
$estimate = CostUnitEstimate::create(array_merge([ $estimate = CostUnitEstimate::create(array_merge([
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
'cost_unit_id' => $this->request->costUnit->id, 'cost_unit_id' => $this->request->costUnit->id,
'type' => $this->request->estimateType, 'type' => $this->request->estimateType,
'description' => $this->request->description, 'description' => $this->request->description,
@@ -33,7 +33,7 @@ class CreateEstimateAction {
} else { } else {
$estimate = CostUnitEstimate::find($this->request->estimateId); $estimate = CostUnitEstimate::find($this->request->estimateId);
$estimate->update(array_merge([ $estimate->update(array_merge([
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
'cost_unit_id' => $this->request->costUnit->id, 'cost_unit_id' => $this->request->costUnit->id,
'type' => $this->request->estimateType, 'type' => $this->request->estimateType,
'description' => $this->request->description, 'description' => $this->request->description,
@@ -15,7 +15,7 @@ class CreateCostUnitCommand {
$response = new CreateCostUnitResponse(); $response = new CreateCostUnitResponse();
$costUnit = CostUnit::create([ $costUnit = CostUnit::create([
'name' => $this->request->name, 'name' => $this->request->name,
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
'type' => $this->request->type, 'type' => $this->request->type,
'billing_deadline' => $this->request->billingDeadline, 'billing_deadline' => $this->request->billingDeadline,
'distance_allowance' => $this->request->distanceAllowance->getAmount(), 'distance_allowance' => $this->request->distanceAllowance->getAmount(),
@@ -93,7 +93,7 @@ class ExportController extends CommonController {
'amount' => $invoice->amount, 'amount' => $invoice->amount,
'recipient_name' => $invoice->contact_bank_owner, 'recipient_name' => $invoice->contact_bank_owner,
'recipient_iban' => $invoice->contact_bank_iban, 'recipient_iban' => $invoice->contact_bank_iban,
'payment_purpose' => $invoice->payment_purpose ?? 'Auslagenerstattung Rechnungsnummer ' . $invoice->invoice_number, 'payment_purpose' => $invoice->paymentPurposeText(),
]); ]);
} }
} }
@@ -89,12 +89,13 @@
<template> <template>
<table v-if="localData.invoices.length > 0" class="invoice-list-table"> <table v-if="localData.invoices.length > 0" class="invoice-list-table">
<tr> <tr>
<td colspan="6">{{props.data.costUnit.name}}</td> <td colspan="7">{{props.data.costUnit.name}}</td>
</tr> </tr>
<tr v-for="invoice in localData.invoices" :id="'invoice_' + invoice.id"> <tr v-for="invoice in localData.invoices" :id="'invoice_' + invoice.id">
<td>{{invoice.invoiceNumber}}</td> <td>{{invoice.invoiceNumber}}</td>
<td>{{invoice.invoiceType}}</td> <td>{{invoice.invoiceTypeShort}}</td>
<td style="max-width: 250px;">{{invoice.purpose}}</td>
<td> <td>
{{invoice.amount}} {{invoice.amount}}
</td> </td>
@@ -114,7 +115,7 @@
</tr> </tr>
<tr v-if="props.data.endpoint === 'approved'"> <tr v-if="props.data.endpoint === 'approved'">
<td colspan="5"></td> <td colspan="6"></td>
<td> <td>
<a style="font-size: 10pt;" class="link" @click="exportPayouts()">Genehmigte Abrechnungen exportieren</a> <a style="font-size: 10pt;" class="link" @click="exportPayouts()">Genehmigte Abrechnungen exportieren</a>
</td> </td>
@@ -13,7 +13,7 @@ class PersonalDataController extends CommonController
return redirect()->intended('/login'); return redirect()->intended('/login');
} }
$user = auth()->user(); $user = currentUser();
$data = $this->users->getPersonalData($user); $data = $this->users->getPersonalData($user);
$inertiaProvider = new InertiaProvider('Dashboard/PersonalData', [ $inertiaProvider = new InertiaProvider('Dashboard/PersonalData', [
@@ -12,7 +12,7 @@ class StorePersonalDataController extends CommonController
{ {
public function __invoke(Request $request): JsonResponse public function __invoke(Request $request): JsonResponse
{ {
$user = auth()->user(); $user = currentUser();
$actionRequest = new UpdatePersonalDataRequest( $actionRequest = new UpdatePersonalDataRequest(
user: $user, user: $user,
@@ -28,7 +28,7 @@ class CreateEventCommand {
} }
$tenant = app('tenant'); $tenant = currentTenant();
// Anlage als Ganzes: der Event-Teil der Rechnungsnummer wird unter der Sperre vergeben und muss // Anlage als Ganzes: der Event-Teil der Rechnungsnummer wird unter der Sperre vergeben und muss
// im selben Zug geschrieben werden, sonst könnten zwei gleichzeitige Anlagen denselben erhalten. // im selben Zug geschrieben werden, sonst könnten zwei gleichzeitige Anlagen denselben erhalten.
@@ -91,12 +91,12 @@ class CreateEventCommand {
]); ]);
} }
if (app('tenant')->slug === 'lv') { if (currentTenant()->slug === 'lv') {
foreach(Tenant::where(['is_active_local_group' => true])->get() as $tenant) { foreach(Tenant::where(['is_active_local_group' => true])->get() as $tenant) {
EventLocalGroups::create(['event_id' => $event->id, 'local_group_id' => $tenant->id]); EventLocalGroups::create(['event_id' => $event->id, 'local_group_id' => $tenant->id]);
} }
} else { } else {
EventLocalGroups::create(['event_id' => $event->id, 'local_group_id' => app('tenant')->id]); EventLocalGroups::create(['event_id' => $event->id, 'local_group_id' => currentTenant()->id]);
} }
@@ -0,0 +1,205 @@
<?php
namespace App\Domains\Event\Actions\CreateIncomeSurplusStatement;
use App\Enumerations\ParticipationType;
use App\Models\CostUnit;
use App\Models\Event;
use App\Providers\PdfGenerateAndDownloadProvider;
use App\Repositories\CostUnitRepository;
use App\ValueObjects\Amount;
use Illuminate\Http\Request;
/**
* Erzeugt die Einnahmen-Überschuss-Rechnung einer Veranstaltung als PDF.
*
* Gezeigt wird ausschließlich Geld, das geflossen ist: gezahlte Beiträge, weitere Einnahmen, was von
* Abmeldungen einbehalten wurde, Fördermittel -- und auf der anderen Seite die erfassten Belege. Was nur
* erwartet (offene Beiträge) oder geplant (Budgetwerte) ist, gehört in eine Einnahmen-Überschuss-Rechnung
* nicht hinein.
*
* Es wird nichts gespeichert: Alle Zahlen leiten sich aus dem aktuellen Stand ab, ein erneuter Abruf
* liefert den dann gültigen Stand.
*/
class CreateIncomeSurplusStatementCommand
{
private Event $event;
private CostUnitRepository $costUnits;
public function __construct(private readonly CreateIncomeSurplusStatementRequest $request)
{
$this->event = $request->event;
$this->costUnits = new CostUnitRepository();
}
public function execute(): CreateIncomeSurplusStatementResponse
{
$response = new CreateIncomeSurplusStatementResponse();
$costUnit = $this->event->costUnit()->first();
if (!$costUnit instanceof CostUnit) {
$response->message = 'Der Veranstaltung ist keine Kostenstelle zugeordnet.';
return $response;
}
// Der Pauschalbetrag wird vor dem Resource-Aufruf gelesen: `EventResource::calculateSupportPerPerson()`
// multipliziert das Amount-Objekt von `support_per_person` in place. Auf `support_flat` wirkt das
// zwar nicht, aber der gesamte Zugriff auf Beträge des Models ist danach nicht mehr vertrauenswürdig.
$otherIncome = $this->event->support_flat->getAmount();
$eventData = $this->event->toResource()->toArray(new Request());
$income = $this->buildIncome($eventData, $otherIncome);
$expenses = $this->buildExpenses($costUnit);
$result = new Amount($income['total']->getAmount() - $expenses['total']->getAmount(), 'Euro');
$html = view('pdfs.income-surplus-statement', [
'event' => $this->event,
'createdAt' => new \DateTime()->format('d.m.Y'),
'income' => $income,
'expenses' => $expenses,
'result' => $result,
'money' => self::money(...),
])->render();
$response->success = true;
$response->filename = 'EUER-' . $this->event->identifier . '.pdf';
$response->income = $income;
$response->expenses = $expenses;
$response->result = $result;
$response->pdfContent = PdfGenerateAndDownloadProvider::fromHtml($html, 'portrait');
return $response;
}
/**
* Die Einnahmenseite in zwei Ober-Kategorien.
*
* Alle Zahlen stammen aus {@see \App\Resources\EventResource} -- derselben Quelle wie die
* Veranstaltungsübersicht am Bildschirm. Eine eigene Rechnung daneben würde über kurz oder lang von
* der Übersicht abweichen, und dann glaubt niemand mehr einer der beiden Zahlen.
*
* @param array<string, mixed> $eventData
*
* @return array{categories: array<int, array{name: string, total: Amount, entries: array<int, array{name: string, amount: Amount}>}>, total: Amount}
*/
private function buildIncome(array $eventData, float $otherIncome): array
{
// Beiträge aller Teilnahmearten in einer Zeile: Für die Mittelverwendung zählt, was an Beiträgen
// hereingekommen ist, nicht von wem.
$participationFees = new Amount(0, 'Euro');
foreach ([
ParticipationType::PARTICIPATION_TYPE_PARTICIPANT,
ParticipationType::PARTICIPATION_TYPE_TEAM,
ParticipationType::PARTICIPATION_TYPE_VOLUNTEER,
ParticipationType::PARTICIPATION_TYPE_OTHER,
] as $participationType) {
$participationFees->addAmount(
new Amount((float) $eventData['participants'][$participationType]['amount']['paid']['value'], 'Euro')
);
}
$ownFunds = [
['name' => 'Teilnahmebeiträge', 'amount' => $participationFees],
['name' => 'Weitere Einnahmen', 'amount' => new Amount($otherIncome, 'Euro')],
[
'name' => 'Einbehaltene Einnahmen aus Abmeldungen',
'amount' => new Amount((float) $eventData['retainedFromUnregistered']['value'], 'Euro'),
],
];
$supportRate = new Amount((float) $eventData['supportPersonValue'], 'Euro');
$funding = [
[
'name' => 'Fördermittel (' . self::money($supportRate) . ' € p.P./Tag)',
'amount' => new Amount($eventData['supportPerson']['amount']->getAmount(), 'Euro'),
],
];
$categories = [
['name' => 'Eigenmittel', 'entries' => $ownFunds, 'total' => self::sum($ownFunds)],
['name' => 'Förderungen', 'entries' => $funding, 'total' => self::sum($funding)],
];
return [
'categories' => $categories,
'total' => self::sum($categories),
];
}
/**
* Die Ausgabenseite: eine Zeile je Ausgabentyp, dazu die Belege für die Anlage.
*
* @return array{groups: array<int, array{name: string, sum: Amount, rows: array<int, array{number: string, date: string, purpose: string, amount: Amount}>}>, total: Amount}
*/
private function buildExpenses(CostUnit $costUnit): array
{
$groups = [];
$total = new Amount(0, 'Euro');
foreach ($this->costUnits->groupExpensesByType($costUnit) as $group) {
$rows = [];
foreach ($group['invoices'] as $invoice) {
$rows[] = [
'number' => (string) $invoice->invoice_number,
'date' => $invoice->created_at?->format('d.m.Y') ?? '',
// Ohne die Anmerkung: dort steht, was die Kassenwart*in beim Korrigieren notiert hat,
// und das gehört auf den Beleg, nicht in den Zweck.
'purpose' => $invoice->purposeText(),
'amount' => Amount::fromString($invoice->amount),
];
}
$groups[] = [
'name' => $group['type']->name,
'sum' => $group['sum'],
'rows' => $rows,
];
$total->addAmount($group['sum']);
}
return ['groups' => $groups, 'total' => $total];
}
/**
* Ein Betrag in deutscher Schreibweise: Punkt als Tausender-, Komma als Dezimaltrennzeichen.
*
* Bewusst nicht {@see Amount::getFormattedAmount()}: Die Methode ersetzt nach `number_format` jeden
* Punkt durch ein Komma und macht aus 1.487,50 damit "1,487,50". Auf einer Aufstellung, in der
* vierstellige Beträge die Regel sind, wäre das nicht lesbar. Der Fehler steckt im Value Object und
* wirkt überall, wo Beträge angezeigt werden -- ihn dort zu beheben ist eine eigene Änderung.
*
* Öffentlich, weil die Vorlage sie als Callable bekommt und weil sie für sich prüfbar sein soll.
*/
public static function money(Amount $amount): string
{
return number_format(round($amount->getAmount(), 2), 2, ',', '.');
}
/**
* Summiert Zeilen, die je ein `amount` oder `total` tragen.
*
* Über ein frisches Amount-Objekt, weil `Amount::addAmount()` den Empfänger verändert -- die
* Einzelbeträge sollen unangetastet bleiben, sie werden anschließend gedruckt.
*
* @param array<int, array<string, mixed>> $rows
*/
private static function sum(array $rows): Amount
{
$sum = new Amount(0, 'Euro');
foreach ($rows as $row) {
/** @var Amount $amount */
$amount = $row['amount'] ?? $row['total'];
$sum->addAmount($amount);
}
return $sum;
}
}
@@ -0,0 +1,12 @@
<?php
namespace App\Domains\Event\Actions\CreateIncomeSurplusStatement;
use App\Models\Event;
class CreateIncomeSurplusStatementRequest
{
public function __construct(public readonly Event $event)
{
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Domains\Event\Actions\CreateIncomeSurplusStatement;
use App\ValueObjects\Amount;
class CreateIncomeSurplusStatementResponse
{
public bool $success = false;
public string $filename = '';
public string $pdfContent = '';
public ?string $message = null;
/**
* Die Zahlen, aus denen das PDF entsteht -- Einnahmen-Kategorien, Ausgaben-Gruppen und das Ergebnis.
*
* Sie stehen hier, weil sie das eigentliche Ergebnis der Action sind; das PDF ist nur ihre Darstellung.
* So lässt sich die Rechnung prüfen, ohne ein PDF zerlegen zu müssen.
*
* @var array{categories: array<int, array{name: string, total: Amount, entries: array<int, array{name: string, amount: Amount}>}>, total: Amount}|array{}
*/
public array $income = [];
/**
* @var array{groups: array<int, array{name: string, sum: Amount, rows: array<int, array<string, mixed>>}>, total: Amount}|array{}
*/
public array $expenses = [];
public ?Amount $result = null;
}
@@ -13,7 +13,7 @@ class GenerateIcalCommand
$participant = $this->request->participant; $participant = $this->request->participant;
$event = $participant->event; $event = $participant->event;
$uid = $participant->identifier . '@' . app('tenant')->slug; $uid = $participant->identifier . '@' . currentTenant()->slug;
$dtStart = $event->start_date->format('Ymd'); $dtStart = $event->start_date->format('Ymd');
$dtEnd = $event->end_date->copy()->addDay()->format('Ymd'); $dtEnd = $event->end_date->copy()->addDay()->format('Ymd');
$now = now()->format('Ymd\THis\Z'); $now = now()->format('Ymd\THis\Z');
@@ -24,7 +24,7 @@ class GenerateIcalCommand
$icalContent = implode("\r\n", [ $icalContent = implode("\r\n", [
'BEGIN:VCALENDAR', 'BEGIN:VCALENDAR',
'VERSION:2.0', 'VERSION:2.0',
'PRODID:-//' . app('tenant')->name . '//Veranstaltungskalender//DE', 'PRODID:-//' . currentTenant()->name . '//Veranstaltungskalender//DE',
'CALSCALE:GREGORIAN', 'CALSCALE:GREGORIAN',
'METHOD:PUBLISH', 'METHOD:PUBLISH',
'BEGIN:VEVENT', 'BEGIN:VEVENT',
@@ -21,11 +21,11 @@ class GenerateIcalForDeadlineCommand {
$icalContent = implode("\r\n", [ $icalContent = implode("\r\n", [
'BEGIN:VCALENDAR', 'BEGIN:VCALENDAR',
'VERSION:2.0', 'VERSION:2.0',
'PRODID:-//' . app('tenant')->name . '//Veranstaltungskalender//DE', 'PRODID:-//' . currentTenant()->name . '//Veranstaltungskalender//DE',
'CALSCALE:GREGORIAN', 'CALSCALE:GREGORIAN',
'METHOD:PUBLISH', 'METHOD:PUBLISH',
'BEGIN:VEVENT', 'BEGIN:VEVENT',
'UID:payment-deadline-' . $event->identifier . '@' . app('tenant')->slug, 'UID:payment-deadline-' . $event->identifier . '@' . currentTenant()->slug,
'DTSTAMP:' . $now, 'DTSTAMP:' . $now,
'DTSTART;VALUE=DATE:' . $dtDate, 'DTSTART;VALUE=DATE:' . $dtDate,
'DTEND;VALUE=DATE:' . $dtDate, 'DTEND;VALUE=DATE:' . $dtDate,
@@ -18,7 +18,7 @@ class SetParticipationFeesCommand {
$this->cleanBefore(); $this->cleanBefore();
$this->request->event->participationFee1()->associate(EventParticipationFee::create([ $this->request->event->participationFee1()->associate(EventParticipationFee::create([
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
'type' => $this->request->participationFeeFirst['type'], 'type' => $this->request->participationFeeFirst['type'],
'name' => $this->request->participationFeeFirst['name'], 'name' => $this->request->participationFeeFirst['name'],
'description' => $this->request->participationFeeFirst['description'], 'description' => $this->request->participationFeeFirst['description'],
@@ -29,7 +29,7 @@ class SetParticipationFeesCommand {
if ($this->request->participationFeeSecond !== null) { if ($this->request->participationFeeSecond !== null) {
$this->request->event->participationFee2()->associate(EventParticipationFee::create([ $this->request->event->participationFee2()->associate(EventParticipationFee::create([
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
'type' => $this->request->participationFeeSecond['type'], 'type' => $this->request->participationFeeSecond['type'],
'name' => $this->request->participationFeeSecond['name'], 'name' => $this->request->participationFeeSecond['name'],
'description' => $this->request->participationFeeSecond['description'], 'description' => $this->request->participationFeeSecond['description'],
@@ -41,7 +41,7 @@ class SetParticipationFeesCommand {
if ($this->request->participationFeeThird !== null) { if ($this->request->participationFeeThird !== null) {
$this->request->event->participationFee3()->associate(EventParticipationFee::create([ $this->request->event->participationFee3()->associate(EventParticipationFee::create([
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
'type' => $this->request->participationFeeThird['type'], 'type' => $this->request->participationFeeThird['type'],
'name' => $this->request->participationFeeThird['name'], 'name' => $this->request->participationFeeThird['name'],
'description' => $this->request->participationFeeThird['description'], 'description' => $this->request->participationFeeThird['description'],
@@ -53,7 +53,7 @@ class SetParticipationFeesCommand {
if ($this->request->participationFeeFourth !== null) { if ($this->request->participationFeeFourth !== null) {
$this->request->event->participationFee4()->associate(EventParticipationFee::create([ $this->request->event->participationFee4()->associate(EventParticipationFee::create([
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
'type' => $this->request->participationFeeFourth['type'], 'type' => $this->request->participationFeeFourth['type'],
'name' => $this->request->participationFeeFourth['name'], 'name' => $this->request->participationFeeFourth['name'],
'description' => $this->request->participationFeeFourth['description'], 'description' => $this->request->participationFeeFourth['description'],
@@ -21,7 +21,7 @@ use Illuminate\Http\Request;
class CreateController extends CommonController { class CreateController extends CommonController {
public function __invoke() { public function __invoke() {
return new InertiaProvider('Event/Create', [ return new InertiaProvider('Event/Create', [
'emailAddress' => auth()->user()->email, 'emailAddress' => currentUserOrFail()->email,
'eventAccount' => $this->tenant->account_name, 'eventAccount' => $this->tenant->account_name,
'eventIban' => $this->tenant->account_iban, 'eventIban' => $this->tenant->account_iban,
'eventPayPerDay' => $this->tenant->slug === 'lv' ? true : false, 'eventPayPerDay' => $this->tenant->slug === 'lv' ? true : false,
@@ -0,0 +1,33 @@
<?php
namespace App\Domains\Event\Controllers;
use App\Domains\Event\Actions\CreateIncomeSurplusStatement\CreateIncomeSurplusStatementCommand;
use App\Domains\Event\Actions\CreateIncomeSurplusStatement\CreateIncomeSurplusStatementRequest;
use App\Scopes\CommonController;
use Illuminate\Http\Response;
class IncomeSurplusStatementController extends CommonController
{
public function __invoke(string $eventId): Response
{
$event = $this->events->getByIdentifier($eventId);
if ($event === null) {
abort(403, 'Zugriff verweigert.');
}
$statementRequest = new CreateIncomeSurplusStatementRequest($event);
$statementCommand = new CreateIncomeSurplusStatementCommand($statementRequest);
$statementResponse = $statementCommand->execute();
if (!$statementResponse->success) {
abort(422, $statementResponse->message ?? 'Die EÜR konnte nicht erstellt werden.');
}
return response($statementResponse->pdfContent, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $statementResponse->filename . '"',
]);
}
}
@@ -38,7 +38,7 @@ class SendController extends CommonController
} }
} }
$user = auth()->user(); $user = currentUser();
$reportSubject = sprintf('Sendebericht für Nachricht mit Betreff "%s"', $subject); $reportSubject = sprintf('Sendebericht für Nachricht mit Betreff "%s"', $subject);
Mail::to($user->email)->send(new ManualMailsReportMail( Mail::to($user->email)->send(new ManualMailsReportMail(
@@ -35,8 +35,9 @@ class SignupController extends CommonController {
'lastname' => '', 'lastname' => '',
]; ];
if (auth()->check()) { $currentUser = currentUser();
$user = new UserResource(auth()->user())->toArray($request); if ($currentUser !== null) {
$user = new UserResource($currentUser)->toArray($request);
$participantData = [ $participantData = [
'id' => $user['id'], 'id' => $user['id'],
+5
View File
@@ -4,6 +4,7 @@ use App\Domains\Event\Controllers\ArchivedEventsController;
use App\Domains\Event\Controllers\AvailableEventsController; use App\Domains\Event\Controllers\AvailableEventsController;
use App\Domains\Event\Controllers\CreateController; use App\Domains\Event\Controllers\CreateController;
use App\Domains\Event\Controllers\DetailsController; use App\Domains\Event\Controllers\DetailsController;
use App\Domains\Event\Controllers\IncomeSurplusStatementController;
use App\Domains\Event\Controllers\SignupController; use App\Domains\Event\Controllers\SignupController;
use App\Middleware\IdentifyTenant; use App\Middleware\IdentifyTenant;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
@@ -18,6 +19,10 @@ Route::middleware(IdentifyTenant::class)->group(function () {
Route::middleware(['auth'])->group(function () { Route::middleware(['auth'])->group(function () {
Route::get('/details/{eventId}', DetailsController::class); Route::get('/details/{eventId}', DetailsController::class);
// Vor der Wildcard darunter: Sonst greift `downloadPdfList()` und sucht ein Blade namens
// `income-surplus-statement` mit Teilnehmendendaten, die die EÜR gar nicht braucht.
Route::get('/details/{eventId}/pdf/income-surplus-statement', IncomeSurplusStatementController::class);
Route::get('/details/{eventId}/pdf/{listType}', [DetailsController::class, 'downloadPdfList']); Route::get('/details/{eventId}/pdf/{listType}', [DetailsController::class, 'downloadPdfList']);
Route::get('/details/{eventId}/csv/{listType}', [DetailsController::class, 'downloadCsvList']); Route::get('/details/{eventId}/csv/{listType}', [DetailsController::class, 'downloadCsvList']);
}); });
@@ -106,6 +106,10 @@ async function showEventAddons() {
<input type="button" value="Beitragsliste (PDF)" /> <input type="button" value="Beitragsliste (PDF)" />
</a><br/> </a><br/>
<a :href="'/event/details/' + props.data.event.identifier + '/pdf/income-surplus-statement'">
<input type="button" value="EüR (PDF)" />
</a><br/>
<a :href="'/event/details/' + props.data.event.identifier + '/pdf/drinking-list'"> <a :href="'/event/details/' + props.data.event.identifier + '/pdf/drinking-list'">
<input type="button" value="Getränkeliste (PDF)" /> <input type="button" value="Getränkeliste (PDF)" />
</a><br/> </a><br/>
@@ -143,6 +147,10 @@ async function showEventAddons() {
<input type="button" value="Beitragsliste (PDF)" /> <input type="button" value="Beitragsliste (PDF)" />
</a><br/> </a><br/>
<a :href="'/event/details/' + props.data.event.identifier + '/pdf/income-surplus-statement'">
<input type="button" value="EüR (PDF)" />
</a><br/>
<a :href="'/event/details/' + props.data.event.identifier + '/pdf/drinking-list'"> <a :href="'/event/details/' + props.data.event.identifier + '/pdf/drinking-list'">
<input type="button" value="Getränkeliste (PDF)" /> <input type="button" value="Getränkeliste (PDF)" />
</a><br/> </a><br/>
@@ -386,7 +386,17 @@ function saveParticipant() {
Bankverbindung des Teilis Bankverbindung des Teilis
</small> </small>
<small v-else-if="props.participant.refund.status === 'accepted'"> <small v-else-if="props.participant.refund.status === 'accepted'">
bestätigt am {{ props.participant.refund.acceptedAt }} bestätigt am {{ props.participant.refund.acceptedAt }}<template
v-if="props.participant.refund.donation"
> &ndash; gespendet, keine Auszahlung</template>
</small>
<!-- Was beim Verband geblieben ist und warum. -->
<small v-if="props.participant.refund.hasRetention" class="retention-note">
<br />Einbehalten: {{ props.participant.refund.retainedAmount }} &ndash;
{{ props.participant.refund.retentionReasonLabel }}<template
v-if="props.participant.refund.retentionReasonNote"
> ({{ props.participant.refund.retentionReasonNote }})</template>
</small> </small>
</td> </td>
</tr> </tr>
@@ -541,4 +551,8 @@ textarea {
select { select {
width: 262px; width: 262px;
} }
.retention-note {
color: #8a6d00;
}
</style> </style>
@@ -51,15 +51,83 @@ const openRefundDialogSwitch = ref(false);
// Der Erstattungsdialog. `captureMode` steuert den Weg: 'participant' schickt dem Teili einen Link, über // Der Erstattungsdialog. `captureMode` steuert den Weg: 'participant' schickt dem Teili einen Link, über
// den er seine Bankverbindung selbst einträgt; 'management' heißt, sie liegt der Aktionsleitung bereits // den er seine Bankverbindung selbst einträgt; 'management' heißt, sie liegt der Aktionsleitung bereits
// vor -- dann wird die Erstattung sofort eingereicht. // vor -- dann wird die Erstattung sofort eingereicht.
const refundForm = reactive({amount: '', reason: '', reasonNote: '', captureMode: 'participant', accountOwner: '', accountIban: ''}); const refundForm = reactive({
amount: '', reason: '', reasonNote: '',
captureMode: 'participant', accountOwner: '', accountIban: '',
retentionReason: '', retentionReasonNote: '',
});
const refundErrors = reactive({amount: '', reason: '', reasonNote: '', accountOwner: '', accountIban: ''}); const refundErrors = reactive({amount: '', reason: '', reasonNote: '', accountOwner: '', accountIban: ''});
const refundReasons = ref([]); const refundReasons = ref([]);
const retentionReasons = ref([]);
const refundSaving = ref(false); const refundSaving = ref(false);
const refundResending = ref(false);
const selectedRefundReason = computed( const selectedRefundReason = computed(
() => refundReasons.value.find(r => r.value === refundForm.reason) ?? null () => refundReasons.value.find(r => r.value === refundForm.reason) ?? null
); );
const selectedRetentionReason = computed(
() => retentionReasons.value.find(r => r.value === refundForm.retentionReason) ?? null
);
/** Was nach der Erstattung beim Verband bleibt -- die Grundlage für den Einbehaltungsblock. */
const retainedAmount = computed(() => {
const paid = Number(showParticipant.value?.amountPaidValue ?? 0);
const refunded = Number((refundForm.amount ?? '').replace(',', '.'));
if (!Number.isFinite(refunded)) {
return 0;
}
const remaining = Math.round((paid - refunded) * 100) / 100;
return remaining > 0.005 ? remaining : 0;
});
const hasRetention = computed(() => retainedAmount.value > 0);
const retainedAmountReadable = computed(
() => retainedAmount.value.toFixed(2).replace('.', ',') + ' Euro'
);
/**
* Ob abgesendet werden kann. Der Knopf erscheint erst dann -- was noch fehlt, soll die Aktionsleitung
* sehen, bevor sie klickt, statt danach eine Fehlermeldung zu lesen.
*/
const refundFormComplete = computed(() => {
const amount = Number((refundForm.amount ?? '').replace(',', '.'));
const paid = Number(showParticipant.value?.amountPaidValue ?? 0);
if (!refundForm.amount || !(amount > 0) || amount > paid + 0.005) {
return false;
}
if (!refundForm.reason) {
return false;
}
if (selectedRefundReason.value?.requiresNote && !refundForm.reasonNote.trim()) {
return false;
}
// Bleibt etwas beim Verband, muss begründet sein, warum.
if (hasRetention.value) {
if (!refundForm.retentionReason) {
return false;
}
if (selectedRetentionReason.value?.requiresNote && !refundForm.retentionReasonNote.trim()) {
return false;
}
}
if (refundForm.captureMode === 'management') {
return refundForm.accountOwner.trim() !== '' && refundForm.accountIban.trim() !== '';
}
return true;
});
defineEmits(['showParticipantDetails', 'markCocExisting', 'paymentComplete']) defineEmits(['showParticipantDetails', 'markCocExisting', 'paymentComplete'])
function openParticipantDetails(input) { function openParticipantDetails(input) {
@@ -323,6 +391,8 @@ async function openRefundDialog(participant) {
refundForm.captureMode = 'participant'; refundForm.captureMode = 'participant';
refundForm.accountOwner = ''; refundForm.accountOwner = '';
refundForm.accountIban = ''; refundForm.accountIban = '';
refundForm.retentionReason = '';
refundForm.retentionReasonNote = '';
Object.keys(refundErrors).forEach(key => refundErrors[key] = ''); Object.keys(refundErrors).forEach(key => refundErrors[key] = '');
@@ -331,6 +401,11 @@ async function openRefundDialog(participant) {
refundReasons.value = reasons ?? []; refundReasons.value = reasons ?? [];
} }
if (retentionReasons.value.length === 0) {
const reasons = await request('/api/v1/core/retrieve-retention-reasons', {method: 'GET'});
retentionReasons.value = reasons ?? [];
}
openRefundDialogSwitch.value = true; openRefundDialogSwitch.value = true;
} }
@@ -384,6 +459,11 @@ async function execRefund() {
// Leer beim Weg über den Teili -- dann verschickt der Server nur den Link. // Leer beim Weg über den Teili -- dann verschickt der Server nur den Link.
accountOwner: refundForm.captureMode === 'management' ? refundForm.accountOwner : '', accountOwner: refundForm.captureMode === 'management' ? refundForm.accountOwner : '',
accountIban: refundForm.captureMode === 'management' ? refundForm.accountIban : '', accountIban: refundForm.captureMode === 'management' ? refundForm.accountIban : '',
// Spende: kein Konto, trotzdem sofort eingereicht.
donation: refundForm.captureMode === 'donation',
// Leer bei voller Erstattung -- dann gibt es nichts zu begründen.
retentionReason: hasRetention.value ? refundForm.retentionReason : '',
retentionReasonNote: hasRetention.value ? refundForm.retentionReasonNote : '',
}, },
}); });
@@ -419,6 +499,32 @@ async function execCancelRefund(participant) {
} }
} }
/**
* Die Mail zur freigegebenen Erstattung noch einmal schicken -- ohne Rückfrage, es ändert sich nichts am
* Vorgang. Der Guard verhindert, dass ein zweiter Klick eine zweite Mail auslöst, bevor die erste durch ist.
*/
async function execResendRefundMail(participant) {
if (refundResending.value) {
return;
}
refundResending.value = true;
try {
const data = await request('/api/v1/participant-refund/' + participant.refund.token + '/resend-mail', {
method: "POST",
});
if (data?.status === 'success') {
toast.success(data.message);
} else {
toast.error(data?.message ?? 'Die Rückerstattungsmail konnte nicht versendet werden.');
}
} finally {
refundResending.value = false;
}
}
async function downloadRefundDocument(participant) { async function downloadRefundDocument(participant) {
const ok = await download('/api/v1/participant-refund/' + participant.refund.token + '/document'); const ok = await download('/api/v1/participant-refund/' + participant.refund.token + '/document');
@@ -479,6 +585,15 @@ function mailToGroup(groupKey) {
<td class="pl-amount" :id="'participant-' + participant.identifier +'-payment'" :class="participant.amount_left_value != 0 && !participant.unregistered ? 'not-paid' : ''"> <td class="pl-amount" :id="'participant-' + participant.identifier +'-payment'" :class="participant.amount_left_value != 0 && !participant.unregistered ? 'not-paid' : ''">
Gezahlt: <label :id="'participant-' + participant.identifier + '-paid'">{{ participant?.amountPaid.readable }}</label> /<br /> Gezahlt: <label :id="'participant-' + participant.identifier + '-paid'">{{ participant?.amountPaid.readable }}</label> /<br />
Gesamt: <label :id="'participant-' + participant.identifier + '-expected'">{{ participant?.amountExpected.readable }}</label> Gesamt: <label :id="'participant-' + participant.identifier + '-expected'">{{ participant?.amountExpected.readable }}</label>
<!-- Warum ein Teil des Beitrags beim Verband geblieben ist. -->
<span v-if="participant.refund?.hasRetention" class="retention-note">
Einbehalten: {{ participant.refund.retainedAmount }}<br />
{{ participant.refund.retentionReasonLabel }}<template
v-if="participant.refund.retentionReasonNote"
> &ndash; {{ participant.refund.retentionReasonNote }}</template>
</span>
<br /><br /> <br /><br />
<span v-if="participant.amount_left_value != 0 && !participant.unregistered" :id="'participant-' + participant.identifier + '-actions'"> <span v-if="participant.amount_left_value != 0 && !participant.unregistered" :id="'participant-' + participant.identifier + '-actions'">
<span class="link" style="font-size:10pt;" @click="paymentComplete(participant)">Zahlung buchen</span> &nbsp; <span class="link" style="font-size:10pt;" @click="paymentComplete(participant)">Zahlung buchen</span> &nbsp;
@@ -541,8 +656,9 @@ function mailToGroup(groupKey) {
> | Beitrag erstatten</span> > | Beitrag erstatten</span>
<template v-else-if="participant.refund?.status === 'pending'"> <template v-else-if="participant.refund?.status === 'pending'">
| <strong>Erstattung offen:</strong> {{ participant.refund.amount }}, | <strong>Rückerstattung vorgemerkt:</strong> {{ participant.refund.amount }}
wartet auf Bankverbindung am {{ participant.refund.releasedAt }}, wartet auf Bankverbindung
<span class="link" @click="execResendRefundMail(participant)">Rückerstattungsmail erneut senden</span>
<span class="link" style="color: #da7070;" @click="execCancelRefund(participant)">Abbrechen</span> <span class="link" style="color: #da7070;" @click="execCancelRefund(participant)">Abbrechen</span>
</template> </template>
@@ -656,8 +772,38 @@ function mailToGroup(groupKey) {
</div> </div>
<!-- <!--
Liegt die Bankverbindung schon vor, entfällt der Umweg über den Teili: die Erstattung wird Bleibt ein Teil beim Verband, muss begründet sein, warum -- ein einbehaltener Betrag ohne
sofort eingereicht. Er bekommt den Beleg trotzdem. Grund ist in der Buchhaltung nicht haltbar. Bei voller Erstattung gibt es nichts zu zeigen.
-->
<template v-if="hasRetention">
<p class="refund-hint">
<strong>{{ retainedAmountReadable }}</strong> verbleiben beim Verband.
</p>
<div class="refund-field">
<label for="refund_retention_reason">Grund der Einbehaltung</label>
<select id="refund_retention_reason" v-model="refundForm.retentionReason" class="form-input">
<option value="">Bitte auswählen </option>
<option v-for="reason in retentionReasons" :key="reason.value" :value="reason.value">
{{ reason.label }}
</option>
</select>
</div>
<div v-if="selectedRetentionReason?.requiresNote" class="refund-field">
<label for="refund_retention_note">Erläuterung zur Einbehaltung</label>
<textarea
id="refund_retention_note"
v-model="refundForm.retentionReasonNote"
class="form-input"
rows="3"
></textarea>
</div>
</template>
<!--
Liegt die Bankverbindung schon vor oder will der Teili spenden, entfällt der Umweg über ihn:
die Erstattung wird sofort eingereicht. Er bekommt den Beleg trotzdem.
--> -->
<div class="refund-field"> <div class="refund-field">
<label class="refund-choice"> <label class="refund-choice">
@@ -668,8 +814,17 @@ function mailToGroup(groupKey) {
<input type="radio" value="management" v-model="refundForm.captureMode" /> <input type="radio" value="management" v-model="refundForm.captureMode" />
Bankverbindung liegt mir vor Bankverbindung liegt mir vor
</label> </label>
<label class="refund-choice">
<input type="radio" value="donation" v-model="refundForm.captureMode" />
Teilnehmer*in spendet den Betrag
</label>
</div> </div>
<p v-if="refundForm.captureMode === 'donation'" class="refund-hint">
Der Betrag wird nicht ausgezahlt, sondern als Spende gebucht. Die Erstattung wird sofort
eingereicht; der Teili erhält den Beleg per E-Mail.
</p>
<template v-if="refundForm.captureMode === 'management'"> <template v-if="refundForm.captureMode === 'management'">
<div class="refund-field"> <div class="refund-field">
<label for="refund_account_owner">Kontoinhaber*in</label> <label for="refund_account_owner">Kontoinhaber*in</label>
@@ -694,9 +849,16 @@ function mailToGroup(groupKey) {
</p> </p>
</template> </template>
<button class="button" :disabled="refundSaving" @click="execRefund()"> <!-- Erscheint erst, wenn alles ausgefüllt ist; während des Speicherns gesperrt statt weg. -->
<button
v-if="refundFormComplete"
class="button"
:disabled="refundSaving"
@click="execRefund()"
>
<template v-if="refundSaving">Wird gespeichert</template> <template v-if="refundSaving">Wird gespeichert</template>
<template v-else-if="refundForm.captureMode === 'management'">Erstattung einreichen</template> <template v-else-if="refundForm.captureMode === 'management'">Erstattung einreichen</template>
<template v-else-if="refundForm.captureMode === 'donation'">Als Spende einreichen</template>
<template v-else>Erstattung freigeben</template> <template v-else>Erstattung freigeben</template>
</button> </button>
</Modal> </Modal>
@@ -749,6 +911,14 @@ function mailToGroup(groupKey) {
margin-right: 6px; margin-right: 6px;
} }
.retention-note {
display: block;
margin-top: 6px;
font-size: 10pt;
color: #ca5a0a;
line-height: 1.4;
}
.refund-hint { .refund-hint {
margin-bottom: 14px; margin-bottom: 14px;
padding: 8px 10px; padding: 8px 10px;
@@ -68,6 +68,17 @@ const props = defineProps({
</td> </td>
</tr> </tr>
<!--
Beiträge, die trotz Abmeldung beim Verband geblieben sind. Eigene Zeile, weil die
Zeilen darüber nur aktive Anmeldungen führen.
-->
<tr v-if="props.event.retainedFromUnregistered.value > 0">
<th style="padding-bottom: 20px" colspan="2">Einbehalten von Abmeldungen</th>
<td style="padding-bottom: 20px" colspan="2">
{{ props.event.retainedFromUnregistered.readable }}
</td>
</tr>
<tr> <tr>
<th colspan="2" style="border-width: 1px; border-top-style: solid">Gesamt</th> <th colspan="2" style="border-width: 1px; border-top-style: solid">Gesamt</th>
<td style="font-weight: bold; border-width: 1px; border-top-style: solid"> <td style="font-weight: bold; border-width: 1px; border-top-style: solid">
@@ -22,7 +22,7 @@ class ChangeStatusCommand {
switch ($this->request->status) { switch ($this->request->status) {
case InvoiceStatus::INVOICE_STATUS_APPROVED: case InvoiceStatus::INVOICE_STATUS_APPROVED:
$this->request->invoice->status = InvoiceStatus::INVOICE_STATUS_APPROVED; $this->request->invoice->status = InvoiceStatus::INVOICE_STATUS_APPROVED;
$this->request->invoice->approved_by = auth()->user()->id; $this->request->invoice->approved_by = currentUserOrFail()->id;
$this->request->invoice->approved_at = now(); $this->request->invoice->approved_at = now();
if ($this->request->invoice->contact_email !== null) { if ($this->request->invoice->contact_email !== null) {
@@ -35,7 +35,7 @@ class ChangeStatusCommand {
case InvoiceStatus::INVOICE_STATUS_DENIED: case InvoiceStatus::INVOICE_STATUS_DENIED:
$this->request->invoice->status = InvoiceStatus::INVOICE_STATUS_DENIED; $this->request->invoice->status = InvoiceStatus::INVOICE_STATUS_DENIED;
$this->request->invoice->denied_by = auth()->user()->id; $this->request->invoice->denied_by = currentUserOrFail()->id;
$this->request->invoice->denied_at = now(); $this->request->invoice->denied_at = now();
$this->request->invoice->denied_reason = $this->request->comment; $this->request->invoice->denied_reason = $this->request->comment;
if ($this->request->invoice->contact_email !== null) { if ($this->request->invoice->contact_email !== null) {
@@ -3,6 +3,8 @@
namespace App\Domains\Invoice\Actions\CreateInvoice; namespace App\Domains\Invoice\Actions\CreateInvoice;
use App\Enumerations\InvoiceStatus; use App\Enumerations\InvoiceStatus;
use App\Enumerations\InvoiceType;
use App\Enumerations\TravelReason;
use App\Mail\InvoiceMails\InvoiceMailsNewInvoiceMail; use App\Mail\InvoiceMails\InvoiceMailsNewInvoiceMail;
use App\Mail\InvoiceMails\InvoiceMailsSubmittedConfirmationMail; use App\Mail\InvoiceMails\InvoiceMailsSubmittedConfirmationMail;
use App\Mail\ParticipantParticipationMails\EventSignUpSuccessfullMail; use App\Mail\ParticipantParticipationMails\EventSignUpSuccessfullMail;
@@ -19,17 +21,27 @@ class CreateInvoiceCommand {
public function execute() : CreateInvoiceResponse { public function execute() : CreateInvoiceResponse {
$response = new CreateInvoiceResponse(); $response = new CreateInvoiceResponse();
$rejection = $this->rejectTravelReason();
if ($rejection !== null) {
$response->message = $rejection;
return $response;
}
if ($this->request->accountIban === 'undefined') { if ($this->request->accountIban === 'undefined') {
$this->request->accountIban = null; $this->request->accountIban = null;
} }
$travelReason = $this->travelReason();
$invoice = Invoice::create([ $invoice = Invoice::create([
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
'cost_unit_id' => $this->request->costUnit->id, 'cost_unit_id' => $this->request->costUnit->id,
'invoice_number' => $this->generateInvoiceNumber(), 'invoice_number' => $this->generateInvoiceNumber(),
'status' => InvoiceStatus::INVOICE_STATUS_NEW, 'status' => InvoiceStatus::INVOICE_STATUS_NEW,
'type' => $this->request->invoiceType, 'type' => $this->request->invoiceType,
'type_other' => $this->request->invoiceTypeExtended, 'type_other' => $this->request->invoiceTypeExtended,
'purpose' => $this->purpose($travelReason),
'donation' => $this->request->isDonation, 'donation' => $this->request->isDonation,
'user_id' => $this->request->paymentPurpose === null ? $this->request->userId : null, 'user_id' => $this->request->paymentPurpose === null ? $this->request->userId : null,
'contact_name' => $this->request->contactName, 'contact_name' => $this->request->contactName,
@@ -40,9 +52,7 @@ class CreateInvoiceCommand {
'amount' => $this->request->totalAmount, 'amount' => $this->request->totalAmount,
'distance' => $this->request->distance, 'distance' => $this->request->distance,
'travel_direction' => $this->request->travelRoute, 'travel_direction' => $this->request->travelRoute,
'travel_reason' => $this->request->travelReason, 'travel_reason' => $travelReason,
'passengers' => $this->request->passengers,
'transportation' => $this->request->transportations,
'payment_purpose' => $this->request->paymentPurpose, 'payment_purpose' => $this->request->paymentPurpose,
'comment' => $this->request->notices, 'comment' => $this->request->notices,
'document_filename' => $this->request->receiptFile !== null ? $this->request->receiptFile->fullPath : null, 'document_filename' => $this->request->receiptFile !== null ? $this->request->receiptFile->fullPath : null,
@@ -61,7 +71,7 @@ class CreateInvoiceCommand {
} }
if ($this->request->costUnit->mail_on_new) { if ($this->request->costUnit->mail_on_new) {
$recipients = [app('tenant')->email_finance]; $recipients = [currentTenant()->email_finance];
foreach ($this->request->costUnit->treasurers()->get() as $treasurer) { foreach ($this->request->costUnit->treasurers()->get() as $treasurer) {
if (!in_array($treasurer->email, $recipients)) { if (!in_array($treasurer->email, $recipients)) {
@@ -81,9 +91,71 @@ class CreateInvoiceCommand {
} }
/**
* Der Zahlungsgrund, einmal beim Anlegen festgehalten.
*
* Danach ist er eine eigene Angabe: Die Kassenwart*in kann ihn korrigieren, und nichts schreibt ihn
* mehr um. Bei Fahrtkosten setzt er sich aus Reisegrund und den gefahrenen Personen zusammen, sonst
* trägt ihn "Was wurde eingekauft". Wo nichts erfasst wird -- Beitragserstattungen -- bleibt er leer.
*
* Steht er schon fest, wird er übernommen: Eine Abrechnungskorrektur kopiert den Beleg, und ein von
* Hand gesetzter Grund darf dabei nicht verloren gehen.
*/
private function purpose(?string $travelReason) : ?string {
if (trim((string) $this->request->purpose) !== '') {
return $this->request->purpose;
}
$purpose = Invoice::joinPurposeParts(
$this->request->invoiceType === InvoiceType::INVOICE_TYPE_TRAVELLING
// Der Name des Grundes, nicht sein Schlüssel: In der Belegliste soll "Materialtransport"
// stehen, nicht "material_transport".
? [TravelReason::text($travelReason), $this->request->travellers]
: [$this->request->invoiceTypeExtended]
);
return $purpose === '' ? null : $purpose;
}
/**
* Was in `travel_reason` landet: der Schlüssel des gewählten Grundes -- oder, bei "Anderer Grund",
* der Text selbst. Der Schlüssel `other` sagt für sich nichts aus, der Text alles.
*
* Ein unbekannter Wert ist deshalb kein Fehler, sondern genau dieser Fall: So kommen auch
* Bestandsbelege und Kopien durch, die ihren Freitext schon mitbringen.
*/
private function travelReason() : ?string {
$reason = TravelReason::find($this->request->travelReason);
if ($reason === null) {
return $this->request->travelReason;
}
return $reason->requires_note
? trim((string) $this->request->travelReasonNote)
: $reason->slug;
}
/**
* Sicherheitsnetz hinter der Oberfläche: Dort geht es erst weiter, wenn die Erläuterung steht. Über
* einen direkten Aufruf ginge das sonst vorbei, und ein "Anderer Grund" ohne Text sagt nichts aus --
* gespeichert würde ein leerer Reisegrund.
*/
private function rejectTravelReason() : ?string {
$reason = TravelReason::find($this->request->travelReason);
if ($reason === null || !$reason->requires_note) {
return null;
}
return trim((string) $this->request->travelReasonNote) === ''
? 'Bitte gib an, was der Grund für die Reise war.'
: null;
}
private function generateInvoiceNumber() : string { private function generateInvoiceNumber() : string {
$lastInvoiceNumber = Invoice::query() $lastInvoiceNumber = Invoice::query()
->where('tenant', app('tenant')->slug) ->where('tenant', currentTenant()->slug)
->whereYear('created_at', date('Y')) ->whereYear('created_at', date('Y'))
->count(); ->count();
@@ -16,16 +16,24 @@ class CreateInvoiceRequest {
public ?string $invoiceTypeExtended; public ?string $invoiceTypeExtended;
public ?string $travelRoute; public ?string $travelRoute;
public ?int $distance; public ?int $distance;
public ?int $passengers;
public ?int $transportations;
public ?InvoiceFile $receiptFile; public ?InvoiceFile $receiptFile;
public float $totalAmount; public float $totalAmount;
public bool $isDonation; public bool $isDonation;
public ?int $userId; public ?int $userId;
/** Der Slug eines Reisegrundes -- oder ein Freitext, wenn er von einem Bestandsbeleg stammt. */
public ?string $travelReason; public ?string $travelReason;
/** Die Erläuterung zu "Anderer Grund"; nur bei einem Grund mit `requires_note` von Belang. */
public ?string $travelReasonNote;
public ?string $paymentPurpose; public ?string $paymentPurpose;
public ?string $notices; public ?string $notices;
/** Wer gereist ist -- Freitext aus dem Fahrtkosten-Formular, geht in den Zahlungsgrund ein. */
public ?string $travellers;
/** Ein bereits feststehender Zahlungsgrund; gesetzt, gewinnt er über die Ermittlung im Command. */
public ?string $purpose;
public function __construct( public function __construct(
CostUnit $costUnit, CostUnit $costUnit,
@@ -42,11 +50,12 @@ class CreateInvoiceRequest {
?string $invoiceTypeExtended = null, ?string $invoiceTypeExtended = null,
?string $travelRoute = null, ?string $travelRoute = null,
?int $distance = null, ?int $distance = null,
?int $passengers = null,
?int $transportations,
?string $travelReason = null, ?string $travelReason = null,
?string $travelReasonNote = null,
?string $paymentPurpose = null, ?string $paymentPurpose = null,
?string $notices = null, ?string $notices = null,
?string $travellers = null,
?string $purpose = null,
) { ) {
$this->costUnit = $costUnit; $this->costUnit = $costUnit;
@@ -55,8 +64,6 @@ class CreateInvoiceRequest {
$this->invoiceTypeExtended = $invoiceTypeExtended; $this->invoiceTypeExtended = $invoiceTypeExtended;
$this->travelRoute = $travelRoute; $this->travelRoute = $travelRoute;
$this->distance = $distance; $this->distance = $distance;
$this->passengers = $passengers;
$this->transportations = $transportations;
$this->receiptFile = $receiptFile; $this->receiptFile = $receiptFile;
$this->contactEmail = $contactEmail; $this->contactEmail = $contactEmail;
$this->contactPhone = $contactPhone; $this->contactPhone = $contactPhone;
@@ -66,8 +73,11 @@ class CreateInvoiceRequest {
$this->isDonation = $isDonation; $this->isDonation = $isDonation;
$this->userId = $userId; $this->userId = $userId;
$this->travelReason = $travelReason; $this->travelReason = $travelReason;
$this->travelReasonNote = $travelReasonNote;
$this->paymentPurpose = $paymentPurpose; $this->paymentPurpose = $paymentPurpose;
$this->notices = $notices; $this->notices = $notices;
$this->travellers = $travellers;
$this->purpose = $purpose;
if ($accountIban === 'undefined') { if ($accountIban === 'undefined') {
$this->accountIban = null; $this->accountIban = null;
@@ -8,8 +8,12 @@ class CreateInvoiceResponse {
public bool $success; public bool $success;
public ?Invoice $invoice; public ?Invoice $invoice;
/** Warum keine Abrechnung entstanden ist -- für die Rückmeldung an die einreichende Person. */
public ?string $message;
public function __construct() { public function __construct() {
$this->success = false; $this->success = false;
$this->invoice = null; $this->invoice = null;
$this->message = null;
} }
} }
@@ -83,10 +83,8 @@ class CreateInvoiceReceiptCommand {
$travelPartTemplate = <<<HTML $travelPartTemplate = <<<HTML
<tr><td>Reiseweg:</td><td>%1\$s</td></tr> <tr><td>Reiseweg:</td><td>%1\$s</td></tr>
<tr><td>Grund der Reise:</td><td>%6\$s</td></tr> <tr><td>Grund der Reise:</td><td>%4\$s</td></tr>
<tr><td>Gesamtlänge der Strecke:</td><td>%2\$s km x %3\$s / km</td></tr> <tr><td>Gesamtlänge der Strecke:</td><td>%2\$s km x %3\$s / km</td></tr>
<tr><td>Materialtransport:</td><td>%4\$s</td></tr>
<tr><td>Mitfahrende im PKW:</td><td>%5\$s</td></tr>
HTML; HTML;
$flatTravelPart = sprintf( $flatTravelPart = sprintf(
@@ -94,8 +92,6 @@ HTML;
$invoiceReadable['travelDirection'] , $invoiceReadable['travelDirection'] ,
$invoiceReadable['distance'], $invoiceReadable['distance'],
$invoiceReadable['distanceAllowance'], $invoiceReadable['distanceAllowance'],
$invoiceReadable['transportation'],
$invoiceReadable['passengers'],
$invoiceReadable['travelReason'] , $invoiceReadable['travelReason'] ,
); );
@@ -180,7 +176,10 @@ HTML;
$invoiceReadable['contactEmail'], $invoiceReadable['contactEmail'],
$invoiceReadable['contactPhone'], $invoiceReadable['contactPhone'],
$invoiceReadable['costUnitName'], $invoiceReadable['costUnitName'],
$invoiceReadable['invoiceType'], // Der erfasste Zahlungsgrund, nicht der Abrechnungstyp: Der steht eine Zeile darüber schon
// als Überschrift. Bei Fahrtkosten ist das die einzige Stelle, an der auf dem Beleg steht,
// wer gereist ist.
$invoiceReadable['purpose'],
$invoiceReadable['donationText'], $invoiceReadable['donationText'],
$paymentType, $paymentType,
$invoiceReadable['amount'], $invoiceReadable['amount'],
@@ -34,6 +34,17 @@ class UpdateInvoiceCommand {
} }
$purpose = trim((string) $this->request->purpose);
$purpose = $purpose === '' ? null : $purpose;
// Verglichen wird gegen den angezeigten Text, nicht gegen die Spalte: Das Formular ist damit
// vorbelegt, und wer ihn unverändert abschickt, hat nichts geändert. Ein Bestandsbeleg behält so
// seine leere Spalte und damit die Ableitung; wer das Feld leert, schaltet zurück auf automatisch.
if (($purpose ?? '') !== $this->request->invoice->purposeText()) {
$changes .= 'Zahlungsgrund geändert von ' . $this->request->invoice->purposeText() . ' auf ' . ($purpose ?? '--') . '.<br />';
$this->request->invoice->purpose = $purpose;
}
$this->request->invoice->comment = $this->request->comment; $this->request->invoice->comment = $this->request->comment;
$this->request->invoice->changes = $changes; $this->request->invoice->changes = $changes;
@@ -13,9 +13,11 @@ class UpdateInvoiceRequest {
public CostUnit $costUnit; public CostUnit $costUnit;
public Invoice $invoice; public Invoice $invoice;
public Amount $amount; public Amount $amount;
public ?string $purpose;
public function __construct(Invoice $invoice, ?string $comment, InvoiceType $invoiceType, CostUnit $costUnit, Amount $amount) { public function __construct(Invoice $invoice, ?string $comment, InvoiceType $invoiceType, CostUnit $costUnit, Amount $amount, ?string $purpose = null) {
$this->comment = $comment; $this->comment = $comment;
$this->purpose = $purpose;
$this->invoiceType = $invoiceType; $this->invoiceType = $invoiceType;
$this->costUnit = $costUnit; $this->costUnit = $costUnit;
$this->invoice = $invoice; $this->invoice = $invoice;
@@ -19,7 +19,7 @@ class UploadInvoiceCommand {
$uploadDir = sprintf( $uploadDir = sprintf(
'%1$s%2$s/%3$s', '%1$s%2$s/%3$s',
WebDavProvider::INVOICE_PREFIX, WebDavProvider::INVOICE_PREFIX,
app('tenant')->url, currentTenant()->url,
$this->request->invoice->costUnit()->first()->name $this->request->invoice->costUnit()->first()->name
); );
@@ -32,25 +32,26 @@ class EditController extends CommonController{
$receiptfile->fullPath = $invoice->document_filename; $receiptfile->fullPath = $invoice->document_filename;
} }
$createInvoiceRequest = new CreateInvoiceRequest( $createInvoiceRequest = new CreateInvoiceRequest(
$invoice->costUnit()->first(), costUnit: $invoice->costUnit()->first(),
$invoice->contact_name, contactName: $invoice->contact_name,
$invoice->type, invoiceType: $invoice->type,
$invoice->amount, totalAmount: $invoice->amount,
$receiptfile, receiptFile: $receiptfile,
$invoice->donation, isDonation: $invoice->donation,
$invoice->user_id, userId: $invoice->user_id,
$invoice->contact_email, contactEmail: $invoice->contact_email,
$invoice->contact_phone, contactPhone: $invoice->contact_phone,
$invoice->contact_bank_owner, accountOwner: $invoice->contact_bank_owner,
$invoice->contact_bank_iban, accountIban: $invoice->contact_bank_iban,
$invoice->type_other, invoiceTypeExtended: $invoice->type_other,
$invoice->travel_direction, travelRoute: $invoice->travel_direction,
$invoice->distance, distance: $invoice->distance,
$invoice->passengers, travelReason: $invoice->travel_reason,
$invoice->transportation, paymentPurpose: $invoice->payment_purpose,
$invoice->travel_reason, notices: $invoice->comment,
$invoice->payment_purpose, // Die rohe Spalte, nicht purposeText(): Ein Beleg, der seinen Zahlungsgrund bisher ableitet,
$invoice->comment, // soll das als Kopie weiter tun.
purpose: $invoice->purpose,
); );
$invoiceCreationCommand = new CreateInvoiceCommand($createInvoiceRequest); $invoiceCreationCommand = new CreateInvoiceCommand($createInvoiceRequest);
@@ -92,7 +93,8 @@ class EditController extends CommonController{
$modifyData['notices'], $modifyData['notices'],
$invoiceType, $invoiceType,
$newCostUnit, $newCostUnit,
$newAmount $newAmount,
$modifyData['purpose'] ?? null
); );
$updateInvoiceCommand = new UpdateInvoiceCommand($updateInvoiceRequest); $updateInvoiceCommand = new UpdateInvoiceCommand($updateInvoiceRequest);
$updateInvoiceCommand->execute(); $updateInvoiceCommand->execute();
@@ -107,22 +109,22 @@ class EditController extends CommonController{
$receiptfile->fullPath = $invoice->document_filename; $receiptfile->fullPath = $invoice->document_filename;
} }
$createInvoiceRequest = new CreateInvoiceRequest( $createInvoiceRequest = new CreateInvoiceRequest(
$invoice->costUnit()->first(), costUnit: $invoice->costUnit()->first(),
$invoice->contact_name, contactName: $invoice->contact_name,
$invoice->type, invoiceType: $invoice->type,
$amountLeft->getAmount(), totalAmount: $amountLeft->getAmount(),
$receiptfile, receiptFile: $receiptfile,
$invoice->donation, isDonation: $invoice->donation,
$invoice->user_id, userId: $invoice->user_id,
$invoice->contact_email, contactEmail: $invoice->contact_email,
$invoice->contact_phone, contactPhone: $invoice->contact_phone,
$invoice->contact_bank_owner, accountOwner: $invoice->contact_bank_owner,
$invoice->contact_bank_iban, accountIban: $invoice->contact_bank_iban,
$invoice->type_other, invoiceTypeExtended: $invoice->type_other,
$invoice->travel_direction, travelRoute: $invoice->travel_direction,
$invoice->distance, distance: $invoice->distance,
$invoice->passengers, travelReason: $invoice->travel_reason,
$invoice->transportation purpose: $invoice->purpose,
); );
$invoiceCreationCommand = new CreateInvoiceCommand($createInvoiceRequest); $invoiceCreationCommand = new CreateInvoiceCommand($createInvoiceRequest);
@@ -66,50 +66,43 @@ class SaveInvoiceController extends CommonController
} }
$createInvoiceRequest = new CreateInvoiceRequest( $createInvoiceRequest = new CreateInvoiceRequest(
$costUnit, costUnit: $costUnit,
$request->input('name'), contactName: $request->input('name'),
InvoiceType::INVOICE_TYPE_TRAVELLING, invoiceType: InvoiceType::INVOICE_TYPE_TRAVELLING,
$amount, totalAmount: $amount,
$uploadedFile, receiptFile: $uploadedFile,
'donation' === $request->input('decision') ? true : false, isDonation: 'donation' === $request->input('decision') ? true : false,
$this->users->getCurrentUserDetails()['userId'], userId: $this->users->getCurrentUserDetails()['userId'],
$request->input('email'), contactEmail: $request->input('email'),
$request->input('telephone'), contactPhone: $request->input('telephone'),
$request->input('accountOwner'), accountOwner: $request->input('accountOwner'),
$request->input('accountIban'), accountIban: $request->input('accountIban'),
null, travelRoute: $request->input('otherText'),
$request->input('otherText'), distance: $distance,
$distance, travelReason: $request->input('travelReason'),
$request->input('havePassengers'), travelReasonNote: $request->input('travelReasonNote'),
$request->input('materialTransportation'), notices: $notices,
$request->input('travelReason'), travellers: $request->input('travellers')
null,
$notices
); );
break; break;
default: default:
$createInvoiceRequest = new CreateInvoiceRequest( $createInvoiceRequest = new CreateInvoiceRequest(
$costUnit, costUnit: $costUnit,
$request->input('name'), contactName: $request->input('name'),
$invoiceType, invoiceType: $invoiceType,
Amount::fromString($request->input('amount'))->getAmount(), totalAmount: Amount::fromString($request->input('amount'))->getAmount(),
$uploadedFile, receiptFile: $uploadedFile,
'donation' === $request->input('decision') ? true : false, isDonation: 'donation' === $request->input('decision') ? true : false,
$this->users->getCurrentUserDetails()['userId'], userId: $this->users->getCurrentUserDetails()['userId'],
$request->input('email'), contactEmail: $request->input('email'),
$request->input('telephone'), contactPhone: $request->input('telephone'),
$request->input('accountOwner'), accountOwner: $request->input('accountOwner'),
$request->input('accountIban'), accountIban: $request->input('accountIban'),
$request->input('otherText'), invoiceTypeExtended: $request->input('otherText'),
null, paymentPurpose: $paymentPurpose,
null, notices: $notices
$request->input('havePassengers'),
$request->input('materialTransportation'),
null,
$paymentPurpose,
$notices
); );
break; break;
@@ -128,5 +121,11 @@ class SaveInvoiceController extends CommonController
'message' => 'Alright' 'message' => 'Alright'
]); ]);
} }
return response()->json([
'status' => 'error',
'message' => $response->message
?? 'Beim Speichern ist ein Fehler aufgetreten. Bitte starte den Vorgang erneut.'
]);
} }
} }
@@ -37,15 +37,6 @@ const props = defineProps({
<td style="font-weight: bold">{{props.invoice.amount}}</td> <td style="font-weight: bold">{{props.invoice.amount}}</td>
</tr> </tr>
<tr>
<th>Marterialtransport</th>
<td>{{props.invoice.transportation}}</td>
</tr>
<tr>
<th>Hat Personen mitgenommen</th>
<td>{{props.invoice.passengers}}</td>
</tr>
</table> </table>
</template> </template>
@@ -16,11 +16,18 @@ const props = defineProps({
const emit = defineEmits(['submit', 'cancel']) const emit = defineEmits(['submit', 'cancel'])
/**
* Die Anmerkung heißt in der Resource `comment` und ist dort `'--'`, wenn keine gesetzt ist -- beides
* muss hier stimmen, sonst startet das Feld leer und das Speichern löscht die vorhandene Anmerkung.
*/
const existingComment = props.newInvoice.comment
const formData = reactive({ const formData = reactive({
type_internal: props.newInvoice.internalType || '', type_internal: props.newInvoice.internalType || '',
cost_unit: props.newInvoice.costUnitId || '', cost_unit: props.newInvoice.costUnitId || '',
amount: props.newInvoice.amountPlain || '', amount: props.newInvoice.amountPlain || '',
notices: props.newInvoice.comments || '', purpose: props.newInvoice.purpose || '',
notices: !existingComment || existingComment === '--' ? '' : existingComment,
}) })
const submitForm = () => { const submitForm = () => {
@@ -70,6 +77,13 @@ onMounted(async () => {
</td> </td>
</tr> </tr>
<tr>
<td>Zahlungsgrund:</td>
<td>
<input type="text" v-model="formData.purpose" class="width-almost-full" />
</td>
</tr>
<tr> <tr>
<td>Anmerkungen:</td> <td>Anmerkungen:</td>
<td> <td>
@@ -100,6 +100,10 @@ const emit = defineEmits(["accept", "deny", "fix", "reopen"])
<td v-else-if="props.data.externalPayment">Rechnungszahlung</td> <td v-else-if="props.data.externalPayment">Rechnungszahlung</td>
<td v-else>Klassische Auszahlung</td> <td v-else>Klassische Auszahlung</td>
</tr> </tr>
<tr>
<td>Zahlungsgrund:</td>
<td colspan="3">{{props.data.purpose}}</td>
</tr>
<tr> <tr>
<td>Status:</td> <td>Status:</td>
<td>{{props.data.readableStatus}}</td> <td>{{props.data.readableStatus}}</td>
@@ -32,15 +32,6 @@ const props = defineProps({
<td style="font-weight: bold">{{props.invoice.amount}}</td> <td style="font-weight: bold">{{props.invoice.amount}}</td>
</tr> </tr>
<tr>
<th>Marterialtransport</th>
<td>{{props.invoice.transportation}}</td>
</tr>
<tr>
<th>Hat Personen mitgenommen</th>
<td>{{props.invoice.passengers}}</td>
</tr>
</table> </table>
</template> </template>
@@ -45,12 +45,13 @@
<template> <template>
<table v-if="localData.invoices.length > 0" class="invoice-list-table"> <table v-if="localData.invoices.length > 0" class="invoice-list-table">
<tr> <tr>
<td colspan="6">{{props.data.title}}</td> <td colspan="7">{{props.data.title}}</td>
</tr> </tr>
<tr v-for="invoice in localData.invoices" :id="'invoice_' + invoice.id"> <tr v-for="invoice in localData.invoices" :id="'invoice_' + invoice.id">
<td>{{invoice.invoiceNumber}}</td> <td>{{invoice.invoiceNumber}}</td>
<td>{{invoice.invoiceType}}</td> <td>{{invoice.invoiceTypeShort}}</td>
<td style="max-width: 250px;">{{invoice.purpose}}</td>
<td> <td>
{{invoice.amount}} {{invoice.amount}}
</td> </td>
@@ -1,6 +1,6 @@
<script setup> <script setup>
import { ref, onMounted, reactive } from 'vue' import { ref, computed, onMounted, reactive } from 'vue'
import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js"; import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js";
import RefundData from "./refund-data.vue"; import RefundData from "./refund-data.vue";
import AmountInput from "../../../../../Views/Components/AmountInput.vue"; import AmountInput from "../../../../../Views/Components/AmountInput.vue";
@@ -38,6 +38,20 @@ onMounted(async () => {
Object.assign(invoiceTypeCollection, data); Object.assign(invoiceTypeCollection, data);
}); });
/**
* Das Beispiel im Feld "Was wurde eingekauft" kommt aus `invoice_types.purchase_example` und ist damit
* ohne Deployment pflegbar. Ein allgemeines "z. B. Material" hilft beim Ausfüllen nicht weiter, und von
* genau diesem Text lebt später die Zweck-Spalte der EüR-Belegliste.
*
* Ist am Typ nichts gepflegt, greift der allgemeine Text -- ein Feld ohne jede Hilfestellung wäre
* schlechter als ein unscharfes Beispiel.
*/
const purchasePlaceholder = computed(() => {
const selected = Object.values(invoiceTypeCollection.invoiceTypes)
.find((type) => type.slug === invoiceType.value)
return selected?.purchaseExample || 'z. B. Material für die Veranstaltung'
})
function handleFileChange(event) { function handleFileChange(event) {
if (checkFilesize('receipt')) { if (checkFilesize('receipt')) {
@@ -66,28 +80,36 @@ function handleFileChange(event) {
<InfoIcon :text="'INFO_INVOICE_TYPE_' + availableInvoiceType.slug" /><br /> <InfoIcon :text="'INFO_INVOICE_TYPE_' + availableInvoiceType.slug" /><br />
</p> </p>
</fieldset><br /><br />
<label for="invoice_type_other"> <!--
Pflichtangabe zu jeder Rechnung, nicht nur zu "Sonstige Kosten": Erst dieser Text sagt, wofür das
Geld ausgegeben wurde, und füllt damit die Zweck-Spalte der EüR-Belegliste.
Die Schritte bauen aufeinander auf -- ohne Ausgabenart gäbe es kein passendes Beispiel für den
Einkauf, und ein Betrag ohne Zweck ließe sich später nicht mehr zuordnen.
-->
<template v-if="invoiceType !== null">
<fieldset>
<legend><span style="font-weight: bolder;">Was wurde eingekauft</span></legend>
<input <input
type="text" type="text"
class="width-full" class="width-full"
name="kostengruppe_sonstiges" id="purchase_description"
placeholder="Sonstige" name="purchase_description"
for="invoice_type_other" :placeholder="purchasePlaceholder"
v-model="otherText" v-model="otherText"
@focus="invoiceType = 'other'"
/> />
</label>
</fieldset><br /><br /> </fieldset><br /><br />
</template>
<fieldset> <fieldset v-if="invoiceType !== null && otherText.trim() !== ''">
<legend><span style="font-weight: bolder;">Wie hoch ist der Betrag</span></legend> <legend><span style="font-weight: bolder;">Wie hoch ist der Betrag</span></legend>
<AmountInput v-model="amount" class="width-small" id="amount" name="amount" /> Euro <AmountInput v-model="amount" class="width-small" id="amount" name="amount" /> Euro
<info-icon></info-icon><br /><br /> <info-icon></info-icon><br /><br />
<input <input
v-if="amount != '' && invoiceType !== null" v-if="amount != ''"
class="mareike-button" class="mareike-button"
onclick="document.getElementById('receipt').click();" onclick="document.getElementById('receipt').click();"
type="button" type="button"
@@ -1,6 +1,6 @@
<script setup> <script setup>
import { ref, onMounted, reactive } from 'vue' import { ref, computed, onMounted, reactive } from 'vue'
import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js"; import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js";
import RefundData from "./refund-data.vue"; import RefundData from "./refund-data.vue";
import AmountInput from "../../../../../Views/Components/AmountInput.vue"; import AmountInput from "../../../../../Views/Components/AmountInput.vue";
@@ -37,6 +37,20 @@ onMounted(async () => {
Object.assign(invoiceTypeCollection, data); Object.assign(invoiceTypeCollection, data);
}); });
/**
* Das Beispiel im Feld "Was wurde eingekauft" kommt aus `invoice_types.purchase_example` und ist damit
* ohne Deployment pflegbar. Ein allgemeines "z. B. Material" hilft beim Ausfüllen nicht weiter, und von
* genau diesem Text lebt später die Zweck-Spalte der EüR-Belegliste.
*
* Ist am Typ nichts gepflegt, greift der allgemeine Text -- ein Feld ohne jede Hilfestellung wäre
* schlechter als ein unscharfes Beispiel.
*/
const purchasePlaceholder = computed(() => {
const selected = Object.values(invoiceTypeCollection.invoiceTypes)
.find((type) => type.slug === invoiceType.value)
return selected?.purchaseExample || 'z. B. Material für die Veranstaltung'
})
function handleFileChange(event) { function handleFileChange(event) {
if (checkFilesize('receipt')) { if (checkFilesize('receipt')) {
@@ -65,28 +79,36 @@ function handleFileChange(event) {
<InfoIcon :text="'INFO_INVOICE_TYPE_' + availableInvoiceType.slug" /><br /> <InfoIcon :text="'INFO_INVOICE_TYPE_' + availableInvoiceType.slug" /><br />
</p> </p>
</fieldset><br /><br />
<label for="invoice_type_other"> <!--
Pflichtangabe zu jeder Abrechnung, nicht nur zu "Sonstige Kosten": Erst dieser Text sagt, wofür
das Geld ausgegeben wurde, und füllt damit die Zweck-Spalte der EüR-Belegliste.
Die Schritte bauen aufeinander auf -- ohne Ausgabenart gäbe es kein passendes Beispiel für den
Einkauf, und ein Betrag ohne Zweck ließe sich später nicht mehr zuordnen.
-->
<template v-if="invoiceType !== null">
<fieldset>
<legend><span style="font-weight: bolder;">Was wurde eingekauft</span></legend>
<input <input
type="text" type="text"
class="width-full" class="width-full"
name="kostengruppe_sonstiges" id="purchase_description"
placeholder="Sonstige" name="purchase_description"
for="invoice_type_other" :placeholder="purchasePlaceholder"
v-model="otherText" v-model="otherText"
@focus="invoiceType = 'other'"
/> />
</label>
</fieldset><br /><br /> </fieldset><br /><br />
</template>
<fieldset> <fieldset v-if="invoiceType !== null && otherText.trim() !== ''">
<legend><span style="font-weight: bolder;">Wie hoch ist der Betrag</span></legend> <legend><span style="font-weight: bolder;">Wie hoch ist der Betrag</span></legend>
<AmountInput v-model="amount" class="width-small" id="amount" name="amount" /> Euro <AmountInput v-model="amount" class="width-small" id="amount" name="amount" /> Euro
<info-icon></info-icon><br /><br /> <info-icon></info-icon><br /><br />
<input <input
v-if="amount != '' && invoiceType !== null" v-if="amount != ''"
class="mareike-button" class="mareike-button"
onclick="document.getElementById('receipt').click();" onclick="document.getElementById('receipt').click();"
type="button" type="button"
@@ -24,8 +24,6 @@ const props = defineProps({
userTelephone: String, userTelephone: String,
userAccountOwner: String, userAccountOwner: String,
userAccountIban: String, userAccountIban: String,
havePassengers: Number,
materialTransportation: Boolean,
travelReason: String, travelReason: String,
}) })
@@ -61,8 +59,6 @@ async function sendData() {
formData.append('accountOwner', userAccountOwner.value) formData.append('accountOwner', userAccountOwner.value)
formData.append('accountIban', userIban.value) formData.append('accountIban', userIban.value)
formData.append('paymentPurpose', paymentPurpose.value) formData.append('paymentPurpose', paymentPurpose.value)
formData.append('havePassengers', props.havePassengers ? 1 : 0)
formData.append('materialTransportation', props.materialTransportation ? 1 : 0)
formData.append('travelReason', props.travelReason) formData.append('travelReason', props.travelReason)
if (props.receipt) { if (props.receipt) {
@@ -24,9 +24,9 @@ const props = defineProps({
userTelephone: String, userTelephone: String,
userAccountOwner: String, userAccountOwner: String,
userAccountIban: String, userAccountIban: String,
havePassengers: Number,
materialTransportation: Boolean,
travelReason: String, travelReason: String,
travelReasonNote: String,
travellers: String,
}) })
const finalStep = ref(true) const finalStep = ref(true)
@@ -60,9 +60,9 @@ async function sendData() {
formData.append('decision', decision.value) formData.append('decision', decision.value)
formData.append('accountOwner', userAccountOwner.value) formData.append('accountOwner', userAccountOwner.value)
formData.append('accountIban', userIban.value) formData.append('accountIban', userIban.value)
formData.append('havePassengers', props.havePassengers ? 1 : 0)
formData.append('materialTransportation', props.materialTransportation ? 1 : 0)
formData.append('travelReason', props.travelReason) formData.append('travelReason', props.travelReason)
formData.append('travelReasonNote', props.travelReasonNote ?? '')
formData.append('travellers', props.travellers ?? '')
formData.append('notices', notices.value) formData.append('notices', notices.value)
if (props.receipt) { if (props.receipt) {
@@ -1,5 +1,5 @@
<script setup> <script setup>
import { ref, onMounted, reactive } from 'vue' import { ref, computed, onMounted, reactive } from 'vue'
import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js"; import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js";
import RefundData from "./refund-data.vue"; import RefundData from "./refund-data.vue";
import NumericInput from "../../../../../Views/Components/NumericInput.vue"; import NumericInput from "../../../../../Views/Components/NumericInput.vue";
@@ -19,15 +19,44 @@ const { request } = useAjax();
const distanceAllowance = ref(null); const distanceAllowance = ref(null);
const travelDirection = ref(null); const travelDirection = ref(null);
const travelReason = ref(null); const travelReason = ref(null);
const travelReasonNote = ref('');
const travelReasonCollection = reactive({
travelReasons: []
});
const selectedTravelReason = computed(() =>
travelReasonCollection.travelReasons.find((reason) => reason.value === travelReason.value)
);
/**
* Ein Grund ist erst vollständig, wenn die Erläuterung steht, die er verlangt: "Anderer Grund" allein
* sagt nichts aus. Die drei anderen Gründe bremsen den Ablauf dadurch nicht.
*/
const travelReasonComplete = computed(() =>
selectedTravelReason.value !== undefined
&& (!selectedTravelReason.value.requiresNote || travelReasonNote.value.trim() !== '')
);
/**
* Wer gereist ist, steht später als Zahlungsgrund in der Belegliste, auf der EüR und auf dem Beleg. Wer
* den Beleg einreicht, war meist selbst dabei -- deshalb der eigene Name als Vorschlag. Ohne Login
* bleibt das Feld leer, und es hält den Ablauf auch dann nicht auf: Ein Name ist eine Hilfe, keine
* Bedingung.
*/
const travellers = ref(data.userName || '');
const have_receipt = ref('') const have_receipt = ref('')
const havePassengers = ref(false);
const materialTransportation = ref(false);
const amount = ref(0.00); const amount = ref(0.00);
const invoiceType = ref(null); const invoiceType = ref(null);
const otherText = ref(''); const otherText = ref('');
const receipt = ref(null) const receipt = ref(null)
const finalStep = ref(false) const finalStep = ref(false)
onMounted(async () => {
const response = await fetch('/api/v1/core/retrieve-travel-reasons');
travelReasonCollection.travelReasons = await response.json();
});
async function getDistanceAllowance() { async function getDistanceAllowance() {
const tempData = await request('/api/v1/cost-unit/get-distance-allowance/' + data.eventId, { const tempData = await request('/api/v1/cost-unit/get-distance-allowance/' + data.eventId, {
method: "GET", method: "GET",
@@ -59,14 +88,40 @@ function handleFileChange(event) {
<fieldset v-if="travelDirection !== null"> <fieldset v-if="travelDirection !== null">
<legend><span style="font-weight: bolder;">Was war der Grund für deine Reise?</span></legend> <legend><span style="font-weight: bolder;">Was war der Grund für deine Reise?</span></legend>
<p v-for="availableReason in travelReasonCollection.travelReasons">
<input
name="travel-reason"
type="radio"
:value="availableReason.value"
:id="'travel_reason_' + availableReason.value"
v-model="travelReason"
>
<label :for="'travel_reason_' + availableReason.value">{{ availableReason.label }}</label><br />
</p>
<template v-if="selectedTravelReason?.requiresNote">
<input <input
type="text" type="text"
name="travel-reason" class="width-full"
v-model="travelReason" name="travel-reason-note"
placeholder="z. B. Abholung der Ausrüstung aus dem Lager"
v-model="travelReasonNote"
/>
</template>
</fieldset><br /><br />
<fieldset v-if="travelReasonComplete">
<legend><span style="font-weight: bolder;">Welche Personen sind gereist?</span></legend>
<input
type="text"
name="travellers"
placeholder="z. B. Mika, Kim und Alex"
v-model="travellers"
/> />
</fieldset><br /><br /> </fieldset><br /><br />
<fieldset v-if="travelReason !== null"> <fieldset v-if="travelReasonComplete">
<legend><span style="font-weight: bolder;">Bist du mit dem ÖPNV gefahren oder besitzt du einen Beleg</span></legend> <legend><span style="font-weight: bolder;">Bist du mit dem ÖPNV gefahren oder besitzt du einen Beleg</span></legend>
<input type="button" style="border-radius: 0; width: 100px;" @click="have_receipt='yes'" value="Ja" /> <input type="button" style="border-radius: 0; width: 100px;" @click="have_receipt='yes'" value="Ja" />
<input type="button" style="border-radius: 0; width: 100px;" @click="getDistanceAllowance" value="Nein" /> <input type="button" style="border-radius: 0; width: 100px;" @click="getDistanceAllowance" value="Nein" />
@@ -93,8 +148,6 @@ function handleFileChange(event) {
invoice-type="travelling" invoice-type="travelling"
:amount="amount" :amount="amount"
:other-text="travelDirection" :other-text="travelDirection"
:materialTransportation="materialTransportation"
:havePassengers="havePassengers"
:userName="data.userName" :userName="data.userName"
:userEmail="data.userEmail" :userEmail="data.userEmail"
:userTelephone="data.userTelephone" :userTelephone="data.userTelephone"
@@ -102,6 +155,8 @@ function handleFileChange(event) {
:userAccountOwner="data.userAccountOwner" :userAccountOwner="data.userAccountOwner"
:receipt="receipt" :receipt="receipt"
:travelReason="travelReason" :travelReason="travelReason"
:travelReasonNote="travelReasonNote"
:travellers="travellers"
@close="finalStep = false" @close="finalStep = false"
/> />
</fieldset> </fieldset>
@@ -117,22 +172,6 @@ function handleFileChange(event) {
<span style="font-weight: normal">({{ amount }} km x {{distanceAllowance.toFixed(2).replace('.', ',')}} Euro / km = <strong>{{ (amount * distanceAllowance).toFixed(2).replace('.', ',') }} Euro</strong>)</span> <span style="font-weight: normal">({{ amount }} km x {{distanceAllowance.toFixed(2).replace('.', ',')}} Euro / km = <strong>{{ (amount * distanceAllowance).toFixed(2).replace('.', ',') }} Euro</strong>)</span>
<br /><br /> <br /><br />
<input
type="checkbox"
name="havePassengers"
v-model="havePassengers"
id="havePassengers"
/> <label style="margin-bottom: 20px;" for="havePassengers">Ich habe Personen mitgenommen</label>
<br />
<input
type="checkbox"
name="materialTransportation"
v-model="materialTransportation"
id="materialTransportation"
/> <label style="margin-bottom: 20px;" for="materialTransportation">Ich habe Material transportiert</label>
<br /><br />
<input <input
v-if="amount !== null && have_receipt === 'no' && amount != '0'" v-if="amount !== null && have_receipt === 'no' && amount != '0'"
@click="finalStep = true;" @click="finalStep = true;"
@@ -145,14 +184,14 @@ function handleFileChange(event) {
invoice-type="travelling" invoice-type="travelling"
:amount="amount" :amount="amount"
:other-text="travelDirection" :other-text="travelDirection"
:materialTransportation="materialTransportation"
:havePassengers="havePassengers"
:userName="data.userName" :userName="data.userName"
:userEmail="data.userEmail" :userEmail="data.userEmail"
:userTelephone="data.userTelephone" :userTelephone="data.userTelephone"
:userAccountIban="data.userAccountIban" :userAccountIban="data.userAccountIban"
:userAccountOwner="data.userAccountOwner" :userAccountOwner="data.userAccountOwner"
:travelReason="travelReason" :travelReason="travelReason"
:travelReasonNote="travelReasonNote"
:travellers="travellers"
@close="finalStep = false" @close="finalStep = false"
/> />
@@ -35,7 +35,7 @@ class CreateParticipantInvoiceCommand
$this->participant = $request->participant; $this->participant = $request->participant;
$this->event = $request->participant->event; $this->event = $request->participant->event;
// Über die Relation und nicht über app('tenant'): die Rechnung hängt an der Veranstaltung, // Über die Relation und nicht über currentTenant(): die Rechnung hängt an der Veranstaltung,
// nicht am gerade aktiven Mandanten. `$event->tenant` liefert das Slug-Attribut, nicht die // nicht am gerade aktiven Mandanten. `$event->tenant` liefert das Slug-Attribut, nicht die
// Relation -- deshalb der ausdrückliche Aufruf. // Relation -- deshalb der ausdrückliche Aufruf.
$this->sender = $this->event->tenant()->first(); $this->sender = $this->event->tenant()->first();
@@ -74,6 +74,15 @@ class AcceptRefundCommand
$response->errorTypes['declaration'] = 'Bitte bestätige die Erklärung, damit wir erstatten können.'; $response->errorTypes['declaration'] = 'Bitte bestätige die Erklärung, damit wir erstatten können.';
} }
// Wer spendet, gibt kein Konto an -- alles Weitere betrifft nur die Auszahlung.
if (!$this->request->donation) {
// Erstattet wird ausschließlich auf das Konto, von dem der Beitrag kam. Ohne diese
// Bestätigung ließe sich über eine Erstattung Geld auf ein fremdes Konto umleiten.
if (!$this->request->accountDeclarationAccepted && $this->request->capturedBy === null) {
$response->errorTypes['accountDeclaration'] = 'Bitte bestätige, dass es das Konto ist, '
. 'von dem der Beitrag gezahlt wurde.';
}
if ($owner === '') { if ($owner === '') {
$response->errorTypes['accountOwner'] = 'Bitte gib an, wem das Konto gehört.'; $response->errorTypes['accountOwner'] = 'Bitte gib an, wem das Konto gehört.';
} }
@@ -83,6 +92,7 @@ class AcceptRefundCommand
} elseif (!Iban::isValid($iban)) { } elseif (!Iban::isValid($iban)) {
$response->errorTypes['accountIban'] = 'Diese IBAN stimmt nicht. Bitte prüfe deine Eingabe.'; $response->errorTypes['accountIban'] = 'Diese IBAN stimmt nicht. Bitte prüfe deine Eingabe.';
} }
}
if ($response->errorTypes !== []) { if ($response->errorTypes !== []) {
$response->message = 'Bitte prüfe deine Angaben.'; $response->message = 'Bitte prüfe deine Angaben.';
@@ -108,20 +118,27 @@ class AcceptRefundCommand
// Der Beleg entsteht in der Transaktion, weil er den bestätigten Stand abbildet; scheitert das // Der Beleg entsteht in der Transaktion, weil er den bestätigten Stand abbildet; scheitert das
// Einreichen, soll auch kein Beleg gelten. // Einreichen, soll auch kein Beleg gelten.
$document = DB::transaction(function () use ($refund, $owner, $iban, $costUnit) { $document = DB::transaction(function () use ($refund, $owner, $iban, $costUnit) {
$refund->account_owner = $owner; // Bei einer Spende bleiben die Kontofelder leer -- und zwar `null` und nicht Leerstring: Der
$refund->account_iban = $iban; // SEPA-Export unterscheidet daran, ob es etwas auszuzahlen gibt.
$refund->account_owner = $this->request->donation ? null : $owner;
$refund->account_iban = $this->request->donation ? null : $iban;
$refund->captured_by = $this->request->capturedBy; $refund->captured_by = $this->request->capturedBy;
$refund->status = ParticipantRefund::STATUS_ACCEPTED; $refund->status = ParticipantRefund::STATUS_ACCEPTED;
$refund->accepted_at = now(); $refund->accepted_at = now();
$refund->save(); $refund->save();
$document = new CreateRefundDocumentCommand(new CreateRefundDocumentRequest($refund))->execute(); // Die Spende wird hier ausdrücklich mitgegeben statt am Vorgang abgelesen: Die Abrechnung,
// die sie führt, entsteht erst weiter unten -- dieser Beleg ist ihr Anhang.
$document = new CreateRefundDocumentCommand(new CreateRefundDocumentRequest(
refund: $refund,
donation: $this->request->donation,
))->execute();
$invoice = $this->createInvoice($refund, $costUnit, $document); $invoice = $this->createInvoice($refund, $costUnit, $document);
// Erst jetzt, nicht früher: Beleg und Anmerkung der Abrechnung weisen den gezahlten Beitrag // Erst jetzt, nicht früher: Beleg und Anmerkung der Abrechnung weisen den gezahlten Beitrag
// aus und läsen sonst bereits die 0. // aus und läsen sonst bereits den verrechneten Stand.
$this->clearAmountPaid($refund); $this->settleAmountPaid($refund);
$refund->invoice_id = $invoice->id; $refund->invoice_id = $invoice->id;
$refund->save(); $refund->save();
@@ -132,7 +149,9 @@ class AcceptRefundCommand
$this->notify($refund, $document); $this->notify($refund, $document);
$response->success = true; $response->success = true;
$response->message = 'Vielen Dank. Deine Angaben liegen uns vor.'; $response->message = $this->request->donation
? 'Vielen Dank für deine Spende.'
: 'Vielen Dank. Deine Angaben liegen uns vor.';
return $response; return $response;
} }
@@ -141,7 +160,7 @@ class AcceptRefundCommand
* Die Kostenstelle der Veranstaltung. * Die Kostenstelle der Veranstaltung.
* *
* Ohne Zugriffsprüfung, weil hier niemand angemeldet ist -- der Teili bestätigt über seinen Token. * Ohne Zugriffsprüfung, weil hier niemand angemeldet ist -- der Teili bestätigt über seinen Token.
* Der Repository-Check greift sonst auf `auth()->user()->id` zu und liefe in einen Fehler. * Der Repository-Check greift sonst auf `currentUserOrFail()->id` zu und liefe in einen Fehler.
* *
* Bewusst ohne Prüfung auf `allow_new`/`archived`: Eine Erstattung fällt oft erst nach dem Ende der * Bewusst ohne Prüfung auf `allow_new`/`archived`: Eine Erstattung fällt oft erst nach dem Ende der
* Veranstaltung an, wenn die Kostenstelle längst geschlossen ist. Sie gehört trotzdem dorthin -- und * Veranstaltung an, wenn die Kostenstelle längst geschlossen ist. Sie gehört trotzdem dorthin -- und
@@ -177,7 +196,9 @@ class AcceptRefundCommand
invoiceType: InvoiceType::INVOICE_TYPE_PARTICIPATION_REFUND, invoiceType: InvoiceType::INVOICE_TYPE_PARTICIPATION_REFUND,
totalAmount: $refund->amount?->getAmount() ?? 0.0, totalAmount: $refund->amount?->getAmount() ?? 0.0,
receiptFile: $this->storeReceipt($costUnit, $document), receiptFile: $this->storeReceipt($costUnit, $document),
isDonation: false, // Hier landet die Entscheidung des Teilis, und nur hier: Die Abrechnung führt sie, der
// Vorgang liest sie über ParticipantRefund::isDonation() zurück.
isDonation: $this->request->donation,
userId: $participant->user_id, userId: $participant->user_id,
contactEmail: $participant->email_1, contactEmail: $participant->email_1,
contactPhone: $participant->phone_1, contactPhone: $participant->phone_1,
@@ -186,15 +207,6 @@ class AcceptRefundCommand
accountOwner: $refund->account_owner, accountOwner: $refund->account_owner,
accountIban: $refund->account_iban, accountIban: $refund->account_iban,
// Die folgenden vier gehören zu Reisekosten und Freitext-Typen und sind hier leer. Sie
// müssen trotzdem stehen: `transportations` hat als einziger Parameter keinen Vorgabewert,
// und PHP macht damit auch alle optionalen Parameter davor zu Pflichtangaben.
invoiceTypeExtended: null,
travelRoute: null,
distance: null,
passengers: null,
transportations: null,
// MUSS null bleiben (nicht ''): CreateInvoiceCommand verwirft die user_id, sobald hier etwas // MUSS null bleiben (nicht ''): CreateInvoiceCommand verwirft die user_id, sobald hier etwas
// steht -- der Teili fände seine Abrechnung dann nicht unter "Meine Abrechnungen". // steht -- der Teili fände seine Abrechnung dann nicht unter "Meine Abrechnungen".
paymentPurpose: null, paymentPurpose: null,
@@ -247,24 +259,38 @@ class AcceptRefundCommand
{ {
$paid = $refund->participant->amount_paid?->toString() ?? '0,00 Euro'; $paid = $refund->participant->amount_paid?->toString() ?? '0,00 Euro';
// Die Schatzmeisterei sieht die Abrechnung ohne den Vorgang dahinter. Dass nichts ausgezahlt
// wird, steht zwar im Spendenkennzeichen -- warum keine Bankverbindung dabei ist, aber nur hier.
$subject = $this->request->donation
? 'Spende statt Rückerstattung Teilnahmebeitrag'
: 'Rückerstattung Teilnahmebeitrag';
return Str::limit(sprintf( return Str::limit(sprintf(
'Rückerstattung Teilnahmebeitrag %s %s', '%s %s %s',
$subject,
$refund->event->name, $refund->event->name,
$refund->reasonLabel() $refund->reasonLabel()
), 180) . sprintf(' | Gezahlter Beitrag vor Erstattung: %s', $paid); ), 180) . sprintf(' | Gezahlter Beitrag vor Erstattung: %s', $paid);
} }
/** /**
* Setzt den gezahlten Beitrag des Teilis auf 0. * Zieht den erstatteten Betrag vom gezahlten Beitrag ab.
* *
* Mit der eingereichten Abrechnung ist der Beitrag nicht mehr beim Verband, sondern auf dem Weg * Danach führt `amount_paid` genau das, was beim Verband geblieben ist -- bei voller Erstattung also
* zurück -- die Zahlungsübersichten der Aktionsleitung sollen ihn nicht länger als offen führen. Der * 0, bei einer Teilerstattung den einbehaltenen Rest. Auf diesem Feld baut die Einnahmenrechnung der
* ursprüngliche Betrag steht zur Kontrolle in der Anmerkung der Abrechnung und auf dem Beleg. * Veranstaltung auf; es muss deshalb den tatsächlichen Bestand abbilden und nicht die Zahlung von
* einst. Der ursprüngliche Betrag steht zur Kontrolle in der Anmerkung der Abrechnung und auf dem
* Beleg.
*/ */
private function clearAmountPaid(ParticipantRefund $refund): void private function settleAmountPaid(ParticipantRefund $refund): void
{ {
$participant = $refund->participant; $participant = $refund->participant;
$participant->amount_paid = new Amount(0.0, 'Euro');
$paid = $participant->amount_paid?->getAmount() ?? 0.0;
$refunded = $refund->amount?->getAmount() ?? 0.0;
// `max` gegen Rundungsreste: Ein negativer gezahlter Betrag wäre in jeder Auswertung Unsinn.
$participant->amount_paid = new Amount(max(0.0, round($paid - $refunded, 2)), 'Euro');
$participant->save(); $participant->save();
} }
@@ -10,8 +10,28 @@ class AcceptRefundRequest
public readonly ?ParticipantRefund $refund, public readonly ?ParticipantRefund $refund,
public readonly string $accountOwner, public readonly string $accountOwner,
public readonly string $accountIban, public readonly string $accountIban,
/** Ob der Teili die Erklärung auf der Seite angekreuzt hat. Ohne sie taugt der Beleg nichts. */ /**
* Ob der Teili die Erklärung auf der Seite angekreuzt hat. Ohne sie taugt der Beleg nichts.
*
* Im Spendenweg ist es die Verzichtserklärung, im Auszahlungsweg die Versicherung über den
* gezahlten Beitrag -- in beiden Fällen die Erklärung, die anschließend auf dem Beleg steht.
*/
public readonly bool $declarationAccepted = false, public readonly bool $declarationAccepted = false,
/**
* Ob auf die Auszahlung verzichtet und der Betrag gespendet wird.
*
* Wird nicht am Vorgang gespeichert: Die Entscheidung landet in der Abrechnung
* (`invoices.donation`), von wo {@see ParticipantRefund::isDonation()} sie zurückliest. Dieses
* Feld ist der Weg dorthin.
*/
public readonly bool $donation = false,
/**
* Nur im Auszahlungsweg: die Bestätigung, dass es das Konto der Ursprungszahlung ist.
*
* Getrennt von der Haupterklärung, weil sie im Spendenweg gegenstandslos ist -- dort gibt es
* kein Konto.
*/
public readonly bool $accountDeclarationAccepted = false,
/** /**
* Die Aktionsleitung, wenn sie die Bankverbindung aufgenommen hat, weil sie ihr vorlag. * Die Aktionsleitung, wenn sie die Bankverbindung aufgenommen hat, weil sie ihr vorlag.
* *
@@ -27,6 +27,12 @@ class CreateRefundDocumentCommand
/** Name des `page_texts`-Eintrags mit der Erklärung -- dieselbe Quelle wie die Bestätigungsseite. */ /** Name des `page_texts`-Eintrags mit der Erklärung -- dieselbe Quelle wie die Bestätigungsseite. */
public const string DECLARATION_TEXT = 'CONFIRMATION_PARTICIPANT_REFUND'; public const string DECLARATION_TEXT = 'CONFIRMATION_PARTICIPANT_REFUND';
/** Die zweite Erklärung des Auszahlungswegs: dass es das Konto der Ursprungszahlung ist. */
public const string ACCOUNT_DECLARATION_TEXT = 'CONFIRMATION_PARTICIPANT_REFUND_ACCOUNT';
/** Tritt im Spendenweg an die Stelle beider anderen -- dort gibt es kein Konto. */
public const string DONATION_DECLARATION_TEXT = 'CONFIRMATION_PARTICIPANT_REFUND_DONATION';
private ParticipantRefund $refund; private ParticipantRefund $refund;
private EventParticipant $participant; private EventParticipant $participant;
@@ -104,6 +110,26 @@ class CreateRefundDocumentCommand
* Fallback stünde hier ein Fatal Error auf `null` -- so steht es heute im Deckblatt-Code der * Fallback stünde hier ein Fatal Error auf `null` -- so steht es heute im Deckblatt-Code der
* Auslagenerstattung, und daran soll sich der Beleg kein Beispiel nehmen. * Auslagenerstattung, und daran soll sich der Beleg kein Beispiel nehmen.
*/ */
/**
* Der Hinweis, warum ein Teil des Beitrags beim Verband bleibt -- leer bei voller Erstattung.
*
* Der Beleg wandert in die Buchhaltung und ins Archiv; dort muss die Differenz zwischen gezahltem
* und erstattetem Betrag ohne Rückfrage erklärt sein.
*/
private function retentionNote(): string
{
if (!$this->refund->hasRetention()) {
return '';
}
$text = trim($this->refund->retentionReasonText());
$label = $this->refund->retentionReasonLabel();
return $text !== '' && $text !== $label
? sprintf('%s (%s)', $label, $text)
: $label;
}
/** /**
* Der Vermerk, wenn die Aktionsleitung die Angaben aufgenommen hat. * Der Vermerk, wenn die Aktionsleitung die Angaben aufgenommen hat.
* *
@@ -128,12 +154,54 @@ class CreateRefundDocumentCommand
private function declarationText(): string private function declarationText(): string
{ {
$text = PageText::where('name', self::DECLARATION_TEXT)->first()?->content; if ($this->request->donation) {
return $this->pageText(
self::DONATION_DECLARATION_TEXT,
'Ich verzichte auf die Auszahlung des genannten Betrags und spende ihn an den Verband. '
. 'Mir ist bewusst, dass dieser Verzicht nicht rückgängig gemacht werden kann.'
);
}
return trim((string) $text) !== '' // Beide Sätze, weil die Person beide angekreuzt hat -- der Beleg schreibt ihr nur zu, was sie
? (string) $text // gelesen hat, und die Kontoerklärung ist der Grund, warum die Auszahlung zulässig ist.
: 'Ich versichere, dass ich den genannten Betrag beglichen habe und nicht anderweitig ' return $this->pageText(
. 'zurückerstattet bekomme.'; self::DECLARATION_TEXT,
'Ich versichere, dass ich den genannten Betrag beglichen habe und nicht anderweitig '
. 'zurückerstattet bekomme.'
) . '<br /><br />' . $this->pageText(
self::ACCOUNT_DECLARATION_TEXT,
'Ich bestätige, dass das angegebene Konto dasselbe ist, von dem der Teilnahmebeitrag '
. 'gezahlt wurde.'
);
}
/**
* Ein Seitentext mit Rückfallwert: Fehlt die Zeile in der Datenbank, soll der Beleg trotzdem
* entstehen. Ohne den Fallback stünde hier ein Fatal Error auf `null` -- so steht es heute im
* Deckblatt-Code der Auslagenerstattung, und daran soll sich der Beleg kein Beispiel nehmen.
*/
private function pageText(string $name, string $fallback): string
{
$text = PageText::where('name', $name)->first()?->content;
return trim((string) $text) !== '' ? (string) $text : $fallback;
}
/**
* Der Einleitungssatz des Belegs, passend zum gewählten Weg.
*
* Als Platzhalter und nicht fest in der Vorlage, weil er sich zwischen Auszahlung und Spende
* unterscheidet -- `{if:…}` kennt keine Verneinung, mit der eine Vorlage den einen Satz gegen den
* anderen tauschen könnte. Ältere, bereits installierte Vorlagen tragen den festen Satz weiter; dass
* gespendet wurde, steht dort in der Angabentabelle und in der Erklärung.
*/
private function introText(): string
{
return $this->request->donation
? 'Ich konnte an der Veranstaltung nicht oder nur teilweise teilnehmen. Auf die Auszahlung '
. 'des erstattungsfähigen Betrags verzichte ich und spende ihn an den Verband:'
: 'Ich konnte an der Veranstaltung nicht oder nur teilweise teilnehmen und bitte um die '
. 'Rückerstattung wie folgt:';
} }
/** /**
@@ -199,6 +267,10 @@ class CreateRefundDocumentCommand
'account_owner' => (string) $refund->account_owner, 'account_owner' => (string) $refund->account_owner,
'account_iban' => $this->formatIban((string) $refund->account_iban), 'account_iban' => $this->formatIban((string) $refund->account_iban),
'retained_amount' => $this->money($refund->retained_amount?->getAmount() ?? 0.0),
'retention_note' => $this->retentionNote(),
'intro_text' => $this->introText(),
'declaration_text' => $this->declarationText(), 'declaration_text' => $this->declarationText(),
'capture_note' => $this->captureNote(), 'capture_note' => $this->captureNote(),
@@ -242,8 +314,24 @@ class CreateRefundDocumentCommand
$rows[] = ['Begründung', e($reasonText)]; $rows[] = ['Begründung', e($reasonText)];
} }
// Nur bei einer Teilerstattung: Ohne diese Zeile bliebe die Differenz zwischen gezahltem und
// erstattetem Betrag im Beleg unerklärt.
if ($refund->hasRetention()) {
$rows[] = ['Einbehalten', $this->money($refund->retained_amount?->getAmount() ?? 0.0)];
$rows[] = ['Grund der Einbehaltung', e($this->retentionNote())];
}
// Bei einer Spende gibt es keine Bankverbindung. Statt zwei leerer Zeilen steht dort, warum --
// der Beleg wandert in die Buchhaltung, und "keine IBAN" allein sähe nach einer Lücke aus.
if ($this->request->donation) {
$rows[] = [
'Auszahlung',
'Auf die Auszahlung wird verzichtet; der Betrag verbleibt als Spende beim Verband.',
];
} else {
$rows[] = ['Kontoinhaber*in', e((string) $refund->account_owner)]; $rows[] = ['Kontoinhaber*in', e((string) $refund->account_owner)];
$rows[] = ['IBAN', e($this->formatIban((string) $refund->account_iban))]; $rows[] = ['IBAN', e($this->formatIban((string) $refund->account_iban))];
}
$html = ''; $html = '';
foreach ($rows as [$key, $value]) { foreach ($rows as [$key, $value]) {
@@ -8,6 +8,14 @@ class CreateRefundDocumentRequest
{ {
public function __construct( public function __construct(
public readonly ParticipantRefund $refund, public readonly ParticipantRefund $refund,
/**
* Ob der Betrag gespendet statt ausgezahlt wird.
*
* Ausdrücklich und nicht über {@see ParticipantRefund::isDonation()}: Beim Einreichen entsteht
* dieser Beleg vor der Abrechnung, die die Spende führt -- er ist ihr Anhang. Wer ihn später
* erneut zieht, liest sie dort und gibt sie hier weiter.
*/
public readonly bool $donation = false,
) { ) {
} }
} }
@@ -5,6 +5,7 @@ namespace App\Domains\ParticipantRefund\Actions\ReleaseRefund;
use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundCommand; use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundCommand;
use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundRequest; use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundRequest;
use App\Enumerations\RefundReason; use App\Enumerations\RefundReason;
use App\Enumerations\RetentionReason;
use App\Mail\ParticipantRefundMails\RefundReleasedMail; use App\Mail\ParticipantRefundMails\RefundReleasedMail;
use App\Models\EventParticipant; use App\Models\EventParticipant;
use App\Models\ParticipantRefund; use App\Models\ParticipantRefund;
@@ -57,26 +58,33 @@ class ReleaseRefundCommand
'amount' => $this->request->amount, 'amount' => $this->request->amount,
'reason' => $this->request->reason, 'reason' => $this->request->reason,
'reason_note' => $this->reasonNote(), 'reason_note' => $this->reasonNote(),
'released_by' => auth()->id(), // Was beim Verband bleibt, wird hier festgeschrieben: Nach dem Einreichen führt
// `amount_paid` bereits diesen Rest, eine spätere Differenz wäre falsch.
'retained_amount' => $this->request->retainedAmount(),
'retention_reason' => $this->retentionReason(),
'retention_reason_note' => $this->retentionReasonNote(),
'released_by' => currentUser()?->id,
'released_at' => now(), 'released_at' => now(),
]); ]);
if ($this->request->hasBankDetails()) { if ($this->request->submitsDirectly()) {
$this->submitDirectly($refund); $this->submitDirectly($refund);
} }
return $refund; return $refund;
}); });
if (!$this->request->hasBankDetails()) { if (!$this->request->submitsDirectly()) {
$this->notify($refund); $this->notify($refund);
} }
$response->success = true; $response->success = true;
$response->refund = $refund->fresh(); $response->refund = $refund->fresh();
$response->message = $this->request->hasBankDetails() $response->message = match (true) {
? 'Die Erstattung wurde eingereicht. Der Teili hat den Beleg per E-Mail erhalten.' $this->request->donation => 'Die Spende wurde eingereicht. Der Teili hat den Beleg per E-Mail erhalten.',
: 'Die Erstattung wurde freigegeben. Der Teili wurde per E-Mail informiert.'; $this->request->hasBankDetails() => 'Die Erstattung wurde eingereicht. Der Teili hat den Beleg per E-Mail erhalten.',
default => 'Die Erstattung wurde freigegeben. Der Teili wurde per E-Mail informiert.',
};
return $response; return $response;
} }
@@ -93,9 +101,10 @@ class ReleaseRefundCommand
refund: $refund, refund: $refund,
accountOwner: (string) $this->request->accountOwner, accountOwner: (string) $this->request->accountOwner,
accountIban: (string) $this->request->accountIban, accountIban: (string) $this->request->accountIban,
donation: $this->request->donation,
// Niemand kreuzt hier eine Erklärung an; wer die Angaben aufgenommen hat, hält `captured_by` // Niemand kreuzt hier eine Erklärung an; wer die Angaben aufgenommen hat, hält `captured_by`
// fest, und der Beleg weist es aus. // fest, und der Beleg weist es aus.
capturedBy: auth()->id(), capturedBy: currentUser()?->id,
))->execute(); ))->execute();
if (!$acceptResponse->success) { if (!$acceptResponse->success) {
@@ -141,7 +150,32 @@ class ReleaseRefundCommand
return 'Für diesen Grund ist eine Erläuterung erforderlich.'; return 'Für diesen Grund ist eine Erläuterung erforderlich.';
} }
return $this->rejectBankDetails(); return $this->rejectRetention() ?? $this->rejectBankDetails();
}
/**
* Prüfungen zum einbehaltenen Teil.
*
* Sicherheitsnetz hinter der Oberfläche: Dort erscheint der Absende-Knopf erst, wenn ein Grund
* gewählt ist. Über einen direkten Aufruf ginge das sonst vorbei, und ein einbehaltener Betrag ohne
* Begründung ist in der Buchhaltung nicht haltbar.
*/
private function rejectRetention(): ?string
{
if (!$this->request->hasRetention()) {
return null;
}
$reason = RetentionReason::find($this->request->retentionReason);
if ($reason === null) {
return 'Bitte gib an, warum ein Teil des Beitrags einbehalten wird.';
}
if ($reason->requires_note && trim((string) $this->request->retentionReasonNote) === '') {
return 'Für diesen Einbehaltungsgrund ist eine Erläuterung erforderlich.';
}
return null;
} }
/** /**
@@ -150,21 +184,29 @@ class ReleaseRefundCommand
*/ */
private function rejectBankDetails(): ?string private function rejectBankDetails(): ?string
{ {
// Eine Spende wird nicht ausgezahlt. Kämen beide Angaben zusammen, wäre unklar, was gilt --
// lieber nachfragen als das eine stillschweigend gegen das andere entscheiden.
if ($this->request->donation && (filled($this->request->accountOwner) || filled($this->request->accountIban))) {
return 'Eine Spende braucht keine Bankverbindung.';
}
// Halb ausgefüllt ist keine Absicht: entweder beides oder der Weg über den Teili. // Halb ausgefüllt ist keine Absicht: entweder beides oder der Weg über den Teili.
if (filled($this->request->accountOwner) !== filled($this->request->accountIban)) { if (!$this->request->donation
&& filled($this->request->accountOwner) !== filled($this->request->accountIban)) {
return 'Für die sofortige Erstattung werden Kontoinhaber*in und IBAN benötigt.'; return 'Für die sofortige Erstattung werden Kontoinhaber*in und IBAN benötigt.';
} }
if (!$this->request->hasBankDetails()) { if (!$this->request->submitsDirectly()) {
return null; return null;
} }
if (!Iban::isValid((string) $this->request->accountIban)) { if ($this->request->hasBankDetails() && !Iban::isValid((string) $this->request->accountIban)) {
return 'Diese IBAN stimmt nicht. Bitte prüfe die Eingabe.'; return 'Diese IBAN stimmt nicht. Bitte prüfe die Eingabe.';
} }
// Ohne Kostenstelle ließe sich die Abrechnung nicht anlegen. Hier abfangen und nicht erst in der // Ohne Kostenstelle ließe sich die Abrechnung nicht anlegen -- auch die Spende braucht eine, sie
// Transaktion, damit die Aktionsleitung eine verständliche Meldung sieht. // wird ja gebucht. Hier abfangen und nicht erst in der Transaktion, damit die Aktionsleitung eine
// verständliche Meldung sieht.
if ($this->participant->event->cost_unit_id === null) { if ($this->participant->event->cost_unit_id === null) {
return 'Die Veranstaltung hat keine Kostenstelle -- die Erstattung kann nicht eingereicht werden.'; return 'Die Veranstaltung hat keine Kostenstelle -- die Erstattung kann nicht eingereicht werden.';
} }
@@ -184,6 +226,33 @@ class ReleaseRefundCommand
return trim((string) $this->request->reasonNote); return trim((string) $this->request->reasonNote);
} }
/**
* Der Einbehaltungsgrund -- nur, wenn tatsächlich etwas beim Verband bleibt.
*
* Bei voller Erstattung wird ein mitgeschickter Grund verworfen: In der Oberfläche ist das Feld dann
* gar nicht sichtbar, und ein Wert ohne Bezug hätte in der Datenbank nichts zu suchen.
*/
private function retentionReason(): ?string
{
return $this->request->hasRetention() ? $this->request->retentionReason : null;
}
/** Der Freitext dazu -- wie beim Erstattungsgrund nur bei Gründen, die ihn verlangen. */
private function retentionReasonNote(): ?string
{
if (!$this->request->hasRetention()) {
return null;
}
$reason = RetentionReason::find($this->request->retentionReason);
if ($reason === null || !$reason->requires_note) {
return null;
}
return trim((string) $this->request->retentionReasonNote);
}
/** /**
* Teili und Kontaktperson bekommen je eine eigene Mail -- dasselbe Muster wie bei der Abmeldung * Teili und Kontaktperson bekommen je eine eigene Mail -- dasselbe Muster wie bei der Abmeldung
* (siehe SetParticipationStateCommand). * (siehe SetParticipationStateCommand).
@@ -20,6 +20,21 @@ class ReleaseRefundRequest
*/ */
public readonly ?string $accountOwner = null, public readonly ?string $accountOwner = null,
public readonly ?string $accountIban = null, public readonly ?string $accountIban = null,
/**
* Warum ein Teil des Beitrags beim Verband bleibt.
*
* Pflicht, sobald weniger erstattet wird als gezahlt wurde: Ein einbehaltener Betrag ohne Grund
* ist in der Buchhaltung nicht haltbar.
*/
public readonly ?string $retentionReason = null,
public readonly ?string $retentionReasonNote = null,
/**
* Der Teili spendet den Betrag, statt ihn ausgezahlt zu bekommen.
*
* Dann braucht es keine Bankverbindung, und die Erstattung wird -- wie beim vorliegenden Konto --
* sofort eingereicht. Gespeichert wird die Entscheidung in der Abrechnung, nicht am Vorgang.
*/
public readonly bool $donation = false,
) { ) {
} }
@@ -28,4 +43,29 @@ class ReleaseRefundRequest
{ {
return filled($this->accountOwner) && filled($this->accountIban); return filled($this->accountOwner) && filled($this->accountIban);
} }
/** Ob sofort eingereicht wird -- entweder liegt die Bankverbindung vor, oder es wird gespendet. */
public function submitsDirectly(): bool
{
return $this->hasBankDetails() || $this->donation;
}
/**
* Der Betrag, der beim Verband bleibt.
*
* Die halbe Cent-Toleranz fängt die Rundung des gespeicherten Floats ab -- ohne sie entstünden
* Restbeträge von Bruchteilen eines Cents, die eine Begründung verlangen würden.
*/
public function retainedAmount(): float
{
$paid = $this->participant->amount_paid?->getAmount() ?? 0.0;
$remaining = round($paid - $this->amount->getAmount(), 2);
return $remaining > 0.005 ? $remaining : 0.0;
}
public function hasRetention(): bool
{
return $this->retainedAmount() > 0.0;
}
} }
@@ -0,0 +1,70 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\ResendRefundMail;
use App\Mail\ParticipantRefundMails\RefundReleasedMail;
use App\Models\EventParticipant;
use Illuminate\Support\Facades\Mail;
/**
* Schickt die Mail zu einer freigegebenen Erstattung noch einmal.
*
* Der häufige Fall, wenn ein Vorgang hängt: die erste Mail ist untergegangen. Am Vorgang ändert sich
* dabei nichts -- `released_at` bleibt der Zeitpunkt der Vormerkung, der Token bleibt derselbe, der alte
* Link funktioniert also weiter.
*
* Nur solange die Bankverbindung fehlt: nach der Bestätigung wäre der Link wertlos, nach dem Abbruch
* liefe er ins Leere.
*/
class ResendRefundMailCommand
{
public function __construct(private readonly ResendRefundMailRequest $request)
{
}
public function execute(): ResendRefundMailResponse
{
$response = new ResendRefundMailResponse();
$refund = $this->request->refund;
if (!$refund->isPending()) {
$response->message = $refund->isAccepted()
? 'Diese Erstattung wurde bereits bestätigt -- es gibt nichts mehr nachzureichen.'
: 'Diese Erstattung wurde abgebrochen.';
return $response;
}
$this->notify();
$response->success = true;
$response->message = 'Die Rückerstattungsmail wurde erneut versendet.';
return $response;
}
/**
* Teili und Kontaktperson bekommen je eine eigene Mail -- dasselbe Muster wie bei der Freigabe
* (siehe ReleaseRefundCommand).
*/
private function notify(): void
{
/** @var EventParticipant $participant */
$participant = $this->request->refund->participant()->first();
$recipients = [$participant->email_1];
// `filled()` und nicht `!== null`: Der Anmeldewizard überspringt den Schritt "Kontaktperson" bei
// Volljährigen und legt das Feld als Leerstring an -- `Mail::to('')` liefe ins Leere.
if (filled($participant->email_2)) {
$recipients[] = $participant->email_2;
}
foreach ($recipients as $recipient) {
Mail::to($recipient)->send(new RefundReleasedMail(
participant: $participant,
refund: $this->request->refund,
));
}
}
}
@@ -0,0 +1,13 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\ResendRefundMail;
use App\Models\ParticipantRefund;
class ResendRefundMailRequest
{
public function __construct(
public readonly ParticipantRefund $refund,
) {
}
}
@@ -0,0 +1,10 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\ResendRefundMail;
class ResendRefundMailResponse
{
public bool $success = false;
public ?string $message = null;
}
@@ -22,6 +22,8 @@ class AcceptRefundController extends CommonController
accountOwner: (string) $request->input('accountOwner'), accountOwner: (string) $request->input('accountOwner'),
accountIban: (string) $request->input('accountIban'), accountIban: (string) $request->input('accountIban'),
declarationAccepted: $request->boolean('declarationAccepted'), declarationAccepted: $request->boolean('declarationAccepted'),
donation: $request->boolean('donation'),
accountDeclarationAccepted: $request->boolean('accountDeclarationAccepted'),
); );
$response = new AcceptRefundCommand($acceptRequest)->execute(); $response = new AcceptRefundCommand($acceptRequest)->execute();
@@ -18,7 +18,11 @@ class RefundDocumentController extends CommonController
abort(403, 'Zugriff verweigert.'); abort(403, 'Zugriff verweigert.');
} }
$documentResponse = new CreateRefundDocumentCommand(new CreateRefundDocumentRequest($refund))->execute(); $documentResponse = new CreateRefundDocumentCommand(new CreateRefundDocumentRequest(
refund: $refund,
// Beim Nachdruck steht die Abrechnung längst -- sie führt die Spende.
donation: $refund->isDonation(),
))->execute();
if (!$documentResponse->success) { if (!$documentResponse->success) {
abort(422, $documentResponse->message ?? 'Der Beleg konnte nicht erstellt werden.'); abort(422, $documentResponse->message ?? 'Der Beleg konnte nicht erstellt werden.');
@@ -53,6 +53,8 @@ class RefundPageController extends CommonController
return array_merge($common, [ return array_merge($common, [
'state' => 'accepted', 'state' => 'accepted',
'acceptedAt' => $refund->accepted_at?->format('d.m.Y'), 'acceptedAt' => $refund->accepted_at?->format('d.m.Y'),
// Wurde gespendet, darf der Abschlusstext keine Überweisung ankündigen, die nicht kommt.
'donation' => $refund->isDonation(),
]); ]);
} }
@@ -28,6 +28,12 @@ class ReleaseRefundController extends CommonController
// Leer, wenn der Teili die Bankverbindung selbst eintragen soll. // Leer, wenn der Teili die Bankverbindung selbst eintragen soll.
accountOwner: Text::nullIfBlank($request->input('accountOwner')), accountOwner: Text::nullIfBlank($request->input('accountOwner')),
accountIban: Text::nullIfBlank($request->input('accountIban')), accountIban: Text::nullIfBlank($request->input('accountIban')),
// Leer, wenn der volle Beitrag erstattet wird -- dann gibt es nichts zu begründen.
retentionReason: Text::nullIfBlank($request->input('retentionReason')),
retentionReasonNote: Text::nullIfBlank($request->input('retentionReasonNote')),
// Der Teili hat der Aktionsleitung gesagt, dass er spenden möchte -- dann entfällt die
// Bankverbindung und die Erstattung wird sofort als Spende eingereicht.
donation: $request->boolean('donation'),
); );
$response = new ReleaseRefundCommand($refundRequest)->execute(); $response = new ReleaseRefundCommand($refundRequest)->execute();
@@ -0,0 +1,30 @@
<?php
namespace App\Domains\ParticipantRefund\Controllers;
use App\Domains\ParticipantRefund\Actions\ResendRefundMail\ResendRefundMailCommand;
use App\Domains\ParticipantRefund\Actions\ResendRefundMail\ResendRefundMailRequest;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ResendRefundMailController extends CommonController
{
public function __invoke(string $refundToken, Request $request): JsonResponse
{
$refund = $this->participantRefunds->getByToken($refundToken);
// Der Token ist hier keine Berechtigung: nachschicken darf nur, wer die Veranstaltung auch
// verwalten kann. `getById()` prüft genau das.
if ($refund === null || $this->events->getById($refund->event_id) === null) {
abort(403, 'Zugriff verweigert.');
}
$response = new ResendRefundMailCommand(new ResendRefundMailRequest($refund))->execute();
return response()->json([
'status' => $response->success ? 'success' : 'error',
'message' => $response->message,
]);
}
}
@@ -61,11 +61,14 @@ final class ParticipantRefundTokens
'paid_amount' => ['description' => 'Bereits gezahlter Teilnahmebeitrag', 'sample' => '300,00 €'], 'paid_amount' => ['description' => 'Bereits gezahlter Teilnahmebeitrag', 'sample' => '300,00 €'],
'invoice_number' => ['description' => 'Nummer der Teilnahmerechnung', 'sample' => 'WM-V-20260701-0005'], 'invoice_number' => ['description' => 'Nummer der Teilnahmerechnung', 'sample' => 'WM-V-20260701-0005'],
'refund_amount' => ['description' => 'Erstattungsbetrag', 'sample' => '220,00 €'], 'refund_amount' => ['description' => 'Erstattungsbetrag', 'sample' => '220,00 €'],
'retained_amount' => ['description' => 'Betrag, der beim Verband bleibt — 0,00 € bei voller Erstattung', 'sample' => '80,00 €'],
'retention_note' => ['description' => 'Grund der Einbehaltung — leer bei voller Erstattung', 'sample' => 'Stornogebühr laut Ausschreibung'],
'refund_reason' => ['description' => 'Bezeichnung des Grundes', 'sample' => 'Krankheitsbedingte Absage'], 'refund_reason' => ['description' => 'Bezeichnung des Grundes', 'sample' => 'Krankheitsbedingte Absage'],
'refund_reason_text' => ['description' => 'Erläuterung des Grundes (bei „Sonstiger Grund" der Freitext)', 'sample' => 'Die Teilnahme konnte krankheitsbedingt nicht angetreten werden.'], 'refund_reason_text' => ['description' => 'Erläuterung des Grundes (bei „Sonstiger Grund" der Freitext)', 'sample' => 'Die Teilnahme konnte krankheitsbedingt nicht angetreten werden.'],
'account_owner' => ['description' => 'Kontoinhaber*in', 'sample' => 'Mika Muster'], 'account_owner' => ['description' => 'Kontoinhaber*in', 'sample' => 'Mika Muster'],
'account_iban' => ['description' => 'IBAN', 'sample' => 'DE02 1203 0000 0000 2020 51'], 'account_iban' => ['description' => 'IBAN', 'sample' => 'DE02 1203 0000 0000 2020 51'],
'declaration_text' => ['description' => 'Die Erklärung, die die teilnehmende Person bestätigt hat (gepflegt als Seitentext CONFIRMATION_PARTICIPANT_REFUND)', 'sample' => 'Ich versichere, dass ich den genannten Betrag beglichen habe und nicht anderweitig zurückerstattet bekomme.'], 'declaration_text' => ['description' => 'Die Erklärungen, die die teilnehmende Person bestätigt hat (gepflegt als Seitentexte CONFIRMATION_PARTICIPANT_REFUND und CONFIRMATION_PARTICIPANT_REFUND_ACCOUNT, bei einer Spende CONFIRMATION_PARTICIPANT_REFUND_DONATION)', 'sample' => 'Ich versichere, dass ich den genannten Betrag beglichen habe und nicht anderweitig zurückerstattet bekomme.<br /><br />Ich bestätige, dass das angegebene Konto dasselbe ist, von dem der Teilnahmebeitrag gezahlt wurde.'],
'intro_text' => ['description' => 'Einleitungssatz des Belegs — bei einer Spende der Verzicht statt der Bitte um Rückerstattung', 'sample' => 'Ich konnte an der Veranstaltung nicht oder nur teilweise teilnehmen und bitte um die Rückerstattung wie folgt:'],
'capture_note' => ['description' => 'Vermerk, wenn die Aktionsleitung die Bankverbindung aufgenommen hat — sonst leer', 'sample' => 'Angaben aufgenommen durch Aktions Leitung am 18.06.2026.'], 'capture_note' => ['description' => 'Vermerk, wenn die Aktionsleitung die Bankverbindung aufgenommen hat — sonst leer', 'sample' => 'Angaben aufgenommen durch Aktions Leitung am 18.06.2026.'],
], ],
], ],
@@ -111,6 +114,8 @@ final class ParticipantRefundTokens
. '<tr><td class="detail-key">Erstattungsbetrag</td><td class="detail-val">220,00&nbsp;&euro;</td></tr>' . '<tr><td class="detail-key">Erstattungsbetrag</td><td class="detail-val">220,00&nbsp;&euro;</td></tr>'
. '<tr><td class="detail-key">Grund</td><td class="detail-val">Krankheitsbedingte Absage</td></tr>' . '<tr><td class="detail-key">Grund</td><td class="detail-val">Krankheitsbedingte Absage</td></tr>'
. '<tr><td class="detail-key">Begr&uuml;ndung</td><td class="detail-val">Die Teilnahme konnte krankheitsbedingt nicht angetreten werden.</td></tr>' . '<tr><td class="detail-key">Begr&uuml;ndung</td><td class="detail-val">Die Teilnahme konnte krankheitsbedingt nicht angetreten werden.</td></tr>'
. '<tr><td class="detail-key">Einbehalten</td><td class="detail-val">80,00&nbsp;&euro;</td></tr>'
. '<tr><td class="detail-key">Grund der Einbehaltung</td><td class="detail-val">Stornogeb&uuml;hr laut Ausschreibung</td></tr>'
. '<tr><td class="detail-key">Kontoinhaber*in</td><td class="detail-val">Mika Muster</td></tr>' . '<tr><td class="detail-key">Kontoinhaber*in</td><td class="detail-val">Mika Muster</td></tr>'
. '<tr><td class="detail-key">IBAN</td><td class="detail-val">DE02 1203 0000 0000 2020 51</td></tr>' . '<tr><td class="detail-key">IBAN</td><td class="detail-val">DE02 1203 0000 0000 2020 51</td></tr>'
. '</table>'; . '</table>';
@@ -4,6 +4,7 @@ use App\Domains\ParticipantRefund\Controllers\AcceptRefundController;
use App\Domains\ParticipantRefund\Controllers\CancelRefundController; use App\Domains\ParticipantRefund\Controllers\CancelRefundController;
use App\Domains\ParticipantRefund\Controllers\RefundDocumentController; use App\Domains\ParticipantRefund\Controllers\RefundDocumentController;
use App\Domains\ParticipantRefund\Controllers\ReleaseRefundController; use App\Domains\ParticipantRefund\Controllers\ReleaseRefundController;
use App\Domains\ParticipantRefund\Controllers\ResendRefundMailController;
use App\Middleware\IdentifyTenant; use App\Middleware\IdentifyTenant;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
@@ -17,6 +18,7 @@ Route::prefix('api/v1')
Route::middleware(['auth'])->group(function () { Route::middleware(['auth'])->group(function () {
Route::post('{participantIdentifier}/release', ReleaseRefundController::class); Route::post('{participantIdentifier}/release', ReleaseRefundController::class);
Route::post('{refundToken}/cancel', CancelRefundController::class); Route::post('{refundToken}/cancel', CancelRefundController::class);
Route::post('{refundToken}/resend-mail', ResendRefundMailController::class);
Route::get('{refundToken}/document', RefundDocumentController::class); Route::get('{refundToken}/document', RefundDocumentController::class);
}); });
}); });
@@ -27,13 +27,33 @@ const props = defineProps({
reason: String, reason: String,
reasonNote: String, reasonNote: String,
acceptedAt: String, acceptedAt: String,
donation: Boolean,
}) })
// Der Zustand wandert in ein ref, damit die Seite nach dem Absenden umschalten kann, ohne neu zu laden. // Der Zustand wandert in ein ref, damit die Seite nach dem Absenden umschalten kann, ohne neu zu laden.
const state = ref(props.state) const state = ref(props.state)
const form = reactive({accountOwner: '', accountIban: '', declarationAccepted: false}) // Ob gespendet wurde -- für den Abschlusstext. Nach dem Absenden setzt submit() den Wert selbst, ein
const errors = reactive({accountOwner: '', accountIban: '', declaration: ''}) // Neuladen holt ihn vom Controller.
const donated = ref(props.donation === true)
/**
* Der Weg durch die Seite, nach dem Muster der Auslagenabrechnung (refund-data.vue): erst die
* Entscheidung, dann die Angaben dazu. Nichts wird gefragt, was für den gewählten Weg keine Rolle spielt.
*
* decision -- '' (noch nichts gewählt) | 'donation' (spenden) | 'payout' (auszahlen lassen)
* sameAccount -- nur bei 'payout': ob es das Konto der Ursprungszahlung ist
*/
const decision = ref('')
const sameAccount = ref(null)
const form = reactive({
accountOwner: '',
accountIban: '',
declarationAccepted: false,
accountDeclarationAccepted: false,
})
const errors = reactive({accountOwner: '', accountIban: '', declaration: '', accountDeclaration: ''})
const saving = ref(false) const saving = ref(false)
/** /**
@@ -48,12 +68,41 @@ const accountComplete = computed(
() => form.accountOwner.trim() !== '' && form.accountIban.trim() !== '' () => form.accountOwner.trim() !== '' && form.accountIban.trim() !== ''
) )
const isDonation = computed(() => decision.value === 'donation')
/**
* Wechselt den Weg und nimmt dabei jedes Kreuz zurück.
*
* Ohne das Zurücksetzen stünde eine Erklärung als bestätigt da, die in diesem Weg gar nicht gezeigt
* wurde -- wer erst die Auszahlung ankreuzt und dann zur Spende wechselt, hätte den Verzicht nie gelesen.
*/
function choose(next) {
decision.value = next
sameAccount.value = null
form.declarationAccepted = false
form.accountDeclarationAccepted = false
Object.keys(errors).forEach((key) => (errors[key] = ''))
}
/** Zurück zur ersten Frage -- aus der Sackgasse „anderes Konto" führt der Weg zur Spende. */
function reset() {
choose('')
}
function validate() { function validate() {
errors.accountOwner = form.accountOwner.trim() ? '' : 'Bitte gib an, wem das Konto gehört.' Object.keys(errors).forEach((key) => (errors[key] = ''))
errors.accountIban = form.accountIban.trim() ? '' : 'Bitte gib die IBAN des Kontos ein.'
errors.declaration = form.declarationAccepted ? '' : 'Bitte bestätige die Erklärung.' errors.declaration = form.declarationAccepted ? '' : 'Bitte bestätige die Erklärung.'
return !errors.accountOwner && !errors.accountIban && !errors.declaration if (!isDonation.value) {
errors.accountOwner = form.accountOwner.trim() ? '' : 'Bitte gib an, wem das Konto gehört.'
errors.accountIban = form.accountIban.trim() ? '' : 'Bitte gib die IBAN des Kontos ein.'
errors.accountDeclaration = form.accountDeclarationAccepted
? ''
: 'Bitte bestätige, dass es das Konto ist, von dem der Beitrag gezahlt wurde.'
}
return Object.values(errors).every((message) => message === '')
} }
async function submit() { async function submit() {
@@ -61,14 +110,21 @@ async function submit() {
saving.value = true saving.value = true
try { // Bei einer Spende geht keine Bankverbindung mit -- es gibt keine, und der Server erwartet auch keine.
const response = await request('/api/v1/participant-refund/' + props.token + '/accept', { const body = isDonation.value
method: 'POST', ? {donation: true, declarationAccepted: form.declarationAccepted}
body: { : {
donation: false,
accountOwner: form.accountOwner, accountOwner: form.accountOwner,
accountIban: form.accountIban, accountIban: form.accountIban,
declarationAccepted: form.declarationAccepted, declarationAccepted: form.declarationAccepted,
}, accountDeclarationAccepted: form.accountDeclarationAccepted,
}
try {
const response = await request('/api/v1/participant-refund/' + props.token + '/accept', {
method: 'POST',
body,
}) })
if (!response) { if (!response) {
@@ -88,6 +144,7 @@ async function submit() {
} }
toast.success(response.message) toast.success(response.message)
donated.value = isDonation.value
state.value = 'accepted' state.value = 'accepted'
} finally { } finally {
saving.value = false saving.value = false
@@ -128,7 +185,12 @@ async function submit() {
</table> </table>
<template v-if="state === 'accepted'"> <template v-if="state === 'accepted'">
<p class="hint"> <p v-if="donated" class="hint">
Du hast den Betrag gespendet<span v-if="props.acceptedAt"> (am {{ props.acceptedAt }})</span>
&ndash; vielen Dank. Es gibt nichts weiter zu tun. Stimmt etwas nicht, wende dich
bitte an die Aktionsleitung: {{ props.eventEmail }}
</p>
<p v-else class="hint">
Deine Angaben liegen uns vor<span v-if="props.acceptedAt"> (seit {{ props.acceptedAt }})</span>. Deine Angaben liegen uns vor<span v-if="props.acceptedAt"> (seit {{ props.acceptedAt }})</span>.
Die Überweisung veranlasst die Aktionsleitung. Stimmt etwas nicht, wende dich bitte Die Überweisung veranlasst die Aktionsleitung. Stimmt etwas nicht, wende dich bitte
an sie: {{ props.eventEmail }} an sie: {{ props.eventEmail }}
@@ -141,9 +203,98 @@ async function submit() {
dich bitte an die Aktionsleitung: {{ props.eventEmail }} dich bitte an die Aktionsleitung: {{ props.eventEmail }}
</p> </p>
<h3>Auf welches Konto sollen wir überweisen?</h3>
<form @submit.prevent="submit"> <form @submit.prevent="submit">
<!--
Erste Frage: Wer spendet, braucht kein Konto anzugeben. Deshalb steht sie
vor allem anderen.
-->
<h3>Möchtest du den Betrag stattdessen spenden?</h3>
<p class="choice-hint">
Spendest du, verbleibt der Betrag beim Verband und kommt unserer Arbeit
zugute. Wir brauchen dann keine Bankverbindung von dir.
</p>
<div class="choices">
<button
type="button"
class="choice"
:class="{active: decision === 'donation'}"
@click="choose('donation')"
>Ja, spenden</button>
<button
type="button"
class="choice"
:class="{active: decision === 'payout'}"
@click="choose('payout')"
>Nein, bitte erstatten</button>
</div>
<!-- Spendenweg: nur der Verzicht, keine Kontoangaben. -->
<template v-if="decision === 'donation'">
<div class="declaration">
<input
id="refund-donation-declaration"
v-model="form.declarationAccepted"
type="checkbox"
/>
<TextResource
text-name="CONFIRMATION_PARTICIPANT_REFUND_DONATION"
belongs-to="refund-donation-declaration"
/>
</div>
<ErrorText :message="errors.declaration" />
<button
v-if="form.declarationAccepted"
class="button"
type="submit"
:disabled="saving"
>
{{ saving ? 'Wird gespeichert…' : 'Betrag spenden' }}
</button>
</template>
<!--
Auszahlungsweg: Erstattet wird ausschließlich auf das Konto, von dem der
Beitrag kam. Das wird gefragt, bevor überhaupt eine IBAN eingegeben wird --
sonst tippt jemand ein Konto ab, das wir anschließend ablehnen müssen.
-->
<template v-else-if="decision === 'payout'">
<h3>Soll der Betrag auf das Konto erstattet werden, von dem der Beitrag
gezahlt wurde?</h3>
<div class="choices">
<button
type="button"
class="choice"
:class="{active: sameAccount === true}"
@click="sameAccount = true"
>Ja</button>
<button
type="button"
class="choice"
:class="{active: sameAccount === false}"
@click="sameAccount = false"
>Nein</button>
</div>
<template v-if="sameAccount === false">
<p class="hint">
So können wir den Betrag leider nicht erstatten: Zurück geht er nur auf
das Konto, von dem der Teilnahmebeitrag gezahlt wurde. Wurde er von
einem anderen Konto überwiesen &ndash; etwa dem eines Elternteils
&ndash;, gib bitte dieses an. Hilft das nicht weiter, wende dich bitte
an die Aktionsleitung: {{ props.eventEmail }}
</p>
<button type="button" class="button" @click="reset()">
Zurück zur Auswahl
</button>
</template>
<template v-else-if="sameAccount === true">
<div class="field"> <div class="field">
<label for="account-owner">Kontoinhaber*in</label> <label for="account-owner">Kontoinhaber*in</label>
<input <input
@@ -163,9 +314,9 @@ async function submit() {
</div> </div>
<!-- <!--
Die Erklärung, die anschließend auf dem Eigenbeleg steht. Sie muss hier Die Erklärungen, die anschließend auf dem Eigenbeleg stehen. Sie
gelesen und angekreuzt werden -- sonst schriebe der Beleg dem Teili eine müssen hier gelesen und angekreuzt werden -- sonst schriebe der Beleg
Zusicherung zu, die er nie abgegeben hat. dem Teili Zusicherungen zu, die er nie abgegeben hat.
--> -->
<template v-if="accountComplete"> <template v-if="accountComplete">
<div class="declaration"> <div class="declaration">
@@ -181,10 +332,23 @@ async function submit() {
</div> </div>
<ErrorText :message="errors.declaration" /> <ErrorText :message="errors.declaration" />
<!-- Beim Speichern gesperrt statt ausgeblendet, sonst verschwände der Knopf <div class="declaration">
unter dem Finger. --> <input
id="refund-account-declaration"
v-model="form.accountDeclarationAccepted"
type="checkbox"
/>
<TextResource
text-name="CONFIRMATION_PARTICIPANT_REFUND_ACCOUNT"
belongs-to="refund-account-declaration"
/>
</div>
<ErrorText :message="errors.accountDeclaration" />
<!-- Beim Speichern gesperrt statt ausgeblendet, sonst verschwände der
Knopf unter dem Finger. -->
<button <button
v-if="form.declarationAccepted" v-if="form.declarationAccepted && form.accountDeclarationAccepted"
class="button" class="button"
type="submit" type="submit"
:disabled="saving" :disabled="saving"
@@ -192,6 +356,8 @@ async function submit() {
{{ saving ? 'Wird gespeichert…' : 'Angaben absenden' }} {{ saving ? 'Wird gespeichert…' : 'Angaben absenden' }}
</button> </button>
</template> </template>
</template>
</template>
</form> </form>
</template> </template>
</template> </template>
@@ -235,6 +401,34 @@ h3 {
padding: 6px 0; padding: 6px 0;
} }
.choice-hint {
margin-bottom: 12px;
font-size: 0.9rem;
color: #4b5563;
}
.choices {
display: flex;
gap: 8px;
margin-bottom: 8px;
}
.choice {
flex: 1;
padding: 10px 12px;
border: 1px solid #d8dde6;
border-radius: 0;
background: #ffffff;
font-size: 0.95rem;
cursor: pointer;
}
.choice.active {
border-color: #1a4799;
background: #eef2fa;
font-weight: bold;
}
.field { .field {
margin-bottom: 16px; margin-bottom: 16px;
} }
@@ -23,7 +23,7 @@ use Illuminate\Http\Request;
class EmailVerificationController extends CommonController class EmailVerificationController extends CommonController
{ {
public function verifyEmailForm(Request $request) { public function verifyEmailForm(Request $request) {
$inertiaProvider = new InertiaProvider('UserManagement/VerifyEmail', ['appName' => app('tenant')->name]); $inertiaProvider = new InertiaProvider('UserManagement/VerifyEmail', ['appName' => currentTenant()->name]);
return $inertiaProvider->render(); return $inertiaProvider->render();
} }
@@ -17,7 +17,7 @@ class LoginController extends CommonController {
} }
$inertiaProvider = new InertiaProvider('UserManagement/Login', ['errors' => $errors, 'appName' => app('tenant')->name]); $inertiaProvider = new InertiaProvider('UserManagement/Login', ['errors' => $errors, 'appName' => currentTenant()->name]);
return $inertiaProvider->render(); return $inertiaProvider->render();
} }
@@ -45,8 +45,8 @@ class LoginController extends CommonController {
]); ]);
} }
$user = Auth::user(); $user = currentUserOrFail();
$tenant = app('tenant'); $tenant = currentTenant();
// Auf "lv" darf sich grundsätzlich jeder aktive Nutzer einloggen. // Auf "lv" darf sich grundsätzlich jeder aktive Nutzer einloggen.
// Auf Sub-Tenants gilt: // Auf Sub-Tenants gilt:
@@ -13,7 +13,7 @@ class ProfileController extends CommonController
return redirect()->intended('/login'); return redirect()->intended('/login');
} }
$user = auth()->user(); $user = currentUser();
$inertiaProvider = new InertiaProvider('UserManagement/Profile', [ $inertiaProvider = new InertiaProvider('UserManagement/Profile', [
'username' => $user->username, 'username' => $user->username,
@@ -26,8 +26,8 @@ class RegistrationController extends CommonController {
$inertiaProvider = new InertiaProvider('UserManagement/Registration', [ $inertiaProvider = new InertiaProvider('UserManagement/Registration', [
'errors' => $errors, 'errors' => $errors,
'appName' => app('tenant')->name, 'appName' => currentTenant()->name,
'tenant' => app('tenant'), 'tenant' => currentTenant(),
]); ]);
return $inertiaProvider->render(); return $inertiaProvider->render();
} }
@@ -46,7 +46,7 @@ class RegistrationController extends CommonController {
$userRoleMain = UserRole::USER_ROLE_USER; $userRoleMain = UserRole::USER_ROLE_USER;
$userRoleLocalGroup = UserRole::USER_ROLE_USER; $userRoleLocalGroup = UserRole::USER_ROLE_USER;
$localGroup = app('tenant')->slug === 'lv' ? $request->get('localGroup') : app('tenant')->slug; $localGroup = currentTenant()->slug === 'lv' ? $request->get('localGroup') : currentTenant()->slug;
$registrationRequest = new UserRegistrationRequest( $registrationRequest = new UserRegistrationRequest(
@@ -7,6 +7,7 @@ use App\Domains\UserManagement\Actions\UserChangePassword\UserChangePasswordRequ
use App\Scopes\CommonController; use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class StoreProfileController extends CommonController class StoreProfileController extends CommonController
{ {
@@ -27,11 +28,11 @@ class StoreProfileController extends CommonController
return response()->json(['success' => false, 'message' => 'Die Passwörter stimmen nicht überein.'], 422); return response()->json(['success' => false, 'message' => 'Die Passwörter stimmen nicht überein.'], 422);
} }
$actionRequest = new UserChangePasswordRequest(auth()->user(), $password); $actionRequest = new UserChangePasswordRequest(currentUserOrFail(), $password);
$command = new UserChangePasswordCommand($actionRequest); $command = new UserChangePasswordCommand($actionRequest);
$command->execute(); $command->execute();
auth()->logout(); Auth::logout();
return response()->json(['success' => true, 'message' => 'Dein Passwort wurde erfolgreich geändert.']); return response()->json(['success' => true, 'message' => 'Dein Passwort wurde erfolgreich geändert.']);
} }
} }
+20
View File
@@ -30,13 +30,16 @@ class InvoiceType extends CommonModel {
protected $fillable = [ protected $fillable = [
'slug', 'slug',
'name', 'name',
'purchase_example',
'sort_order', 'sort_order',
'selectable', 'selectable',
'counts_as_expense',
]; ];
protected $casts = [ protected $casts = [
'sort_order' => 'integer', 'sort_order' => 'integer',
'selectable' => 'boolean', 'selectable' => 'boolean',
'counts_as_expense' => 'boolean',
]; ];
/** /**
@@ -51,4 +54,21 @@ class InvoiceType extends CommonModel {
{ {
return self::where('selectable', true)->orderBy('sort_order')->get(); return self::where('selectable', true)->orderBy('sort_order')->get();
} }
/**
* Die Typen, die in der Ausgabenrechnung einer Veranstaltung zählen -- nach Sortierung.
*
* Ausgenommen ist, was fachlich keine Ausgabe ist, sondern die Rücknahme einer Einnahme: Eine
* Beitragserstattung mindert bereits die Einnahmenseite, weil der abgemeldete Teili dort herausfällt.
* Als Ausgabe gezählt, ginge derselbe Vorgang ein zweites Mal in die Bilanz.
*
* Der Name ist zweiter Sortierschlüssel: Die meisten Typen teilen sich `sort_order = 1`, und ohne ihn
* stünden die Zeilen der Ausgabenrechnung bei jedem Aufruf in einer anderen Reihenfolge.
*
* @return \Illuminate\Database\Eloquent\Collection<int, self>
*/
public static function countingAsExpense(): \Illuminate\Database\Eloquent\Collection
{
return self::where('counts_as_expense', true)->orderBy('sort_order')->orderBy('name')->get();
}
} }
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Enumerations;
use App\Scopes\CommonModel;
/**
* Gründe, aus denen ein Teil des gezahlten Teilnahmebeitrags beim Verband bleibt.
*
* Gegenstück zu {@see RefundReason}: Jener sagt, warum erstattet wird, dieser, warum nicht alles.
*
* @property string $slug
* @property string $name
* @property string|null $document_text
* @property bool $requires_note
* @property int $sort_order
*/
class RetentionReason extends CommonModel
{
public const string CANCELLATION_FEE = 'cancellation_fee';
public const string INCURRED_COSTS = 'incurred_costs';
public const string MATERIAL = 'material';
public const string CUSTOM = 'custom';
protected $table = 'retention_reasons';
protected $primaryKey = 'slug';
public $incrementing = false;
protected $keyType = 'string';
protected $fillable = [
'slug',
'name',
'document_text',
'requires_note',
'sort_order',
];
protected $casts = [
'requires_note' => 'boolean',
'sort_order' => 'integer',
];
/**
* Der Text, der auf dem Beleg unter „Einbehalten" steht. Bei einem Grund, der einen Freitext
* verlangt, ist es der Text der Aktionsleitung.
*/
public function documentText(?string $note = null): string
{
return $this->requires_note ? trim((string) $note) : (string) $this->document_text;
}
/**
* Optionen für das Frontend. `requiresNote` steuert dort das Freitextfeld.
*
* @return array<int, array{value: string, label: string, requiresNote: bool}>
*/
public static function options(): array
{
return self::orderBy('sort_order')->get()
->map(static fn (self $reason): array => [
'value' => $reason->slug,
'label' => $reason->name,
'requiresNote' => $reason->requires_note,
])
->all();
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace App\Enumerations;
use App\Scopes\CommonModel;
/**
* Gründe für eine Reisekostenabrechnung -- DB-gestützt (analog {@see RetentionReason}), damit die
* Auswahl ohne Deployment pflegbar bleibt.
*
* Gespeichert wird an der Abrechnung der Slug, bei `other` stattdessen der Freitext: Der Slug sagt für
* sich nichts aus, der Text alles. {@see \App\Models\Invoice::travelReasonText()} löst beides auf.
*
* @property string $slug
* @property string $name
* @property bool $requires_note
* @property int $sort_order
*/
class TravelReason extends CommonModel
{
public const string EVENT_TRAVEL = 'event_travel';
public const string MATERIAL_TRANSPORT = 'material_transport';
public const string PURCHASE = 'purchase';
public const string OTHER = 'other';
protected $table = 'travel_reasons';
protected $primaryKey = 'slug';
public $incrementing = false;
protected $keyType = 'string';
protected $fillable = [
'slug',
'name',
'requires_note',
'sort_order',
];
protected $casts = [
'requires_note' => 'boolean',
'sort_order' => 'integer',
];
/**
* Ein gespeicherter Wert als lesbarer Text: der Name des Grundes, sonst der Wert selbst.
*
* Der ist dann der Freitext von "Anderer Grund" oder stammt aus der Zeit vor der Auswahl -- beides
* ist bereits die Antwort auf die Frage und braucht keine Übersetzung.
*/
public static function text(?string $value): string
{
return self::find($value)?->name ?? (string) $value;
}
/**
* Optionen für das Frontend. `requiresNote` steuert dort das Freitextfeld.
*
* @return array<int, array{value: string, label: string, requiresNote: bool}>
*/
public static function options(): array
{
return self::orderBy('sort_order')->get()
->map(static fn (self $reason): array => [
'value' => $reason->slug,
'label' => $reason->name,
'requiresNote' => $reason->requires_note,
])
->all();
}
}
@@ -7,7 +7,7 @@ use App\Providers\InertiaProvider;
class TestRenderInertiaProvider class TestRenderInertiaProvider
{ {
public function index() { public function index() {
$inertiaProvider = new InertiaProvider('Invoice/CreateInvoice', ['appName' => app('tenant')->name]); $inertiaProvider = new InertiaProvider('Invoice/CreateInvoice', ['appName' => currentTenant()->name]);
return $inertiaProvider->render(); return $inertiaProvider->render();
} }
} }
+12 -4
View File
@@ -121,29 +121,37 @@ class ProductionDataSeeder {
private function installInvoiceMetaData() { private function installInvoiceMetaData() {
// `purchase_example` steht im Formular als Beispiel im Feld "Was wurde eingekauft" und ist dort
// Pflicht. Der Text hängt an der Ausgabenart, weil ein allgemeines "z. B. Material" beim
// Ausfüllen nicht weiterhilft; pflegen lässt er sich anschließend in der Tabelle.
InvoiceType::create([ InvoiceType::create([
'slug' => InvoiceType::INVOICE_TYPE_TRAVELLING, 'slug' => InvoiceType::INVOICE_TYPE_TRAVELLING,
'name' => 'Reisekosten' 'name' => 'Reisekosten',
'purchase_example' => 'z. B. Bahnfahrt HalleLeipzig',
]); ]);
InvoiceType::create([ InvoiceType::create([
'slug' => InvoiceType::INVOICE_TYPE_PROGRAM, 'slug' => InvoiceType::INVOICE_TYPE_PROGRAM,
'name' => 'Programmkosten' 'name' => 'Programmkosten',
'purchase_example' => 'z. B. Bastelmaterial für den Workshop',
]); ]);
InvoiceType::create([ InvoiceType::create([
'slug' => InvoiceType::INVOICE_TYPE_ACCOMMODATION, 'slug' => InvoiceType::INVOICE_TYPE_ACCOMMODATION,
'name' => 'Unterkunftskosten' 'name' => 'Unterkunftskosten',
'purchase_example' => 'z. B. zwei Nächte Jugendherberge',
]); ]);
InvoiceType::create([ InvoiceType::create([
'slug' => InvoiceType::INVOICE_TYPE_CATERING, 'slug' => InvoiceType::INVOICE_TYPE_CATERING,
'name' => 'Verpflegungskosten', 'name' => 'Verpflegungskosten',
'purchase_example' => 'z. B. Wocheneinkauf für das Frühstück',
]); ]);
InvoiceType::create([ InvoiceType::create([
'slug' => InvoiceType::INVOICE_TYPE_OTHER, 'slug' => InvoiceType::INVOICE_TYPE_OTHER,
'name' => 'Sonstige Kosten' 'name' => 'Sonstige Kosten',
'purchase_example' => 'z. B. Erste-Hilfe-Set',
]); ]);
InvoiceStatus::create(['slug' => InvoiceStatus::INVOICE_STATUS_NEW]); InvoiceStatus::create(['slug' => InvoiceStatus::INVOICE_STATUS_NEW]);
@@ -31,7 +31,9 @@ class RefundAcceptedMail extends Mailable
{ {
return new Envelope( return new Envelope(
subject: sprintf( subject: sprintf(
'Deine Angaben zur Rückerstattung für %s', $this->refund->isDonation()
? 'Deine Spende statt Rückerstattung für %s'
: 'Deine Angaben zur Rückerstattung für %s',
$this->participant->event()->first()->name $this->participant->event()->first()->name
), ),
); );
@@ -54,6 +56,14 @@ class RefundAcceptedMail extends Mailable
'accountIban' => Iban::format((string) $this->refund->account_iban), 'accountIban' => Iban::format((string) $this->refund->account_iban),
'hasDocument' => $this->pdfContent !== null, 'hasDocument' => $this->pdfContent !== null,
'invoiceNumber' => $invoice?->invoice_number, 'invoiceNumber' => $invoice?->invoice_number,
// Wurde gespendet, gibt es keine Bankverbindung und keine Überweisung, die angekündigt
// werden könnte. Steht in der Abrechnung, die hier ohnehin gelesen wird.
'donation' => (bool) $invoice?->donation,
// Wird nur ein Teil erstattet, soll der Teili nicht rätseln, wo der Rest geblieben ist.
'hasRetention' => $this->refund->hasRetention(),
'retainedAmount' => $this->refund->retained_amount?->toString() ?? '0,00 Euro',
'retentionReason' => $this->refund->retentionReasonLabel(),
'retentionReasonNote' => $this->refund->retention_reason_note,
// Hat die Aktionsleitung die Bankverbindung aufgenommen, hat der Teili selbst nichts // Hat die Aktionsleitung die Bankverbindung aufgenommen, hat der Teili selbst nichts
// eingetragen -- dann darf die Mail sich nicht für seine Angaben bedanken. // eingetragen -- dann darf die Mail sich nicht für seine Angaben bedanken.
'capturedByManagement' => $this->refund->wasCapturedByManagement(), 'capturedByManagement' => $this->refund->wasCapturedByManagement(),
+1 -1
View File
@@ -10,7 +10,7 @@ class AdminRoleMiddleware
{ {
public function handle($request, Closure $next) public function handle($request, Closure $next)
{ {
if (!auth()->check()) { if (currentUser() === null) {
return redirect('/login')->with('message', 'Du musst eingeloggt sein.'); return redirect('/login')->with('message', 'Du musst eingeloggt sein.');
} }
+1 -1
View File
@@ -8,7 +8,7 @@ class LvOnlyMiddleware
{ {
public function handle($request, Closure $next) public function handle($request, Closure $next)
{ {
if (app('tenant')->slug !== 'lv') { if (currentTenant()->slug !== 'lv') {
return redirect('/admin')->with('message', 'Diese Funktion ist nur auf LV-Ebene verfügbar.'); return redirect('/admin')->with('message', 'Diese Funktion ist nur auf LV-Ebene verfügbar.');
} }
+1 -1
View File
@@ -15,7 +15,7 @@ class MainAdminRoleMiddleware
{ {
public function handle($request, Closure $next) public function handle($request, Closure $next)
{ {
if (!auth()->check()) { if (currentUser() === null) {
return redirect('/login')->with('message', 'Du musst eingeloggt sein.'); return redirect('/login')->with('message', 'Du musst eingeloggt sein.');
} }
+1 -1
View File
@@ -169,7 +169,7 @@ class Event extends InstancedModel
public function paymentMethods() : BelongsToMany { public function paymentMethods() : BelongsToMany {
// Pivot verknüpft über den Slug (payment_methods.slug), nicht über die numerische id // Pivot verknüpft über den Slug (payment_methods.slug), nicht über die numerische id
// von available_payment_methods -- die tenant-spezifische Instanz wird dadurch implizit // von available_payment_methods -- die tenant-spezifische Instanz wird dadurch implizit
// über den globalen SiteScope von AvailablePaymentMethod (gefiltert auf app('tenant')) aufgelöst. // über den globalen SiteScope von AvailablePaymentMethod (gefiltert auf currentTenant()) aufgelöst.
return $this->belongsToMany(AvailablePaymentMethod::class, 'event_payment_methods', 'event_id', 'slug', 'id', 'slug') return $this->belongsToMany(AvailablePaymentMethod::class, 'event_payment_methods', 'event_id', 'slug', 'id', 'slug')
->using(EventPaymentMethods::class) ->using(EventPaymentMethods::class)
->withPivot('configuration') ->withPivot('configuration')
+76 -2
View File
@@ -4,6 +4,7 @@ namespace App\Models;
use App\Enumerations\InvoiceStatus; use App\Enumerations\InvoiceStatus;
use App\Enumerations\InvoiceType; use App\Enumerations\InvoiceType;
use App\Enumerations\TravelReason;
use App\Scopes\InstancedModel; use App\Scopes\InstancedModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -14,6 +15,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property string $status * @property string $status
* @property string $type * @property string $type
* @property string $type_other * @property string $type_other
* @property string $purpose
* @property boolean $donation * @property boolean $donation
* @property string $user_id * @property string $user_id
* @property string $contact_name * @property string $contact_name
@@ -26,8 +28,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property string $comment * @property string $comment
* @property string $changes * @property string $changes
* @property string $travel_direction * @property string $travel_direction
* @property boolean $passengers * @property boolean $passengers Nicht mehr erfasst -- siehe Hinweis unten
* @property boolean $transportation * @property boolean $transportation Nicht mehr erfasst -- siehe Hinweis unten
* @property string $document_filename * @property string $document_filename
* @property string $approved_by * @property string $approved_by
* @property string $approved_at * @property string $approved_at
@@ -35,6 +37,13 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property string $denied_by * @property string $denied_by
* @property string $denied_at * @property string $denied_at
* @property string $denied_reason * @property string $denied_reason
*
* `passengers` ("Ich habe Personen mitgenommen") und `transportation` ("Ich habe Material transportiert")
* werden seit dem Ausbau des Reisekosten-Formulars nicht mehr erfasst: Sie waren reine Ja/Nein-Angaben
* ohne Wirkung auf den Betrag -- eine Kostenstelle führt genau eine Kilometerpauschale, es gibt also
* keinen zweiten Satz, auf den sie umschalten könnten. Wer gereist ist, steht jetzt im `purpose`.
* Die Spalten bleiben für die Altdaten stehen; sollen sie je wiederkommen, dann als Angaben, die in die
* Berechnung eingehen (Mitnahmeentschädigung: eine Anzahl, kein Häkchen).
*/ */
class Invoice extends InstancedModel class Invoice extends InstancedModel
{ {
@@ -45,6 +54,7 @@ class Invoice extends InstancedModel
'status', 'status',
'type', 'type',
'type_other', 'type_other',
'purpose',
'donation', 'donation',
'user_id', 'user_id',
'contact_name', 'contact_name',
@@ -71,6 +81,70 @@ class Invoice extends InstancedModel
'denied_reason', 'denied_reason',
]; ];
/**
* Der Verwendungszweck für Überweisung, Buchungstext und Anzeige.
*
* Der Freitext gewinnt, wenn einer erfasst wurde. Sonst benennt der Text den Vorgang: eine
* Beitragserstattung ist keine Auslage des Teilis, sondern die Rücknahme seiner Zahlung -- auf dem
* Kontoauszug muss der Unterschied erkennbar sein. Genannt wird die Abrechnungsnummer, und zwar als
* Belegnummer: unter "Rechnungsnummer" gibt es sie nirgends.
*/
public function paymentPurposeText() : string {
if ($this->payment_purpose !== null) {
return $this->payment_purpose;
}
$subject = $this->type === InvoiceType::INVOICE_TYPE_PARTICIPATION_REFUND
? 'Beitragserstattung'
: 'Auslagenerstattung';
return $subject . ' Belegnummer ' . $this->invoice_number;
}
/**
* Wofür der Beleg steht -- der "Zahlungsgrund" der Beleglisten und der "Zweck" der EüR-Anlage.
*
* Erfasst wird er beim Anlegen und steht danach in der eigenen Spalte: eine Angabe, keine Ableitung.
* Nur so lässt er sich korrigieren, ohne dass ihn der nächste Vorgang wieder überschreibt.
*
* Bestandsbelege haben die Spalte leer -- für sie wird weiter abgeleitet, bei Fahrtkosten aus
* Reisegrund und `contact_name`, weil es die Frage "wer ist gefahren" damals nicht gab. Bleibt auch
* dabei nichts übrig, bleibt der Text leer; ein "--" würde in einer Belegliste nur Platz kosten.
*/
public function purposeText() : string {
if (trim((string) $this->purpose) !== '') {
return $this->purpose;
}
return self::joinPurposeParts(
$this->type === InvoiceType::INVOICE_TYPE_TRAVELLING
? [$this->travelReasonText(), $this->contact_name]
: [$this->type_other]
);
}
/**
* Der Reisegrund als lesbarer Text.
*
* Der Name des gewählten Grundes -- oder der Wert selbst, wenn er zu keinem passt. Der ist dann der
* Freitext von "Anderer Grund" oder stammt aus der Zeit vor der Auswahl.
*/
public function travelReasonText() : string {
return TravelReason::text($this->travel_reason);
}
/**
* Setzt einen Zahlungsgrund aus seinen Teilen zusammen: leere fallen weg, damit kein "" führt
* oder hängt.
*
* @param array<int, ?string> $parts
*/
public static function joinPurposeParts(array $parts) : string {
$parts = array_map(fn ($part) => trim((string) $part), $parts);
return implode(' — ', array_filter($parts, fn ($part) => $part !== ''));
}
public function costUnit() : BelongsTo{ public function costUnit() : BelongsTo{
return $this->belongsTo(CostUnit::class); return $this->belongsTo(CostUnit::class);
} }
+48
View File
@@ -4,6 +4,7 @@ namespace App\Models;
use App\Casts\AmountCast; use App\Casts\AmountCast;
use App\Enumerations\RefundReason; use App\Enumerations\RefundReason;
use App\Enumerations\RetentionReason;
use App\Scopes\InstancedModel; use App\Scopes\InstancedModel;
use App\ValueObjects\Amount; use App\ValueObjects\Amount;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -20,6 +21,9 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property Amount|null $amount * @property Amount|null $amount
* @property string|null $reason * @property string|null $reason
* @property string|null $reason_note * @property string|null $reason_note
* @property string|null $retention_reason
* @property string|null $retention_reason_note
* @property Amount|null $retained_amount
* @property string|null $account_owner * @property string|null $account_owner
* @property string|null $account_iban * @property string|null $account_iban
* @property int|null $captured_by * @property int|null $captured_by
@@ -51,6 +55,9 @@ class ParticipantRefund extends InstancedModel
'amount', 'amount',
'reason', 'reason',
'reason_note', 'reason_note',
'retention_reason',
'retention_reason_note',
'retained_amount',
'account_owner', 'account_owner',
'account_iban', 'account_iban',
'captured_by', 'captured_by',
@@ -63,6 +70,7 @@ class ParticipantRefund extends InstancedModel
protected $casts = [ protected $casts = [
'amount' => AmountCast::class, 'amount' => AmountCast::class,
'retained_amount' => AmountCast::class,
'released_at' => 'datetime', 'released_at' => 'datetime',
'accepted_at' => 'datetime', 'accepted_at' => 'datetime',
'cancelled_at' => 'datetime', 'cancelled_at' => 'datetime',
@@ -109,6 +117,18 @@ class ParticipantRefund extends InstancedModel
return $this->captured_by !== null; return $this->captured_by !== null;
} }
/**
* Ob auf die Auszahlung verzichtet und der Betrag gespendet wurde.
*
* Steht in der Abrechnung und nicht am Vorgang -- wie der Auszahlungsstand, aus demselben Grund: eine
* zweite Spalte könnte davon abweichen. Vor dem Einreichen gibt es keine Abrechnung und nichts zu
* entscheiden, dann ist die Antwort `false`.
*/
public function isDonation(): bool
{
return (bool) $this->invoice()->first()?->donation;
}
public function isPending(): bool public function isPending(): bool
{ {
return $this->status === self::STATUS_PENDING; return $this->status === self::STATUS_PENDING;
@@ -129,4 +149,32 @@ class ParticipantRefund extends InstancedModel
{ {
return (string) ($this->reasonRelation()->first()?->name ?? ''); return (string) ($this->reasonRelation()->first()?->name ?? '');
} }
/** Der Einbehaltungsgrund als Stammdatensatz -- leer, wenn voll erstattet wurde. */
public function retentionReasonRelation(): BelongsTo
{
return $this->belongsTo(RetentionReason::class, 'retention_reason', 'slug');
}
public function retentionReasonLabel(): string
{
return (string) ($this->retentionReasonRelation()->first()?->name ?? '');
}
/** Der auf dem Beleg auszuweisende Text zur Einbehaltung. */
public function retentionReasonText(): string
{
return $this->retentionReasonRelation()->first()?->documentText($this->retention_reason_note) ?? '';
}
/**
* Ob etwas beim Verband bleibt -- die halbe Cent-Toleranz fängt die Float-Rundung ab.
*
* Der Betrag steht in `retained_amount` und wird beim Einreichen festgeschrieben. Ihn zur Laufzeit
* aus `amount_paid` zu rechnen ginge schief: Danach führt das Feld bereits den Rest.
*/
public function hasRetention(): bool
{
return ($this->retained_amount?->getAmount() ?? 0.0) > 0.005;
}
} }
+1 -1
View File
@@ -50,7 +50,7 @@ class Tenant extends CommonModel
} }
public static function getTempDirectory() : string { public static function getTempDirectory() : string {
return app('tenant')->slug . '/temp-data/'; return currentTenant()->slug . '/temp-data/';
} }
/** /**
+3 -3
View File
@@ -2,7 +2,7 @@
namespace App\Models; namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
@@ -115,10 +115,10 @@ class User extends Authenticatable
} }
public function localGroup() : Tenant { public function localGroup() : Tenant {
return $this->belongsTo(Tenant::class, 'local_group', 'slug')->first(); return $this->belongsTo(Tenant::class, 'local_group', 'slug')->firstOrFail();
} }
public function costUnits() public function costUnits() : BelongsToMany
{ {
return $this->belongsToMany(CostUnit::class, 'cost_unit_treasurers', 'user_id', 'cost_unit_id') return $this->belongsToMany(CostUnit::class, 'cost_unit_treasurers', 'user_id', 'cost_unit_id')
->withTimestamps(); ->withTimestamps();
+6 -6
View File
@@ -7,12 +7,12 @@ use App\Models\User;
class AuthCheckProvider { class AuthCheckProvider {
public function checkLoggedIn() : bool { public function checkLoggedIn() : bool {
if (!auth()->check()) { $user = currentUser();
if ($user === null) {
return false; return false;
} }
$user = auth()->user(); $tenant = currentTenant();
$tenant = app('tenant');
if ($tenant->slug === 'lv') { if ($tenant->slug === 'lv') {
return $user->active; return $user->active;
} }
@@ -29,9 +29,9 @@ class AuthCheckProvider {
return null; return null;
} }
$user = auth()->user(); $user = currentUserOrFail();
if (app('tenant')->slug === 'lv') { if (currentTenant()->slug === 'lv') {
return $user->user_role_main; return $user->user_role_main;
} }
@@ -50,7 +50,7 @@ class AuthCheckProvider {
* Diese Rolle hebt das lokale Rechtesystem für alle Sub-Tenants auf. * Diese Rolle hebt das lokale Rechtesystem für alle Sub-Tenants auf.
*/ */
public function isMainAdministrator(?User $user = null) : bool { public function isMainAdministrator(?User $user = null) : bool {
$user ??= auth()->user(); $user ??= currentUser();
return $user !== null return $user !== null
&& $user->user_role_main === UserRole::USER_ROLE_ADMIN; && $user->user_role_main === UserRole::USER_ROLE_ADMIN;
+2 -2
View File
@@ -61,7 +61,7 @@ class CronTaskHandleProvider extends CommonController
private function runTask(CronTask $task) private function runTask(CronTask $task)
{ {
$logger = $this->taskLogger($task->name, app('tenant')); $logger = $this->taskLogger($task->name, currentTenant());
app()->instance('taskLogger', $logger); app()->instance('taskLogger', $logger);
$taskClass = "\\App\\Tasks\\" . $task->name; $taskClass = "\\App\\Tasks\\" . $task->name;
@@ -73,7 +73,7 @@ class CronTaskHandleProvider extends CommonController
$lastRun = []; $lastRun = [];
} }
$lastRun[app('tenant')->slug] = now(); $lastRun[currentTenant()->slug] = now();
// Update last_run // Update last_run
$task->last_run = $lastRun; $task->last_run = $lastRun;
$task->save(); $task->save();
+20 -5
View File
@@ -5,6 +5,8 @@ namespace App\Providers;
use App\Enumerations\EatingHabit; use App\Enumerations\EatingHabit;
use App\Enumerations\InvoiceType; use App\Enumerations\InvoiceType;
use App\Enumerations\RefundReason; use App\Enumerations\RefundReason;
use App\Enumerations\RetentionReason;
use App\Enumerations\TravelReason;
use App\Enumerations\UserRole; use App\Enumerations\UserRole;
use App\Models\AvailablePaymentMethod; use App\Models\AvailablePaymentMethod;
use App\Models\Tenant; use App\Models\Tenant;
@@ -21,7 +23,7 @@ class GlobalDataProvider {
private ?User $user; private ?User $user;
public function __invoke() { public function __invoke() {
$this->user = auth()->user(); $this->user = currentUser();
$canAccessAdmin = false; $canAccessAdmin = false;
$isMainAdmin = false; $isMainAdmin = false;
@@ -37,7 +39,7 @@ class GlobalDataProvider {
return response()->json([ return response()->json([
'user' => null !== $this->user ? new UserResource($this->user)->toArray(request()) : null, 'user' => null !== $this->user ? new UserResource($this->user)->toArray(request()) : null,
'navbar' => $this->generateNavbar(), 'navbar' => $this->generateNavbar(),
'tenant' => app('tenant'), 'tenant' => currentTenant(),
'activeUsers' => $this->getActiveUsers(), 'activeUsers' => $this->getActiveUsers(),
'version' => config('app.version'), 'version' => config('app.version'),
'currentEvent' => $this->getCurrentEventData(), 'currentEvent' => $this->getCurrentEventData(),
@@ -58,7 +60,10 @@ class GlobalDataProvider {
$invoiceTypes[] = [ $invoiceTypes[] = [
'slug' => $invoiceType->slug, 'slug' => $invoiceType->slug,
'name' => $invoiceType->name 'name' => $invoiceType->name,
// Beispieltext für "Was wurde eingekauft". Ist er nicht gepflegt, setzt das Formular
// seinen eigenen allgemeinen Text ein.
'purchaseExample' => $invoiceType->purchase_example,
]; ];
} }
@@ -185,8 +190,8 @@ class GlobalDataProvider {
$activeUsers = []; $activeUsers = [];
$conditions = ['active' => true]; $conditions = ['active' => true];
if (app('tenant')->slug !== 'lv') { if (currentTenant()->slug !== 'lv') {
$conditions['local_group'] = app('tenant')->slug; $conditions['local_group'] = currentTenant()->slug;
} }
foreach ($rawUsers = User::where($conditions)->get() as $user) { foreach ($rawUsers = User::where($conditions)->get() as $user) {
@@ -202,6 +207,16 @@ class GlobalDataProvider {
return response()->json(RefundReason::options()); return response()->json(RefundReason::options());
} }
/** Auswahl der Gründe, aus denen ein Teil des Beitrags beim Verband bleibt. */
public function getRetentionReasons() : JsonResponse {
return response()->json(RetentionReason::options());
}
/** Auswahl der Reisegründe für die Reisekostenabrechnung. */
public function getTravelReasons() : JsonResponse {
return response()->json(TravelReason::options());
}
public function getEventSettingData(Request $request) : JsonResponse { public function getEventSettingData(Request $request) : JsonResponse {
return response()->json( return response()->json(
[ [
+1 -1
View File
@@ -16,7 +16,7 @@ final class InertiaProvider
private ?User $user; private ?User $user;
public function __construct(string $vueFile, array $props) { public function __construct(string $vueFile, array $props) {
$this->user = auth()->user(); $this->user = currentUser();
$this->vueFile = $vueFile; $this->vueFile = $vueFile;
$this->props = $props; $this->props = $props;
} }
+2 -2
View File
@@ -20,7 +20,7 @@ class TenantUserProvider extends EloquentUserProvider
} }
// Auf "lv" gilt grundsätzlich keine local_group-Einschränkung. // Auf "lv" gilt grundsätzlich keine local_group-Einschränkung.
if (app('tenant')->slug === 'lv') { if (currentTenant()->slug === 'lv') {
return $query->first(); return $query->first();
} }
@@ -30,7 +30,7 @@ class TenantUserProvider extends EloquentUserProvider
// -> "Bundesrecht steht über Landesrecht": Login überall möglich. // -> "Bundesrecht steht über Landesrecht": Login überall möglich.
$query->where('active', true) $query->where('active', true)
->where(function ($q) { ->where(function ($q) {
$q->where('local_group', app('tenant')->slug) $q->where('local_group', currentTenant()->slug)
->orWhere('user_role_main', UserRole::USER_ROLE_ADMIN); ->orWhere('user_role_main', UserRole::USER_ROLE_ADMIN);
}); });
+1 -1
View File
@@ -25,7 +25,7 @@ class UploadFileProvider {
* wo alle anderen Belege liegen. * wo alle anderen Belege liegen.
*/ */
public static function directoryFor(CostUnit $costUnit) : string { public static function directoryFor(CostUnit $costUnit) : string {
return sprintf('%1$s/invoices/%2$s', app('tenant')->slug, $costUnit->id); return sprintf('%1$s/invoices/%2$s', currentTenant()->slug, $costUnit->id);
} }
public function saveUploadedFile() : ?InvoiceFile { public function saveUploadedFile() : ?InvoiceFile {
+51 -5
View File
@@ -2,11 +2,13 @@
namespace App\Repositories; namespace App\Repositories;
use \currentUser;
use App\Enumerations\CostUnitType; use App\Enumerations\CostUnitType;
use App\Enumerations\InvoiceStatus; use App\Enumerations\InvoiceStatus;
use App\Enumerations\InvoiceType; use App\Enumerations\InvoiceType;
use App\Enumerations\UserRole; use App\Enumerations\UserRole;
use App\Models\CostUnit; use App\Models\CostUnit;
use App\Models\Invoice;
use App\Providers\AuthCheckProvider; use App\Providers\AuthCheckProvider;
use App\Resources\CostUnitResource; use App\Resources\CostUnitResource;
use App\ValueObjects\Amount; use App\ValueObjects\Amount;
@@ -66,8 +68,7 @@ class CostUnitRepository {
} }
public function getCostUnitsByCriteria(array $criteria, bool $forDisplay = true, $disableAccessCheck = false) : array { public function getCostUnitsByCriteria(array $criteria, bool $forDisplay = true, $disableAccessCheck = false) : array {
$user = Auth()->user(); $user = currentUser();
if ($disableAccessCheck) { if ($disableAccessCheck) {
$canSeeAll = true; $canSeeAll = true;
} else { } else {
@@ -96,7 +97,7 @@ class CostUnitRepository {
public function listForSummary(int $maxCountCostUnits) : array { public function listForSummary(int $maxCountCostUnits) : array {
$costUnits = $this->getCostUnitsByCriteria([ $costUnits = $this->getCostUnitsByCriteria([
'archived' => false, 'archived' => false,
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
],false); ],false);
foreach ($costUnits as &$cu) { foreach ($costUnits as &$cu) {
@@ -153,8 +154,7 @@ class CostUnitRepository {
foreach ($costUnit->invoices()->get() as $invoice) { foreach ($costUnit->invoices()->get() as $invoice) {
if ( if (
$invoice->status === InvoiceStatus::INVOICE_STATUS_DENIED || !self::countsAsExpense($invoice) ||
$invoice->donation ||
$invoice->type !== $invoiceType->slug $invoice->type !== $invoiceType->slug
) { ) {
continue; continue;
@@ -165,6 +165,52 @@ class CostUnitRepository {
return $amount; return $amount;
} }
/**
* Die Ausgaben einer Kostenstelle, nach Ausgabentyp gruppiert -- Summe und die Belege dahinter.
*
* Jeder zählende Typ steht im Ergebnis, auch ohne Beleg: Die Einnahmen-Überschuss-Rechnung zeigt
* damit immer dieselbe Gliederung, und eine fehlende Zeile lässt sich nicht mit einer vergessenen
* verwechseln.
*
* @return array<string, array{type: InvoiceType, invoices: array<int, Invoice>, sum: Amount}>
*/
public function groupExpensesByType(CostUnit $costUnit) : array {
$groups = [];
foreach (InvoiceType::countingAsExpense() as $invoiceType) {
$groups[$invoiceType->slug] = [
'type' => $invoiceType,
'invoices' => [],
'sum' => new Amount(0, 'Euro'),
];
}
foreach ($costUnit->invoices()->orderBy('invoice_number')->get() as $invoice) {
if (!self::countsAsExpense($invoice) || !isset($groups[$invoice->type])) {
continue;
}
$groups[$invoice->type]['invoices'][] = $invoice;
$groups[$invoice->type]['sum']->addAmount(Amount::fromString($invoice->amount));
}
return $groups;
}
/**
* Ob ein Beleg als Ausgabe zählt.
*
* Abgelehnt und gelöscht sind keine Ausgabe, weil kein Geld fließt. Dasselbe gilt für eine gespendete
* Auslage: Auf die Auszahlung wurde verzichtet, die Kostenstelle gibt nichts aus.
*/
private static function countsAsExpense(Invoice $invoice) : bool {
return !in_array($invoice->status, [
InvoiceStatus::INVOICE_STATUS_DENIED,
InvoiceStatus::INVOICE_STATUS_DELETED,
], true)
&& !$invoice->donation;
}
public function sumupEstimatedByInvoiceType(CostUnit $costUnit, InvoiceType $invoiceType) : Amount { public function sumupEstimatedByInvoiceType(CostUnit $costUnit, InvoiceType $invoiceType) : Amount {
$amount = new Amount(0, 'Euro'); $amount = new Amount(0, 'Euro');
foreach ($costUnit->estimates()->get() as $estimate) { foreach ($costUnit->estimates()->get() as $estimate) {
@@ -297,7 +297,7 @@ class EventParticipantRepository {
public function getMyParticipations(?int $maxEvents = null) : array { public function getMyParticipations(?int $maxEvents = null) : array {
$participations = []; $participations = [];
$user = auth()->user(); $user = currentUser();
if ($user === null) { if ($user === null) {
return $participations; return $participations;
} }
@@ -326,13 +326,13 @@ class EventParticipantRepository {
} }
public function getMyParticipationByIdentifier(string $identifier) : ?EventParticipant { public function getMyParticipationByIdentifier(string $identifier) : ?EventParticipant {
$user = auth()->user(); $user = currentUser();
if ($user === null) { if ($user === null) {
return null; return null;
} }
return EventParticipant::where('identifier', $identifier) return EventParticipant::where('identifier', $identifier)
->where('tenant', app('tenant')->slug) ->where('tenant', currentTenant()->slug)
->where('user_id', $user->id) ->where('user_id', $user->id)
->whereNull('unregistered_at') ->whereNull('unregistered_at')
->first(); ->first();
+5 -5
View File
@@ -20,7 +20,7 @@ class InvoiceRepository {
]; ];
$user = auth()->user(); $user = currentUser();
if (null === $user) { if (null === $user) {
return $invoices; return $invoices;
} }
@@ -41,7 +41,7 @@ class InvoiceRepository {
} }
public function getUnexportedInvoices() : Collection { public function getUnexportedInvoices() : Collection {
return Invoice::where(['tenant' => app('tenant')->slug, 'status' => InvoiceStatus::INVOICE_STATUS_EXPORTED, 'upload_required' => true])->get(); return Invoice::where(['tenant' => currentTenant()->slug, 'status' => InvoiceStatus::INVOICE_STATUS_EXPORTED, 'upload_required' => true])->get();
} }
public function getByStatus(CostUnit $costUnit, string $status, bool $forDisplay = true) : array { public function getByStatus(CostUnit $costUnit, string $status, bool $forDisplay = true) : array {
@@ -63,8 +63,8 @@ class InvoiceRepository {
foreach (Invoice::where( foreach (Invoice::where(
[ [
'status' => $status, 'status' => $status,
'user_id' => auth()->user()->id, 'user_id' => currentUserOrFail()->id,
'tenant' => app('tenant')->slug, 'tenant' => currentTenant()->slug,
] ]
)->get() as $invoice) { )->get() as $invoice) {
@@ -79,7 +79,7 @@ class InvoiceRepository {
return null; return null;
} }
$isTreasurer = $invoice->costUnit()->first()->treasurers()->where('user_id', auth()->user()->id)->exists(); $isTreasurer = $invoice->costUnit()->first()->treasurers()->where('user_id', currentUserOrFail()->id)->exists();
if ($isTreasurer) { if ($isTreasurer) {
return $invoice; return $invoice;
} }
+2 -2
View File
@@ -20,7 +20,7 @@ class UserRepository {
} }
public function getCurrentUserDetails() : array { public function getCurrentUserDetails() : array {
$user = auth()->user(); $user = currentUser();
$return = [ $return = [
'userId' => null, 'userId' => null,
@@ -31,7 +31,7 @@ class UserRepository {
'userAccountIban' => '', 'userAccountIban' => '',
]; ];
if (null !== auth()->user()) { if ($user !== null) {
$return = [ $return = [
'userId' => $user->id, 'userId' => $user->id,
'userName' => trim($user->getOfficialName()), 'userName' => trim($user->getOfficialName()),
+4 -1
View File
@@ -32,7 +32,10 @@ class CostUnitResource {
$amounts = []; $amounts = [];
$overAllAmount = new Amount(0, 'Euro'); $overAllAmount = new Amount(0, 'Euro');
$overAllEstimatedAmount = new Amount(0, 'Euro'); $overAllEstimatedAmount = new Amount(0, 'Euro');
foreach (InvoiceType::orderBy('sort_order')->get() as $invoiceType) { // Nur echte Aufwandsarten: Eine Beitragserstattung ist die Rücknahme einer Einnahme und wird auf
// der Einnahmenseite bereits berücksichtigt -- hier gezählt, stünde sie ein zweites Mal in der
// Bilanz. `totalAmount` weiter oben bleibt davon unberührt, das ist die Kassensicht.
foreach (InvoiceType::countingAsExpense() as $invoiceType) {
$overAllAmount->addAmount($costUnitRepository->sumupByInvoiceType($this->costUnit, $invoiceType)); $overAllAmount->addAmount($costUnitRepository->sumupByInvoiceType($this->costUnit, $invoiceType));
$overAllEstimatedAmount->addAmount($costUnitRepository->sumupEstimatedByInvoiceType($this->costUnit, $invoiceType)); $overAllEstimatedAmount->addAmount($costUnitRepository->sumupEstimatedByInvoiceType($this->costUnit, $invoiceType));
$amounts[$invoiceType->slug]['string'] = $costUnitRepository->sumupByInvoiceType($this->costUnit, $invoiceType)->toString(); $amounts[$invoiceType->slug]['string'] = $costUnitRepository->sumupByInvoiceType($this->costUnit, $invoiceType)->toString();
+39 -2
View File
@@ -27,8 +27,8 @@ class EventResource extends JsonResource{
'id' => $this->event->id, 'id' => $this->event->id,
'name' => $this->event->name, 'name' => $this->event->name,
'identifier' => $this->event->identifier, 'identifier' => $this->event->identifier,
'url' => 'https://' . app('tenant')->url . '/event/' . $this->event->identifier . '/signup', 'url' => 'https://' . currentTenant()->url . '/event/' . $this->event->identifier . '/signup',
'urlShort' => 'https://' . app('tenant')->url . '/event/' . $this->event->identifier, 'urlShort' => 'https://' . currentTenant()->url . '/event/' . $this->event->identifier,
'location' => $this->event->location, 'location' => $this->event->location,
'postalCode' => $this->event->postal_code, 'postalCode' => $this->event->postal_code,
'email' => $this->event->email, 'email' => $this->event->email,
@@ -96,6 +96,14 @@ class EventResource extends JsonResource{
$returnArray['income'] = $this->calculateIncomes($returnArray['participants'], $returnArray['supportPerson']['amount']); $returnArray['income'] = $this->calculateIncomes($returnArray['participants'], $returnArray['supportPerson']['amount']);
// Eigene Zeile in der Übersicht: In den Zeilen je Teilnahmeart hätte der Betrag nichts zu suchen,
// dort stehen nur aktive Anmeldungen.
$retainedFromUnregistered = $this->sumPaidOfUnregistered();
$returnArray['retainedFromUnregistered'] = [
'value' => $retainedFromUnregistered->getAmount(),
'readable' => $retainedFromUnregistered->toString(),
];
$totalBalanceReal = new Amount(0, 'Euro'); $totalBalanceReal = new Amount(0, 'Euro');
$totalBalanceExpected = new Amount(0, 'Euro'); $totalBalanceExpected = new Amount(0, 'Euro');
@@ -272,6 +280,13 @@ class EventResource extends JsonResource{
$realAmount->addAmount(new Amount($participantData['amount']['paid']['value'], 'Euro')); $realAmount->addAmount(new Amount($participantData['amount']['paid']['value'], 'Euro'));
} }
// Was abgemeldete Teilis gezahlt haben und nicht zurückbekommen, gehört in beide Spalten: Das
// Geld liegt beim Verband (real) und fließt nicht mehr ab (erwartet). Ohne diese Zeile stünde
// jede Veranstaltung mit Abmeldungen dauerhaft schlechter da, als sie ist.
$retained = $this->sumPaidOfUnregistered();
$realAmount->addAmount($retained);
$expectedAmount->addAmount($retained);
return ['real' => [ return ['real' => [
'amount' => $realAmount, 'amount' => $realAmount,
'readable' => $realAmount->toString() 'readable' => $realAmount->toString()
@@ -283,6 +298,28 @@ class EventResource extends JsonResource{
]; ];
} }
/**
* Was von abgemeldeten Teilis beim Verband geblieben ist.
*
* `amount_paid` führt nach einer Erstattung genau den einbehaltenen Rest; wurde nie erstattet, steht
* dort der volle gezahlte Beitrag. Beides ist Geld, das der Veranstaltung zusteht.
*
* Bewusst eine direkte Abfrage wie in {@see self::getParticipants()} nebenan -- ein einzelner
* Repository-Aufruf zwischen den Inline-Queries dieser Klasse würde sie uneinheitlicher machen.
*/
public function sumPaidOfUnregistered() : Amount
{
$sum = new Amount(0, 'Euro');
foreach ($this->event->participants()->whereNotNull('unregistered_at')->get() as $participant) {
if ($participant->amount_paid !== null) {
$sum->addAmount($participant->amount_paid);
}
}
return $sum;
}
public function getParticipants(string $participationType) : array { public function getParticipants(string $participationType) : array {
$returnData = []; $returnData = [];
$returnData['amount'] = [ $returnData['amount'] = [
+5 -4
View File
@@ -30,6 +30,7 @@ class InvoiceResource {
} }
$returnData['invoiceTypeShort'] = $this->invoice->invoiceType()->name; $returnData['invoiceTypeShort'] = $this->invoice->invoiceType()->name;
$returnData['purpose'] = $this->invoice->purposeText();
$returnData['costUnitName'] = $this->invoice->costUnit()->first()->name; $returnData['costUnitName'] = $this->invoice->costUnit()->first()->name;
$returnData['invoiceNumber'] = $this->invoice->invoice_number; $returnData['invoiceNumber'] = $this->invoice->invoice_number;
$returnData['contactName'] = $this->invoice->contact_name; $returnData['contactName'] = $this->invoice->contact_name;
@@ -39,7 +40,7 @@ class InvoiceResource {
$returnData['id'] = $this->invoice->id; $returnData['id'] = $this->invoice->id;
$returnData['donation'] = $this->invoice->donation; $returnData['donation'] = $this->invoice->donation;
$returnData['externalPayment'] = null !== $this->invoice->payment_purpose; $returnData['externalPayment'] = null !== $this->invoice->payment_purpose;
$returnData['paymentPurpose'] = $this->invoice->payment_purpose ?? 'Auslagenerstattung Rechnungsnummer ' . $returnData['invoiceNumber']; $returnData['paymentPurpose'] = $this->invoice->paymentPurposeText();
$returnData['accountOwner'] = $this->invoice->contact_bank_owner ?? '--'; $returnData['accountOwner'] = $this->invoice->contact_bank_owner ?? '--';
$returnData['accountIban'] = $this->invoice->contact_bank_iban ?? '--'; $returnData['accountIban'] = $this->invoice->contact_bank_iban ?? '--';
$returnData['status'] = $this->invoice->status; $returnData['status'] = $this->invoice->status;
@@ -49,11 +50,11 @@ class InvoiceResource {
$returnData['changes'] = $this->invoice->changes ?? '--'; $returnData['changes'] = $this->invoice->changes ?? '--';
$returnData['deniedReason'] = $this->invoice->denied_reason ?? '--'; $returnData['deniedReason'] = $this->invoice->denied_reason ?? '--';
$returnData['travelDirection'] = $this->invoice->travel_direction ?? '--'; $returnData['travelDirection'] = $this->invoice->travel_direction ?? '--';
$returnData['travelReason'] = $this->invoice->travel_reason ?? '--'; $returnData['travelReason'] = $this->invoice->travel_reason === null
? '--'
: $this->invoice->travelReasonText();
$returnData['distance'] = $this->invoice->distance ?? '--'; $returnData['distance'] = $this->invoice->distance ?? '--';
$returnData['distanceAllowance'] = new Amount($this->invoice->costUnit()->first()->distance_allowance, '')->toString(); $returnData['distanceAllowance'] = new Amount($this->invoice->costUnit()->first()->distance_allowance, '')->toString();
$returnData['passengers'] = $this->invoice->passengers ? 'Ja' : 'Nein';
$returnData['transportation'] = $this->invoice->transportation ? 'Ja' : 'Nein';
$returnData['travelRoute'] = $this->invoice->travel_direction; $returnData['travelRoute'] = $this->invoice->travel_direction;
$returnData['costUnitId'] = $this->invoice->cost_unit_id; $returnData['costUnitId'] = $this->invoice->cost_unit_id;
$returnData['amountPlain'] = new Amount($this->invoice->amount, '')->toString(); $returnData['amountPlain'] = new Amount($this->invoice->amount, '')->toString();
@@ -29,11 +29,20 @@ class ParticipantRefundResource extends JsonResource
'reason' => $this->resource->reason, 'reason' => $this->resource->reason,
'reasonLabel' => $this->resource->reasonLabel(), 'reasonLabel' => $this->resource->reasonLabel(),
'reasonNote' => $this->resource->reason_note, 'reasonNote' => $this->resource->reason_note,
// Was beim Verband bleibt. `hasRetention` erspart dem Frontend den Betragsvergleich samt
// Rundungsfrage -- es soll nur entscheiden, ob der Hinweis angezeigt wird.
'hasRetention' => $this->resource->hasRetention(),
'retainedAmount' => $this->resource->retained_amount?->toString() ?? '0,00 Euro',
'retentionReasonLabel' => $this->resource->retentionReasonLabel(),
'retentionReasonNote' => $this->resource->retention_reason_note,
'releasedAt' => $this->resource->released_at?->format('d.m.Y'), 'releasedAt' => $this->resource->released_at?->format('d.m.Y'),
'acceptedAt' => $this->resource->accepted_at?->format('d.m.Y'), 'acceptedAt' => $this->resource->accepted_at?->format('d.m.Y'),
'cancelledAt' => $this->resource->cancelled_at?->format('d.m.Y'), 'cancelledAt' => $this->resource->cancelled_at?->format('d.m.Y'),
// Die Abrechnung, über die ausgezahlt wird -- ihr Status ist der Auszahlungsstand. // Die Abrechnung, über die ausgezahlt wird -- ihr Status ist der Auszahlungsstand.
'invoiceNumber' => $this->resource->invoice()->first()?->invoice_number, 'invoiceNumber' => $this->resource->invoice()->first()?->invoice_number,
// Ob überhaupt ausgezahlt wird: Bei einer Spende bleibt der Betrag beim Verband. Steht wie
// die Belegnummer in der Abrechnung.
'donation' => $this->resource->isDonation(),
]; ];
} }
} }
+1 -1
View File
@@ -31,7 +31,7 @@ abstract class CommonController {
protected AdminTenantRepository $adminTenants; protected AdminTenantRepository $adminTenants;
public function __construct() { public function __construct() {
$this->tenant = app('tenant'); $this->tenant = currentTenant();
$this->users = new UserRepository(); $this->users = new UserRepository();
$this->costUnits = new CostUnitRepository(); $this->costUnits = new CostUnitRepository();
$this->pageTexts = new PageTextRepository(); $this->pageTexts = new PageTextRepository();
+1 -1
View File
@@ -9,6 +9,6 @@ class SiteScope implements Scope
{ {
public function apply(Builder $builder, Model $model): void public function apply(Builder $builder, Model $model): void
{ {
$builder->where($model->getTable() . '.tenant', app('tenant')->slug); $builder->where($model->getTable() . '.tenant', currentTenant()->slug);
} }
} }

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