14 Commits
132 changed files with 37423 additions and 432 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([
'user' => $userData,
'isOwnUser' => auth()->id() === $user->id,
'isOwnUser' => currentUser()?->id === $user->id,
'isLvTenant' => $this->tenant->slug === 'lv',
'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]),
@@ -16,7 +16,7 @@ class UserToggleActiveController extends CommonController
$action = new ToggleUserActiveAction(new ToggleUserActiveRequest(
user: $user,
currentUserId: auth()->id(),
currentUserId: currentUser()?->id,
));
$response = $action->execute();
@@ -17,7 +17,7 @@ class UserUpdateController extends CommonController
$action = new UpdateUserAction(new UpdateUserRequest(
user: $user,
data: $request->all(),
isOwnUser: auth()->id() === $user->id,
isOwnUser: currentUser()?->id === $user->id,
isLvTenant: $this->tenant->slug === 'lv',
));
@@ -25,7 +25,7 @@ class CreateEstimateAction {
if ($this->request->estimateId === 0) {
$estimate = CostUnitEstimate::create(array_merge([
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
'cost_unit_id' => $this->request->costUnit->id,
'type' => $this->request->estimateType,
'description' => $this->request->description,
@@ -33,7 +33,7 @@ class CreateEstimateAction {
} else {
$estimate = CostUnitEstimate::find($this->request->estimateId);
$estimate->update(array_merge([
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
'cost_unit_id' => $this->request->costUnit->id,
'type' => $this->request->estimateType,
'description' => $this->request->description,
@@ -15,7 +15,7 @@ class CreateCostUnitCommand {
$response = new CreateCostUnitResponse();
$costUnit = CostUnit::create([
'name' => $this->request->name,
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
'type' => $this->request->type,
'billing_deadline' => $this->request->billingDeadline,
'distance_allowance' => $this->request->distanceAllowance->getAmount(),
@@ -93,7 +93,7 @@ class ExportController extends CommonController {
'amount' => $invoice->amount,
'recipient_name' => $invoice->contact_bank_owner,
'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>
<table v-if="localData.invoices.length > 0" class="invoice-list-table">
<tr>
<td colspan="6">{{props.data.costUnit.name}}</td>
<td colspan="7">{{props.data.costUnit.name}}</td>
</tr>
<tr v-for="invoice in localData.invoices" :id="'invoice_' + invoice.id">
<td>{{invoice.invoiceNumber}}</td>
<td>{{invoice.invoiceType}}</td>
<td>{{invoice.invoiceTypeShort}}</td>
<td style="max-width: 250px;">{{invoice.purpose}}</td>
<td>
{{invoice.amount}}
</td>
@@ -114,7 +115,7 @@
</tr>
<tr v-if="props.data.endpoint === 'approved'">
<td colspan="5"></td>
<td colspan="6"></td>
<td>
<a style="font-size: 10pt;" class="link" @click="exportPayouts()">Genehmigte Abrechnungen exportieren</a>
</td>
@@ -13,7 +13,7 @@ class PersonalDataController extends CommonController
return redirect()->intended('/login');
}
$user = auth()->user();
$user = currentUser();
$data = $this->users->getPersonalData($user);
$inertiaProvider = new InertiaProvider('Dashboard/PersonalData', [
@@ -12,7 +12,7 @@ class StorePersonalDataController extends CommonController
{
public function __invoke(Request $request): JsonResponse
{
$user = auth()->user();
$user = currentUser();
$actionRequest = new UpdatePersonalDataRequest(
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
// 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) {
EventLocalGroups::create(['event_id' => $event->id, 'local_group_id' => $tenant->id]);
}
} 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;
$event = $participant->event;
$uid = $participant->identifier . '@' . app('tenant')->slug;
$uid = $participant->identifier . '@' . currentTenant()->slug;
$dtStart = $event->start_date->format('Ymd');
$dtEnd = $event->end_date->copy()->addDay()->format('Ymd');
$now = now()->format('Ymd\THis\Z');
@@ -24,7 +24,7 @@ class GenerateIcalCommand
$icalContent = implode("\r\n", [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//' . app('tenant')->name . '//Veranstaltungskalender//DE',
'PRODID:-//' . currentTenant()->name . '//Veranstaltungskalender//DE',
'CALSCALE:GREGORIAN',
'METHOD:PUBLISH',
'BEGIN:VEVENT',
@@ -21,11 +21,11 @@ class GenerateIcalForDeadlineCommand {
$icalContent = implode("\r\n", [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//' . app('tenant')->name . '//Veranstaltungskalender//DE',
'PRODID:-//' . currentTenant()->name . '//Veranstaltungskalender//DE',
'CALSCALE:GREGORIAN',
'METHOD:PUBLISH',
'BEGIN:VEVENT',
'UID:payment-deadline-' . $event->identifier . '@' . app('tenant')->slug,
'UID:payment-deadline-' . $event->identifier . '@' . currentTenant()->slug,
'DTSTAMP:' . $now,
'DTSTART;VALUE=DATE:' . $dtDate,
'DTEND;VALUE=DATE:' . $dtDate,
@@ -18,7 +18,7 @@ class SetParticipationFeesCommand {
$this->cleanBefore();
$this->request->event->participationFee1()->associate(EventParticipationFee::create([
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
'type' => $this->request->participationFeeFirst['type'],
'name' => $this->request->participationFeeFirst['name'],
'description' => $this->request->participationFeeFirst['description'],
@@ -29,7 +29,7 @@ class SetParticipationFeesCommand {
if ($this->request->participationFeeSecond !== null) {
$this->request->event->participationFee2()->associate(EventParticipationFee::create([
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
'type' => $this->request->participationFeeSecond['type'],
'name' => $this->request->participationFeeSecond['name'],
'description' => $this->request->participationFeeSecond['description'],
@@ -41,7 +41,7 @@ class SetParticipationFeesCommand {
if ($this->request->participationFeeThird !== null) {
$this->request->event->participationFee3()->associate(EventParticipationFee::create([
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
'type' => $this->request->participationFeeThird['type'],
'name' => $this->request->participationFeeThird['name'],
'description' => $this->request->participationFeeThird['description'],
@@ -53,7 +53,7 @@ class SetParticipationFeesCommand {
if ($this->request->participationFeeFourth !== null) {
$this->request->event->participationFee4()->associate(EventParticipationFee::create([
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
'type' => $this->request->participationFeeFourth['type'],
'name' => $this->request->participationFeeFourth['name'],
'description' => $this->request->participationFeeFourth['description'],
@@ -21,7 +21,7 @@ use Illuminate\Http\Request;
class CreateController extends CommonController {
public function __invoke() {
return new InertiaProvider('Event/Create', [
'emailAddress' => auth()->user()->email,
'emailAddress' => currentUserOrFail()->email,
'eventAccount' => $this->tenant->account_name,
'eventIban' => $this->tenant->account_iban,
'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);
Mail::to($user->email)->send(new ManualMailsReportMail(
@@ -35,8 +35,9 @@ class SignupController extends CommonController {
'lastname' => '',
];
if (auth()->check()) {
$user = new UserResource(auth()->user())->toArray($request);
$currentUser = currentUser();
if ($currentUser !== null) {
$user = new UserResource($currentUser)->toArray($request);
$participantData = [
'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\CreateController;
use App\Domains\Event\Controllers\DetailsController;
use App\Domains\Event\Controllers\IncomeSurplusStatementController;
use App\Domains\Event\Controllers\SignupController;
use App\Middleware\IdentifyTenant;
use Illuminate\Support\Facades\Route;
@@ -18,6 +19,10 @@ Route::middleware(IdentifyTenant::class)->group(function () {
Route::middleware(['auth'])->group(function () {
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}/csv/{listType}', [DetailsController::class, 'downloadCsvList']);
});
@@ -106,6 +106,10 @@ async function showEventAddons() {
<input type="button" value="Beitragsliste (PDF)" />
</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'">
<input type="button" value="Getränkeliste (PDF)" />
</a><br/>
@@ -143,6 +147,10 @@ async function showEventAddons() {
<input type="button" value="Beitragsliste (PDF)" />
</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'">
<input type="button" value="Getränkeliste (PDF)" />
</a><br/>
@@ -386,7 +386,17 @@ function saveParticipant() {
Bankverbindung des Teilis
</small>
<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>
</td>
</tr>
@@ -541,4 +551,8 @@ textarea {
select {
width: 262px;
}
.retention-note {
color: #8a6d00;
}
</style>
@@ -10,6 +10,7 @@ import AmountInput from "../../../../Views/Components/AmountInput.vue";
import FullScreenModal from "../../../../Views/Components/FullScreenModal.vue";
import DialableTelephoneNumber from "../../../../Views/Components/DialableTelephoneNumber.vue";
import ErrorText from "../../../../Views/Components/ErrorText.vue";
import IbanInput from "../../../../Views/Components/IbanInput.vue";
const props = defineProps({
data: {
@@ -47,17 +48,86 @@ const openCancelDialog = ref(false);
const openPartialPaymentDialogSwitch = ref(false);
const openRefundDialogSwitch = ref(false);
// Der Erstattungsdialog. Betrag und Grund werden hier gesetzt; die Bankverbindung erfasst der Teili
// selbst über den Link, den die Freigabe ihm schickt.
const refundForm = reactive({amount: '', reason: '', reasonNote: ''});
const refundErrors = reactive({amount: '', reason: '', reasonNote: ''});
// 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
// vor -- dann wird die Erstattung sofort eingereicht.
const refundForm = reactive({
amount: '', reason: '', reasonNote: '',
captureMode: 'participant', accountOwner: '', accountIban: '',
retentionReason: '', retentionReasonNote: '',
});
const refundErrors = reactive({amount: '', reason: '', reasonNote: '', accountOwner: '', accountIban: ''});
const refundReasons = ref([]);
const retentionReasons = ref([]);
const refundSaving = ref(false);
const refundResending = ref(false);
const selectedRefundReason = computed(
() => 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'])
function openParticipantDetails(input) {
@@ -317,15 +387,25 @@ async function openRefundDialog(participant) {
refundForm.amount = participant.amountPaid?.short ?? '';
refundForm.reason = '';
refundForm.reasonNote = '';
refundErrors.amount = '';
refundErrors.reason = '';
refundErrors.reasonNote = '';
// Vorgabe ist der übliche Weg über den Teili.
refundForm.captureMode = 'participant';
refundForm.accountOwner = '';
refundForm.accountIban = '';
refundForm.retentionReason = '';
refundForm.retentionReasonNote = '';
Object.keys(refundErrors).forEach(key => refundErrors[key] = '');
if (refundReasons.value.length === 0) {
const reasons = await request('/api/v1/core/retrieve-refund-reasons', {method: 'GET'});
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;
}
@@ -333,9 +413,7 @@ function validateRefund() {
const amount = Number((refundForm.amount ?? '').replace(',', '.'));
const paid = Number(showParticipant.value?.amountPaidValue ?? 0);
refundErrors.amount = '';
refundErrors.reason = '';
refundErrors.reasonNote = '';
Object.keys(refundErrors).forEach(key => refundErrors[key] = '');
if (!refundForm.amount || !(amount > 0)) {
refundErrors.amount = 'Bitte gib einen Betrag größer als 0 ein.';
@@ -349,7 +427,19 @@ function validateRefund() {
refundErrors.reasonNote = 'Bitte erläutere den Grund.';
}
return !refundErrors.amount && !refundErrors.reason && !refundErrors.reasonNote;
// Beim Direktweg wird sofort eingereicht -- danach gibt es keine Gelegenheit mehr zu berichtigen.
// Ob die IBAN wirklich stimmt, prüft der Server mit Prüfziffer und länderabhängiger Länge.
if (refundForm.captureMode === 'management') {
if (!refundForm.accountOwner.trim()) {
refundErrors.accountOwner = 'Bitte gib an, wem das Konto gehört.';
}
if (!refundForm.accountIban.trim()) {
refundErrors.accountIban = 'Bitte gib die IBAN des Kontos ein.';
}
}
return Object.values(refundErrors).every(message => !message);
}
async function execRefund() {
@@ -366,13 +456,27 @@ async function execRefund() {
amount: refundForm.amount,
reason: refundForm.reason,
reasonNote: refundForm.reasonNote,
// Leer beim Weg über den Teili -- dann verschickt der Server nur den Link.
accountOwner: refundForm.captureMode === 'management' ? refundForm.accountOwner : '',
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 : '',
},
});
if (data?.status === 'success') {
toast.success(data.message);
// Reaktiv statt per getElementById: die Meta-Zeile hängt am Vorgang und wechselt mit ihm.
// Beim Direktweg steht dort sofort "Erstattet" samt Abrechnungsnummer.
showParticipant.value.refund = data.refund;
// Der gezahlte Beitrag wird beim Einreichen auf 0 gesetzt -- sonst zeigte die Zeile weiter
// den alten Stand, bis jemand neu lädt.
if (data.refund?.status === 'accepted') {
showParticipant.value.amountPaidValue = 0;
}
openRefundDialogSwitch.value = false;
} else {
toast.error(data?.message ?? 'Die Erstattung konnte nicht freigegeben werden.');
@@ -395,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) {
const ok = await download('/api/v1/participant-refund/' + participant.refund.token + '/document');
@@ -455,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' : ''">
Gezahlt: <label :id="'participant-' + participant.identifier + '-paid'">{{ participant?.amountPaid.readable }}</label> /<br />
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 />
<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;
@@ -517,13 +656,17 @@ function mailToGroup(groupKey) {
> | Beitrag erstatten</span>
<template v-else-if="participant.refund?.status === 'pending'">
| <strong>Erstattung offen:</strong> {{ participant.refund.amount }},
wartet auf Bankverbindung
| <strong>Rückerstattung vorgemerkt:</strong> {{ participant.refund.amount }}
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>
</template>
<template v-else-if="participant.refund?.status === 'accepted'">
| <strong>Erstattet:</strong> {{ participant.refund.amount }}
<template v-if="participant.refund.invoiceNumber">
&middot; Abrechnung {{ participant.refund.invoiceNumber }}
</template>
<span class="link" @click="downloadRefundDocument(participant)">Beleg</span>
</template>
</template>
@@ -600,8 +743,7 @@ function mailToGroup(groupKey) {
>
<p class="refund-intro">
{{ showParticipant?.fullname }} hat
<strong>{{ showParticipant?.amountPaid?.readable }}</strong> gezahlt. Nach der Freigabe erhält
der Teili eine E-Mail und trägt seine Bankverbindung selbst ein.
<strong>{{ showParticipant?.amountPaid?.readable }}</strong> gezahlt.
</p>
<div class="refund-field">
@@ -629,8 +771,95 @@ function mailToGroup(groupKey) {
<ErrorText :message="refundErrors.reasonNote" />
</div>
<button class="button" :disabled="refundSaving" @click="execRefund()">
{{ refundSaving ? 'Wird freigegeben' : 'Erstattung freigeben' }}
<!--
Bleibt ein Teil beim Verband, muss begründet sein, warum -- ein einbehaltener Betrag ohne
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">
<label class="refund-choice">
<input type="radio" value="participant" v-model="refundForm.captureMode" />
Teilnehmer*in trägt die Bankverbindung selbst ein
</label>
<label class="refund-choice">
<input type="radio" value="management" v-model="refundForm.captureMode" />
Bankverbindung liegt mir vor
</label>
<label class="refund-choice">
<input type="radio" value="donation" v-model="refundForm.captureMode" />
Teilnehmer*in spendet den Betrag
</label>
</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'">
<div class="refund-field">
<label for="refund_account_owner">Kontoinhaber*in</label>
<input
id="refund_account_owner"
v-model="refundForm.accountOwner"
type="text"
class="form-input"
/>
<ErrorText :message="refundErrors.accountOwner" />
</div>
<div class="refund-field">
<label for="refund_account_iban">IBAN</label>
<IbanInput id="refund_account_iban" v-model="refundForm.accountIban" class="form-input" />
<ErrorText :message="refundErrors.accountIban" />
</div>
<p class="refund-hint">
Die Erstattung wird sofort als Abrechnung eingereicht. Der Teili erhält den Beleg per
E-Mail und kann die Angaben prüfen.
</p>
</template>
<!-- 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-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>
</button>
</Modal>
@@ -665,10 +894,40 @@ function mailToGroup(groupKey) {
}
.refund-field select,
.refund-field textarea {
.refund-field textarea,
.refund-field .form-input {
width: 100%;
}
.refund-choice {
display: block;
margin-bottom: 6px;
font-size: 0.9rem;
color: #1a1a1a;
cursor: pointer;
}
.refund-choice input {
margin-right: 6px;
}
.retention-note {
display: block;
margin-top: 6px;
font-size: 10pt;
color: #ca5a0a;
line-height: 1.4;
}
.refund-hint {
margin-bottom: 14px;
padding: 8px 10px;
border-left: 3px solid #f5c400;
background-color: #fffef5;
font-size: 0.85rem;
color: #4b5563;
}
.participants-table {
width: 95%;
margin: 20px auto;
@@ -68,6 +68,17 @@ const props = defineProps({
</td>
</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>
<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">
@@ -22,7 +22,7 @@ class ChangeStatusCommand {
switch ($this->request->status) {
case 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();
if ($this->request->invoice->contact_email !== null) {
@@ -35,7 +35,7 @@ class ChangeStatusCommand {
case 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_reason = $this->request->comment;
if ($this->request->invoice->contact_email !== null) {
@@ -3,6 +3,8 @@
namespace App\Domains\Invoice\Actions\CreateInvoice;
use App\Enumerations\InvoiceStatus;
use App\Enumerations\InvoiceType;
use App\Enumerations\TravelReason;
use App\Mail\InvoiceMails\InvoiceMailsNewInvoiceMail;
use App\Mail\InvoiceMails\InvoiceMailsSubmittedConfirmationMail;
use App\Mail\ParticipantParticipationMails\EventSignUpSuccessfullMail;
@@ -19,17 +21,27 @@ class CreateInvoiceCommand {
public function execute() : CreateInvoiceResponse {
$response = new CreateInvoiceResponse();
$rejection = $this->rejectTravelReason();
if ($rejection !== null) {
$response->message = $rejection;
return $response;
}
if ($this->request->accountIban === 'undefined') {
$this->request->accountIban = null;
}
$travelReason = $this->travelReason();
$invoice = Invoice::create([
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
'cost_unit_id' => $this->request->costUnit->id,
'invoice_number' => $this->generateInvoiceNumber(),
'status' => InvoiceStatus::INVOICE_STATUS_NEW,
'type' => $this->request->invoiceType,
'type_other' => $this->request->invoiceTypeExtended,
'purpose' => $this->purpose($travelReason),
'donation' => $this->request->isDonation,
'user_id' => $this->request->paymentPurpose === null ? $this->request->userId : null,
'contact_name' => $this->request->contactName,
@@ -40,9 +52,7 @@ class CreateInvoiceCommand {
'amount' => $this->request->totalAmount,
'distance' => $this->request->distance,
'travel_direction' => $this->request->travelRoute,
'travel_reason' => $this->request->travelReason,
'passengers' => $this->request->passengers,
'transportation' => $this->request->transportations,
'travel_reason' => $travelReason,
'payment_purpose' => $this->request->paymentPurpose,
'comment' => $this->request->notices,
'document_filename' => $this->request->receiptFile !== null ? $this->request->receiptFile->fullPath : null,
@@ -61,7 +71,7 @@ class CreateInvoiceCommand {
}
if ($this->request->costUnit->mail_on_new) {
$recipients = [app('tenant')->email_finance];
$recipients = [currentTenant()->email_finance];
foreach ($this->request->costUnit->treasurers()->get() as $treasurer) {
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 {
$lastInvoiceNumber = Invoice::query()
->where('tenant', app('tenant')->slug)
->where('tenant', currentTenant()->slug)
->whereYear('created_at', date('Y'))
->count();
@@ -16,16 +16,24 @@ class CreateInvoiceRequest {
public ?string $invoiceTypeExtended;
public ?string $travelRoute;
public ?int $distance;
public ?int $passengers;
public ?int $transportations;
public ?InvoiceFile $receiptFile;
public float $totalAmount;
public bool $isDonation;
public ?int $userId;
/** Der Slug eines Reisegrundes -- oder ein Freitext, wenn er von einem Bestandsbeleg stammt. */
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 $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(
CostUnit $costUnit,
@@ -42,11 +50,12 @@ class CreateInvoiceRequest {
?string $invoiceTypeExtended = null,
?string $travelRoute = null,
?int $distance = null,
?int $passengers = null,
?int $transportations,
?string $travelReason = null,
?string $travelReasonNote = null,
?string $paymentPurpose = null,
?string $notices = null,
?string $travellers = null,
?string $purpose = null,
) {
$this->costUnit = $costUnit;
@@ -55,8 +64,6 @@ class CreateInvoiceRequest {
$this->invoiceTypeExtended = $invoiceTypeExtended;
$this->travelRoute = $travelRoute;
$this->distance = $distance;
$this->passengers = $passengers;
$this->transportations = $transportations;
$this->receiptFile = $receiptFile;
$this->contactEmail = $contactEmail;
$this->contactPhone = $contactPhone;
@@ -66,8 +73,11 @@ class CreateInvoiceRequest {
$this->isDonation = $isDonation;
$this->userId = $userId;
$this->travelReason = $travelReason;
$this->travelReasonNote = $travelReasonNote;
$this->paymentPurpose = $paymentPurpose;
$this->notices = $notices;
$this->travellers = $travellers;
$this->purpose = $purpose;
if ($accountIban === 'undefined') {
$this->accountIban = null;
@@ -8,8 +8,12 @@ class CreateInvoiceResponse {
public bool $success;
public ?Invoice $invoice;
/** Warum keine Abrechnung entstanden ist -- für die Rückmeldung an die einreichende Person. */
public ?string $message;
public function __construct() {
$this->success = false;
$this->invoice = null;
$this->message = null;
}
}
@@ -83,10 +83,8 @@ class CreateInvoiceReceiptCommand {
$travelPartTemplate = <<<HTML
<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>Materialtransport:</td><td>%4\$s</td></tr>
<tr><td>Mitfahrende im PKW:</td><td>%5\$s</td></tr>
HTML;
$flatTravelPart = sprintf(
@@ -94,8 +92,6 @@ HTML;
$invoiceReadable['travelDirection'] ,
$invoiceReadable['distance'],
$invoiceReadable['distanceAllowance'],
$invoiceReadable['transportation'],
$invoiceReadable['passengers'],
$invoiceReadable['travelReason'] ,
);
@@ -180,7 +176,10 @@ HTML;
$invoiceReadable['contactEmail'],
$invoiceReadable['contactPhone'],
$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'],
$paymentType,
$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->changes = $changes;
@@ -13,9 +13,11 @@ class UpdateInvoiceRequest {
public CostUnit $costUnit;
public Invoice $invoice;
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->purpose = $purpose;
$this->invoiceType = $invoiceType;
$this->costUnit = $costUnit;
$this->invoice = $invoice;
@@ -19,7 +19,7 @@ class UploadInvoiceCommand {
$uploadDir = sprintf(
'%1$s%2$s/%3$s',
WebDavProvider::INVOICE_PREFIX,
app('tenant')->url,
currentTenant()->url,
$this->request->invoice->costUnit()->first()->name
);
@@ -32,25 +32,26 @@ class EditController extends CommonController{
$receiptfile->fullPath = $invoice->document_filename;
}
$createInvoiceRequest = new CreateInvoiceRequest(
$invoice->costUnit()->first(),
$invoice->contact_name,
$invoice->type,
$invoice->amount,
$receiptfile,
$invoice->donation,
$invoice->user_id,
$invoice->contact_email,
$invoice->contact_phone,
$invoice->contact_bank_owner,
$invoice->contact_bank_iban,
$invoice->type_other,
$invoice->travel_direction,
$invoice->distance,
$invoice->passengers,
$invoice->transportation,
$invoice->travel_reason,
$invoice->payment_purpose,
$invoice->comment,
costUnit: $invoice->costUnit()->first(),
contactName: $invoice->contact_name,
invoiceType: $invoice->type,
totalAmount: $invoice->amount,
receiptFile: $receiptfile,
isDonation: $invoice->donation,
userId: $invoice->user_id,
contactEmail: $invoice->contact_email,
contactPhone: $invoice->contact_phone,
accountOwner: $invoice->contact_bank_owner,
accountIban: $invoice->contact_bank_iban,
invoiceTypeExtended: $invoice->type_other,
travelRoute: $invoice->travel_direction,
distance: $invoice->distance,
travelReason: $invoice->travel_reason,
paymentPurpose: $invoice->payment_purpose,
notices: $invoice->comment,
// Die rohe Spalte, nicht purposeText(): Ein Beleg, der seinen Zahlungsgrund bisher ableitet,
// soll das als Kopie weiter tun.
purpose: $invoice->purpose,
);
$invoiceCreationCommand = new CreateInvoiceCommand($createInvoiceRequest);
@@ -92,7 +93,8 @@ class EditController extends CommonController{
$modifyData['notices'],
$invoiceType,
$newCostUnit,
$newAmount
$newAmount,
$modifyData['purpose'] ?? null
);
$updateInvoiceCommand = new UpdateInvoiceCommand($updateInvoiceRequest);
$updateInvoiceCommand->execute();
@@ -107,22 +109,22 @@ class EditController extends CommonController{
$receiptfile->fullPath = $invoice->document_filename;
}
$createInvoiceRequest = new CreateInvoiceRequest(
$invoice->costUnit()->first(),
$invoice->contact_name,
$invoice->type,
$amountLeft->getAmount(),
$receiptfile,
$invoice->donation,
$invoice->user_id,
$invoice->contact_email,
$invoice->contact_phone,
$invoice->contact_bank_owner,
$invoice->contact_bank_iban,
$invoice->type_other,
$invoice->travel_direction,
$invoice->distance,
$invoice->passengers,
$invoice->transportation
costUnit: $invoice->costUnit()->first(),
contactName: $invoice->contact_name,
invoiceType: $invoice->type,
totalAmount: $amountLeft->getAmount(),
receiptFile: $receiptfile,
isDonation: $invoice->donation,
userId: $invoice->user_id,
contactEmail: $invoice->contact_email,
contactPhone: $invoice->contact_phone,
accountOwner: $invoice->contact_bank_owner,
accountIban: $invoice->contact_bank_iban,
invoiceTypeExtended: $invoice->type_other,
travelRoute: $invoice->travel_direction,
distance: $invoice->distance,
travelReason: $invoice->travel_reason,
purpose: $invoice->purpose,
);
$invoiceCreationCommand = new CreateInvoiceCommand($createInvoiceRequest);
@@ -66,50 +66,43 @@ class SaveInvoiceController extends CommonController
}
$createInvoiceRequest = new CreateInvoiceRequest(
$costUnit,
$request->input('name'),
InvoiceType::INVOICE_TYPE_TRAVELLING,
$amount,
$uploadedFile,
'donation' === $request->input('decision') ? true : false,
$this->users->getCurrentUserDetails()['userId'],
$request->input('email'),
$request->input('telephone'),
$request->input('accountOwner'),
$request->input('accountIban'),
null,
$request->input('otherText'),
$distance,
$request->input('havePassengers'),
$request->input('materialTransportation'),
$request->input('travelReason'),
null,
$notices
costUnit: $costUnit,
contactName: $request->input('name'),
invoiceType: InvoiceType::INVOICE_TYPE_TRAVELLING,
totalAmount: $amount,
receiptFile: $uploadedFile,
isDonation: 'donation' === $request->input('decision') ? true : false,
userId: $this->users->getCurrentUserDetails()['userId'],
contactEmail: $request->input('email'),
contactPhone: $request->input('telephone'),
accountOwner: $request->input('accountOwner'),
accountIban: $request->input('accountIban'),
travelRoute: $request->input('otherText'),
distance: $distance,
travelReason: $request->input('travelReason'),
travelReasonNote: $request->input('travelReasonNote'),
notices: $notices,
travellers: $request->input('travellers')
);
break;
default:
$createInvoiceRequest = new CreateInvoiceRequest(
$costUnit,
$request->input('name'),
$invoiceType,
Amount::fromString($request->input('amount'))->getAmount(),
$uploadedFile,
'donation' === $request->input('decision') ? true : false,
$this->users->getCurrentUserDetails()['userId'],
$request->input('email'),
$request->input('telephone'),
$request->input('accountOwner'),
$request->input('accountIban'),
$request->input('otherText'),
null,
null,
$request->input('havePassengers'),
$request->input('materialTransportation'),
null,
$paymentPurpose,
$notices
costUnit: $costUnit,
contactName: $request->input('name'),
invoiceType: $invoiceType,
totalAmount: Amount::fromString($request->input('amount'))->getAmount(),
receiptFile: $uploadedFile,
isDonation: 'donation' === $request->input('decision') ? true : false,
userId: $this->users->getCurrentUserDetails()['userId'],
contactEmail: $request->input('email'),
contactPhone: $request->input('telephone'),
accountOwner: $request->input('accountOwner'),
accountIban: $request->input('accountIban'),
invoiceTypeExtended: $request->input('otherText'),
paymentPurpose: $paymentPurpose,
notices: $notices
);
break;
@@ -128,5 +121,11 @@ class SaveInvoiceController extends CommonController
'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>
</tr>
<tr>
<th>Marterialtransport</th>
<td>{{props.invoice.transportation}}</td>
</tr>
<tr>
<th>Hat Personen mitgenommen</th>
<td>{{props.invoice.passengers}}</td>
</tr>
</table>
</template>
@@ -16,11 +16,18 @@ const props = defineProps({
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({
type_internal: props.newInvoice.internalType || '',
cost_unit: props.newInvoice.costUnitId || '',
amount: props.newInvoice.amountPlain || '',
notices: props.newInvoice.comments || '',
purpose: props.newInvoice.purpose || '',
notices: !existingComment || existingComment === '--' ? '' : existingComment,
})
const submitForm = () => {
@@ -70,6 +77,13 @@ onMounted(async () => {
</td>
</tr>
<tr>
<td>Zahlungsgrund:</td>
<td>
<input type="text" v-model="formData.purpose" class="width-almost-full" />
</td>
</tr>
<tr>
<td>Anmerkungen:</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>Klassische Auszahlung</td>
</tr>
<tr>
<td>Zahlungsgrund:</td>
<td colspan="3">{{props.data.purpose}}</td>
</tr>
<tr>
<td>Status:</td>
<td>{{props.data.readableStatus}}</td>
@@ -32,15 +32,6 @@ const props = defineProps({
<td style="font-weight: bold">{{props.invoice.amount}}</td>
</tr>
<tr>
<th>Marterialtransport</th>
<td>{{props.invoice.transportation}}</td>
</tr>
<tr>
<th>Hat Personen mitgenommen</th>
<td>{{props.invoice.passengers}}</td>
</tr>
</table>
</template>
@@ -45,12 +45,13 @@
<template>
<table v-if="localData.invoices.length > 0" class="invoice-list-table">
<tr>
<td colspan="6">{{props.data.title}}</td>
<td colspan="7">{{props.data.title}}</td>
</tr>
<tr v-for="invoice in localData.invoices" :id="'invoice_' + invoice.id">
<td>{{invoice.invoiceNumber}}</td>
<td>{{invoice.invoiceType}}</td>
<td>{{invoice.invoiceTypeShort}}</td>
<td style="max-width: 250px;">{{invoice.purpose}}</td>
<td>
{{invoice.amount}}
</td>
@@ -1,6 +1,6 @@
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ref, computed, onMounted, reactive } from 'vue'
import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js";
import RefundData from "./refund-data.vue";
import AmountInput from "../../../../../Views/Components/AmountInput.vue";
@@ -38,6 +38,20 @@ onMounted(async () => {
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) {
if (checkFilesize('receipt')) {
@@ -66,28 +80,36 @@ function handleFileChange(event) {
<InfoIcon :text="'INFO_INVOICE_TYPE_' + availableInvoiceType.slug" /><br />
</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
type="text"
class="width-full"
name="kostengruppe_sonstiges"
placeholder="Sonstige"
for="invoice_type_other"
id="purchase_description"
name="purchase_description"
:placeholder="purchasePlaceholder"
v-model="otherText"
@focus="invoiceType = 'other'"
/>
</label>
</fieldset><br /><br />
</template>
</fieldset><br /><br />
<fieldset>
<fieldset v-if="invoiceType !== null && otherText.trim() !== ''">
<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
<info-icon></info-icon><br /><br />
<input
v-if="amount != '' && invoiceType !== null"
v-if="amount != ''"
class="mareike-button"
onclick="document.getElementById('receipt').click();"
type="button"
@@ -1,6 +1,6 @@
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ref, computed, onMounted, reactive } from 'vue'
import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js";
import RefundData from "./refund-data.vue";
import AmountInput from "../../../../../Views/Components/AmountInput.vue";
@@ -37,6 +37,20 @@ onMounted(async () => {
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) {
if (checkFilesize('receipt')) {
@@ -65,28 +79,36 @@ function handleFileChange(event) {
<InfoIcon :text="'INFO_INVOICE_TYPE_' + availableInvoiceType.slug" /><br />
</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
type="text"
class="width-full"
name="kostengruppe_sonstiges"
placeholder="Sonstige"
for="invoice_type_other"
id="purchase_description"
name="purchase_description"
:placeholder="purchasePlaceholder"
v-model="otherText"
@focus="invoiceType = 'other'"
/>
</label>
</fieldset><br /><br />
</template>
</fieldset><br /><br />
<fieldset>
<fieldset v-if="invoiceType !== null && otherText.trim() !== ''">
<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
<info-icon></info-icon><br /><br />
<input
v-if="amount != '' && invoiceType !== null"
v-if="amount != ''"
class="mareike-button"
onclick="document.getElementById('receipt').click();"
type="button"
@@ -24,8 +24,6 @@ const props = defineProps({
userTelephone: String,
userAccountOwner: String,
userAccountIban: String,
havePassengers: Number,
materialTransportation: Boolean,
travelReason: String,
})
@@ -61,8 +59,6 @@ async function sendData() {
formData.append('accountOwner', userAccountOwner.value)
formData.append('accountIban', userIban.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)
if (props.receipt) {
@@ -24,9 +24,9 @@ const props = defineProps({
userTelephone: String,
userAccountOwner: String,
userAccountIban: String,
havePassengers: Number,
materialTransportation: Boolean,
travelReason: String,
travelReasonNote: String,
travellers: String,
})
const finalStep = ref(true)
@@ -60,9 +60,9 @@ async function sendData() {
formData.append('decision', decision.value)
formData.append('accountOwner', userAccountOwner.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('travelReasonNote', props.travelReasonNote ?? '')
formData.append('travellers', props.travellers ?? '')
formData.append('notices', notices.value)
if (props.receipt) {
@@ -1,5 +1,5 @@
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ref, computed, onMounted, reactive } from 'vue'
import {checkFilesize} from "../../../../../../resources/js/components/InvoiceUploadChecks.js";
import RefundData from "./refund-data.vue";
import NumericInput from "../../../../../Views/Components/NumericInput.vue";
@@ -19,15 +19,44 @@ const { request } = useAjax();
const distanceAllowance = ref(null);
const travelDirection = 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 havePassengers = ref(false);
const materialTransportation = ref(false);
const amount = ref(0.00);
const invoiceType = ref(null);
const otherText = ref('');
const receipt = ref(null)
const finalStep = ref(false)
onMounted(async () => {
const response = await fetch('/api/v1/core/retrieve-travel-reasons');
travelReasonCollection.travelReasons = await response.json();
});
async function getDistanceAllowance() {
const tempData = await request('/api/v1/cost-unit/get-distance-allowance/' + data.eventId, {
method: "GET",
@@ -59,14 +88,40 @@ function handleFileChange(event) {
<fieldset v-if="travelDirection !== null">
<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
type="text"
class="width-full"
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="travel-reason"
v-model="travelReason"
name="travellers"
placeholder="z. B. Mika, Kim und Alex"
v-model="travellers"
/>
</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>
<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" />
@@ -93,8 +148,6 @@ function handleFileChange(event) {
invoice-type="travelling"
:amount="amount"
:other-text="travelDirection"
:materialTransportation="materialTransportation"
:havePassengers="havePassengers"
:userName="data.userName"
:userEmail="data.userEmail"
:userTelephone="data.userTelephone"
@@ -102,6 +155,8 @@ function handleFileChange(event) {
:userAccountOwner="data.userAccountOwner"
:receipt="receipt"
:travelReason="travelReason"
:travelReasonNote="travelReasonNote"
:travellers="travellers"
@close="finalStep = false"
/>
</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>
<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
v-if="amount !== null && have_receipt === 'no' && amount != '0'"
@click="finalStep = true;"
@@ -145,14 +184,14 @@ function handleFileChange(event) {
invoice-type="travelling"
:amount="amount"
:other-text="travelDirection"
:materialTransportation="materialTransportation"
:havePassengers="havePassengers"
:userName="data.userName"
:userEmail="data.userEmail"
:userTelephone="data.userTelephone"
:userAccountIban="data.userAccountIban"
:userAccountOwner="data.userAccountOwner"
:travelReason="travelReason"
:travelReasonNote="travelReasonNote"
:travellers="travellers"
@close="finalStep = false"
/>
@@ -35,7 +35,7 @@ class CreateParticipantInvoiceCommand
$this->participant = $request->participant;
$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
// Relation -- deshalb der ausdrückliche Aufruf.
$this->sender = $this->event->tenant()->first();
@@ -2,12 +2,27 @@
namespace App\Domains\ParticipantRefund\Actions\AcceptRefund;
use App\Domains\Invoice\Actions\CreateInvoice\CreateInvoiceCommand;
use App\Domains\Invoice\Actions\CreateInvoice\CreateInvoiceRequest;
use App\Domains\ParticipantRefund\Actions\CreateRefundDocument\CreateRefundDocumentCommand;
use App\Domains\ParticipantRefund\Actions\CreateRefundDocument\CreateRefundDocumentRequest;
use App\Domains\ParticipantRefund\Actions\CreateRefundDocument\CreateRefundDocumentResponse;
use App\Enumerations\InvoiceType;
use App\Mail\ParticipantRefundMails\RefundAcceptedMail;
use App\Models\CostUnit;
use App\Models\Invoice;
use App\Models\ParticipantRefund;
use App\Providers\FileWriteProvider;
use App\Providers\UploadFileProvider;
use App\Repositories\CostUnitRepository;
use App\Support\Iban;
use App\ValueObjects\Amount;
use App\ValueObjects\InvoiceFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use RuntimeException;
/**
* Der Teili bestätigt die Erstattung und hinterlegt seine Bankverbindung.
@@ -52,18 +67,31 @@ class AcceptRefundCommand
// Serverseitig und nicht nur im Formular: die Erklärung ist der einzige Grund, warum der Beleg
// als Eigenbeleg etwas wert ist. Ließe sie sich mit einem direkten Aufruf übergehen, stünde auf
// dem PDF eine Zusicherung, die niemand abgegeben hat.
if (!$this->request->declarationAccepted) {
//
// Nimmt die Aktionsleitung die Angaben auf, kreuzt naturgemäß niemand etwas an. Nachvollziehbar
// bleibt es trotzdem: `captured_by` hält fest, wer sie aufgenommen hat, und der Beleg weist es aus.
if (!$this->request->declarationAccepted && $this->request->capturedBy === null) {
$response->errorTypes['declaration'] = 'Bitte bestätige die Erklärung, damit wir erstatten können.';
}
if ($owner === '') {
$response->errorTypes['accountOwner'] = 'Bitte gib an, wem das Konto gehört.';
}
// 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 ($iban === '') {
$response->errorTypes['accountIban'] = 'Bitte gib die IBAN des Kontos ein.';
} elseif (!Iban::isValid($iban)) {
$response->errorTypes['accountIban'] = 'Diese IBAN stimmt nicht. Bitte prüfe deine Eingabe.';
if ($owner === '') {
$response->errorTypes['accountOwner'] = 'Bitte gib an, wem das Konto gehört.';
}
if ($iban === '') {
$response->errorTypes['accountIban'] = 'Bitte gib die IBAN des Kontos ein.';
} elseif (!Iban::isValid($iban)) {
$response->errorTypes['accountIban'] = 'Diese IBAN stimmt nicht. Bitte prüfe deine Eingabe.';
}
}
if ($response->errorTypes !== []) {
@@ -72,45 +100,226 @@ class AcceptRefundCommand
return $response;
}
$refund->account_owner = $owner;
$refund->account_iban = $iban;
$refund->status = ParticipantRefund::STATUS_ACCEPTED;
$refund->accepted_at = now();
$refund->save();
// Ohne Kostenstelle gibt es nichts, worauf gebucht werden könnte. Lieber hier abbrechen, als den
// Vorgang zu bestätigen und die Auszahlung stillschweigend nirgends einzureichen.
$costUnit = $this->costUnit($refund);
if ($costUnit === null) {
$response->message = 'Die Erstattung kann gerade nicht bearbeitet werden. '
. 'Bitte wende dich an die Aktionsleitung.';
$this->notify($refund);
Log::error('Beitragserstattung: Veranstaltung ohne Kostenstelle, Abrechnung nicht möglich.', [
'refund_id' => $refund->id,
'event_id' => $refund->event_id,
]);
return $response;
}
// Der Beleg entsteht in der Transaktion, weil er den bestätigten Stand abbildet; scheitert das
// Einreichen, soll auch kein Beleg gelten.
$document = DB::transaction(function () use ($refund, $owner, $iban, $costUnit) {
// Bei einer Spende bleiben die Kontofelder leer -- und zwar `null` und nicht Leerstring: Der
// 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->status = ParticipantRefund::STATUS_ACCEPTED;
$refund->accepted_at = now();
$refund->save();
// 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);
// Erst jetzt, nicht früher: Beleg und Anmerkung der Abrechnung weisen den gezahlten Beitrag
// aus und läsen sonst bereits den verrechneten Stand.
$this->settleAmountPaid($refund);
$refund->invoice_id = $invoice->id;
$refund->save();
return $document;
});
$this->notify($refund, $document);
$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;
}
/**
* Bestätigung mit dem Beleg im Anhang, an Teili und Kontaktperson.
* Die Kostenstelle der Veranstaltung.
*
* Scheitert die Belegerzeugung, geht die Mail trotzdem raus -- der Vorgang ist gespeichert, und die
* Aktionsleitung kann den Beleg jederzeit erneut abrufen. Ein Fehler hier darf nicht dazu führen,
* dass der Teili gar nichts hört.
* Ohne Zugriffsprüfung, weil hier niemand angemeldet ist -- der Teili bestätigt über seinen Token.
* 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
* Veranstaltung an, wenn die Kostenstelle längst geschlossen ist. Sie gehört trotzdem dorthin -- und
* der reguläre Weg über SaveInvoiceController prüft das ebenso wenig.
*/
private function notify(ParticipantRefund $refund): void
private function costUnit(ParticipantRefund $refund): ?CostUnit
{
$document = new CreateRefundDocumentCommand(new CreateRefundDocumentRequest($refund))->execute();
if ($refund->event->cost_unit_id === null) {
return null;
}
return new CostUnitRepository()->getById($refund->event->cost_unit_id, true);
}
/**
* Reicht die Erstattung als gewöhnliche Auslagenabrechnung ein.
*
* Über denselben Command wie jede von Hand erfasste Abrechnung: damit stimmen Nummernkreis, Status
* `new`, die Bestätigungsmail an den Teili und die Benachrichtigung der Kassenwart*innen mit dem
* überein, was die Buchhaltung kennt.
*/
private function createInvoice(
ParticipantRefund $refund,
CostUnit $costUnit,
CreateRefundDocumentResponse $document,
): Invoice {
$participant = $refund->participant;
$invoiceRequest = new CreateInvoiceRequest(
costUnit: $costUnit,
// getOfficialName() und nicht getFullName(): letzteres enthält HTML für die Oberfläche.
contactName: $participant->getOfficialName(),
invoiceType: InvoiceType::INVOICE_TYPE_PARTICIPATION_REFUND,
totalAmount: $refund->amount?->getAmount() ?? 0.0,
receiptFile: $this->storeReceipt($costUnit, $document),
// 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,
contactEmail: $participant->email_1,
contactPhone: $participant->phone_1,
// Die Bankverbindung stammt aus dem Vorgang, nicht vom Teilnehmer: das Konto kann einem
// Elternteil gehören.
accountOwner: $refund->account_owner,
accountIban: $refund->account_iban,
// MUSS null bleiben (nicht ''): CreateInvoiceCommand verwirft die user_id, sobald hier etwas
// steht -- der Teili fände seine Abrechnung dann nicht unter "Meine Abrechnungen".
paymentPurpose: null,
notices: $this->notice($refund),
);
$invoiceResponse = new CreateInvoiceCommand($invoiceRequest)->execute();
if (!$invoiceResponse->success || $invoiceResponse->invoice === null) {
// Rollt die Transaktion zurück -- der Vorgang bleibt offen, der Teili kann es erneut versuchen.
throw new RuntimeException('Die Abrechnung zur Beitragserstattung konnte nicht angelegt werden.');
}
return $invoiceResponse->invoice;
}
/**
* Legt den Eigenbeleg dort ab, wo auch hochgeladene Belege liegen, und verpackt ihn für die
* Abrechnung. `CreateInvoiceCommand` speichert nur den Pfad und schreibt selbst keine Dateien.
*/
private function storeReceipt(CostUnit $costUnit, CreateRefundDocumentResponse $document): ?InvoiceFile
{
if (!$document->success) {
return null;
}
$path = UploadFileProvider::directoryFor($costUnit) . '/' . $document->filename;
new FileWriteProvider($path, $document->pdfContent)->writeToFile();
$receipt = new InvoiceFile();
// Beide Eigenschaften sind typisiert und ohne Vorbelegung; gespeichert wird nur `fullPath`.
$receipt->filename = $document->filename;
$receipt->fullPath = $path;
return $receipt;
}
/**
* Die Anmerkung auf der Abrechnung.
*
* Sie nennt den gezahlten Beitrag, weil er am Teilnehmer gleich auf 0 gesetzt wird
* ({@see self::clearAmountPaid()}) -- die Schatzmeisterei kann den Vorgang so nachvollziehen, ohne
* den vorherigen Stand irgendwo suchen zu müssen.
*
* Gekürzt wird nur der vordere, freie Teil: Veranstaltungsname und Grund sind beliebig lang, der
* Betrag darf nie abgeschnitten werden.
*/
private function notice(ParticipantRefund $refund): string
{
$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(
'%s %s %s',
$subject,
$refund->event->name,
$refund->reasonLabel()
), 180) . sprintf(' | Gezahlter Beitrag vor Erstattung: %s', $paid);
}
/**
* Zieht den erstatteten Betrag vom gezahlten Beitrag ab.
*
* Danach führt `amount_paid` genau das, was beim Verband geblieben ist -- bei voller Erstattung also
* 0, bei einer Teilerstattung den einbehaltenen Rest. Auf diesem Feld baut die Einnahmenrechnung der
* 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 settleAmountPaid(ParticipantRefund $refund): void
{
$participant = $refund->participant;
$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();
}
/**
* Die eigene Bestätigung mit dem Beleg im Anhang, an Teili und Kontaktperson.
*
* Sie kommt zusätzlich zu der, die CreateInvoiceCommand verschickt: diese trägt den Beleg, jene ist
* die Quittung des Abrechnungssystems. Erst nach der Transaktion, damit nichts verschickt wird, was
* anschließend zurückgerollt würde.
*
* Scheitert die Belegerzeugung, geht die Mail ohne Anhang raus statt gar nicht.
*/
private function notify(ParticipantRefund $refund, CreateRefundDocumentResponse $document): void
{
$pdf = $document->success ? $document->pdfContent : null;
$filename = $document->success ? $document->filename : null;
$participant = $refund->participant;
Mail::to($participant->email_1)->send(new RefundAcceptedMail(
participant: $participant,
refund: $refund,
pdfContent: $pdf,
pdfFilename: $filename,
));
$recipients = [$participant->email_1];
if ($participant->email_2 !== null) {
Mail::to($participant->email_2)->send(new RefundAcceptedMail(
// `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 RefundAcceptedMail(
participant: $participant,
refund: $refund,
pdfContent: $pdf,
@@ -10,8 +10,35 @@ class AcceptRefundRequest
public readonly ?ParticipantRefund $refund,
public readonly string $accountOwner,
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,
/**
* 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.
*
* Dann kreuzt niemand die Erklärung an -- sie wird stellvertretend aufgenommen, und der Beleg
* weist genau das aus.
*/
public readonly ?int $capturedBy = null,
) {
}
}
@@ -27,6 +27,12 @@ class CreateRefundDocumentCommand
/** Name des `page_texts`-Eintrags mit der Erklärung -- dieselbe Quelle wie die Bestätigungsseite. */
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 EventParticipant $participant;
@@ -104,14 +110,98 @@ class CreateRefundDocumentCommand
* 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.
*/
/**
* 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.
*
* Er nennt Name und Datum, weil in diesem Fall niemand die Erklärung darüber angekreuzt hat: Wer den
* Beleg prüft, soll erkennen, dass dort eine aufgenommene Angabe steht und keine Bestätigung des
* Teilis selbst. Beim gewöhnlichen Weg bleibt der Platzhalter leer und der Block fällt weg.
*/
private function captureNote(): string
{
if (!$this->refund->wasCapturedByManagement()) {
return '';
}
$name = $this->refund->capturedBy()->first()?->getOfficialName();
return sprintf(
'Angaben aufgenommen durch %s am %s.',
trim((string) $name) !== '' ? $name : 'die Aktionsleitung',
$this->refund->accepted_at?->format('d.m.Y') ?? ''
);
}
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) !== ''
? (string) $text
: 'Ich versichere, dass ich den genannten Betrag beglichen habe und nicht anderweitig '
. 'zurückerstattet bekomme.';
// Beide Sätze, weil die Person beide angekreuzt hat -- der Beleg schreibt ihr nur zu, was sie
// gelesen hat, und die Kontoerklärung ist der Grund, warum die Auszahlung zulässig ist.
return $this->pageText(
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:';
}
/**
@@ -177,7 +267,12 @@ class CreateRefundDocumentCommand
'account_owner' => (string) $refund->account_owner,
'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(),
'capture_note' => $this->captureNote(),
'details_table' => $this->renderDetails(),
];
@@ -219,8 +314,24 @@ class CreateRefundDocumentCommand
$rows[] = ['Begründung', e($reasonText)];
}
$rows[] = ['Kontoinhaber*in', e((string) $refund->account_owner)];
$rows[] = ['IBAN', e($this->formatIban((string) $refund->account_iban))];
// 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[] = ['IBAN', e($this->formatIban((string) $refund->account_iban))];
}
$html = '';
foreach ($rows as [$key, $value]) {
@@ -8,6 +8,14 @@ class CreateRefundDocumentRequest
{
public function __construct(
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,
) {
}
}
@@ -2,13 +2,19 @@
namespace App\Domains\ParticipantRefund\Actions\ReleaseRefund;
use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundCommand;
use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundRequest;
use App\Enumerations\RefundReason;
use App\Enumerations\RetentionReason;
use App\Mail\ParticipantRefundMails\RefundReleasedMail;
use App\Models\EventParticipant;
use App\Models\ParticipantRefund;
use App\Repositories\ParticipantRefundRepository;
use App\Support\Iban;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use RuntimeException;
/**
* Gibt die Erstattung eines Teilnahmebeitrags frei.
@@ -40,28 +46,74 @@ class ReleaseRefundCommand
return $response;
}
$refund = ParticipantRefund::create([
'tenant' => $this->participant->tenant,
'event_id' => $this->participant->event_id,
'event_participant_id' => $this->participant->id,
'token' => Str::random(32),
'status' => ParticipantRefund::STATUS_PENDING,
'amount' => $this->request->amount,
'reason' => $this->request->reason,
'reason_note' => $this->reasonNote(),
'released_by' => auth()->id(),
'released_at' => now(),
]);
// Liegt die Bankverbindung schon vor, entsteht in einem Zug auch die Abrechnung. Scheitert die,
// soll keine halbe Freigabe zurückbleiben -- deshalb beides in einer Transaktion.
$refund = DB::transaction(function (): ParticipantRefund {
$refund = ParticipantRefund::create([
'tenant' => $this->participant->tenant,
'event_id' => $this->participant->event_id,
'event_participant_id' => $this->participant->id,
'token' => Str::random(32),
'status' => ParticipantRefund::STATUS_PENDING,
'amount' => $this->request->amount,
'reason' => $this->request->reason,
'reason_note' => $this->reasonNote(),
// 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(),
]);
$this->notify($refund);
if ($this->request->submitsDirectly()) {
$this->submitDirectly($refund);
}
return $refund;
});
if (!$this->request->submitsDirectly()) {
$this->notify($refund);
}
$response->success = true;
$response->refund = $refund;
$response->message = 'Die Erstattung wurde freigegeben. Der Teili wurde per E-Mail informiert.';
$response->refund = $refund->fresh();
$response->message = match (true) {
$this->request->donation => 'Die Spende wurde eingereicht. Der Teili hat den Beleg per E-Mail erhalten.',
$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;
}
/**
* Reicht die Erstattung sofort ein, ohne den Umweg über den Teili.
*
* Über denselben Command, den sonst der Bestätigungslink auslöst: Beleg, Abrechnung, das Nullstellen
* des gezahlten Beitrags und die Mail mit dem Beleg laufen dadurch in beiden Wegen identisch ab.
*/
private function submitDirectly(ParticipantRefund $refund): void
{
$acceptResponse = new AcceptRefundCommand(new AcceptRefundRequest(
refund: $refund,
accountOwner: (string) $this->request->accountOwner,
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`
// fest, und der Beleg weist es aus.
capturedBy: currentUser()?->id,
))->execute();
if (!$acceptResponse->success) {
// Rollt die Freigabe zurück -- die Aktionsleitung soll den Fehler sehen und nicht einen
// Vorgang vorfinden, der nirgends eingereicht ist.
throw new RuntimeException($acceptResponse->message ?? 'Die Erstattung konnte nicht eingereicht werden.');
}
}
/**
* Alle Gründe, aus denen eine Freigabe nicht zulässig ist.
*
@@ -98,6 +150,67 @@ class ReleaseRefundCommand
return 'Für diesen Grund ist eine Erläuterung erforderlich.';
}
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;
}
/**
* Prüfungen, die nur den Direktweg betreffen -- die Erstattung wird dabei sofort eingereicht, es gibt
* also keine zweite Gelegenheit, Angaben zu berichtigen.
*/
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.
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.';
}
if (!$this->request->submitsDirectly()) {
return null;
}
if ($this->request->hasBankDetails() && !Iban::isValid((string) $this->request->accountIban)) {
return 'Diese IBAN stimmt nicht. Bitte prüfe die Eingabe.';
}
// Ohne Kostenstelle ließe sich die Abrechnung nicht anlegen -- auch die Spende braucht eine, sie
// 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) {
return 'Die Veranstaltung hat keine Kostenstelle -- die Erstattung kann nicht eingereicht werden.';
}
return null;
}
@@ -113,19 +226,49 @@ class ReleaseRefundCommand
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
* (siehe SetParticipationStateCommand).
*/
private function notify(ParticipantRefund $refund): void
{
Mail::to($this->participant->email_1)->send(new RefundReleasedMail(
participant: $this->participant,
refund: $refund,
));
$recipients = [$this->participant->email_1];
if ($this->participant->email_2 !== null) {
Mail::to($this->participant->email_2)->send(new RefundReleasedMail(
// `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($this->participant->email_2)) {
$recipients[] = $this->participant->email_2;
}
foreach ($recipients as $recipient) {
Mail::to($recipient)->send(new RefundReleasedMail(
participant: $this->participant,
refund: $refund,
));
@@ -12,6 +12,60 @@ class ReleaseRefundRequest
public readonly Amount $amount,
public readonly string $reason,
public readonly ?string $reasonNote = null,
/**
* Die Bankverbindung, wenn sie der Aktionsleitung bereits vorliegt.
*
* Sind beide gesetzt, entfällt der Umweg über den Teili: die Erstattung wird sofort eingereicht.
* Bleiben sie leer, läuft der übliche Weg über den Bestätigungslink.
*/
public readonly ?string $accountOwner = 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,
) {
}
/** Ob die Erstattung ohne Zutun des Teilis eingereicht werden kann. */
public function hasBankDetails(): bool
{
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'),
accountIban: (string) $request->input('accountIban'),
declarationAccepted: $request->boolean('declarationAccepted'),
donation: $request->boolean('donation'),
accountDeclarationAccepted: $request->boolean('accountDeclarationAccepted'),
);
$response = new AcceptRefundCommand($acceptRequest)->execute();
@@ -18,7 +18,11 @@ class RefundDocumentController extends CommonController
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) {
abort(422, $documentResponse->message ?? 'Der Beleg konnte nicht erstellt werden.');
@@ -53,6 +53,8 @@ class RefundPageController extends CommonController
return array_merge($common, [
'state' => 'accepted',
'acceptedAt' => $refund->accepted_at?->format('d.m.Y'),
// Wurde gespendet, darf der Abschlusstext keine Überweisung ankündigen, die nicht kommt.
'donation' => $refund->isDonation(),
]);
}
@@ -25,6 +25,15 @@ class ReleaseRefundController extends CommonController
amount: Amount::fromString((string) $request->input('amount'), 'Euro'),
reason: (string) $request->input('reason'),
reasonNote: Text::nullIfBlank($request->input('reasonNote')),
// Leer, wenn der Teili die Bankverbindung selbst eintragen soll.
accountOwner: Text::nullIfBlank($request->input('accountOwner')),
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();
@@ -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,15 @@ final class ParticipantRefundTokens
'paid_amount' => ['description' => 'Bereits gezahlter Teilnahmebeitrag', 'sample' => '300,00 €'],
'invoice_number' => ['description' => 'Nummer der Teilnahmerechnung', 'sample' => 'WM-V-20260701-0005'],
'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_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_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.'],
],
],
'body' => [
@@ -110,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">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">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">IBAN</td><td class="detail-val">DE02 1203 0000 0000 2020 51</td></tr>'
. '</table>';
@@ -4,6 +4,7 @@ use App\Domains\ParticipantRefund\Controllers\AcceptRefundController;
use App\Domains\ParticipantRefund\Controllers\CancelRefundController;
use App\Domains\ParticipantRefund\Controllers\RefundDocumentController;
use App\Domains\ParticipantRefund\Controllers\ReleaseRefundController;
use App\Domains\ParticipantRefund\Controllers\ResendRefundMailController;
use App\Middleware\IdentifyTenant;
use Illuminate\Support\Facades\Route;
@@ -17,6 +18,7 @@ Route::prefix('api/v1')
Route::middleware(['auth'])->group(function () {
Route::post('{participantIdentifier}/release', ReleaseRefundController::class);
Route::post('{refundToken}/cancel', CancelRefundController::class);
Route::post('{refundToken}/resend-mail', ResendRefundMailController::class);
Route::get('{refundToken}/document', RefundDocumentController::class);
});
});
@@ -27,13 +27,33 @@ const props = defineProps({
reason: String,
reasonNote: String,
acceptedAt: String,
donation: Boolean,
})
// Der Zustand wandert in ein ref, damit die Seite nach dem Absenden umschalten kann, ohne neu zu laden.
const state = ref(props.state)
const form = reactive({accountOwner: '', accountIban: '', declarationAccepted: false})
const errors = reactive({accountOwner: '', accountIban: '', declaration: ''})
// Ob gespendet wurde -- für den Abschlusstext. Nach dem Absenden setzt submit() den Wert selbst, ein
// 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)
/**
@@ -48,12 +68,41 @@ const accountComplete = computed(
() => 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() {
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.'
Object.keys(errors).forEach((key) => (errors[key] = ''))
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() {
@@ -61,14 +110,21 @@ async function submit() {
saving.value = true
// Bei einer Spende geht keine Bankverbindung mit -- es gibt keine, und der Server erwartet auch keine.
const body = isDonation.value
? {donation: true, declarationAccepted: form.declarationAccepted}
: {
donation: false,
accountOwner: form.accountOwner,
accountIban: form.accountIban,
declarationAccepted: form.declarationAccepted,
accountDeclarationAccepted: form.accountDeclarationAccepted,
}
try {
const response = await request('/api/v1/participant-refund/' + props.token + '/accept', {
method: 'POST',
body: {
accountOwner: form.accountOwner,
accountIban: form.accountIban,
declarationAccepted: form.declarationAccepted,
},
body,
})
if (!response) {
@@ -88,6 +144,7 @@ async function submit() {
}
toast.success(response.message)
donated.value = isDonation.value
state.value = 'accepted'
} finally {
saving.value = false
@@ -128,7 +185,12 @@ async function submit() {
</table>
<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>.
Die Überweisung veranlasst die Aktionsleitung. Stimmt etwas nicht, wende dich bitte
an sie: {{ props.eventEmail }}
@@ -141,57 +203,161 @@ async function submit() {
dich bitte an die Aktionsleitung: {{ props.eventEmail }}
</p>
<h3>Auf welches Konto sollen wir überweisen?</h3>
<form @submit.prevent="submit">
<div class="field">
<label for="account-owner">Kontoinhaber*in</label>
<input
id="account-owner"
v-model="form.accountOwner"
type="text"
class="form-input"
autocomplete="name"
/>
<ErrorText :message="errors.accountOwner" />
</div>
<div class="field">
<label for="account-iban">IBAN</label>
<IbanInput id="account-iban" v-model="form.accountIban" class="form-input" />
<ErrorText :message="errors.accountIban" />
</div>
<!--
Die Erklärung, die anschließend auf dem Eigenbeleg steht. Sie muss hier
gelesen und angekreuzt werden -- sonst schriebe der Beleg dem Teili eine
Zusicherung zu, die er nie abgegeben hat.
Erste Frage: Wer spendet, braucht kein Konto anzugeben. Deshalb steht sie
vor allem anderen.
-->
<template v-if="accountComplete">
<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-declaration"
id="refund-donation-declaration"
v-model="form.declarationAccepted"
type="checkbox"
/>
<TextResource
text-name="CONFIRMATION_PARTICIPANT_REFUND"
belongs-to="refund-declaration"
text-name="CONFIRMATION_PARTICIPANT_REFUND_DONATION"
belongs-to="refund-donation-declaration"
/>
</div>
<ErrorText :message="errors.declaration" />
<!-- Beim Speichern gesperrt statt ausgeblendet, sonst verschwände der Knopf
unter dem Finger. -->
<button
v-if="form.declarationAccepted"
class="button"
type="submit"
:disabled="saving"
>
{{ saving ? 'Wird gespeichert…' : 'Angaben absenden' }}
{{ 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">
<label for="account-owner">Kontoinhaber*in</label>
<input
id="account-owner"
v-model="form.accountOwner"
type="text"
class="form-input"
autocomplete="name"
/>
<ErrorText :message="errors.accountOwner" />
</div>
<div class="field">
<label for="account-iban">IBAN</label>
<IbanInput id="account-iban" v-model="form.accountIban" class="form-input" />
<ErrorText :message="errors.accountIban" />
</div>
<!--
Die Erklärungen, die anschließend auf dem Eigenbeleg stehen. Sie
müssen hier gelesen und angekreuzt werden -- sonst schriebe der Beleg
dem Teili Zusicherungen zu, die er nie abgegeben hat.
-->
<template v-if="accountComplete">
<div class="declaration">
<input
id="refund-declaration"
v-model="form.declarationAccepted"
type="checkbox"
/>
<TextResource
text-name="CONFIRMATION_PARTICIPANT_REFUND"
belongs-to="refund-declaration"
/>
</div>
<ErrorText :message="errors.declaration" />
<div class="declaration">
<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
v-if="form.declarationAccepted && form.accountDeclarationAccepted"
class="button"
type="submit"
:disabled="saving"
>
{{ saving ? 'Wird gespeichert…' : 'Angaben absenden' }}
</button>
</template>
</template>
</template>
</form>
</template>
</template>
@@ -235,6 +401,34 @@ h3 {
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 {
margin-bottom: 16px;
}
@@ -23,7 +23,7 @@ use Illuminate\Http\Request;
class EmailVerificationController extends CommonController
{
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();
}
@@ -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();
}
@@ -45,8 +45,8 @@ class LoginController extends CommonController {
]);
}
$user = Auth::user();
$tenant = app('tenant');
$user = currentUserOrFail();
$tenant = currentTenant();
// Auf "lv" darf sich grundsätzlich jeder aktive Nutzer einloggen.
// Auf Sub-Tenants gilt:
@@ -13,7 +13,7 @@ class ProfileController extends CommonController
return redirect()->intended('/login');
}
$user = auth()->user();
$user = currentUser();
$inertiaProvider = new InertiaProvider('UserManagement/Profile', [
'username' => $user->username,
@@ -26,8 +26,8 @@ class RegistrationController extends CommonController {
$inertiaProvider = new InertiaProvider('UserManagement/Registration', [
'errors' => $errors,
'appName' => app('tenant')->name,
'tenant' => app('tenant'),
'appName' => currentTenant()->name,
'tenant' => currentTenant(),
]);
return $inertiaProvider->render();
}
@@ -46,7 +46,7 @@ class RegistrationController extends CommonController {
$userRoleMain = 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(
@@ -7,6 +7,7 @@ use App\Domains\UserManagement\Actions\UserChangePassword\UserChangePasswordRequ
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
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);
}
$actionRequest = new UserChangePasswordRequest(auth()->user(), $password);
$actionRequest = new UserChangePasswordRequest(currentUserOrFail(), $password);
$command = new UserChangePasswordCommand($actionRequest);
$command->execute();
auth()->logout();
Auth::logout();
return response()->json(['success' => true, 'message' => 'Dein Passwort wurde erfolgreich geändert.']);
}
}
+46
View File
@@ -21,8 +21,54 @@ class InvoiceType extends CommonModel {
public const INVOICE_TYPE_MANAGEMENT = 'management';
/**
* Erstattung eines Teilnahmebeitrags. Entsteht ausschließlich aus einem bestätigten
* Erstattungsvorgang und ist deshalb nicht von Hand wählbar ({@see self::selectable()}).
*/
public const INVOICE_TYPE_PARTICIPATION_REFUND = 'participation_refund';
protected $fillable = [
'slug',
'name',
'purchase_example',
'sort_order',
'selectable',
'counts_as_expense',
];
protected $casts = [
'sort_order' => 'integer',
'selectable' => 'boolean',
'counts_as_expense' => 'boolean',
];
/**
* Die Typen, die in einem Formular zur Auswahl stehen dürfen -- nach Sortierung.
*
* Automatisch vergebene Typen bleiben außen vor: Ihre Abrechnungen entstehen aus einem Vorgang, der
* die Daten mitbringt; von Hand gewählt stünde ein leerer Rahmen ohne diesen Vorgang da.
*
* @return \Illuminate\Database\Eloquent\Collection<int, self>
*/
public static function selectable(): \Illuminate\Database\Eloquent\Collection
{
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
{
public function index() {
$inertiaProvider = new InertiaProvider('Invoice/CreateInvoice', ['appName' => app('tenant')->name]);
$inertiaProvider = new InertiaProvider('Invoice/CreateInvoice', ['appName' => currentTenant()->name]);
return $inertiaProvider->render();
}
}
+12 -4
View File
@@ -121,29 +121,37 @@ class ProductionDataSeeder {
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([
'slug' => InvoiceType::INVOICE_TYPE_TRAVELLING,
'name' => 'Reisekosten'
'name' => 'Reisekosten',
'purchase_example' => 'z. B. Bahnfahrt HalleLeipzig',
]);
InvoiceType::create([
'slug' => InvoiceType::INVOICE_TYPE_PROGRAM,
'name' => 'Programmkosten'
'name' => 'Programmkosten',
'purchase_example' => 'z. B. Bastelmaterial für den Workshop',
]);
InvoiceType::create([
'slug' => InvoiceType::INVOICE_TYPE_ACCOMMODATION,
'name' => 'Unterkunftskosten'
'name' => 'Unterkunftskosten',
'purchase_example' => 'z. B. zwei Nächte Jugendherberge',
]);
InvoiceType::create([
'slug' => InvoiceType::INVOICE_TYPE_CATERING,
'name' => 'Verpflegungskosten',
'purchase_example' => 'z. B. Wocheneinkauf für das Frühstück',
]);
InvoiceType::create([
'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]);
@@ -31,7 +31,9 @@ class RefundAcceptedMail extends Mailable
{
return new Envelope(
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
),
);
@@ -40,6 +42,7 @@ class RefundAcceptedMail extends Mailable
public function content(): Content
{
$event = $this->participant->event()->first();
$invoice = $this->refund->invoice()->first();
return new Content(
view: 'emails.events.refund_accepted',
@@ -52,6 +55,21 @@ class RefundAcceptedMail extends Mailable
'accountOwner' => $this->refund->account_owner,
'accountIban' => Iban::format((string) $this->refund->account_iban),
'hasDocument' => $this->pdfContent !== null,
'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
// eingetragen -- dann darf die Mail sich nicht für seine Angaben bedanken.
'capturedByManagement' => $this->refund->wasCapturedByManagement(),
// Der Hinweis auf "Meine Abrechnungen" nur, wenn die Anmeldung an einem Konto hängt --
// die Seite filtert über die Nutzer-Verknüpfung und bliebe sonst leer.
'myInvoicesUrl' => $invoice?->user_id !== null ? url('/invoice/my-invoices/new') : null,
],
);
}
+1 -1
View File
@@ -10,7 +10,7 @@ class AdminRoleMiddleware
{
public function handle($request, Closure $next)
{
if (!auth()->check()) {
if (currentUser() === null) {
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)
{
if (app('tenant')->slug !== 'lv') {
if (currentTenant()->slug !== 'lv') {
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)
{
if (!auth()->check()) {
if (currentUser() === null) {
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 {
// 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
// ü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')
->using(EventPaymentMethods::class)
->withPivot('configuration')
+76 -2
View File
@@ -4,6 +4,7 @@ namespace App\Models;
use App\Enumerations\InvoiceStatus;
use App\Enumerations\InvoiceType;
use App\Enumerations\TravelReason;
use App\Scopes\InstancedModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -14,6 +15,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property string $status
* @property string $type
* @property string $type_other
* @property string $purpose
* @property boolean $donation
* @property string $user_id
* @property string $contact_name
@@ -26,8 +28,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property string $comment
* @property string $changes
* @property string $travel_direction
* @property boolean $passengers
* @property boolean $transportation
* @property boolean $passengers Nicht mehr erfasst -- siehe Hinweis unten
* @property boolean $transportation Nicht mehr erfasst -- siehe Hinweis unten
* @property string $document_filename
* @property string $approved_by
* @property string $approved_at
@@ -35,6 +37,13 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property string $denied_by
* @property string $denied_at
* @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
{
@@ -45,6 +54,7 @@ class Invoice extends InstancedModel
'status',
'type',
'type_other',
'purpose',
'donation',
'user_id',
'contact_name',
@@ -71,6 +81,70 @@ class Invoice extends InstancedModel
'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{
return $this->belongsTo(CostUnit::class);
}
+75
View File
@@ -4,6 +4,7 @@ namespace App\Models;
use App\Casts\AmountCast;
use App\Enumerations\RefundReason;
use App\Enumerations\RetentionReason;
use App\Scopes\InstancedModel;
use App\ValueObjects\Amount;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -20,8 +21,13 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property Amount|null $amount
* @property string|null $reason
* @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_iban
* @property int|null $captured_by
* @property int|null $invoice_id
* @property int|null $released_by
* @property \Illuminate\Support\Carbon|null $released_at
* @property \Illuminate\Support\Carbon|null $accepted_at
@@ -49,8 +55,13 @@ class ParticipantRefund extends InstancedModel
'amount',
'reason',
'reason_note',
'retention_reason',
'retention_reason_note',
'retained_amount',
'account_owner',
'account_iban',
'captured_by',
'invoice_id',
'released_by',
'released_at',
'accepted_at',
@@ -59,6 +70,7 @@ class ParticipantRefund extends InstancedModel
protected $casts = [
'amount' => AmountCast::class,
'retained_amount' => AmountCast::class,
'released_at' => 'datetime',
'accepted_at' => 'datetime',
'cancelled_at' => 'datetime',
@@ -82,6 +94,41 @@ class ParticipantRefund extends InstancedModel
return $this->belongsTo(RefundReason::class, 'reason', 'slug');
}
/**
* Die Abrechnung, die aus diesem Vorgang entstanden ist. Der Auszahlungsstand steht dort und wird
* hier nicht gedoppelt.
*/
public function invoice(): BelongsTo
{
return $this->belongsTo(Invoice::class);
}
/**
* Wer die Bankverbindung aufgenommen hat -- leer, wenn der Teili sie selbst eingetragen hat.
*/
public function capturedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'captured_by');
}
/** Ob die Angaben von der Aktionsleitung stammen und nicht vom Teili selbst. */
public function wasCapturedByManagement(): bool
{
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
{
return $this->status === self::STATUS_PENDING;
@@ -102,4 +149,32 @@ class ParticipantRefund extends InstancedModel
{
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 {
return app('tenant')->slug . '/temp-data/';
return currentTenant()->slug . '/temp-data/';
}
/**
+3 -3
View File
@@ -2,7 +2,7 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
@@ -115,10 +115,10 @@ class User extends Authenticatable
}
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')
->withTimestamps();
+6 -6
View File
@@ -7,12 +7,12 @@ use App\Models\User;
class AuthCheckProvider {
public function checkLoggedIn() : bool {
if (!auth()->check()) {
$user = currentUser();
if ($user === null) {
return false;
}
$user = auth()->user();
$tenant = app('tenant');
$tenant = currentTenant();
if ($tenant->slug === 'lv') {
return $user->active;
}
@@ -29,9 +29,9 @@ class AuthCheckProvider {
return null;
}
$user = auth()->user();
$user = currentUserOrFail();
if (app('tenant')->slug === 'lv') {
if (currentTenant()->slug === 'lv') {
return $user->user_role_main;
}
@@ -50,7 +50,7 @@ class AuthCheckProvider {
* Diese Rolle hebt das lokale Rechtesystem für alle Sub-Tenants auf.
*/
public function isMainAdministrator(?User $user = null) : bool {
$user ??= auth()->user();
$user ??= currentUser();
return $user !== null
&& $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)
{
$logger = $this->taskLogger($task->name, app('tenant'));
$logger = $this->taskLogger($task->name, currentTenant());
app()->instance('taskLogger', $logger);
$taskClass = "\\App\\Tasks\\" . $task->name;
@@ -73,7 +73,7 @@ class CronTaskHandleProvider extends CommonController
$lastRun = [];
}
$lastRun[app('tenant')->slug] = now();
$lastRun[currentTenant()->slug] = now();
// Update last_run
$task->last_run = $lastRun;
$task->save();
+29 -7
View File
@@ -5,6 +5,8 @@ namespace App\Providers;
use App\Enumerations\EatingHabit;
use App\Enumerations\InvoiceType;
use App\Enumerations\RefundReason;
use App\Enumerations\RetentionReason;
use App\Enumerations\TravelReason;
use App\Enumerations\UserRole;
use App\Models\AvailablePaymentMethod;
use App\Models\Tenant;
@@ -21,7 +23,7 @@ class GlobalDataProvider {
private ?User $user;
public function __invoke() {
$this->user = auth()->user();
$this->user = currentUser();
$canAccessAdmin = false;
$isMainAdmin = false;
@@ -37,7 +39,7 @@ class GlobalDataProvider {
return response()->json([
'user' => null !== $this->user ? new UserResource($this->user)->toArray(request()) : null,
'navbar' => $this->generateNavbar(),
'tenant' => app('tenant'),
'tenant' => currentTenant(),
'activeUsers' => $this->getActiveUsers(),
'version' => config('app.version'),
'currentEvent' => $this->getCurrentEventData(),
@@ -46,9 +48,10 @@ class GlobalDataProvider {
]);
}
/** Die Typen für die Neuanlage durch Nutzer*innen. Reisekosten haben ein eigenes Formular. */
public function getInvoiceTypes() : JsonResponse {
$invoiceTypes = [];
foreach (InvoiceType::orderBy('sort_order')->get() as $invoiceType) {
foreach (InvoiceType::selectable() as $invoiceType) {
if (
$invoiceType->slug === InvoiceType::INVOICE_TYPE_TRAVELLING
) {
@@ -57,7 +60,10 @@ class GlobalDataProvider {
$invoiceTypes[] = [
'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,
];
}
@@ -110,9 +116,15 @@ class GlobalDataProvider {
];
}
/**
* Die Typen zum Umbuchen durch die Kassenwart*innen -- „Sonstige Kosten" ans Ende.
*
* Auch hier nur wählbare Typen: sonst ließe sich eine beliebige Abrechnung nachträglich zu einer
* Beitragserstattung machen, ohne dass ein Erstattungsvorgang dahinterstünde.
*/
public function getAllInvoiceTypes() : JsonResponse {
$invoiceTypes = [];
foreach (InvoiceType::orderBy('sort_order')->get() as $invoiceType) {
foreach (InvoiceType::selectable() as $invoiceType) {
if (
$invoiceType->slug === InvoiceType::INVOICE_TYPE_OTHER
) {
@@ -178,8 +190,8 @@ class GlobalDataProvider {
$activeUsers = [];
$conditions = ['active' => true];
if (app('tenant')->slug !== 'lv') {
$conditions['local_group'] = app('tenant')->slug;
if (currentTenant()->slug !== 'lv') {
$conditions['local_group'] = currentTenant()->slug;
}
foreach ($rawUsers = User::where($conditions)->get() as $user) {
@@ -195,6 +207,16 @@ class GlobalDataProvider {
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 {
return response()->json(
[
+1 -1
View File
@@ -16,7 +16,7 @@ final class InertiaProvider
private ?User $user;
public function __construct(string $vueFile, array $props) {
$this->user = auth()->user();
$this->user = currentUser();
$this->vueFile = $vueFile;
$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.
if (app('tenant')->slug === 'lv') {
if (currentTenant()->slug === 'lv') {
return $query->first();
}
@@ -30,7 +30,7 @@ class TenantUserProvider extends EloquentUserProvider
// -> "Bundesrecht steht über Landesrecht": Login überall möglich.
$query->where('active', true)
->where(function ($q) {
$q->where('local_group', app('tenant')->slug)
$q->where('local_group', currentTenant()->slug)
->orWhere('user_role_main', UserRole::USER_ROLE_ADMIN);
});
+13 -5
View File
@@ -16,13 +16,21 @@ class UploadFileProvider {
$this->costUnit = $costUnit;
}
/**
* Das Ablageverzeichnis der Belege einer Kostenstelle, relativ zur Disk `local`
* (Wurzel `storage/app/private`).
*
* Öffentlich, weil Belege nicht nur aus einem Upload entstehen: Eine Beitragserstattung erzeugt ihren
* Eigenbeleg im Speicher und legt ihn über den FileWriteProvider ab -- landen soll er trotzdem dort,
* wo alle anderen Belege liegen.
*/
public static function directoryFor(CostUnit $costUnit) : string {
return sprintf('%1$s/invoices/%2$s', currentTenant()->slug, $costUnit->id);
}
public function saveUploadedFile() : ?InvoiceFile {
try {
$directory = sprintf(
'%1$s/invoices/%2$s',
app('tenant')->slug,
$this->costUnit->id
);
$directory = self::directoryFor($this->costUnit);
$filename = $this->normalizeFilename($this->file->getClientOriginalName());
+51 -5
View File
@@ -2,11 +2,13 @@
namespace App\Repositories;
use \currentUser;
use App\Enumerations\CostUnitType;
use App\Enumerations\InvoiceStatus;
use App\Enumerations\InvoiceType;
use App\Enumerations\UserRole;
use App\Models\CostUnit;
use App\Models\Invoice;
use App\Providers\AuthCheckProvider;
use App\Resources\CostUnitResource;
use App\ValueObjects\Amount;
@@ -66,8 +68,7 @@ class CostUnitRepository {
}
public function getCostUnitsByCriteria(array $criteria, bool $forDisplay = true, $disableAccessCheck = false) : array {
$user = Auth()->user();
$user = currentUser();
if ($disableAccessCheck) {
$canSeeAll = true;
} else {
@@ -96,7 +97,7 @@ class CostUnitRepository {
public function listForSummary(int $maxCountCostUnits) : array {
$costUnits = $this->getCostUnitsByCriteria([
'archived' => false,
'tenant' => app('tenant')->slug,
'tenant' => currentTenant()->slug,
],false);
foreach ($costUnits as &$cu) {
@@ -153,8 +154,7 @@ class CostUnitRepository {
foreach ($costUnit->invoices()->get() as $invoice) {
if (
$invoice->status === InvoiceStatus::INVOICE_STATUS_DENIED ||
$invoice->donation ||
!self::countsAsExpense($invoice) ||
$invoice->type !== $invoiceType->slug
) {
continue;
@@ -165,6 +165,52 @@ class CostUnitRepository {
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 {
$amount = new Amount(0, 'Euro');
foreach ($costUnit->estimates()->get() as $estimate) {
@@ -297,7 +297,7 @@ class EventParticipantRepository {
public function getMyParticipations(?int $maxEvents = null) : array {
$participations = [];
$user = auth()->user();
$user = currentUser();
if ($user === null) {
return $participations;
}
@@ -326,13 +326,13 @@ class EventParticipantRepository {
}
public function getMyParticipationByIdentifier(string $identifier) : ?EventParticipant {
$user = auth()->user();
$user = currentUser();
if ($user === null) {
return null;
}
return EventParticipant::where('identifier', $identifier)
->where('tenant', app('tenant')->slug)
->where('tenant', currentTenant()->slug)
->where('user_id', $user->id)
->whereNull('unregistered_at')
->first();
+5 -5
View File
@@ -20,7 +20,7 @@ class InvoiceRepository {
];
$user = auth()->user();
$user = currentUser();
if (null === $user) {
return $invoices;
}
@@ -41,7 +41,7 @@ class InvoiceRepository {
}
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 {
@@ -63,8 +63,8 @@ class InvoiceRepository {
foreach (Invoice::where(
[
'status' => $status,
'user_id' => auth()->user()->id,
'tenant' => app('tenant')->slug,
'user_id' => currentUserOrFail()->id,
'tenant' => currentTenant()->slug,
]
)->get() as $invoice) {
@@ -79,7 +79,7 @@ class InvoiceRepository {
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) {
return $invoice;
}
+2 -2
View File
@@ -20,7 +20,7 @@ class UserRepository {
}
public function getCurrentUserDetails() : array {
$user = auth()->user();
$user = currentUser();
$return = [
'userId' => null,
@@ -31,7 +31,7 @@ class UserRepository {
'userAccountIban' => '',
];
if (null !== auth()->user()) {
if ($user !== null) {
$return = [
'userId' => $user->id,
'userName' => trim($user->getOfficialName()),
+4 -1
View File
@@ -32,7 +32,10 @@ class CostUnitResource {
$amounts = [];
$overAllAmount = 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));
$overAllEstimatedAmount->addAmount($costUnitRepository->sumupEstimatedByInvoiceType($this->costUnit, $invoiceType));
$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,
'name' => $this->event->name,
'identifier' => $this->event->identifier,
'url' => 'https://' . app('tenant')->url . '/event/' . $this->event->identifier . '/signup',
'urlShort' => 'https://' . app('tenant')->url . '/event/' . $this->event->identifier,
'url' => 'https://' . currentTenant()->url . '/event/' . $this->event->identifier . '/signup',
'urlShort' => 'https://' . currentTenant()->url . '/event/' . $this->event->identifier,
'location' => $this->event->location,
'postalCode' => $this->event->postal_code,
'email' => $this->event->email,
@@ -96,6 +96,14 @@ class EventResource extends JsonResource{
$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');
$totalBalanceExpected = new Amount(0, 'Euro');
@@ -272,6 +280,13 @@ class EventResource extends JsonResource{
$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' => [
'amount' => $realAmount,
'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 {
$returnData = [];
$returnData['amount'] = [
+5 -4
View File
@@ -30,6 +30,7 @@ class InvoiceResource {
}
$returnData['invoiceTypeShort'] = $this->invoice->invoiceType()->name;
$returnData['purpose'] = $this->invoice->purposeText();
$returnData['costUnitName'] = $this->invoice->costUnit()->first()->name;
$returnData['invoiceNumber'] = $this->invoice->invoice_number;
$returnData['contactName'] = $this->invoice->contact_name;
@@ -39,7 +40,7 @@ class InvoiceResource {
$returnData['id'] = $this->invoice->id;
$returnData['donation'] = $this->invoice->donation;
$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['accountIban'] = $this->invoice->contact_bank_iban ?? '--';
$returnData['status'] = $this->invoice->status;
@@ -49,11 +50,11 @@ class InvoiceResource {
$returnData['changes'] = $this->invoice->changes ?? '--';
$returnData['deniedReason'] = $this->invoice->denied_reason ?? '--';
$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['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['costUnitId'] = $this->invoice->cost_unit_id;
$returnData['amountPlain'] = new Amount($this->invoice->amount, '')->toString();
@@ -29,9 +29,20 @@ class ParticipantRefundResource extends JsonResource
'reason' => $this->resource->reason,
'reasonLabel' => $this->resource->reasonLabel(),
'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'),
'acceptedAt' => $this->resource->accepted_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.
'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;
public function __construct() {
$this->tenant = app('tenant');
$this->tenant = currentTenant();
$this->users = new UserRepository();
$this->costUnits = new CostUnitRepository();
$this->pageTexts = new PageTextRepository();
+1 -1
View File
@@ -9,6 +9,6 @@ class SiteScope implements Scope
{
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