4 Commits
Author SHA1 Message Date
th.guenther b01288b5e0 Small Improvements 2026-09-03 21:53:04 +02:00
th.guenther 6a183d6498 Creating Participation refunds 2026-09-03 21:23:26 +02:00
th.guenther 9c4c28e566 Teilnahmerechnungen erstellen 2026-09-03 00:08:46 +02:00
th.guenther a61344395a Fix Anmeldung für Personen Ü18 2026-08-27 11:22:47 +02:00
126 changed files with 8276 additions and 80 deletions
+3
View File
@@ -23,3 +23,6 @@ Homestead.json
Homestead.yaml Homestead.yaml
Thumbs.db Thumbs.db
/docker-compose.yaml /docker-compose.yaml
# HTML-Report von composer test:coverage
/storage/coverage
@@ -0,0 +1,87 @@
<?php
namespace App\Domains\Admin\Actions\UpdateDocumentAsset;
use App\Models\DocumentAsset;
/**
* Legt ein Bild für die Dokumentvorlagen an oder ersetzt es.
*
* Gespeichert wird der base64-Payload in der Datenbank -- so überlebt das Bild ein Release (das als
* `git checkout` alles unter `public/` überschreibt) und wandert mit jedem Dump mit.
*/
class UpdateDocumentAssetAction
{
/** Über 2 MB wird die Vorlage träge und das PDF unnötig groß. */
private const int MAX_BYTES = 2 * 1024 * 1024;
/** @var array<string, string> */
private const array ALLOWED_MIME_TYPES = [
'image/png' => 'png',
'image/jpeg' => 'jpg',
'image/gif' => 'gif',
'image/svg+xml' => 'svg',
];
public function __construct(private readonly UpdateDocumentAssetRequest $request)
{
}
public function execute(): UpdateDocumentAssetResponse
{
$response = new UpdateDocumentAssetResponse();
$name = $this->normalizeName($this->request->name);
if ($name === null) {
$response->message = 'Bitte einen Namen aus Kleinbuchstaben, Ziffern, Bindestrich oder Unterstrich angeben.';
return $response;
}
$asset = DocumentAsset::where('name', $name)->first();
$file = $this->request->file;
if ($file === null && $asset === null) {
$response->message = 'Für ein neues Bild wird eine Datei benötigt.';
return $response;
}
$attributes = ['name' => $name, 'label' => $this->request->label];
if ($file !== null) {
if (!array_key_exists($file->getMimeType(), self::ALLOWED_MIME_TYPES)) {
$response->message = 'Nur PNG, JPEG, GIF oder SVG sind zulässig.';
return $response;
}
if ($file->getSize() > self::MAX_BYTES) {
$response->message = 'Das Bild darf höchstens 2 MB groß sein.';
return $response;
}
$attributes['mime'] = $file->getMimeType();
$attributes['data'] = base64_encode(file_get_contents($file->getRealPath()));
}
$response->asset = $asset === null
? DocumentAsset::create($attributes)
: tap($asset)->update($attributes);
$response->success = true;
$response->message = 'Das Bild wurde gespeichert.';
return $response;
}
/** Namen sind Slugs, damit `{asset:name}` eindeutig erkennbar bleibt. */
private function normalizeName(string $name): ?string
{
$name = strtolower(trim($name));
return preg_match('/^[a-z0-9_-]+$/', $name) === 1 ? $name : null;
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Domains\Admin\Actions\UpdateDocumentAsset;
use Illuminate\Http\UploadedFile;
class UpdateDocumentAssetRequest
{
public function __construct(
/** Slug, unter dem das Bild in der Vorlage als `{asset:name}` referenziert wird. */
public readonly string $name,
public readonly ?string $label = null,
public readonly ?UploadedFile $file = null,
) {
}
}
@@ -0,0 +1,14 @@
<?php
namespace App\Domains\Admin\Actions\UpdateDocumentAsset;
use App\Models\DocumentAsset;
class UpdateDocumentAssetResponse
{
public bool $success = false;
public ?string $message = null;
public ?DocumentAsset $asset = null;
}
@@ -0,0 +1,73 @@
<?php
namespace App\Domains\Admin\Actions\UpdateDocumentTemplate;
use App\Models\DocumentTemplate;
/**
* Speichert die Blockinhalte einer Dokumentvorlage.
*
* Es werden nur bereits angelegte, als editierbar markierte Blöcke geschrieben. Neue Blöcke entstehen
* nicht über das Formular -- welche Blöcke eine Dokumentart hat, gibt die Vorlage vor (das Layout
* verweist mit `{block:...}` auf sie).
*/
class UpdateDocumentTemplateAction
{
public function __construct(private readonly UpdateDocumentTemplateRequest $request)
{
}
public function execute(): UpdateDocumentTemplateResponse
{
$response = new UpdateDocumentTemplateResponse();
$existing = DocumentTemplate::forType($this->request->documentType);
// Erst prüfen, dann schreiben -- sonst bliebe bei einem Fehler ein halb gespeicherter Stand übrig.
$rejection = $this->rejectBareAssetInStyle();
if ($rejection !== null) {
$response->message = $rejection;
return $response;
}
foreach ($this->request->blocks as $block => $content) {
$template = $existing->get($block);
if ($template === null || !$template->editable) {
$response->skipped[] = $block;
continue;
}
$template->update(['content' => (string) $content]);
}
$response->success = true;
$response->message = $response->skipped === []
? 'Die Vorlage wurde gespeichert.'
: 'Die Vorlage wurde gespeichert; nicht editierbare Blöcke blieben unverändert.';
return $response;
}
/**
* Ein Bild-Platzhalter, der im CSS nicht in `url(...)` steht, expandiert zu einem Data-URI, das
* dompdf nicht auslagern kann -- der Parser läuft dann minutenlang und der FPM-Worker stirbt am
* Zeitlimit (502). Solches CSS wird gar nicht erst gespeichert.
*
* @return string|null Fehlermeldung, oder null wenn nichts zu beanstanden ist.
*/
private function rejectBareAssetInStyle(): ?string
{
$style = $this->request->blocks[DocumentTemplate::BLOCK_STYLE] ?? null;
if ($style === null || preg_match('/(?<![("\'])\{asset:([a-z0-9_-]+)}/i', (string) $style, $match) !== 1) {
return null;
}
return sprintf(
'Im CSS-Block steht der Bild-Platzhalter {asset:%1$s} direkt im Text. Dort gehört er in url("{asset:%1$s}").',
$match[1]
);
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Domains\Admin\Actions\UpdateDocumentTemplate;
class UpdateDocumentTemplateRequest
{
/**
* @param array<string, string> $blocks Blockinhalte, adressiert über den Block-Slug.
*/
public function __construct(
public readonly string $documentType,
public readonly array $blocks,
) {
}
}
@@ -0,0 +1,13 @@
<?php
namespace App\Domains\Admin\Actions\UpdateDocumentTemplate;
class UpdateDocumentTemplateResponse
{
public bool $success = false;
public ?string $message = null;
/** @var array<int, string> Blöcke, die nicht gespeichert wurden (unbekannt oder nicht editierbar). */
public array $skipped = [];
}
@@ -2,6 +2,8 @@
namespace App\Domains\Admin\Actions\UpdateTenantContact; namespace App\Domains\Admin\Actions\UpdateTenantContact;
use App\Support\Text;
class UpdateTenantContactAction class UpdateTenantContactAction
{ {
public function __construct(private UpdateTenantContactRequest $request) public function __construct(private UpdateTenantContactRequest $request)
@@ -15,8 +17,14 @@ class UpdateTenantContactAction
$this->request->tenant->update([ $this->request->tenant->update([
'email' => $this->request->email, 'email' => $this->request->email,
'email_finance' => $this->request->emailFinance, 'email_finance' => $this->request->emailFinance,
'invoice_sender_name' => Text::nullIfBlank($this->request->invoiceSenderName),
// Leergelassene optionale Felder als NULL, damit sie im Briefkopf sauber wegfallen.
'address_1' => Text::nullIfBlank($this->request->address1),
'address_2' => Text::nullIfBlank($this->request->address2),
'address_3' => Text::nullIfBlank($this->request->address3),
'postcode' => $this->request->postcode, 'postcode' => $this->request->postcode,
'city' => $this->request->city, 'city' => $this->request->city,
'phone' => Text::nullIfBlank($this->request->phone),
]); ]);
$response->success = true; $response->success = true;
@@ -12,6 +12,14 @@ class UpdateTenantContactRequest
public string $emailFinance, public string $emailFinance,
public string $postcode, public string $postcode,
public string $city, public string $city,
/** Bezeichnung des Rechnungsstellers; leer bedeutet "Name des Mandanten verwenden". */
public ?string $invoiceSenderName = null,
/** Straße und Hausnummer -- Pflichtangabe auf Rechnungen nach § 14 Abs. 4 UStG. */
public ?string $address1 = null,
/** Optionale Zusatzzeile, z.B. "c/o ...". */
public ?string $address2 = null,
public ?string $address3 = null,
public ?string $phone = null,
) { ) {
} }
} }
@@ -3,6 +3,8 @@
namespace App\Domains\Admin\Actions\UpdateTenantTax; namespace App\Domains\Admin\Actions\UpdateTenantTax;
use App\Enumerations\VatPricingMode; use App\Enumerations\VatPricingMode;
use App\Models\Tenant;
use App\Support\Text;
class UpdateTenantTaxAction class UpdateTenantTaxAction
{ {
@@ -14,14 +16,23 @@ class UpdateTenantTaxAction
{ {
$response = new UpdateTenantTaxResponse(); $response = new UpdateTenantTaxResponse();
// Präfixe sind großgeschrieben; null heißt "nicht mitgeschickt" und damit "unverändert".
$prefix = Text::nullIfBlank(strtoupper((string) $this->request->invoicePrefix));
if ($prefix !== null && $this->prefixTakenByAnotherTenant($prefix)) {
$response->message = sprintf('Das Rechnungs-Präfix "%s" wird bereits von einem anderen Mandanten genutzt.', $prefix);
return $response;
}
if ($this->request->taxLiable) { if ($this->request->taxLiable) {
$this->request->tenant->update([ $this->request->tenant->update($this->withInvoiceDetails([
'tax_liable' => true, 'tax_liable' => true,
'vat_rate' => $this->clampVatRate($this->request->vatRate), 'vat_rate' => $this->clampVatRate($this->request->vatRate),
'vat_pricing_mode' => $this->request->vatPricingMode->value, 'vat_pricing_mode' => $this->request->vatPricingMode->value,
'tax_exemption_reason' => null, 'tax_exemption_reason' => null,
'tax_exemption_note' => null, 'tax_exemption_note' => null,
]); ], $prefix));
$response->success = true; $response->success = true;
$response->message = 'Steuerinformationen wurden gespeichert.'; $response->message = 'Steuerinformationen wurden gespeichert.';
@@ -45,13 +56,13 @@ class UpdateTenantTaxAction
return $response; return $response;
} }
$this->request->tenant->update([ $this->request->tenant->update($this->withInvoiceDetails([
'tax_liable' => false, 'tax_liable' => false,
'vat_rate' => 0, 'vat_rate' => 0,
'vat_pricing_mode' => VatPricingMode::Inclusive->value, 'vat_pricing_mode' => VatPricingMode::Inclusive->value,
'tax_exemption_reason' => $reason->slug, 'tax_exemption_reason' => $reason->slug,
'tax_exemption_note' => $reason->requires_note ? $note : null, 'tax_exemption_note' => $reason->requires_note ? $note : null,
]); ], $prefix));
$response->success = true; $response->success = true;
$response->message = 'Steuerinformationen wurden gespeichert.'; $response->message = 'Steuerinformationen wurden gespeichert.';
@@ -63,4 +74,31 @@ class UpdateTenantTaxAction
{ {
return max(0, min(100, $vatRate)); return max(0, min(100, $vatRate));
} }
/**
* Ergänzt die Rechnungsstellerangaben. Sie gelten unabhängig davon, ob Steuerpflicht besteht -- eine
* Steuernummer gehört auch auf eine steuerfreie Rechnung.
*
* @param array<string, mixed> $attributes
* @return array<string, mixed>
*/
private function withInvoiceDetails(array $attributes, ?string $prefix): array
{
$attributes['tax_number'] = Text::nullIfBlank($this->request->taxNumber);
$attributes['vat_id'] = Text::nullIfBlank($this->request->vatId);
// Nicht mitgeschickt heißt "unverändert", nicht "leeren".
if ($prefix !== null) {
$attributes['invoice_prefix'] = $prefix;
}
return $attributes;
}
private function prefixTakenByAnotherTenant(string $prefix): bool
{
return Tenant::where('invoice_prefix', $prefix)
->where('id', '!=', $this->request->tenant->id)
->exists();
}
} }
@@ -15,6 +15,14 @@ class UpdateTenantTaxRequest
public ?TaxExemptionReason $exemptionReason, public ?TaxExemptionReason $exemptionReason,
public ?string $exemptionNote, public ?string $exemptionNote,
public VatPricingMode $vatPricingMode, public VatPricingMode $vatPricingMode,
/** Steuernummer bzw. USt-IdNr. -- Pflichtangabe auf Rechnungen (§ 14 Abs. 4 Nr. 2 UStG). */
public ?string $taxNumber = null,
public ?string $vatId = null,
/**
* Erster Block der Rechnungsnummer. `null` heißt "unverändert lassen" -- im Self-Service wird das
* Feld gar nicht erst mitgeschickt, damit ein bestehender Nummernkreis nicht bricht.
*/
public ?string $invoicePrefix = null,
) )
{ {
} }
@@ -0,0 +1,42 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Models\DocumentAsset;
use App\Models\DocumentTemplate;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
class DocumentAssetDeleteController extends CommonController
{
public function __invoke(string $name): JsonResponse
{
$asset = DocumentAsset::where('name', $name)->first();
// Durchweg 200 mit Status im Body -- wie die übrigen Admin-Endpunkte, damit der Grund im Frontend
// ankommt (der Ajax-Helfer verwirft den Body bei Fehler-Statuscodes).
if ($asset === null) {
return response()->json(['status' => 'error', 'message' => 'Das Bild existiert nicht.']);
}
// Ein noch referenziertes Bild zu löschen würde stillschweigend eine Lücke in jede künftige
// Rechnung reißen -- der Platzhalter löst dann zu einem Leerstring auf.
if ($this->isReferenced($asset->name)) {
return response()->json([
'status' => 'error',
'message' => sprintf('Das Bild wird noch als {asset:%s} in der Vorlage verwendet.', $asset->name),
]);
}
$asset->delete();
return response()->json(['status' => 'success', 'message' => 'Das Bild wurde gelöscht.']);
}
private function isReferenced(string $name): bool
{
return DocumentTemplate::query()
->where('content', 'like', '%{asset:' . $name . '}%')
->exists();
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Domains\Admin\Actions\UpdateDocumentAsset\UpdateDocumentAssetAction;
use App\Domains\Admin\Actions\UpdateDocumentAsset\UpdateDocumentAssetRequest;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class DocumentAssetUpdateController extends CommonController
{
public function __invoke(Request $request): JsonResponse
{
$action = new UpdateDocumentAssetAction(new UpdateDocumentAssetRequest(
name: (string) $request->input('name'),
label: $request->input('label'),
file: $request->file('file'),
));
$response = $action->execute();
return response()->json([
'status' => $response->success ? 'success' : 'error',
'message' => $response->message,
'token' => $response->asset !== null ? '{asset:' . $response->asset->name . '}' : null,
]);
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Models\DocumentAsset;
use App\Models\DocumentTemplate;
use App\Models\DocumentTypeCatalog;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class DocumentTemplatesGetController extends CommonController
{
public function __invoke(Request $request): JsonResponse
{
$documentType = (string) $request->input('type', DocumentTypeCatalog::default());
if (!DocumentTypeCatalog::has($documentType)) {
abort(422, 'Unbekannte Dokumentart.');
}
$blocks = DocumentTemplate::forType($documentType)
->values()
->map(fn(DocumentTemplate $block): array => [
'block' => $block->block,
'label' => DocumentTypeCatalog::blockLabel($documentType, $block->block),
'content' => (string) $block->content,
'editable' => $block->editable,
'source' => in_array($block->block, DocumentTypeCatalog::SOURCE_BLOCKS, true),
]);
return response()->json([
'documentType' => $documentType,
'documentTypes' => DocumentTypeCatalog::options(),
'blocks' => $blocks,
// Die Bilder gelten für alle Dokumentarten -- sie hängen nicht am Typ.
'assets' => DocumentAsset::orderBy('name')->get()->map(fn(DocumentAsset $asset): array => [
'name' => $asset->name,
'label' => $asset->label,
'mime' => $asset->mime,
'token' => '{asset:' . $asset->name . '}',
'preview' => $asset->toDataUri(),
]),
'tokenGroups' => DocumentTypeCatalog::tokenGroups($documentType),
]);
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Providers\InertiaProvider;
use App\Scopes\CommonController;
use Inertia\Response;
class DocumentTemplatesPageController extends CommonController
{
public function __invoke(): Response
{
return new InertiaProvider('Admin/DocumentTemplates', [])->render();
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Models\DocumentTypeCatalog;
use App\Providers\DocumentTemplateRenderProvider;
use App\Providers\PdfGenerateAndDownloadProvider;
use App\Scopes\CommonController;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* Rendert die Vorlage mit Beispieldaten, ohne sie zu speichern -- damit niemand blind HTML editiert.
*/
class DocumentTemplatesPreviewController extends CommonController
{
public function __invoke(Request $request): Response
{
$documentType = (string) $request->input('type', DocumentTypeCatalog::default());
if (!DocumentTypeCatalog::has($documentType)) {
abort(422, 'Unbekannte Dokumentart.');
}
$html = new DocumentTemplateRenderProvider(
$documentType,
(array) $request->input('blocks', []),
)->render(DocumentTypeCatalog::sampleTokens($documentType));
return response(PdfGenerateAndDownloadProvider::fromHtml($html, 'portrait'), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="vorschau.pdf"',
]);
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Domains\Admin\Actions\UpdateDocumentTemplate\UpdateDocumentTemplateAction;
use App\Domains\Admin\Actions\UpdateDocumentTemplate\UpdateDocumentTemplateRequest;
use App\Models\DocumentTypeCatalog;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class DocumentTemplatesUpdateController extends CommonController
{
public function __invoke(Request $request): JsonResponse
{
$documentType = (string) $request->input('type', DocumentTypeCatalog::default());
// Die Dokumentart bestimmt, welche Zeilen geschrieben werden -- ungeprüft weitergereicht wäre
// sie ein Weg, in beliebige Vorlagen zu schreiben.
if (!DocumentTypeCatalog::has($documentType)) {
abort(422, 'Unbekannte Dokumentart.');
}
$action = new UpdateDocumentTemplateAction(new UpdateDocumentTemplateRequest(
documentType: $documentType,
blocks: (array) $request->input('blocks', []),
));
$response = $action->execute();
return response()->json([
'status' => $response->success ? 'success' : 'error',
'message' => $response->message,
]);
}
}
@@ -15,6 +15,13 @@ class ManagedTenantContactGetController extends CommonController
return response()->json([ return response()->json([
'email' => $tenant->email, 'email' => $tenant->email,
'email_finance' => $tenant->email_finance, 'email_finance' => $tenant->email_finance,
'invoice_sender_name' => $tenant->invoice_sender_name,
// Als Platzhalter im Formular: so heisst der Absender, solange nichts eingetragen ist.
'name' => $tenant->name,
'phone' => $tenant->phone,
'address_1' => $tenant->address_1,
'address_2' => $tenant->address_2,
'address_3' => $tenant->address_3,
'postcode' => $tenant->postcode, 'postcode' => $tenant->postcode,
'city' => $tenant->city, 'city' => $tenant->city,
'saveEndpoint' => '/api/v1/admin/tenants/' . $slug . '/contact', 'saveEndpoint' => '/api/v1/admin/tenants/' . $slug . '/contact',
@@ -20,6 +20,11 @@ class ManagedTenantContactUpdateController extends CommonController
emailFinance: $request->input('email_finance'), emailFinance: $request->input('email_finance'),
postcode: $request->input('postcode'), postcode: $request->input('postcode'),
city: $request->input('city'), city: $request->input('city'),
invoiceSenderName: $request->input('invoice_sender_name'),
address1: $request->input('address_1'),
address2: $request->input('address_2'),
address3: $request->input('address_3'),
phone: $request->input('phone'),
)); ));
$response = $action->execute(); $response = $action->execute();
@@ -20,6 +20,11 @@ class ManagedTenantTaxGetController extends CommonController
'tax_exemption_reason' => $tenant->tax_exemption_reason, 'tax_exemption_reason' => $tenant->tax_exemption_reason,
'tax_exemption_note' => $tenant->tax_exemption_note, 'tax_exemption_note' => $tenant->tax_exemption_note,
'vat_pricing_mode' => $tenant->vat_pricing_mode, 'vat_pricing_mode' => $tenant->vat_pricing_mode,
'tax_number' => $tenant->tax_number,
'vat_id' => $tenant->vat_id,
'invoice_prefix' => $tenant->invoice_prefix,
// In der Mandanten-Verwaltung ist der Nummernkreis änderbar.
'can_edit_invoice_prefix' => true,
'exemption_reasons' => TaxExemptionReason::options(), 'exemption_reasons' => TaxExemptionReason::options(),
'pricing_modes' => VatPricingMode::options(), 'pricing_modes' => VatPricingMode::options(),
'saveEndpoint' => '/api/v1/admin/tenants/' . $slug . '/tax', 'saveEndpoint' => '/api/v1/admin/tenants/' . $slug . '/tax',
@@ -23,6 +23,9 @@ class ManagedTenantTaxUpdateController extends CommonController
exemptionReason: TaxExemptionReason::where('slug', $request->input('tax_exemption_reason'))->first(), exemptionReason: TaxExemptionReason::where('slug', $request->input('tax_exemption_reason'))->first(),
exemptionNote: $request->input('tax_exemption_note'), exemptionNote: $request->input('tax_exemption_note'),
vatPricingMode: VatPricingMode::tryFrom((string) $request->input('vat_pricing_mode', 'inclusive')) ?? VatPricingMode::Inclusive, vatPricingMode: VatPricingMode::tryFrom((string) $request->input('vat_pricing_mode', 'inclusive')) ?? VatPricingMode::Inclusive,
taxNumber: $request->input('tax_number'),
vatId: $request->input('vat_id'),
invoicePrefix: $request->input('invoice_prefix'),
)); ));
$response = $action->execute(); $response = $action->execute();
@@ -13,6 +13,13 @@ class TenantContactGetController extends CommonController
return response()->json([ return response()->json([
'email' => $this->tenant->email, 'email' => $this->tenant->email,
'email_finance' => $this->tenant->email_finance, 'email_finance' => $this->tenant->email_finance,
'invoice_sender_name' => $this->tenant->invoice_sender_name,
// Als Platzhalter im Formular: so heisst der Absender, solange nichts eingetragen ist.
'name' => $this->tenant->name,
'phone' => $this->tenant->phone,
'address_1' => $this->tenant->address_1,
'address_2' => $this->tenant->address_2,
'address_3' => $this->tenant->address_3,
'postcode' => $this->tenant->postcode, 'postcode' => $this->tenant->postcode,
'city' => $this->tenant->city, 'city' => $this->tenant->city,
'saveEndpoint' => '/api/v1/admin/tenant/contact', 'saveEndpoint' => '/api/v1/admin/tenant/contact',
@@ -18,6 +18,11 @@ class TenantContactUpdateController extends CommonController
emailFinance: $request->input('email_finance'), emailFinance: $request->input('email_finance'),
postcode: $request->input('postcode'), postcode: $request->input('postcode'),
city: $request->input('city'), city: $request->input('city'),
invoiceSenderName: $request->input('invoice_sender_name'),
address1: $request->input('address_1'),
address2: $request->input('address_2'),
address3: $request->input('address_3'),
phone: $request->input('phone'),
)); ));
$response = $action->execute(); $response = $action->execute();
@@ -18,6 +18,11 @@ class TenantTaxGetController extends CommonController
'tax_exemption_reason' => $this->tenant->tax_exemption_reason, 'tax_exemption_reason' => $this->tenant->tax_exemption_reason,
'tax_exemption_note' => $this->tenant->tax_exemption_note, 'tax_exemption_note' => $this->tenant->tax_exemption_note,
'vat_pricing_mode' => $this->tenant->vat_pricing_mode, 'vat_pricing_mode' => $this->tenant->vat_pricing_mode,
'tax_number' => $this->tenant->tax_number,
'vat_id' => $this->tenant->vat_id,
'invoice_prefix' => $this->tenant->invoice_prefix,
// Im Self-Service nicht änderbar: das Präfix bestimmt den Nummernkreis.
'can_edit_invoice_prefix' => false,
'exemption_reasons' => TaxExemptionReason::options(), 'exemption_reasons' => TaxExemptionReason::options(),
'pricing_modes' => VatPricingMode::options(), 'pricing_modes' => VatPricingMode::options(),
'saveEndpoint' => '/api/v1/admin/tenant/tax', 'saveEndpoint' => '/api/v1/admin/tenant/tax',
@@ -21,6 +21,10 @@ class TenantTaxUpdateController extends CommonController
exemptionReason: TaxExemptionReason::where('slug', $request->input('tax_exemption_reason'))->first(), exemptionReason: TaxExemptionReason::where('slug', $request->input('tax_exemption_reason'))->first(),
exemptionNote: $request->input('tax_exemption_note'), exemptionNote: $request->input('tax_exemption_note'),
vatPricingMode: VatPricingMode::tryFrom((string) $request->input('vat_pricing_mode', 'inclusive')) ?? VatPricingMode::Inclusive, vatPricingMode: VatPricingMode::tryFrom((string) $request->input('vat_pricing_mode', 'inclusive')) ?? VatPricingMode::Inclusive,
taxNumber: $request->input('tax_number'),
vatId: $request->input('vat_id'),
// invoice_prefix wird hier bewusst nicht durchgereicht -- der Nummernkreis ist nur in der
// Mandanten-Verwaltung änderbar.
)); ));
$response = $action->execute(); $response = $action->execute();
+18
View File
@@ -1,5 +1,10 @@
<?php <?php
use App\Domains\Admin\Controllers\DocumentAssetDeleteController;
use App\Domains\Admin\Controllers\DocumentAssetUpdateController;
use App\Domains\Admin\Controllers\DocumentTemplatesGetController;
use App\Domains\Admin\Controllers\DocumentTemplatesPreviewController;
use App\Domains\Admin\Controllers\DocumentTemplatesUpdateController;
use App\Domains\Admin\Controllers\ManagedTenantContactGetController; use App\Domains\Admin\Controllers\ManagedTenantContactGetController;
use App\Domains\Admin\Controllers\ManagedTenantContactUpdateController; use App\Domains\Admin\Controllers\ManagedTenantContactUpdateController;
use App\Domains\Admin\Controllers\ManagedTenantGdprGetController; use App\Domains\Admin\Controllers\ManagedTenantGdprGetController;
@@ -34,6 +39,7 @@ use App\Domains\Admin\Controllers\UserUpdateController;
use App\Middleware\AdminRoleMiddleware; use App\Middleware\AdminRoleMiddleware;
use App\Middleware\IdentifyTenant; use App\Middleware\IdentifyTenant;
use App\Middleware\LvOnlyMiddleware; use App\Middleware\LvOnlyMiddleware;
use App\Middleware\MainAdminRoleMiddleware;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::middleware([IdentifyTenant::class, 'auth', AdminRoleMiddleware::class])->group(function () { Route::middleware([IdentifyTenant::class, 'auth', AdminRoleMiddleware::class])->group(function () {
@@ -60,6 +66,18 @@ Route::middleware([IdentifyTenant::class, 'auth', AdminRoleMiddleware::class])->
Route::post('/{id}/reset-password', UserResetPasswordController::class); Route::post('/{id}/reset-password', UserResetPasswordController::class);
}); });
// Dokumentvorlagen gelten app-weit für alle Mandanten -- deshalb nur für Hauptadministrator*innen,
// AdminRoleMiddleware allein ließe auch Gruppenleitungen durch.
Route::middleware(MainAdminRoleMiddleware::class)->group(function () {
Route::prefix('api/v1/admin/document-templates')->group(function () {
Route::get('/', DocumentTemplatesGetController::class);
Route::post('/', DocumentTemplatesUpdateController::class);
Route::post('/preview', DocumentTemplatesPreviewController::class);
Route::post('/assets', DocumentAssetUpdateController::class);
Route::delete('/assets/{name}', DocumentAssetDeleteController::class);
});
});
Route::middleware(LvOnlyMiddleware::class)->group(function () { Route::middleware(LvOnlyMiddleware::class)->group(function () {
Route::prefix('api/v1/admin/tenants')->group(function () { Route::prefix('api/v1/admin/tenants')->group(function () {
Route::get('/list', TenantListApiController::class); Route::get('/list', TenantListApiController::class);
+7
View File
@@ -1,6 +1,7 @@
<?php <?php
use App\Domains\Admin\Controllers\AdminDashboardController; use App\Domains\Admin\Controllers\AdminDashboardController;
use App\Domains\Admin\Controllers\DocumentTemplatesPageController;
use App\Domains\Admin\Controllers\TenantEditPageController; use App\Domains\Admin\Controllers\TenantEditPageController;
use App\Domains\Admin\Controllers\TenantListPageController; use App\Domains\Admin\Controllers\TenantListPageController;
use App\Domains\Admin\Controllers\TenantPageController; use App\Domains\Admin\Controllers\TenantPageController;
@@ -8,6 +9,7 @@ use App\Domains\Admin\Controllers\UserListPageController;
use App\Middleware\AdminRoleMiddleware; use App\Middleware\AdminRoleMiddleware;
use App\Middleware\IdentifyTenant; use App\Middleware\IdentifyTenant;
use App\Middleware\LvOnlyMiddleware; use App\Middleware\LvOnlyMiddleware;
use App\Middleware\MainAdminRoleMiddleware;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::middleware([IdentifyTenant::class, 'auth', AdminRoleMiddleware::class])->group(function () { Route::middleware([IdentifyTenant::class, 'auth', AdminRoleMiddleware::class])->group(function () {
@@ -16,6 +18,11 @@ Route::middleware([IdentifyTenant::class, 'auth', AdminRoleMiddleware::class])->
Route::get('/tenant', TenantPageController::class); Route::get('/tenant', TenantPageController::class);
Route::get('/users', UserListPageController::class); Route::get('/users', UserListPageController::class);
// App-weit gültige Dokumentvorlagen -- nur für Hauptadministrator*innen.
Route::middleware(MainAdminRoleMiddleware::class)->group(function () {
Route::get('/document-templates', DocumentTemplatesPageController::class);
});
Route::middleware(LvOnlyMiddleware::class)->group(function () { Route::middleware(LvOnlyMiddleware::class)->group(function () {
Route::get('/tenants', TenantListPageController::class); Route::get('/tenants', TenantListPageController::class);
Route::get('/tenants/{slug}', TenantEditPageController::class); Route::get('/tenants/{slug}', TenantEditPageController::class);
@@ -0,0 +1,666 @@
<script setup>
import {computed, onMounted, ref} from 'vue'
import {toast} from 'vue3-toastify'
import AdminAppLayout from '../../../../resources/js/layouts/AdminAppLayout.vue'
import ShadowedBox from '../../../Views/Components/ShadowedBox.vue'
import TextEditor from '../../../Views/Components/TextEditor.vue'
import {useAjax} from '../../../../resources/js/components/ajaxHandler.js'
const {request} = useAjax()
const blocks = ref([])
const assets = ref([])
const tokenGroups = ref({})
// Die Vorlagen sind nach Dokumentart getrennt; der Umschalter lädt jeweils deren Blöcke neu.
const documentType = ref(null)
const documentTypes = ref([])
const activeBlock = ref(null)
const saving = ref(false)
// Die Vorschau ist ein PDF, das aus den aktuellen -- auch ungespeicherten -- Blockinhalten entsteht.
const previewUrl = ref(null)
const previewLoading = ref(false)
const newAsset = ref({name: '', label: '', file: null})
const assetInput = ref(null)
const current = computed(() => blocks.value.find(b => b.block === activeBlock.value) ?? null)
/** Beim Blockwechsel die gemerkte Einfügemarke verwerfen -- sie gehört zum vorigen Text. */
function selectBlock(block) {
activeBlock.value = block
caret.value = null
}
onMounted(load)
async function load() {
const query = documentType.value ? '?type=' + encodeURIComponent(documentType.value) : ''
const data = await request('/api/v1/admin/document-templates' + query, {method: 'GET'})
if (!data) {
toast.error('Die Vorlage konnte nicht geladen werden.')
return
}
documentType.value = data.documentType
documentTypes.value = data.documentTypes ?? []
blocks.value = data.blocks ?? []
assets.value = data.assets ?? []
tokenGroups.value = data.tokenGroups ?? {}
activeBlock.value = blocks.value.find(b => b.editable)?.block ?? blocks.value[0]?.block ?? null
await refreshPreview()
}
/** Beim Wechsel der Dokumentart alles neu holen -- Blöcke und Platzhalter sind je Art andere. */
async function selectDocumentType(type) {
if (type === documentType.value) return
documentType.value = type
caret.value = null
await load()
}
/** Nur editierbare Blöcke werden gesendet; der generierte Rechnungsinhalt bleibt unverändert. */
function editableBlocks() {
return Object.fromEntries(
blocks.value.filter(b => b.editable).map(b => [b.block, b.content ?? ''])
)
}
async function save() {
saving.value = true
try {
const response = await request('/api/v1/admin/document-templates', {
method: 'POST',
body: {type: documentType.value, blocks: editableBlocks()},
})
if (response?.status === 'success') {
toast.success(response.message)
} else {
toast.error(response?.message ?? 'Fehler beim Speichern')
}
} finally {
saving.value = false
}
}
async function refreshPreview() {
previewLoading.value = true
try {
const response = await fetch('/api/v1/admin/document-templates/preview', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content ?? '',
},
body: JSON.stringify({type: documentType.value, blocks: editableBlocks()}),
})
if (!response.ok) {
toast.error('Die Vorschau konnte nicht erzeugt werden.')
return
}
if (previewUrl.value) {
URL.revokeObjectURL(previewUrl.value)
}
previewUrl.value = URL.createObjectURL(await response.blob())
} finally {
previewLoading.value = false
}
}
/**
* Platzhalter an der Einfügemarke ergänzen. Im WYSIWYG-Editor übernimmt das TinyMCE selbst, im
* Quelltext-Editor wird an der zuletzt bekannten Cursorposition eingesetzt.
*/
function insertToken(token) {
const block = current.value
if (!block) return
const placeholder = wrapForBlock('{' + token + '}', token, block)
if (block.source) {
insertIntoTextarea(placeholder)
return
}
const editor = window.tinymce?.activeEditor
if (editor) {
editor.execCommand('mceInsertContent', false, placeholder)
} else {
block.content = (block.content ?? '') + placeholder
}
}
/**
* Ein Bild-Platzhalter allein ist nirgends sinnvoll: er expandiert zum nackten Data-URI, das dann als
* Zeichenkette im Dokument steht. Er braucht immer eine Hülle — im CSS url("..."), sonst ein <img>.
*
* Im CSS ist das zusätzlich eine Frage der Funktionsfähigkeit: ein Data-URI ausserhalb von url()
* kann dompdf nicht verarbeiten und läuft ins Zeitlimit.
*/
function wrapForBlock(placeholder, token, block) {
if (!token.startsWith('asset:')) {
return placeholder
}
return block.block === 'style'
? `url("${placeholder}")`
: `<img src="${placeholder}" alt="" />`
}
const sourceArea = ref(null)
// Zuletzt bekannte Einfügemarke im Quelltext-Feld. Ohne das würde ein Klick in der weit darunter
// liegenden Platzhalter- oder Bilder-Liste an unvorhersehbarer Stelle einfügen.
const caret = ref(null)
function rememberCaret() {
const area = sourceArea.value
if (!area) return
caret.value = {start: area.selectionStart, end: area.selectionEnd}
}
function insertIntoTextarea(text) {
const block = current.value
if (!block) return
const content = block.content ?? ''
const position = caret.value
if (position === null) {
block.content = content + text
return
}
block.content = content.slice(0, position.start) + text + content.slice(position.end)
caret.value = {start: position.start + text.length, end: position.start + text.length}
}
async function uploadAsset() {
const form = new FormData()
form.append('name', newAsset.value.name)
form.append('label', newAsset.value.label ?? '')
if (newAsset.value.file) {
form.append('file', newAsset.value.file)
}
const result = await request('/api/v1/admin/document-templates/assets', {
method: 'POST',
body: form,
})
if (result?.status === 'success') {
toast.success(result.message)
newAsset.value = {name: '', label: '', file: null}
if (assetInput.value) assetInput.value.value = ''
await load()
} else {
toast.error(result?.message ?? 'Fehler beim Hochladen')
}
}
async function deleteAsset(name) {
if (!confirm(`Das Bild „${name}" wirklich löschen?`)) return
const result = await request('/api/v1/admin/document-templates/assets/' + name, {method: 'DELETE'})
if (result?.status === 'success') {
toast.success(result.message)
await load()
} else {
// Ein noch in der Vorlage referenziertes Bild lehnt der Server ab.
toast.error(result?.message ?? 'Das Bild konnte nicht gelöscht werden.')
}
}
function copyToken(token) {
navigator.clipboard?.writeText(token)
toast.success(`${token} kopiert`)
}
function onFileChosen(event) {
newAsset.value.file = event.target.files?.[0] ?? null
}
</script>
<template>
<AdminAppLayout title="Dokumentvorlagen">
<shadowed-box style="width: 95%; margin: 20px auto; padding: 20px;">
<p class="intro">
Die Vorlagen gelten für <strong>alle Mandanten</strong>; die eingesetzten Werte kommen je
Dokument aus dem jeweiligen Mandanten. Sie liegen in der Datenbank und werden von einem
Update nicht überschrieben.
</p>
<div class="type-switch">
<label for="document-type">Dokumentart</label>
<select
id="document-type"
class="form-input"
:value="documentType"
@change="selectDocumentType($event.target.value)"
>
<option v-for="type in documentTypes" :key="type.value" :value="type.value">
{{ type.label }}
</option>
</select>
</div>
<div class="layout">
<!-- Blöcke und Editor -->
<div class="editor-column">
<div class="block-tabs">
<button
v-for="block in blocks"
:key="block.block"
class="block-tab"
:class="{active: block.block === activeBlock, readonly: !block.editable}"
@click="selectBlock(block.block)"
>
{{ block.label }}
<span v-if="!block.editable" class="badge">generiert</span>
</button>
</div>
<div v-if="current" class="editor-panel">
<p v-if="!current.editable" class="notice">
Dieser Block wird beim Erzeugen des Dokuments aus den Daten der Anmeldung
zusammengesetzt und lässt sich nicht bearbeiten.
</p>
<p v-else-if="current.source" class="notice">
Enthält den Seitenaufbau bzw. die Gestaltung und wird deshalb im Quelltext
bearbeitet. Für Adresse, Logo oder Fußnote ist das nicht nötig.
</p>
<textarea
v-if="current.source || !current.editable"
ref="sourceArea"
v-model="current.content"
class="source-editor"
:readonly="!current.editable"
spellcheck="false"
rows="24"
@click="rememberCaret"
@keyup="rememberCaret"
@blur="rememberCaret"
></textarea>
<!-- convert-urls aus: sonst schreibt TinyMCE {asset:...} in einem src um. -->
<TextEditor v-else v-model="current.content" :convert-urls="false" />
</div>
<div class="actions">
<button class="btn-save" :disabled="saving" @click="save">
{{ saving ? 'Wird gespeichert' : 'Speichern' }}
</button>
<button class="btn-secondary" :disabled="previewLoading" @click="refreshPreview">
{{ previewLoading ? 'Wird erzeugt' : 'Vorschau aktualisieren' }}
</button>
</div>
<!-- Platzhalter -->
<div class="tokens">
<h3>Platzhalter</h3>
<p class="tokens-hint">
Klicken fügt den Platzhalter an der Einfügemarke ein in
<strong>{{ current?.label ?? '—' }}</strong>. Mit
<code>{if:name}{/if:name}</code> lässt sich ein Abschnitt weglassen, solange
der Platzhalter leer ist.
</p>
<div v-for="(group, key) in tokenGroups" :key="key" class="token-group">
<h4>{{ group.label }}</h4>
<button
v-for="(token, name) in group.tokens"
:key="name"
class="token"
:title="token.description"
@click="insertToken(name)"
>{{ '{' + name + '}' }}</button>
</div>
</div>
<!-- Bilder -->
<div class="assets">
<h3>Bilder</h3>
<p class="tokens-hint">
Liegen in der Datenbank, damit ein Update sie nicht überschreibt. Einfügen"
schreibt in <strong>{{ current?.label ?? '—' }}</strong><template
v-if="current?.block === 'style'"> — im CSS als
<code>url("")</code>, anders kann dompdf ein Bild dort nicht verarbeiten</template>.
</p>
<table class="asset-table">
<tr v-for="asset in assets" :key="asset.name">
<td class="asset-preview"><img :src="asset.preview" :alt="asset.name" /></td>
<td>
<strong>{{ asset.name }}</strong>
<span v-if="asset.label" class="asset-label">{{ asset.label }}</span>
</td>
<td>
<code class="token-code" @click="copyToken(asset.token)">{{ asset.token }}</code>
</td>
<td class="asset-actions">
<button class="btn-link" @click="insertToken('asset:' + asset.name)">Einfügen</button>
<button class="btn-link danger" @click="deleteAsset(asset.name)">Löschen</button>
</td>
</tr>
</table>
<div class="asset-upload">
<input v-model="newAsset.name" type="text" placeholder="Name, z. B. logo" class="form-input" />
<input v-model="newAsset.label" type="text" placeholder="Beschreibung (optional)" class="form-input" />
<input ref="assetInput" type="file" accept="image/*" @change="onFileChosen" />
<button class="btn-secondary" :disabled="!newAsset.name" @click="uploadAsset">
Hochladen
</button>
</div>
</div>
</div>
<!-- ── Vorschau ── -->
<div class="preview-column">
<h3>Vorschau</h3>
<p class="tokens-hint">Mit Beispieldaten, ohne zu speichern.</p>
<iframe v-if="previewUrl" :src="previewUrl" class="preview-frame"></iframe>
<p v-else class="notice">Noch keine Vorschau erzeugt.</p>
</div>
</div>
</shadowed-box>
</AdminAppLayout>
</template>
<style scoped>
.intro {
margin-bottom: 20px;
padding: 10px 12px;
border-left: 3px solid #f5c400;
background-color: #fffef5;
font-size: 0.9rem;
color: #4b5563;
}
.type-switch {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 18px;
}
.type-switch label {
font-weight: bold;
font-size: 0.9rem;
color: #4b5563;
}
.type-switch select {
width: auto;
min-width: 220px;
}
.layout {
display: flex;
gap: 24px;
align-items: flex-start;
}
.editor-column {
flex: 1 1 60%;
min-width: 0;
}
.preview-column {
flex: 1 1 40%;
min-width: 320px;
position: sticky;
top: 20px;
}
.block-tabs {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 12px;
}
.block-tab {
padding: 6px 12px;
border: 1px solid #d1d5db;
border-radius: 6px;
background-color: #ffffff;
cursor: pointer;
font-size: 0.85rem;
color: #374151;
}
.block-tab.active {
background-color: #1d4899;
border-color: #1d4899;
color: #ffffff;
}
.block-tab.readonly {
color: #6b7280;
}
.badge {
margin-left: 6px;
padding: 1px 5px;
border-radius: 3px;
background-color: #e5e7eb;
color: #4b5563;
font-size: 0.7rem;
}
.block-tab.active .badge {
background-color: rgba(255, 255, 255, 0.25);
color: #ffffff;
}
.editor-panel {
margin-bottom: 12px;
}
.notice {
margin-bottom: 10px;
font-size: 0.85rem;
color: #6b7280;
}
.source-editor {
width: 100%;
padding: 10px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-family: 'DejaVu Sans Mono', Menlo, Consolas, monospace;
font-size: 0.82rem;
line-height: 1.5;
box-sizing: border-box;
resize: vertical;
}
.source-editor[readonly] {
background-color: #f9fafb;
color: #6b7280;
}
.actions {
display: flex;
gap: 10px;
margin-bottom: 24px;
}
.btn-save, .btn-secondary {
padding: 8px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: bold;
font-size: 0.9rem;
}
.btn-save {
background-color: #16a34a;
color: #ffffff;
}
.btn-save:hover:not(:disabled) {
background-color: #15803d;
}
.btn-secondary {
background-color: #e5e7eb;
color: #374151;
}
.btn-secondary:hover:not(:disabled) {
background-color: #d1d5db;
}
.btn-save:disabled, .btn-secondary:disabled {
opacity: 0.6;
cursor: default;
}
.tokens, .assets {
margin-bottom: 24px;
}
.tokens h3, .assets h3, .preview-column h3 {
margin-bottom: 6px;
font-size: 1rem;
color: #111827;
}
.tokens-hint {
margin-bottom: 10px;
font-size: 0.8rem;
color: #6b7280;
}
.tokens-hint code, .token-code {
padding: 1px 4px;
background-color: #f3f4f6;
border-radius: 3px;
font-size: 0.95em;
}
.token-group {
margin-bottom: 10px;
}
.token-group h4 {
margin-bottom: 4px;
font-size: 0.8rem;
font-weight: normal;
color: #6b7280;
}
.token {
margin: 0 4px 4px 0;
padding: 3px 8px;
border: 1px solid #d1d5db;
border-radius: 4px;
background-color: #f9fafb;
cursor: pointer;
font-family: 'DejaVu Sans Mono', Menlo, Consolas, monospace;
font-size: 0.75rem;
color: #374151;
}
.token:hover {
background-color: #eef2ff;
border-color: #1d4899;
}
.asset-table {
width: 100%;
border-collapse: collapse;
margin-bottom: 12px;
}
.asset-table td {
padding: 6px 8px;
border-bottom: 1px solid #e5e7eb;
vertical-align: middle;
font-size: 0.85rem;
}
.asset-preview img {
max-width: 60px;
max-height: 40px;
display: block;
}
.asset-label {
display: block;
font-size: 0.75rem;
color: #6b7280;
}
.token-code {
cursor: pointer;
font-family: 'DejaVu Sans Mono', Menlo, Consolas, monospace;
}
.asset-actions {
text-align: right;
white-space: nowrap;
}
.btn-link {
padding: 2px 6px;
border: none;
background: none;
cursor: pointer;
font-size: 0.8rem;
color: #1d4899;
}
.btn-link.danger {
color: #b91c1c;
}
.asset-upload {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.form-input {
padding: 6px 10px;
border: 1px solid #d1d5db;
border-radius: 6px;
font-size: 0.9rem;
}
.preview-frame {
width: 100%;
height: 780px;
border: 1px solid #d1d5db;
border-radius: 6px;
background-color: #ffffff;
}
@media (max-width: 1100px) {
.layout {
flex-direction: column;
}
.preview-column {
position: static;
width: 100%;
}
}
</style>
@@ -13,9 +13,17 @@ const props = defineProps({
const { request } = useAjax() const { request } = useAjax()
const editing = ref(false) const editing = ref(false)
// Solange kein eigener Absender eingetragen ist, steht auf der Rechnung der Name des Mandanten.
const senderFallback = props.data.name ?? ''
const form = ref({ const form = ref({
invoice_sender_name: props.data.invoice_sender_name ?? '',
email: props.data.email ?? '', email: props.data.email ?? '',
email_finance: props.data.email_finance ?? '', email_finance: props.data.email_finance ?? '',
phone: props.data.phone ?? '',
address_1: props.data.address_1 ?? '',
address_2: props.data.address_2 ?? '',
address_3: props.data.address_3 ?? '',
postcode: props.data.postcode ?? '', postcode: props.data.postcode ?? '',
city: props.data.city ?? '', city: props.data.city ?? '',
}) })
@@ -39,16 +47,49 @@ async function save() {
<template> <template>
<div v-if="!editing"> <div v-if="!editing">
<table class="data-table"> <table class="data-table">
<tr>
<th>Rechnungs-Absender:</th>
<td>
{{ form.invoice_sender_name || senderFallback }}
<span v-if="!form.invoice_sender_name" class="field-hint">
Name des Mandanten, da nichts Eigenes hinterlegt ist
</span>
</td>
</tr>
<tr><th>Email:</th><td>{{ form.email }}</td></tr> <tr><th>Email:</th><td>{{ form.email }}</td></tr>
<tr><th>Email Schatzmeister*in:</th><td>{{ form.email_finance }}</td></tr> <tr><th>Email Schatzmeister*in:</th><td>{{ form.email_finance }}</td></tr>
<tr><th>Telefon:</th><td>{{ form.phone || '—' }}</td></tr>
<tr><th>Straße &amp; Hausnummer:</th><td>{{ form.address_1 || '—' }}</td></tr>
<tr><th>Adresszusatz:</th><td>{{ form.address_2 || '—' }}</td></tr>
<tr><th>Weiterer Zusatz:</th><td>{{ form.address_3 || '—' }}</td></tr>
<tr><th>Postleitzahl:</th><td>{{ form.postcode }}</td></tr> <tr><th>Postleitzahl:</th><td>{{ form.postcode }}</td></tr>
<tr><th>Ort:</th><td>{{ form.city }}</td></tr> <tr><th>Ort:</th><td>{{ form.city }}</td></tr>
</table> </table>
<p v-if="!form.address_1" class="hint">
Ohne Straße &amp; Hausnummer ist die Anschrift auf Rechnungen unvollständig
(§ 14 Abs. 4 UStG).
</p>
<button class="btn-edit" @click="editing = true">Bearbeiten</button> <button class="btn-edit" @click="editing = true">Bearbeiten</button>
</div> </div>
<div v-else> <div v-else>
<table class="data-table"> <table class="data-table">
<tr>
<th>Rechnungs-Absender:</th>
<td>
<input
type="text"
v-model="form.invoice_sender_name"
class="form-input"
:placeholder="senderFallback"
/>
<span class="field-hint">
Vollständige Bezeichnung mit Rechtsform, wie sie auf der Rechnung stehen soll.
Leer lassen, um den Namen des Mandanten zu verwenden.
</span>
</td>
</tr>
<tr> <tr>
<th>Email:</th> <th>Email:</th>
<td><input type="email" v-model="form.email" class="form-input" /></td> <td><input type="email" v-model="form.email" class="form-input" /></td>
@@ -57,6 +98,27 @@ async function save() {
<th>Email Schatzmeister*in:</th> <th>Email Schatzmeister*in:</th>
<td><input type="email" v-model="form.email_finance" class="form-input" /></td> <td><input type="email" v-model="form.email_finance" class="form-input" /></td>
</tr> </tr>
<tr>
<th>Telefon:</th>
<td><input type="text" v-model="form.phone" class="form-input" /></td>
</tr>
<tr>
<th>Straße &amp; Hausnummer:</th>
<td>
<input type="text" v-model="form.address_1" class="form-input" />
<span class="field-hint">Pflichtangabe für Rechnungen (§ 14 Abs. 4 UStG)</span>
</td>
</tr>
<tr>
<th>Adresszusatz:</th>
<td>
<input type="text" v-model="form.address_2" class="form-input" placeholder="z. B. c/o Mustermensch" />
</td>
</tr>
<tr>
<th>Weiterer Zusatz:</th>
<td><input type="text" v-model="form.address_3" class="form-input" /></td>
</tr>
<tr> <tr>
<th>Postleitzahl:</th> <th>Postleitzahl:</th>
<td><input type="text" v-model="form.postcode" class="form-input" /></td> <td><input type="text" v-model="form.postcode" class="form-input" /></td>
@@ -101,6 +163,22 @@ async function save() {
box-sizing: border-box; box-sizing: border-box;
} }
.field-hint {
display: block;
margin-top: 4px;
font-size: 0.8rem;
color: #6b7280;
}
.hint {
margin-top: 12px;
padding: 10px 12px;
border-left: 3px solid #f5c400;
background-color: #fffef5;
font-size: 0.85rem;
color: #4b5563;
}
.btn-edit, .btn-save, .btn-cancel { .btn-edit, .btn-save, .btn-cancel {
margin-top: 15px; margin-top: 15px;
padding: 8px 20px; padding: 8px 20px;
@@ -29,8 +29,15 @@ const form = ref({
tax_exemption_reason: props.data.tax_exemption_reason ?? '', tax_exemption_reason: props.data.tax_exemption_reason ?? '',
tax_exemption_note: props.data.tax_exemption_note ?? '', tax_exemption_note: props.data.tax_exemption_note ?? '',
vat_pricing_mode: props.data.vat_pricing_mode ?? 'inclusive', vat_pricing_mode: props.data.vat_pricing_mode ?? 'inclusive',
tax_number: props.data.tax_number ?? '',
vat_id: props.data.vat_id ?? '',
invoice_prefix: props.data.invoice_prefix ?? '',
}) })
// Das Präfix bestimmt den Nummernkreis und darf sich nachträglich nicht ändern -- sonst gehörten bereits
// herausgegebene Rechnungen plötzlich zu einer anderen Nummer. Nur in der verwalteten Ansicht editierbar.
const canEditPrefix = computed(() => props.data.can_edit_invoice_prefix === true)
const isLiable = computed(() => form.value.tax_liable === '1') const isLiable = computed(() => form.value.tax_liable === '1')
const isCustomReason = computed(() => form.value.tax_exemption_reason === 'custom') const isCustomReason = computed(() => form.value.tax_exemption_reason === 'custom')
@@ -65,6 +72,9 @@ async function save() {
tax_exemption_reason: isLiable.value ? null : form.value.tax_exemption_reason, tax_exemption_reason: isLiable.value ? null : form.value.tax_exemption_reason,
tax_exemption_note: form.value.tax_exemption_note, tax_exemption_note: form.value.tax_exemption_note,
vat_pricing_mode: form.value.vat_pricing_mode, vat_pricing_mode: form.value.vat_pricing_mode,
tax_number: form.value.tax_number,
vat_id: form.value.vat_id,
invoice_prefix: canEditPrefix.value ? form.value.invoice_prefix : undefined,
}, },
}) })
@@ -100,6 +110,18 @@ async function save() {
<th>Rechnungshinweis</th> <th>Rechnungshinweis</th>
<td>{{ invoiceHint }}</td> <td>{{ invoiceHint }}</td>
</tr> </tr>
<tr>
<th>Steuernummer</th>
<td>{{ form.tax_number || '—' }}</td>
</tr>
<tr>
<th>USt-IdNr.</th>
<td>{{ form.vat_id || '—' }}</td>
</tr>
<tr>
<th>Rechnungs-Präfix</th>
<td>{{ form.invoice_prefix || '—' }}</td>
</tr>
</table> </table>
<button class="btn-edit" @click="editing = true">Bearbeiten</button> <button class="btn-edit" @click="editing = true">Bearbeiten</button>
</div> </div>
@@ -152,6 +174,42 @@ async function save() {
<th>Rechnungshinweis</th> <th>Rechnungshinweis</th>
<td class="hint-preview">{{ invoiceHint }}</td> <td class="hint-preview">{{ invoiceHint }}</td>
</tr> </tr>
<tr>
<th>Steuernummer</th>
<td>
<input type="text" v-model="form.tax_number" class="form-input" />
<span class="field-hint">
Pflichtangabe auf Rechnungen alternativ die USt-IdNr. (§ 14 Abs. 4 Nr. 2 UStG)
</span>
</td>
</tr>
<tr>
<th>USt-IdNr.</th>
<td><input type="text" v-model="form.vat_id" class="form-input" /></td>
</tr>
<tr>
<th>Rechnungs-Präfix</th>
<td>
<input
type="text"
v-model="form.invoice_prefix"
class="form-input"
:disabled="!canEditPrefix"
/>
<span class="field-hint">
Erster Block der Rechnungsnummer, z. B. <code>WM</code> in
<code>WM-V-20260701-0005</code>.
<template v-if="canEditPrefix">
Eine Änderung wirkt nur auf künftige Veranstaltungen; bereits angelegte behalten
ihre Nummer.
</template>
<template v-else>
Änderbar nur in der Mandanten-Verwaltung.
</template>
</span>
</td>
</tr>
</table> </table>
<div class="btn-group"> <div class="btn-group">
<button class="btn-save" @click="save">Speichern</button> <button class="btn-save" @click="save">Speichern</button>
@@ -195,6 +253,25 @@ async function save() {
font-style: italic; font-style: italic;
} }
.field-hint {
display: block;
margin-top: 4px;
font-size: 0.8rem;
color: #6b7280;
}
.field-hint code {
padding: 1px 4px;
background-color: #f3f4f6;
border-radius: 3px;
font-size: 0.95em;
}
.form-input:disabled {
background-color: #f3f4f6;
color: #6b7280;
}
.btn-edit, .btn-save, .btn-cancel { .btn-edit, .btn-save, .btn-cancel {
margin-top: 15px; margin-top: 15px;
padding: 8px 20px; padding: 8px 20px;
+3 -14
View File
@@ -2,11 +2,6 @@
use App\Domains\CostUnit\Controllers\CreateController; use App\Domains\CostUnit\Controllers\CreateController;
use App\Domains\CostUnit\Controllers\ListController; use App\Domains\CostUnit\Controllers\ListController;
use App\Domains\CostUnit\Controllers\OpenController; use App\Domains\CostUnit\Controllers\OpenController;
use App\Domains\UserManagement\Controllers\EmailVerificationController;
use App\Domains\UserManagement\Controllers\LoginController;
use App\Domains\UserManagement\Controllers\LogOutController;
use App\Domains\UserManagement\Controllers\RegistrationController;
use App\Domains\UserManagement\Controllers\ResetPasswordController;
use App\Middleware\IdentifyTenant; use App\Middleware\IdentifyTenant;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
@@ -23,16 +18,10 @@ Route::middleware(IdentifyTenant::class)->group(function () {
}); });
Route::get('/register', [RegistrationController::class, 'loginForm']);
Route::get('/register/verifyEmail', [EmailVerificationController::class, 'verifyEmailForm']);
Route::get('/reset-password', [ResetPasswordController::class, 'resetPasswordForm']);
route::get('/logout', LogOutController::class);
route::post('/login', [LoginController::class, 'doLogin']);
route::get('/login', [LoginController::class, 'loginForm']);
// Anmeldung, Registrierung und Passwort-Reset gehören zur Domain UserManagement und sind dort
// definiert. Die Duplikate hier überschrieben die dortigen Routen -- unter anderem die benannte
// Route `login`, auf die Laravels `auth`-Middleware Gäste umleitet.
}); });
@@ -9,6 +9,7 @@ use App\Models\Tenant;
use App\RelationModels\EventEatingHabits; use App\RelationModels\EventEatingHabits;
use App\RelationModels\EventLocalGroups; use App\RelationModels\EventLocalGroups;
use App\RelationModels\EventPaymentMethods; use App\RelationModels\EventPaymentMethods;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
class CreateEventCommand { class CreateEventCommand {
@@ -27,8 +28,13 @@ class CreateEventCommand {
} }
$tenant = app('tenant');
// 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.
$event = DB::transaction(function () use ($tenant): Event {
$event = Event::create([ $event = Event::create([
'tenant' => app('tenant')->slug, 'tenant' => $tenant->slug,
'name' => $this->request->name, 'name' => $this->request->name,
'identifier' => Str::random(10), 'identifier' => Str::random(10),
'location' => $this->request->location, 'location' => $this->request->location,
@@ -49,13 +55,23 @@ class CreateEventCommand {
'support_flat' => 0, 'support_flat' => 0,
// Umsatzsteuerliche Grundlage bei Anlage einfrieren (unveränderlich), damit Preisermittlung und // Umsatzsteuerliche Grundlage bei Anlage einfrieren (unveränderlich), damit Preisermittlung und
// spätere Rechnungen von späteren Tenant-Änderungen unberührt bleiben. // spätere Rechnungen von späteren Tenant-Änderungen unberührt bleiben.
'tax_liable' => app('tenant')->tax_liable, 'tax_liable' => $tenant->tax_liable,
'vat_rate' => app('tenant')->vat_rate, 'vat_rate' => $tenant->vat_rate,
'vat_pricing_mode' => app('tenant')->vat_pricing_mode, 'vat_pricing_mode' => $tenant->vat_pricing_mode,
'tax_exemption_reason' => app('tenant')->tax_exemption_reason, 'tax_exemption_reason' => $tenant->tax_exemption_reason,
'tax_exemption_note' => app('tenant')->tax_exemption_note, 'tax_exemption_note' => $tenant->tax_exemption_note,
// Den Event-Teil der Rechnungsnummer einfrieren: Tenant-Präfix und Startdatum sind später
// änderbar, eine herausgegebene Rechnung würde sonst zu einer anderen Nummer gehören.
//
// Der Rechnungssteller wird bewusst NICHT mitkopiert -- er ist der Mandant und wird beim
// Erzeugen der Rechnung von dort gelesen, damit eine Korrektur an Name oder Anschrift auch
// auf bestehende Veranstaltungen wirkt.
'invoice_key' => $this->nextInvoiceKey($tenant),
]); ]);
return $event;
});
if ($event !== null) { if ($event !== null) {
EventEatingHabits::create([ EventEatingHabits::create([
'event_id' => $event->id, 'event_id' => $event->id,
@@ -90,4 +106,35 @@ class CreateEventCommand {
return $response; return $response;
} }
/**
* Event-Teil der Rechnungsnummer, z.B. `WM-V-20260701`: Tenant-Präfix, Dokumentart „V" für
* Veranstaltung, dann ohne Trenner Jahr, Monat des Beginns und die laufende Nummer der
* Veranstaltungen dieses Tenants in diesem Monat.
*
* Gezählt wird über die bereits vergebenen Schlüssel desselben Monats. Die Sperre auf der
* Tenant-Zeile serialisiert gleichzeitige Anlagen; der Aufruf erfolgt innerhalb der
* Anlage-Transaktion, sodass die Sperre bis zum Schreiben des Events steht.
*/
private function nextInvoiceKey(Tenant $tenant): string
{
// Jahr und Monat ohne Trenner; die laufende Nummer haengt unmittelbar daran. Alle drei Teile
// haben feste Laenge, der Schluessel bleibt dadurch eindeutig zerlegbar.
$month = $this->request->begin->format('Ym');
$prefix = sprintf('%s-V-%s', $tenant->invoice_prefix ?? strtoupper($tenant->slug), $month);
DB::table('tenants')->where('id', $tenant->id)->lockForUpdate()->first();
$used = DB::table('events')
->where('tenant', $tenant->slug)
->where('invoice_key', 'like', $prefix . '%')
->pluck('invoice_key');
$highest = 0;
foreach ($used as $key) {
$highest = max($highest, (int) substr((string) $key, strlen($prefix)));
}
return $prefix . str_pad((string) ($highest + 1), 2, '0', STR_PAD_LEFT);
}
} }
@@ -6,6 +6,7 @@ use App\Enumerations\EatingHabit;
use App\Enumerations\EfzStatus; use App\Enumerations\EfzStatus;
use App\EventPaymentModules\EventPaymentModuleRegistry; use App\EventPaymentModules\EventPaymentModuleRegistry;
use App\ValueObjects\Age; use App\ValueObjects\Age;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
class SignUpCommand { class SignUpCommand {
@@ -43,15 +44,21 @@ class SignUpCommand {
$participantAge = new Age($this->request->birthday); $participantAge = new Age($this->request->birthday);
$response->participant = $this->request->event->participants()->create( // Anmeldung als Ganzes: die laufende Nummer (invoice_sequence) muss unter der Sperre vergeben und
// im selben Zug geschrieben werden, sonst könnten zwei gleichzeitige Anmeldungen dieselbe erhalten.
$response->participant = DB::transaction(function () use ($participantAge, $eatingHabit, $paymentOptions, $participationOptionRows) {
$participant = $this->request->event->participants()->create(
[ [
'tenant' => $this->request->event->tenant, 'tenant' => $this->request->event->tenant,
'user_id' => $this->request->user_id, 'user_id' => $this->request->user_id,
'identifier' => Str::random(10), 'identifier' => Str::random(10),
'invoice_sequence' => $this->nextInvoiceSequence(),
'firstname' => $this->request->firstname, 'firstname' => $this->request->firstname,
'lastname' => $this->request->lastname, 'lastname' => $this->request->lastname,
'nickname' => $this->request->nickname, 'nickname' => $this->request->nickname,
'participation_type' => $this->request->participationType, 'participation_type' => $this->request->participationType,
'fee_type' => $this->request->feeType,
'sibling_reduction' => $this->request->siblingReduction,
'local_group' => $this->request->localGroup->slug, 'local_group' => $this->request->localGroup->slug,
'birthday' => $this->request->birthday, 'birthday' => $this->request->birthday,
'address_1' => $this->request->address_1, 'address_1' => $this->request->address_1,
@@ -68,8 +75,12 @@ class SignUpCommand {
'medications' => $this->request->medications, 'medications' => $this->request->medications,
'tetanus_vaccination' => $this->request->tetanus_vaccination, 'tetanus_vaccination' => $this->request->tetanus_vaccination,
'eating_habit' => $eatingHabit, 'eating_habit' => $eatingHabit,
'swimming_permission' => $participantAge->isfullAged() ? 'SWIMMING_PERMISSION_ALLOWED' : $this->request->swimming_permission, 'swimming_permission' => ($participantAge->isfullAged() || $this->request->swimming_permission === '-1')
'first_aid_permission' => $participantAge->isfullAged() ? 'FIRST_AID_PERMISSION_ALLOWED' : $this->request->first_aid_permission, ? 'SWIMMING_PERMISSION_ALLOWED'
: $this->request->swimming_permission,
'first_aid_permission' => ($participantAge->isfullAged() || $this->request->first_aid_permission === '-1')
? 'FIRST_AID_PERMISSION_ALLOWED'
: $this->request->first_aid_permission,
'foto_socialmedia' => $this->request->foto_socialmedia, 'foto_socialmedia' => $this->request->foto_socialmedia,
'foto_print' => $this->request->foto_print, 'foto_print' => $this->request->foto_print,
'foto_webseite' => $this->request->foto_webseite, 'foto_webseite' => $this->request->foto_webseite,
@@ -88,13 +99,38 @@ class SignUpCommand {
] ]
); );
$this->persistParticipationOptions($response->participant, $participationOptionRows); $this->persistParticipationOptions($participant, $participationOptionRows);
$this->persistAddons($response->participant); $this->persistAddons($participant);
return $participant;
});
$response->success = true; $response->success = true;
return $response; return $response;
} }
/**
* Nächste laufende Nummer des Teilis innerhalb der Veranstaltung -- der letzte Block der
* Rechnungsnummer. Die Event-Zeile wird gesperrt, damit gleichzeitige Anmeldungen derselben
* Veranstaltung serialisiert werden; der Aufruf erfolgt innerhalb der Anmelde-Transaktion, sodass die
* Sperre bis zum Schreiben des Teilis steht.
*
* Abgemeldete Teilis behalten ihre Nummer, gezählt wird deshalb über MAX und nicht über COUNT.
*/
private function nextInvoiceSequence(): int
{
DB::table('events')
->where('id', $this->request->event->id)
->lockForUpdate()
->first();
$highest = DB::table('event_participants')
->where('event_id', $this->request->event->id)
->max('invoice_sequence');
return (int) $highest + 1;
}
/** /**
* Speichert die gewählten Zusätze (Event-Addons) als Snapshot-Zeilen (Titel/Preis/Betrag) für die spätere * Speichert die gewählten Zusätze (Event-Addons) als Snapshot-Zeilen (Titel/Preis/Betrag) für die spätere
* Rechnung. Die Beträge sind bereits in der Controller-Auflösung (`resolveAddons`) berechnet, inkl. USt. * Rechnung. Die Beträge sind bereits in der Controller-Auflösung (`resolveAddons`) berechnet, inkl. USt.
@@ -50,6 +50,10 @@ class SignUpRequest {
public array $participationOptions = [], public array $participationOptions = [],
/** Aufgelöste Zusätze (Event-Addons): je Eintrag [ key, title, price, flat, days, amount ]. */ /** Aufgelöste Zusätze (Event-Addons): je Eintrag [ key, title, price, flat, days, amount ]. */
public array $addonItems = [], public array $addonItems = [],
/** Gewählte Preisspalte: standard | reduced | solidarity. Wird für die Rechnung mitgeschrieben. */
public ?string $feeType = null,
/** Ob die 50-%-Geschwisterermäßigung in `amount` eingerechnet ist. */
public bool $siblingReduction = false,
) { ) {
} }
} }
@@ -150,6 +150,8 @@ class SignupController extends CommonController {
(array)($registrationData['paymentOptions'] ?? []), (array)($registrationData['paymentOptions'] ?? []),
(array)($registrationData['participationOptions'] ?? []), (array)($registrationData['participationOptions'] ?? []),
$addonResolution['items'], $addonResolution['items'],
$registrationData['beitrag'],
$siblingReduction,
); );
$signupCommand = new SignUpCommand($signupRequest); $signupCommand = new SignUpCommand($signupRequest);
@@ -1,7 +1,11 @@
<script setup> <script setup>
import {computed, onMounted, reactive, watch} from "vue"; import {computed, onMounted, reactive, ref, watch} from "vue";
import {toast} from "vue3-toastify";
import AmountInput from "../../../../Views/Components/AmountInput.vue"; import AmountInput from "../../../../Views/Components/AmountInput.vue";
import DialableTelephoneNumber from "../../../../Views/Components/DialableTelephoneNumber.vue"; import DialableTelephoneNumber from "../../../../Views/Components/DialableTelephoneNumber.vue";
import {useAjax} from "../../../../../resources/js/components/ajaxHandler.js";
const {download} = useAjax();
const staticProps = defineProps({ const staticProps = defineProps({
editMode: Boolean, editMode: Boolean,
@@ -146,6 +150,31 @@ function enableEditMode() {
emit('editParticipant'); emit('editParticipant');
} }
/**
* Rechnung über den Teilnahmebeitrag herunterladen. Sie wird bei jedem Klick neu erzeugt und trägt immer
* dieselbe, aus Veranstaltung und Position des Teilis abgeleitete Nummer.
*
* Bei einem Beitrag von 0 € gibt es nichts zu berechnen -- dann entfällt der Knopf.
*/
const creatingInvoice = ref(false)
const hasAmount = computed(() => Number(props.participant?.amountExpectedValue ?? 0) > 0)
async function downloadInvoice() {
creatingInvoice.value = true
try {
// Der Dateiname (mit der Rechnungsnummer) kommt aus dem Content-Disposition-Header.
const ok = await download('/api/v1/participant-invoice/' + staticProps.participant.identifier)
if (!ok) {
toast.error('Die Rechnung konnte nicht erstellt werden.')
}
} finally {
creatingInvoice.value = false
}
}
function saveParticipant() { function saveParticipant() {
emit('saveParticipant', { ...form }); emit('saveParticipant', { ...form });
close(); close();
@@ -348,6 +377,19 @@ function saveParticipant() {
</span> </span>
</td> </td>
</tr> </tr>
<tr v-if="props.participant.refund">
<th>Erstattung</th>
<td>
{{ props.participant.refund.amount }} &ndash; {{ props.participant.refund.reasonLabel }}<br />
<small v-if="props.participant.refund.status === 'pending'">
freigegeben am {{ props.participant.refund.releasedAt }}, wartet auf die
Bankverbindung des Teilis
</small>
<small v-else-if="props.participant.refund.status === 'accepted'">
bestätigt am {{ props.participant.refund.acceptedAt }}
</small>
</td>
</tr>
</table> </table>
</div> </div>
@@ -457,6 +499,12 @@ function saveParticipant() {
<button v-if="!props.participant.unregistered" class="button" @click="paymentComplete(props.participant)">Zahlung vollständig</button> <button v-if="!props.participant.unregistered" class="button" @click="paymentComplete(props.participant)">Zahlung vollständig</button>
<button v-if="!props.participant.unregistered" class="button" @click="markCocExisting(props.participant)">eFZ liegt vor</button> <button v-if="!props.participant.unregistered" class="button" @click="markCocExisting(props.participant)">eFZ liegt vor</button>
<button
v-if="!props.participant.unregistered && hasAmount"
class="button"
:disabled="creatingInvoice"
@click="downloadInvoice"
>{{ creatingInvoice ? 'Wird erstellt…' : 'Rechnung erstellen' }}</button>
<button v-if="!props.participant.unregistered" class="button" @click="cancelParticipation(props.participant)">Abmelden</button> <button v-if="!props.participant.unregistered" class="button" @click="cancelParticipation(props.participant)">Abmelden</button>
<button class="button" @click="close">Schließen</button> <button class="button" @click="close">Schließen</button>
@@ -9,6 +9,7 @@ import {format} from "date-fns";
import AmountInput from "../../../../Views/Components/AmountInput.vue"; import AmountInput from "../../../../Views/Components/AmountInput.vue";
import FullScreenModal from "../../../../Views/Components/FullScreenModal.vue"; import FullScreenModal from "../../../../Views/Components/FullScreenModal.vue";
import DialableTelephoneNumber from "../../../../Views/Components/DialableTelephoneNumber.vue"; import DialableTelephoneNumber from "../../../../Views/Components/DialableTelephoneNumber.vue";
import ErrorText from "../../../../Views/Components/ErrorText.vue";
const props = defineProps({ const props = defineProps({
data: { data: {
@@ -29,7 +30,7 @@ const props = defineProps({
const today = format(new Date(), "yyyy-MM-dd"); const today = format(new Date(), "yyyy-MM-dd");
const { request } = useAjax(); const { request, download } = useAjax();
const searchTerms = reactive({}); const searchTerms = reactive({});
const selectedStatuses = reactive({}); const selectedStatuses = reactive({});
@@ -44,6 +45,18 @@ const mailCompose = ref(false);
const openCancelDialog = ref(false); const openCancelDialog = ref(false);
const openPartialPaymentDialogSwitch = 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: ''});
const refundReasons = ref([]);
const refundSaving = ref(false);
const selectedRefundReason = computed(
() => refundReasons.value.find(r => r.value === refundForm.reason) ?? null
);
defineEmits(['showParticipantDetails', 'markCocExisting', 'paymentComplete']) defineEmits(['showParticipantDetails', 'markCocExisting', 'paymentComplete'])
@@ -292,6 +305,104 @@ async function execPartialPayment() {
openPartialPaymentDialogSwitch.value = false; openPartialPaymentDialogSwitch.value = false;
} }
/**
* Erstattung freigeben.
*
* Der Betrag ist mit dem vor, was der Teili gezahlt hat -- das ist der Regelfall; Abzüge trägt die
* Aktionsleitung von Hand ein.
*/
async function openRefundDialog(participant) {
showParticipant.value = participant;
refundForm.amount = participant.amountPaid?.short ?? '';
refundForm.reason = '';
refundForm.reasonNote = '';
refundErrors.amount = '';
refundErrors.reason = '';
refundErrors.reasonNote = '';
if (refundReasons.value.length === 0) {
const reasons = await request('/api/v1/core/retrieve-refund-reasons', {method: 'GET'});
refundReasons.value = reasons ?? [];
}
openRefundDialogSwitch.value = true;
}
function validateRefund() {
const amount = Number((refundForm.amount ?? '').replace(',', '.'));
const paid = Number(showParticipant.value?.amountPaidValue ?? 0);
refundErrors.amount = '';
refundErrors.reason = '';
refundErrors.reasonNote = '';
if (!refundForm.amount || !(amount > 0)) {
refundErrors.amount = 'Bitte gib einen Betrag größer als 0 ein.';
} else if (amount > paid + 0.005) {
refundErrors.amount = 'Mehr als der gezahlte Beitrag kann nicht erstattet werden.';
}
if (!refundForm.reason) {
refundErrors.reason = 'Bitte wähle einen Grund aus.';
} else if (selectedRefundReason.value?.requiresNote && !refundForm.reasonNote.trim()) {
refundErrors.reasonNote = 'Bitte erläutere den Grund.';
}
return !refundErrors.amount && !refundErrors.reason && !refundErrors.reasonNote;
}
async function execRefund() {
if (!validateRefund() || refundSaving.value) {
return;
}
refundSaving.value = true;
try {
const data = await request('/api/v1/participant-refund/' + showParticipant.value.identifier + '/release', {
method: "POST",
body: {
amount: refundForm.amount,
reason: refundForm.reason,
reasonNote: refundForm.reasonNote,
},
});
if (data?.status === 'success') {
toast.success(data.message);
// Reaktiv statt per getElementById: die Meta-Zeile hängt am Vorgang und wechselt mit ihm.
showParticipant.value.refund = data.refund;
openRefundDialogSwitch.value = false;
} else {
toast.error(data?.message ?? 'Die Erstattung konnte nicht freigegeben werden.');
}
} finally {
refundSaving.value = false;
}
}
async function execCancelRefund(participant) {
const data = await request('/api/v1/participant-refund/' + participant.refund.token + '/cancel', {
method: "POST",
});
if (data?.status === 'success') {
toast.success(data.message);
participant.refund = null;
} else {
toast.error(data?.message ?? 'Die Erstattung konnte nicht abgebrochen werden.');
}
}
async function downloadRefundDocument(participant) {
const ok = await download('/api/v1/participant-refund/' + participant.refund.token + '/document');
if (!ok) {
toast.error('Der Beleg konnte nicht erstellt werden.');
}
}
const mailToType = ref('') const mailToType = ref('')
const recipientIdentifier = ref('') const recipientIdentifier = ref('')
@@ -395,6 +506,27 @@ function mailToGroup(groupKey) {
<span class="link">E-Mail senden</span> | <span class="link">E-Mail senden</span> |
<span @click="openCancelParticipationDialog(participant)" v-if="!participant.unregistered" class="link" style="color: #da7070;">Abmelden</span> <span @click="openCancelParticipationDialog(participant)" v-if="!participant.unregistered" class="link" style="color: #da7070;">Abmelden</span>
<span v-else class="link" @click="execResignonParticipant(participant)" style="color: #3cb62e;">Wieder anmelden</span> <span v-else class="link" @click="execResignonParticipant(participant)" style="color: #3cb62e;">Wieder anmelden</span>
<!-- Erstattung: erst der Einstieg, danach der Zustand des Vorgangs. -->
<template v-if="participant.unregistered">
<span
v-if="!participant.refund && Number(participant.amountPaidValue ?? 0) > 0"
class="link"
style="color: #da7070;"
@click="openRefundDialog(participant)"
> | Beitrag erstatten</span>
<template v-else-if="participant.refund?.status === 'pending'">
| <strong>Erstattung offen:</strong> {{ participant.refund.amount }},
wartet auf Bankverbindung
<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 }}
<span class="link" @click="downloadRefundDocument(participant)">Beleg</span>
</template>
</template>
</td> </td>
</tr> </tr>
</template> </template>
@@ -460,6 +592,48 @@ function mailToGroup(groupKey) {
<button class="button" @click="execPartialPayment()">Teilbetrag buchen</button> <button class="button" @click="execPartialPayment()">Teilbetrag buchen</button>
</Modal> </Modal>
<Modal
:show="openRefundDialogSwitch"
title="Beitrag erstatten"
width="480px"
@close="openRefundDialogSwitch = false"
>
<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.
</p>
<div class="refund-field">
<label for="refund_amount">Zu erstattender Betrag</label>
<div>
<AmountInput id="refund_amount" v-model="refundForm.amount" style="width: 100px !important;" /> Euro
</div>
<ErrorText :message="refundErrors.amount" />
</div>
<div class="refund-field">
<label for="refund_reason">Grund</label>
<select id="refund_reason" v-model="refundForm.reason" class="form-input">
<option value="">Bitte auswählen </option>
<option v-for="reason in refundReasons" :key="reason.value" :value="reason.value">
{{ reason.label }}
</option>
</select>
<ErrorText :message="refundErrors.reason" />
</div>
<div v-if="selectedRefundReason?.requiresNote" class="refund-field">
<label for="refund_reason_note">Erläuterung</label>
<textarea id="refund_reason_note" v-model="refundForm.reasonNote" class="form-input" rows="3"></textarea>
<ErrorText :message="refundErrors.reasonNote" />
</div>
<button class="button" :disabled="refundSaving" @click="execRefund()">
{{ refundSaving ? 'Wird freigegeben' : 'Erstattung freigeben' }}
</button>
</Modal>
<FullScreenModal <FullScreenModal
:show="mailCompose" :show="mailCompose"
title="E-Mail senden" title="E-Mail senden"
@@ -473,6 +647,28 @@ function mailToGroup(groupKey) {
</template> </template>
<style scoped> <style scoped>
.refund-intro {
margin-bottom: 16px;
font-size: 0.9rem;
color: #4b5563;
}
.refund-field {
margin-bottom: 14px;
}
.refund-field label {
display: block;
margin-bottom: 4px;
font-size: 0.9rem;
color: #4b5563;
}
.refund-field select,
.refund-field textarea {
width: 100%;
}
.participants-table { .participants-table {
width: 95%; width: 95%;
margin: 20px auto; margin: 20px auto;
@@ -0,0 +1,418 @@
<?php
namespace App\Domains\ParticipantInvoice\Actions\CreateParticipantInvoice;
use App\Enumerations\TaxExemptionReason;
use App\EventPaymentModules\DTO\CreateInvoiceRequest;
use App\Models\DocumentTemplate;
use App\Models\Event;
use App\Models\EventParticipant;
use App\Models\Tenant;
use App\Providers\DocumentTemplateRenderProvider;
use App\Providers\PdfGenerateAndDownloadProvider;
use App\RelationModels\EventParticipationFee;
use App\Support\DateRange;
use App\ValueObjects\Amount;
/**
* Erzeugt die Rechnung über den Teilnahmebeitrag als PDF.
*
* Es wird nichts gespeichert: die Rechnungsnummer ergibt sich deterministisch aus Veranstaltung und
* Position des Teilis, der Inhalt aus dessen aktuellem Stand. Ein erneuter Abruf liefert unter derselben
* Nummer den dann gültigen Stand.
*/
class CreateParticipantInvoiceCommand
{
private EventParticipant $participant;
private Event $event;
/** Der Rechnungssteller. Gehört zum Mandanten, nicht zur Veranstaltung -- siehe buildTokens(). */
private ?Tenant $sender;
public function __construct(private readonly CreateParticipantInvoiceRequest $request)
{
$this->participant = $request->participant;
$this->event = $request->participant->event;
// Über die Relation und nicht über app('tenant'): 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();
}
public function execute(): CreateParticipantInvoiceResponse
{
$response = new CreateParticipantInvoiceResponse();
if ($this->event->invoice_key === null || $this->participant->invoice_sequence === null) {
$response->message = 'Für diese Anmeldung lässt sich keine Rechnungsnummer bilden.';
return $response;
}
$invoiceNumber = sprintf(
'%s-%s',
$this->event->invoice_key,
str_pad((string) $this->participant->invoice_sequence, 4, '0', STR_PAD_LEFT)
);
$lines = $this->buildLines();
$gross = round($this->participant->amount?->getAmount() ?? 0.0, 2);
$html = new DocumentTemplateRenderProvider(DocumentTemplate::TYPE_PARTICIPANT_INVOICE)
->render($this->buildTokens($invoiceNumber, $lines, $gross));
$response->success = true;
$response->invoiceNumber = $invoiceNumber;
$response->filename = 'Rechnung-' . $invoiceNumber . '.pdf';
$response->pdfContent = PdfGenerateAndDownloadProvider::fromHtml($html, 'portrait');
return $response;
}
/**
* Die Rechnungspositionen.
*
* Der Beitragsanteil wird nicht neu berechnet, sondern aus dem gespeicherten Gesamtbetrag abgeleitet:
* `amount` ist Beitrag + Zusätze (siehe SignupController), die Zusätze liegen als Snapshot-Zeilen vor.
* Damit stimmt die Rechnung immer mit dem überein, was der Teili tatsächlich zahlen soll -- unabhängig
* davon, ob die Beiträge der Veranstaltung inzwischen geändert wurden oder der Early-Bird-Stichtag
* verstrichen ist.
*
* @return array<int, array{description: string, quantity: ?float, unit: string, unitPrice: ?float, amount: float}>
*/
private function buildLines(): array
{
$addons = $this->participant->selectedAddons;
$addonTotal = 0.0;
foreach ($addons as $addon) {
$addonTotal += $addon->amount?->getAmount() ?? 0.0;
}
$fee = round(($this->participant->amount?->getAmount() ?? 0.0) - $addonTotal, 2);
$days = $this->attendanceDays();
// Die Preiskette in EventResource::calculateAmount() besteht nur aus Multiplikationen; der Faktor
// 0,5 der Geschwisterermäßigung wirkt damit auf den gesamten Endbetrag. Der Listenpreis ist also
// exakt das Doppelte des gespeicherten Beitragsanteils, der Rabatt genau dieser Anteil.
$listed = $this->participant->sibling_reduction ? round($fee * 2, 2) : $fee;
$lines = [$this->line(
$this->feeDescription(),
$listed,
$this->event->pay_per_day ? $days : 1
)];
if ($this->participant->sibling_reduction) {
$lines[] = [
'description' => 'Geschwisterermäßigung 50 %',
'quantity' => null,
'unit' => '',
'unitPrice' => null,
'amount' => -$fee,
];
}
foreach ($addons as $addon) {
$lines[] = $this->line(
(string) $addon->title,
$addon->amount?->getAmount() ?? 0.0,
$addon->flat ? 1 : (int) $addon->days
);
}
return $lines;
}
/**
* Eine Position mit Mengenaufteilung -- aber nur, wenn sie aufgeht.
*
* Der Endbetrag ist gerundet gespeichert; bei krummen Tagessätzen (etwa nach einem
* Early-Bird-Aufschlag) ergäbe Menge × gerundeter Einzelpreis einen anderen Wert als der Betrag der
* Zeile. Eine Rechnung, deren Positionen sich nicht nachrechnen lassen, ist unbrauchbar -- in dem
* Fall entfällt die Aufteilung und die Position steht als Gesamtbetrag da.
*
* @return array{description: string, quantity: ?float, unit: string, unitPrice: ?float, amount: float}
*/
private function line(string $description, float $amount, int $quantity): array
{
$amount = round($amount, 2);
if ($quantity > 1) {
$unitPrice = round($amount / $quantity, 2);
if (abs($unitPrice * $quantity - $amount) < 0.005) {
return [
'description' => $description,
'quantity' => (float) $quantity,
'unit' => 'Tage',
'unitPrice' => $unitPrice,
'amount' => $amount,
];
}
}
return [
'description' => $description,
'quantity' => 1.0,
'unit' => '',
'unitPrice' => $amount,
'amount' => $amount,
];
}
/**
* Bezeichnung der Beitragsposition. Der Gruppenname stammt aus dem am Event hinterlegten Beitrag,
* dessen `type` der Teilnahmeart entspricht -- dieselbe Auflösung wie in EventResource.
*/
private function feeDescription(): string
{
$group = $this->participationFee()?->name;
$description = $group !== null && trim($group) !== ''
? sprintf('Teilnahme %s in Gruppe %s', $this->event->name, $group)
: sprintf('Teilnahme %s', $this->event->name);
$feeTypeLabel = match ($this->participant->fee_type) {
'standard' => 'Standardbeitrag',
'reduced' => 'Reduzierter Beitrag',
'solidarity' => 'Solidaritätsbeitrag',
// Altanmeldungen vor Einführung von `fee_type` -- dann bleibt der Zusatz weg.
default => null,
};
return $feeTypeLabel === null
? $description
: sprintf('%s (%s)', $description, $feeTypeLabel);
}
private function participationFee(): ?EventParticipationFee
{
return collect([
$this->event->participationFee1,
$this->event->participationFee2,
$this->event->participationFee3,
$this->event->participationFee4,
])
->filter(fn(?EventParticipationFee $fee) => $fee !== null)
->first(fn(EventParticipationFee $fee) => $fee->type === $this->participant->participation_type);
}
private function attendanceDays(): int
{
$arrival = $this->participant->arrival_date;
$departure = $this->participant->departure_date;
if ($arrival === null || $departure === null) {
return 1;
}
return DateRange::inclusiveDays($arrival, $departure);
}
/**
* Umsatzsteuer aus dem Brutto herausrechnen. Gespeichert ist immer der finale Brutto-Betrag -- beim
* Preismodus `add_on` wurde die USt bereits bei der Anmeldung aufgeschlagen, bei `inclusive` war sie
* von Anfang an enthalten. Für die Rechnung ist die Rechnung deshalb in beiden Fällen dieselbe, der
* Preismodus spielt hier keine Rolle mehr.
*
* @return array{net: float, vat: float}
*/
private function splitVat(float $gross): array
{
if (!$this->event->tax_liable || $this->event->vat_rate <= 0) {
return ['net' => $gross, 'vat' => 0.0];
}
$vat = round($gross * $this->event->vat_rate / (100 + $this->event->vat_rate), 2);
return ['net' => round($gross - $vat, 2), 'vat' => $vat];
}
/**
* Der je Zahlungsart variierende Schlusssatz, bezogen auf den noch offenen Betrag.
*/
private function closingStatement(): string
{
$module = $this->participant->paymentModule();
if ($module === null) {
return '';
}
$open = new Amount($this->participant->amount?->getAmount() ?? 0.0, 'Euro');
if ($this->participant->amount_paid !== null) {
$open->subtractAmount($this->participant->amount_paid);
}
$result = $module->createInvoice(new CreateInvoiceRequest(
$this->event,
$this->participant,
$open,
$this->participant->paymentConfiguration(),
));
return (string) ($result->closingStatement ?? '');
}
/**
* Leistungszeitraum: bei eintägigen Veranstaltungen nur ein Datum, sonst der Zeitraum.
*/
private function servicePeriod(): string
{
$start = $this->event->start_date;
$end = $this->event->end_date;
if ($start === null) {
return '';
}
if ($end === null || $start->isSameDay($end)) {
return $start->format('d.m.Y');
}
return sprintf('%s %s', $start->format('d.m.Y'), $end->format('d.m.Y'));
}
/**
* @param array<int, array<string, mixed>> $lines
* @return array<string, string>
*/
private function buildTokens(string $invoiceNumber, array $lines, float $gross): array
{
$participant = $this->participant;
$sender = $this->sender;
return [
'document_title' => 'Rechnung ' . $invoiceNumber,
'invoice_number' => $invoiceNumber,
// Rechnungsdatum ist das Anmeldedatum, Leistungsdatum der Veranstaltungszeitraum.
'invoice_date' => $participant->created_at?->format('d.m.Y') ?? '',
'service_period' => $this->servicePeriod(),
// Der Rechnungssteller wird live vom Mandanten gelesen, nicht auf der Veranstaltung
// eingefroren: eine Korrektur an Name oder Anschrift soll auch auf bestehende
// Veranstaltungen wirken. Eingefroren bleibt nur, was den Preis erklärt (Steuergrundlage)
// und die Nummer (invoice_key).
'sender_name' => $sender?->invoiceSenderName() ?? '',
'sender_address_1' => (string) $sender?->address_1,
'sender_address_2' => (string) $sender?->address_2,
'sender_address_3' => (string) $sender?->address_3,
'sender_postcode' => (string) $sender?->postcode,
'sender_city' => (string) $sender?->city,
'sender_email' => (string) $sender?->email,
'sender_phone' => (string) $sender?->phone,
'sender_tax_number' => (string) $sender?->tax_number,
'sender_vat_id' => (string) $sender?->vat_id,
'recipient_name' => $participant->getOfficialName(),
'recipient_address_1' => (string) $participant->address_1,
'recipient_address_2' => (string) $participant->address_2,
'recipient_postcode' => (string) $participant->postcode,
'recipient_city' => (string) $participant->city,
'positions_table' => $this->renderPositions($lines),
'summary_table' => $this->renderSummary($gross),
'closing_statement' => $this->closingStatement(),
];
}
/** @param array<int, array<string, mixed>> $lines */
private function renderPositions(array $lines): string
{
$rows = '';
foreach ($lines as $index => $line) {
$quantity = $line['quantity'] === null
? ''
: trim($this->quantity((float) $line['quantity']) . ' ' . $line['unit']);
$rows .= sprintf(
'<tr><td>%d</td><td>%s</td><td class="r">%s</td><td class="r">%s</td><td class="r">%s</td></tr>',
$index + 1,
e((string) $line['description']),
e($quantity),
$line['unitPrice'] === null ? '' : $this->money((float) $line['unitPrice']),
$this->money((float) $line['amount']),
);
}
return '<table class="pos-table">'
. '<thead><tr>'
. '<th style="width:8%;">Nr.</th>'
. '<th style="width:44%;">Bezeichnung</th>'
. '<th style="width:12%;" class="r">Menge</th>'
. '<th style="width:18%;" class="r">Einzelpreis</th>'
. '<th style="width:18%;" class="r">Gesamt</th>'
. '</tr></thead>'
. '<tbody>' . $rows . '</tbody>'
. '</table>';
}
/**
* Summenblock. Bei Steuerpflicht wird die USt aus dem Brutto ausgewiesen, sonst steht statt der
* USt-Zeile der Pflichthinweis nach § 14 Abs. 4 Nr. 8 UStG.
*/
private function renderSummary(float $gross): string
{
$rows = '';
if ($this->event->tax_liable && $this->event->vat_rate > 0) {
$split = $this->splitVat($gross);
$rows .= sprintf(
'<tr><td class="sum-key">Nettobetrag</td><td class="sum-val">%s</td></tr>',
$this->money($split['net'])
);
$rows .= sprintf(
'<tr class="sum-line"><td class="sum-key">enthaltene USt. %d&nbsp;%%</td><td class="sum-val">%s</td></tr>',
$this->event->vat_rate,
$this->money($split['vat'])
);
}
$rows .= sprintf(
'<tr class="sum-total"><td class="sum-key">Gesamtbetrag</td><td class="sum-val">%s</td></tr>',
$this->money($gross)
);
$table = '<table class="sum-outer"><tr><td class="sum-spacer"></td><td>'
. '<table class="sum-inner">' . $rows . '</table>'
. '</td></tr></table>';
return $table . $this->taxExemptionNote();
}
/** Pflichthinweis auf den Grund der Steuerbefreiung, aus dem Event-Snapshot. */
private function taxExemptionNote(): string
{
if ($this->event->tax_liable) {
return '';
}
$reason = $this->event->tax_exemption_reason !== null
? TaxExemptionReason::find($this->event->tax_exemption_reason)
: null;
$text = $reason?->invoiceText($this->event->tax_exemption_note);
if ($text === null || trim($text) === '') {
return '';
}
return '<div class="tax-note">' . e($text) . '</div>';
}
private function money(float $value): string
{
return new Amount($value, 'Euro')->getFormattedAmount() . '&nbsp;&euro;';
}
/** Mengen ohne Nachkommastellen, solange sie ganzzahlig sind ("3 Tage", nicht "3,00 Tage"). */
private function quantity(float $value): string
{
return abs($value - round($value)) < 0.005
? (string) (int) round($value)
: number_format($value, 2, ',', '.');
}
}
@@ -0,0 +1,13 @@
<?php
namespace App\Domains\ParticipantInvoice\Actions\CreateParticipantInvoice;
use App\Models\EventParticipant;
class CreateParticipantInvoiceRequest
{
public function __construct(
public readonly EventParticipant $participant,
) {
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Domains\ParticipantInvoice\Actions\CreateParticipantInvoice;
class CreateParticipantInvoiceResponse
{
public bool $success = false;
public string $invoiceNumber = '';
public string $filename = '';
public string $pdfContent = '';
public ?string $message = null;
}
@@ -0,0 +1,33 @@
<?php
namespace App\Domains\ParticipantInvoice\Controllers;
use App\Domains\ParticipantInvoice\Actions\CreateParticipantInvoice\CreateParticipantInvoiceCommand;
use App\Domains\ParticipantInvoice\Actions\CreateParticipantInvoice\CreateParticipantInvoiceRequest;
use App\Scopes\CommonController;
use Illuminate\Http\Response;
class CreateParticipantInvoiceController extends CommonController
{
public function __invoke(string $participantIdentifier): Response
{
$participant = $this->eventParticipants->getByIdentifier($participantIdentifier, $this->events);
if ($participant === null) {
abort(403, 'Zugriff verweigert.');
}
$invoiceRequest = new CreateParticipantInvoiceRequest($participant);
$invoiceCommand = new CreateParticipantInvoiceCommand($invoiceRequest);
$invoiceResponse = $invoiceCommand->execute();
if (!$invoiceResponse->success) {
abort(422, $invoiceResponse->message ?? 'Die Rechnung konnte nicht erstellt werden.');
}
return response($invoiceResponse->pdfContent, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $invoiceResponse->filename . '"',
]);
}
}
@@ -0,0 +1,112 @@
<?php
namespace App\Domains\ParticipantInvoice;
/**
* Katalog der Platzhalter, die in der Rechnungsvorlage zur Verfügung stehen.
*
* Dient zwei Zwecken: der Platzhalter-Liste in der Vorlagen-Verwaltung und den Beispieldaten für die
* Vorschau. Die echten Werte setzt
* {@see \App\Domains\ParticipantInvoice\Actions\CreateParticipantInvoice\CreateParticipantInvoiceCommand}
* zusammen -- dass beide Seiten dieselben Namen kennen, sichert ein Test ab.
*/
final class ParticipantInvoiceTokens
{
/**
* Platzhalter nach Gruppen, je Eintrag Name, Beschreibung und Beispielwert.
*
* @return array<string, array{label: string, tokens: array<string, array{description: string, sample: string}>}>
*/
public static function groups(): array
{
return [
'document' => [
'label' => 'Dokument',
'tokens' => [
'document_title' => ['description' => 'Titel des PDF-Dokuments', 'sample' => 'Rechnung WM-V-20260701-0005'],
'invoice_number' => ['description' => 'Rechnungsnummer', 'sample' => 'WM-V-20260701-0005'],
'invoice_date' => ['description' => 'Rechnungsdatum (= Anmeldedatum)', 'sample' => '03.02.2026'],
'service_period' => ['description' => 'Leistungszeitraum der Veranstaltung', 'sample' => '16.07.2026 20.07.2026'],
],
],
'sender' => [
'label' => 'Absender',
'tokens' => [
'sender_name' => ['description' => 'Rechnungs-Absender (Standard: Name des Mandanten)', 'sample' => 'BdP Landesverband Sachsen e.V.'],
'sender_address_1' => ['description' => 'Straße und Hausnummer', 'sample' => 'Musterweg 1'],
'sender_address_2' => ['description' => 'Adresszusatz, z. B. „c/o …"', 'sample' => 'c/o Mustermensch'],
'sender_address_3' => ['description' => 'Weiterer Adresszusatz', 'sample' => ''],
'sender_postcode' => ['description' => 'Postleitzahl', 'sample' => '01623'],
'sender_city' => ['description' => 'Ort', 'sample' => 'Lommatzsch'],
'sender_email' => ['description' => 'E-Mail-Adresse', 'sample' => 'kontakt@example.com'],
'sender_phone' => ['description' => 'Telefonnummer', 'sample' => '0351 1234567'],
'sender_tax_number' => ['description' => 'Steuernummer', 'sample' => '201/123/45678'],
'sender_vat_id' => ['description' => 'USt-IdNr.', 'sample' => ''],
],
],
'recipient' => [
'label' => 'Empfänger',
'tokens' => [
'recipient_name' => ['description' => 'Name der teilnehmenden Person', 'sample' => 'Mika Muster'],
'recipient_address_1' => ['description' => 'Straße und Hausnummer', 'sample' => 'Beispielstraße 3'],
'recipient_address_2' => ['description' => 'Adresszusatz', 'sample' => ''],
'recipient_postcode' => ['description' => 'Postleitzahl', 'sample' => '11111'],
'recipient_city' => ['description' => 'Ort', 'sample' => 'Beispielstadt'],
],
],
'body' => [
'label' => 'Rechnungsinhalt (generiert)',
'tokens' => [
'positions_table' => ['description' => 'Positionstabelle', 'sample' => self::samplePositions()],
'summary_table' => ['description' => 'Summenblock inkl. USt bzw. Befreiungshinweis', 'sample' => self::sampleSummary()],
'closing_statement' => ['description' => 'Zahlungshinweis der gewählten Zahlungsart', 'sample' => 'Bitte überweise 300,00 Euro bis zum 01.07.2026 auf folgendes Konto:<br />IBAN: DE00 0000 0000 0000 0000 00'],
],
],
];
}
/**
* Beispielwerte für die Vorschau.
*
* @return array<string, string>
*/
public static function sample(): array
{
$sample = [];
foreach (self::groups() as $group) {
foreach ($group['tokens'] as $name => $token) {
$sample[$name] = $token['sample'];
}
}
return $sample;
}
/** @return array<int, string> */
public static function names(): array
{
return array_keys(self::sample());
}
private static function samplePositions(): string
{
return '<table class="pos-table">'
. '<thead><tr>'
. '<th style="width:8%;">Nr.</th><th style="width:44%;">Bezeichnung</th>'
. '<th style="width:12%;" class="r">Menge</th><th style="width:18%;" class="r">Einzelpreis</th>'
. '<th style="width:18%;" class="r">Gesamt</th>'
. '</tr></thead><tbody>'
. '<tr><td>1</td><td>Teilnahme Sommerlager in Gruppe Sippe (Standardbeitrag)</td>'
. '<td class="r">5 Tage</td><td class="r">60,00&nbsp;&euro;</td><td class="r">300,00&nbsp;&euro;</td></tr>'
. '</tbody></table>';
}
private static function sampleSummary(): string
{
return '<table class="sum-outer"><tr><td class="sum-spacer"></td><td>'
. '<table class="sum-inner">'
. '<tr class="sum-total"><td class="sum-key">Gesamtbetrag</td><td class="sum-val">300,00&nbsp;&euro;</td></tr>'
. '</table></td></tr></table>';
}
}
@@ -0,0 +1,14 @@
<?php
use App\Domains\ParticipantInvoice\Controllers\CreateParticipantInvoiceController;
use App\Middleware\IdentifyTenant;
use Illuminate\Support\Facades\Route;
Route::prefix('api/v1')
->group(function () {
Route::middleware(IdentifyTenant::class)->group(function () {
Route::middleware(['auth'])->group(function () {
Route::get('participant-invoice/{participantIdentifier}', CreateParticipantInvoiceController::class);
});
});
});
@@ -0,0 +1,121 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\AcceptRefund;
use App\Domains\ParticipantRefund\Actions\CreateRefundDocument\CreateRefundDocumentCommand;
use App\Domains\ParticipantRefund\Actions\CreateRefundDocument\CreateRefundDocumentRequest;
use App\Mail\ParticipantRefundMails\RefundAcceptedMail;
use App\Models\ParticipantRefund;
use App\Support\Iban;
use Illuminate\Support\Facades\Mail;
/**
* Der Teili bestätigt die Erstattung und hinterlegt seine Bankverbindung.
*
* Läuft ohne Login -- der Token aus der Mail ist die Autorisierung, dasselbe Modell wie bei
* /print-girocode/{identifier}. Betrag und Grund stehen fest und werden hier nicht angefasst: sie kommen
* aus der Freigabe der Aktionsleitung.
*
* Danach ist der Vorgang festgeschrieben; der Beleg geht mit der Bestätigungsmail raus.
*/
class AcceptRefundCommand
{
/**
* Wortlaut für jeden Fall, in dem der Link nicht (mehr) zu einem offenen Vorgang führt.
*
* Bewusst ein und derselbe Text für „Token unbekannt" und „abgebrochen": eine abgebrochene Freigabe
* soll sich verhalten, als hätte es sie nie gegeben.
*/
public const string NO_OPEN_REFUND = 'Zu deiner Anmeldung liegt keine freigegebene Rückerstattung vor. '
. 'Bitte wende dich an die Aktionsleitung.';
public function __construct(private readonly AcceptRefundRequest $request)
{
}
public function execute(): AcceptRefundResponse
{
$response = new AcceptRefundResponse();
$refund = $this->request->refund;
if ($refund === null || !$refund->isPending()) {
$response->message = $refund?->isAccepted() === true
? 'Deine Angaben liegen uns bereits vor.'
: self::NO_OPEN_REFUND;
return $response;
}
$owner = trim($this->request->accountOwner);
$iban = Iban::normalize($this->request->accountIban);
// 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) {
$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.';
}
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 !== []) {
$response->message = 'Bitte prüfe deine Angaben.';
return $response;
}
$refund->account_owner = $owner;
$refund->account_iban = $iban;
$refund->status = ParticipantRefund::STATUS_ACCEPTED;
$refund->accepted_at = now();
$refund->save();
$this->notify($refund);
$response->success = true;
$response->message = 'Vielen Dank. Deine Angaben liegen uns vor.';
return $response;
}
/**
* Bestätigung mit dem Beleg im Anhang, an Teili und Kontaktperson.
*
* 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.
*/
private function notify(ParticipantRefund $refund): void
{
$document = new CreateRefundDocumentCommand(new CreateRefundDocumentRequest($refund))->execute();
$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,
));
if ($participant->email_2 !== null) {
Mail::to($participant->email_2)->send(new RefundAcceptedMail(
participant: $participant,
refund: $refund,
pdfContent: $pdf,
pdfFilename: $filename,
));
}
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\AcceptRefund;
use App\Models\ParticipantRefund;
class AcceptRefundRequest
{
public function __construct(
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. */
public readonly bool $declarationAccepted = false,
) {
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\AcceptRefund;
class AcceptRefundResponse
{
public bool $success = false;
public ?string $message = null;
/**
* Feldbezogene Fehler für das Formular. Schlüssel sind die Feldnamen des Frontends.
*
* @var array<string, string>
*/
public array $errorTypes = [];
}
@@ -0,0 +1,45 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\CancelRefund;
use App\Models\ParticipantRefund;
/**
* Bricht eine freigegebene, aber noch nicht bestätigte Erstattung ab.
*
* Danach läuft der Link des Teilis ins Leere und die Anmeldung sieht aus wie vor der Freigabe. Bewusst
* ohne Mail: der Teili soll nicht über etwas informiert werden, das für ihn nie stattgefunden hat --
* die Aktionsleitung klärt das im Zweifel direkt.
*
* Ein bereits bestätigter Vorgang ist unantastbar: dazu gibt es einen Beleg, und der Teili hat seine
* Bankverbindung im Vertrauen darauf herausgegeben.
*/
class CancelRefundCommand
{
public function __construct(private readonly CancelRefundRequest $request)
{
}
public function execute(): CancelRefundResponse
{
$response = new CancelRefundResponse();
$refund = $this->request->refund;
if (!$refund->isPending()) {
$response->message = $refund->isAccepted()
? 'Diese Erstattung wurde bereits bestätigt und kann nicht mehr abgebrochen werden.'
: 'Diese Erstattung wurde bereits abgebrochen.';
return $response;
}
$refund->status = ParticipantRefund::STATUS_CANCELLED;
$refund->cancelled_at = now();
$refund->save();
$response->success = true;
$response->message = 'Die Erstattung wurde abgebrochen.';
return $response;
}
}
@@ -0,0 +1,13 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\CancelRefund;
use App\Models\ParticipantRefund;
class CancelRefundRequest
{
public function __construct(
public readonly ParticipantRefund $refund,
) {
}
}
@@ -0,0 +1,10 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\CancelRefund;
class CancelRefundResponse
{
public bool $success = false;
public ?string $message = null;
}
@@ -0,0 +1,247 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\CreateRefundDocument;
use App\Models\DocumentTemplate;
use App\Models\Event;
use App\Models\EventParticipant;
use App\Models\PageText;
use App\Models\ParticipantRefund;
use App\Models\Tenant;
use App\Providers\DocumentTemplateRenderProvider;
use App\Providers\PdfGenerateAndDownloadProvider;
use App\ValueObjects\Amount;
/**
* Erzeugt den Beleg über die erstattete Teilnahmegebühr als PDF.
*
* Wie bei der Teilnahmerechnung wird nichts gespeichert: die Belegnummer leitet sich aus Veranstaltung
* und Position des Teilis ab, der Inhalt aus dem Erstattungsvorgang. Da ein bestätigter Vorgang nicht
* mehr verändert wird, liefert ein erneuter Abruf denselben Beleg.
*
* Keine Umsatzsteuer: eine Erstattung ist keine Rechnung. Ausgewiesen wird der Betrag, den der Teili
* zurückbekommt. Eine Stornorechnung mit USt-Ausweis wäre eine eigene Dokumentart.
*/
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';
private ParticipantRefund $refund;
private EventParticipant $participant;
private Event $event;
/** Der Aussteller. Gehört zum Mandanten der Veranstaltung, nicht zum gerade aktiven. */
private ?Tenant $sender;
public function __construct(private readonly CreateRefundDocumentRequest $request)
{
$this->refund = $request->refund;
$this->participant = $request->refund->participant;
$this->event = $request->refund->event;
// Wie in CreateParticipantInvoiceCommand: `$event->tenant` liefert das Slug-Attribut, nicht die
// Relation. Der Aussteller wird live gelesen, damit eine Korrektur an Name oder Anschrift auch
// auf bestehende Veranstaltungen wirkt.
$this->sender = $this->event->tenant()->first();
}
public function execute(): CreateRefundDocumentResponse
{
$response = new CreateRefundDocumentResponse();
if ($this->event->invoice_key === null || $this->participant->invoice_sequence === null) {
$response->message = 'Für diese Anmeldung lässt sich keine Belegnummer bilden.';
return $response;
}
if (!$this->refund->isAccepted()) {
$response->message = 'Der Beleg entsteht erst, wenn die Erstattung bestätigt wurde.';
return $response;
}
$documentNumber = $this->documentNumber();
$html = new DocumentTemplateRenderProvider(DocumentTemplate::TYPE_PARTICIPANT_REFUND)
->render($this->buildTokens($documentNumber));
$response->success = true;
$response->documentNumber = $documentNumber;
$response->filename = 'Rueckerstattung-' . $documentNumber . '.pdf';
$response->pdfContent = PdfGenerateAndDownloadProvider::fromHtml($html, 'portrait');
return $response;
}
/**
* Dieselbe Nummer wie die Rechnung, mit angehängtem `-R`. Kein zweiter Nummernkreis: der Beleg
* gehört zu genau einer Anmeldung, und so ist auf einen Blick erkennbar, zu welcher Rechnung.
*/
private function documentNumber(): string
{
return $this->invoiceNumber() . '-R';
}
/** Die Nummer der Teilnahmerechnung -- der Beleg weist sie aus, damit die Zahlung auffindbar ist. */
private function invoiceNumber(): string
{
return sprintf(
'%s-%s',
$this->event->invoice_key,
str_pad((string) $this->participant->invoice_sequence, 4, '0', STR_PAD_LEFT)
);
}
/**
* Der Erklärungssatz aus `page_texts` -- derselbe, den der Teili auf der Bestätigungsseite gelesen
* und angekreuzt hat.
*
* 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 declarationText(): string
{
$text = PageText::where('name', self::DECLARATION_TEXT)->first()?->content;
return trim((string) $text) !== ''
? (string) $text
: 'Ich versichere, dass ich den genannten Betrag beglichen habe und nicht anderweitig '
. 'zurückerstattet bekomme.';
}
/**
* Leistungszeitraum: bei eintägigen Veranstaltungen nur ein Datum, sonst der Zeitraum.
*/
private function servicePeriod(): string
{
$start = $this->event->start_date;
$end = $this->event->end_date;
if ($start === null) {
return '';
}
if ($end === null || $start->isSameDay($end)) {
return $start->format('d.m.Y');
}
return sprintf('%s %s', $start->format('d.m.Y'), $end->format('d.m.Y'));
}
/**
* @return array<string, string>
*/
private function buildTokens(string $documentNumber): array
{
$participant = $this->participant;
$sender = $this->sender;
$refund = $this->refund;
return [
'document_title' => 'Rückerstattung ' . $documentNumber,
'document_number' => $documentNumber,
// Belegdatum ist der Tag, an dem der Teili bestätigt hat -- da stand der Vorgang fest.
'document_date' => $refund->accepted_at?->format('d.m.Y') ?? '',
'event_name' => (string) $this->event->name,
'service_period' => $this->servicePeriod(),
'unregistered_at' => $participant->unregistered_at?->format('d.m.Y') ?? '',
'sender_name' => $sender?->invoiceSenderName() ?? '',
'sender_address_1' => (string) $sender?->address_1,
'sender_address_2' => (string) $sender?->address_2,
'sender_address_3' => (string) $sender?->address_3,
'sender_postcode' => (string) $sender?->postcode,
'sender_city' => (string) $sender?->city,
'sender_email' => (string) $sender?->email,
'sender_phone' => (string) $sender?->phone,
'sender_tax_number' => (string) $sender?->tax_number,
'sender_vat_id' => (string) $sender?->vat_id,
'recipient_name' => $participant->getOfficialName(),
'recipient_address_1' => (string) $participant->address_1,
'recipient_address_2' => (string) $participant->address_2,
'recipient_postcode' => (string) $participant->postcode,
'recipient_city' => (string) $participant->city,
'paid_amount' => $this->money($participant->amount_paid?->getAmount() ?? 0.0),
'invoice_number' => $this->invoiceNumber(),
'refund_amount' => $this->money($refund->amount?->getAmount() ?? 0.0),
'refund_reason' => $refund->reasonLabel(),
'refund_reason_text' => $refund->reasonText(),
'account_owner' => (string) $refund->account_owner,
'account_iban' => $this->formatIban((string) $refund->account_iban),
'declaration_text' => $this->declarationText(),
'details_table' => $this->renderDetails(),
];
}
/**
* Der generierte Block: wer erklärt, worauf sich die Erstattung bezieht, warum, und auf welches
* Konto sie geht.
*
* Alles, was die Person erklärt, steht in dieser einen Tabelle -- auch die Begründung, die früher als
* Fließtext darunter hing. Was daneben steht (Anschrift im Briefkopf, Veranstaltung im Betreff),
* beschreibt den Vorgang, gehört aber nicht zur Erklärung selbst.
*/
private function renderDetails(): string
{
$refund = $this->refund;
$participant = $this->participant;
$rows = [
// Der Name steht voran: die Tabelle trägt alles, was die Person erklärt, und die Anschrift
// allein im Briefkopf würde den Bezug lösen, sobald der Beleg als Anlage hinter einem
// Deckblatt liegt. Kontoinhaber*in weiter unten kann eine andere Person sein -- etwa ein
// Elternteil.
['Name', e($participant->getOfficialName())],
// Der gezahlte Beitrag ist die Bezugsgröße. Ohne ihn lässt sich bei einer Teilerstattung
// nicht erkennen, warum nur ein Teil zurückgeht -- und die Zusicherung „ich habe den Betrag
// beglichen" bliebe unbelegt, obwohl mareike ihn kennt.
['Gezahlter Teilnahmebeitrag', $this->money($participant->amount_paid?->getAmount() ?? 0.0)],
['Rechnung', e($this->invoiceNumber())],
['Erstattungsbetrag', $this->money($refund->amount?->getAmount() ?? 0.0)],
['Grund', e($refund->reasonLabel())],
];
// Bei einem Freitext-Grund ist die Begründung der Text der Aktionsleitung, sonst der des
// Katalogs. Fehlt beides, entfällt die Zeile -- eine Beschriftung ohne Wert sieht nach Fehler aus.
$reasonText = trim($refund->reasonText());
if ($reasonText !== '') {
$rows[] = ['Begründung', e($reasonText)];
}
$rows[] = ['Kontoinhaber*in', e((string) $refund->account_owner)];
$rows[] = ['IBAN', e($this->formatIban((string) $refund->account_iban))];
$html = '';
foreach ($rows as [$key, $value]) {
$html .= sprintf(
'<tr><td class="detail-key">%s</td><td class="detail-val">%s</td></tr>',
e($key),
$value
);
}
return '<table class="detail-table">' . $html . '</table>';
}
/** IBAN in Vierergruppen -- so steht sie auf jedem Beleg und lässt sich abtippen. */
private function formatIban(string $iban): string
{
return trim(chunk_split($iban, 4, ' '));
}
private function money(float $value): string
{
return new Amount($value, 'Euro')->getFormattedAmount() . '&nbsp;&euro;';
}
}
@@ -0,0 +1,13 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\CreateRefundDocument;
use App\Models\ParticipantRefund;
class CreateRefundDocumentRequest
{
public function __construct(
public readonly ParticipantRefund $refund,
) {
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\CreateRefundDocument;
class CreateRefundDocumentResponse
{
public bool $success = false;
public string $documentNumber = '';
public string $filename = '';
public string $pdfContent = '';
public ?string $message = null;
}
@@ -0,0 +1,134 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\ReleaseRefund;
use App\Enumerations\RefundReason;
use App\Mail\ParticipantRefundMails\RefundReleasedMail;
use App\Models\EventParticipant;
use App\Models\ParticipantRefund;
use App\Repositories\ParticipantRefundRepository;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
/**
* Gibt die Erstattung eines Teilnahmebeitrags frei.
*
* Der Vorgang entsteht hier nur als Absichtserklärung: Betrag und Grund stehen fest, die Bankverbindung
* fehlt noch. Der Teili ergänzt sie über den Link in der Mail. `amount_paid` bleibt unangetastet --
* gezahlt hat er bis zur Auszahlung weiterhin, was er gezahlt hat.
*/
class ReleaseRefundCommand
{
private EventParticipant $participant;
private ParticipantRefundRepository $refunds;
public function __construct(private readonly ReleaseRefundRequest $request)
{
$this->participant = $request->participant;
$this->refunds = new ParticipantRefundRepository();
}
public function execute(): ReleaseRefundResponse
{
$response = new ReleaseRefundResponse();
$rejection = $this->reject();
if ($rejection !== null) {
$response->message = $rejection;
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(),
]);
$this->notify($refund);
$response->success = true;
$response->refund = $refund;
$response->message = 'Die Erstattung wurde freigegeben. Der Teili wurde per E-Mail informiert.';
return $response;
}
/**
* Alle Gründe, aus denen eine Freigabe nicht zulässig ist.
*
* @return string|null Meldung, oder null wenn nichts dagegen spricht.
*/
private function reject(): ?string
{
if ($this->participant->unregistered_at === null) {
return 'Eine Erstattung ist nur für abgemeldete Teilis möglich.';
}
if ($this->refunds->openFor($this->participant) !== null) {
return 'Für diese Anmeldung läuft bereits eine Erstattung.';
}
$amount = $this->request->amount->getAmount();
if ($amount <= 0) {
return 'Der Erstattungsbetrag muss größer als 0 sein.';
}
// Mehr zurückgeben als eingegangen ist wäre keine Erstattung mehr. Die halbe Cent-Toleranz
// fängt die Rundung des gespeicherten Floats ab.
$paid = $this->participant->amount_paid?->getAmount() ?? 0.0;
if ($amount > $paid + 0.005) {
return 'Der Erstattungsbetrag darf den gezahlten Beitrag nicht übersteigen.';
}
$reason = RefundReason::find($this->request->reason);
if ($reason === null) {
return 'Bitte wähle einen Erstattungsgrund aus.';
}
if ($reason->requires_note && trim((string) $this->request->reasonNote) === '') {
return 'Für diesen Grund ist eine Erläuterung erforderlich.';
}
return null;
}
/** Der Freitext gehört nur zu Gründen, die ihn verlangen -- sonst stünde er ungenutzt in der DB. */
private function reasonNote(): ?string
{
$reason = RefundReason::find($this->request->reason);
if ($reason === null || !$reason->requires_note) {
return null;
}
return trim((string) $this->request->reasonNote);
}
/**
* 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,
));
if ($this->participant->email_2 !== null) {
Mail::to($this->participant->email_2)->send(new RefundReleasedMail(
participant: $this->participant,
refund: $refund,
));
}
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\ReleaseRefund;
use App\Models\EventParticipant;
use App\ValueObjects\Amount;
class ReleaseRefundRequest
{
public function __construct(
public readonly EventParticipant $participant,
public readonly Amount $amount,
public readonly string $reason,
public readonly ?string $reasonNote = null,
) {
}
}
@@ -0,0 +1,14 @@
<?php
namespace App\Domains\ParticipantRefund\Actions\ReleaseRefund;
use App\Models\ParticipantRefund;
class ReleaseRefundResponse
{
public bool $success = false;
public ?ParticipantRefund $refund = null;
public ?string $message = null;
}
@@ -0,0 +1,37 @@
<?php
namespace App\Domains\ParticipantRefund\Controllers;
use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundCommand;
use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundRequest;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* Öffentlich erreichbar -- der Token aus der Mail ist die Autorisierung.
*/
class AcceptRefundController extends CommonController
{
public function __invoke(string $refundToken, Request $request): JsonResponse
{
$refund = $this->participantRefunds->getByToken($refundToken);
$acceptRequest = new AcceptRefundRequest(
refund: $refund,
accountOwner: (string) $request->input('accountOwner'),
accountIban: (string) $request->input('accountIban'),
declarationAccepted: $request->boolean('declarationAccepted'),
);
$response = new AcceptRefundCommand($acceptRequest)->execute();
// Immer Status 200: der HttpClient des Frontends verwirft Antworten mit Fehlerstatus, die
// Feldfehler kämen dort nie an (siehe resources/js/components/HttpClient.js).
return response()->json([
'status' => $response->success ? 'success' : 'error',
'message' => $response->message,
'error_types' => $response->errorTypes,
]);
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Domains\ParticipantRefund\Controllers;
use App\Domains\ParticipantRefund\Actions\CancelRefund\CancelRefundCommand;
use App\Domains\ParticipantRefund\Actions\CancelRefund\CancelRefundRequest;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class CancelRefundController extends CommonController
{
public function __invoke(string $refundToken, Request $request): JsonResponse
{
$refund = $this->participantRefunds->getByToken($refundToken);
// Der Token ist hier keine Berechtigung: abbrechen 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 CancelRefundCommand(new CancelRefundRequest($refund))->execute();
return response()->json([
'status' => $response->success ? 'success' : 'error',
'message' => $response->message,
]);
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Domains\ParticipantRefund\Controllers;
use App\Domains\ParticipantRefund\Actions\CreateRefundDocument\CreateRefundDocumentCommand;
use App\Domains\ParticipantRefund\Actions\CreateRefundDocument\CreateRefundDocumentRequest;
use App\Scopes\CommonController;
use Illuminate\Http\Response;
class RefundDocumentController extends CommonController
{
public function __invoke(string $refundToken): Response
{
$refund = $this->participantRefunds->getByToken($refundToken);
// Der Beleg enthält die Bankverbindung -- er gehört der Aktionsleitung, nicht dem Token.
if ($refund === null || $this->events->getById($refund->event_id) === null) {
abort(403, 'Zugriff verweigert.');
}
$documentResponse = new CreateRefundDocumentCommand(new CreateRefundDocumentRequest($refund))->execute();
if (!$documentResponse->success) {
abort(422, $documentResponse->message ?? 'Der Beleg konnte nicht erstellt werden.');
}
return response($documentResponse->pdfContent, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $documentResponse->filename . '"',
]);
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Domains\ParticipantRefund\Controllers;
use App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundCommand;
use App\Models\ParticipantRefund;
use App\Providers\InertiaProvider;
use App\Scopes\CommonController;
use Inertia\Response;
/**
* Die öffentliche Seite, auf der der Teili seine Bankverbindung hinterlegt.
*
* Liefert ausschließlich Anzeigedaten -- niemals die bereits erfasste Bankverbindung: der Token wandert
* durch ein Postfach, und was einmal eingetragen ist, muss von dort nicht wieder herauslesbar sein.
*/
class RefundPageController extends CommonController
{
public function __invoke(string $refundToken): Response
{
$refund = $this->participantRefunds->getByToken($refundToken);
return new InertiaProvider('ParticipantRefund/RefundPage', $this->props($refund))->render();
}
/**
* @return array<string, mixed>
*/
private function props(?ParticipantRefund $refund): array
{
// Unbekannt und abgebrochen sind für den Teili derselbe Zustand: es gibt nichts zu tun.
if ($refund === null || $refund->status === ParticipantRefund::STATUS_CANCELLED) {
return [
'state' => 'unavailable',
'message' => AcceptRefundCommand::NO_OPEN_REFUND,
];
}
$participant = $refund->participant;
$event = $refund->event;
$common = [
'token' => $refund->token,
'name' => $participant->getNicename(),
'eventTitle' => $event->name,
'eventEmail' => $event->email,
'amount' => $refund->amount?->toString() ?? '0,00 Euro',
'reason' => $refund->reasonLabel(),
'reasonNote' => $refund->reason_note,
];
if ($refund->isAccepted()) {
return array_merge($common, [
'state' => 'accepted',
'acceptedAt' => $refund->accepted_at?->format('d.m.Y'),
]);
}
return array_merge($common, ['state' => 'open']);
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Domains\ParticipantRefund\Controllers;
use App\Domains\ParticipantRefund\Actions\ReleaseRefund\ReleaseRefundCommand;
use App\Domains\ParticipantRefund\Actions\ReleaseRefund\ReleaseRefundRequest;
use App\Scopes\CommonController;
use App\Support\Text;
use App\ValueObjects\Amount;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ReleaseRefundController extends CommonController
{
public function __invoke(string $participantIdentifier, Request $request): JsonResponse
{
$participant = $this->eventParticipants->getByIdentifier($participantIdentifier, $this->events);
if ($participant === null) {
abort(403, 'Zugriff verweigert.');
}
$refundRequest = new ReleaseRefundRequest(
participant: $participant,
amount: Amount::fromString((string) $request->input('amount'), 'Euro'),
reason: (string) $request->input('reason'),
reasonNote: Text::nullIfBlank($request->input('reasonNote')),
);
$response = new ReleaseRefundCommand($refundRequest)->execute();
return response()->json([
'status' => $response->success ? 'success' : 'error',
'message' => $response->message,
'refund' => $response->refund?->toResource()->toArray($request),
]);
}
}
@@ -0,0 +1,117 @@
<?php
namespace App\Domains\ParticipantRefund;
/**
* Katalog der Platzhalter, die in der Vorlage des Erstattungsbelegs zur Verfügung stehen.
*
* Dient wie {@see \App\Domains\ParticipantInvoice\ParticipantInvoiceTokens} zwei Zwecken: der
* Platzhalter-Liste in der Vorlagen-Verwaltung und den Beispieldaten für die Vorschau. Die echten Werte
* setzt
* {@see \App\Domains\ParticipantRefund\Actions\CreateRefundDocument\CreateRefundDocumentCommand}
* zusammen -- dass beide Seiten dieselben Namen kennen, sichert ein Test ab.
*/
final class ParticipantRefundTokens
{
/**
* @return array<string, array{label: string, tokens: array<string, array{description: string, sample: string}>}>
*/
public static function groups(): array
{
return [
'document' => [
'label' => 'Dokument',
'tokens' => [
'document_title' => ['description' => 'Titel des PDF-Dokuments', 'sample' => 'Rückerstattung WM-V-20260701-0005-R'],
'document_number' => ['description' => 'Belegnummer', 'sample' => 'WM-V-20260701-0005-R'],
'document_date' => ['description' => 'Datum der Bestätigung durch die teilnehmende Person', 'sample' => '18.06.2026'],
'event_name' => ['description' => 'Name der Veranstaltung', 'sample' => 'Sommerlager'],
'service_period' => ['description' => 'Zeitraum der Veranstaltung', 'sample' => '16.07.2026 20.07.2026'],
'unregistered_at' => ['description' => 'Datum der Abmeldung', 'sample' => '12.06.2026'],
],
],
'sender' => [
'label' => 'Absender',
'tokens' => [
'sender_name' => ['description' => 'Absender (Standard: Name des Mandanten)', 'sample' => 'BdP Landesverband Sachsen e.V.'],
'sender_address_1' => ['description' => 'Straße und Hausnummer', 'sample' => 'Musterweg 1'],
'sender_address_2' => ['description' => 'Adresszusatz, z. B. „c/o …"', 'sample' => 'c/o Mustermensch'],
'sender_address_3' => ['description' => 'Weiterer Adresszusatz', 'sample' => ''],
'sender_postcode' => ['description' => 'Postleitzahl', 'sample' => '01623'],
'sender_city' => ['description' => 'Ort', 'sample' => 'Lommatzsch'],
'sender_email' => ['description' => 'E-Mail-Adresse', 'sample' => 'kontakt@example.com'],
'sender_phone' => ['description' => 'Telefonnummer', 'sample' => '0351 1234567'],
'sender_tax_number' => ['description' => 'Steuernummer', 'sample' => '201/123/45678'],
'sender_vat_id' => ['description' => 'USt-IdNr.', 'sample' => ''],
],
],
'recipient' => [
'label' => 'Empfänger',
'tokens' => [
'recipient_name' => ['description' => 'Name der teilnehmenden Person', 'sample' => 'Mika Muster'],
'recipient_address_1' => ['description' => 'Straße und Hausnummer', 'sample' => 'Beispielstraße 3'],
'recipient_address_2' => ['description' => 'Adresszusatz', 'sample' => ''],
'recipient_postcode' => ['description' => 'Postleitzahl', 'sample' => '11111'],
'recipient_city' => ['description' => 'Ort', 'sample' => 'Beispielstadt'],
],
],
'refund' => [
'label' => 'Erstattung',
'tokens' => [
'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 €'],
'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.'],
],
],
'body' => [
'label' => 'Beleginhalt (generiert)',
'tokens' => [
'details_table' => ['description' => 'Tabelle mit Name, gezahltem Beitrag, Rechnung, Erstattungsbetrag, Grund, Begründung und Bankverbindung', 'sample' => self::sampleDetails()],
],
],
];
}
/**
* Beispielwerte für die Vorschau.
*
* @return array<string, string>
*/
public static function sample(): array
{
$sample = [];
foreach (self::groups() as $group) {
foreach ($group['tokens'] as $name => $token) {
$sample[$name] = $token['sample'];
}
}
return $sample;
}
/** @return array<int, string> */
public static function names(): array
{
return array_keys(self::sample());
}
private static function sampleDetails(): string
{
return '<table class="detail-table">'
. '<tr><td class="detail-key">Name</td><td class="detail-val">Mika Muster</td></tr>'
. '<tr><td class="detail-key">Gezahlter Teilnahmebeitrag</td><td class="detail-val">300,00&nbsp;&euro;</td></tr>'
. '<tr><td class="detail-key">Rechnung</td><td class="detail-val">WM-V-20260701-0005</td></tr>'
. '<tr><td class="detail-key">Erstattungsbetrag</td><td class="detail-val">220,00&nbsp;&euro;</td></tr>'
. '<tr><td class="detail-key">Grund</td><td class="detail-val">Krankheitsbedingte Absage</td></tr>'
. '<tr><td class="detail-key">Begr&uuml;ndung</td><td class="detail-val">Die Teilnahme konnte krankheitsbedingt nicht angetreten werden.</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>';
}
}
@@ -0,0 +1,24 @@
<?php
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\Middleware\IdentifyTenant;
use Illuminate\Support\Facades\Route;
Route::prefix('api/v1')
->group(function () {
Route::middleware(IdentifyTenant::class)->group(function () {
Route::prefix('participant-refund')->group(function () {
// Der Teili bestätigt über den Token aus seiner Mail -- ohne Login.
Route::post('{refundToken}/accept', AcceptRefundController::class);
Route::middleware(['auth'])->group(function () {
Route::post('{participantIdentifier}/release', ReleaseRefundController::class);
Route::post('{refundToken}/cancel', CancelRefundController::class);
Route::get('{refundToken}/document', RefundDocumentController::class);
});
});
});
});
@@ -0,0 +1,10 @@
<?php
use App\Domains\ParticipantRefund\Controllers\RefundPageController;
use App\Middleware\IdentifyTenant;
use Illuminate\Support\Facades\Route;
Route::middleware(IdentifyTenant::class)->group(function () {
// Bewusst ohne `auth`: die Seite ist der Link aus der Mail an den Teili.
Route::get('/rueckerstattung/{refundToken}', RefundPageController::class);
});
@@ -0,0 +1,270 @@
<script setup>
import {computed, reactive, ref} from 'vue'
import {toast} from 'vue3-toastify'
import AppLayout from '../../../../resources/js/layouts/AppLayout.vue'
import ShadowedBox from '../../../Views/Components/ShadowedBox.vue'
import ErrorText from '../../../Views/Components/ErrorText.vue'
import IbanInput from '../../../Views/Components/IbanInput.vue'
import TextResource from '../../../Views/Components/TextResource.vue'
import {useAjax} from '../../../../resources/js/components/ajaxHandler.js'
const {request} = useAjax()
/**
* `state` steuert die ganze Seite:
* open -- Formular für die Bankverbindung
* accepted -- Angaben liegen vor, nichts mehr zu tun
* unavailable -- Token unbekannt oder Erstattung abgebrochen
*/
const props = defineProps({
state: String,
message: String,
token: String,
name: String,
eventTitle: String,
eventEmail: String,
amount: String,
reason: String,
reasonNote: String,
acceptedAt: String,
})
// 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: ''})
const saving = ref(false)
/**
* Die Erklärung erscheint erst, wenn beide Kontoangaben stehen -- man bestätigt nichts, bevor man weiß,
* worüber. Dasselbe Vorgehen wie beim Erfassen einer Abrechnung (refund-data.vue).
*
* Dort wird zusätzlich auf `iban.length === 27` geprüft, also auf die Länge einer formatierten deutschen
* IBAN. Das bleibt hier bewusst weg: eine österreichische oder schweizerische käme sonst nie durch. Ob
* die IBAN stimmt, prüft der Server mit Prüfziffer und länderabhängiger Länge.
*/
const accountComplete = computed(
() => form.accountOwner.trim() !== '' && form.accountIban.trim() !== ''
)
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.'
errors.declaration = form.declarationAccepted ? '' : 'Bitte bestätige die Erklärung.'
return !errors.accountOwner && !errors.accountIban && !errors.declaration
}
async function submit() {
if (!validate() || saving.value) return
saving.value = true
try {
const response = await request('/api/v1/participant-refund/' + props.token + '/accept', {
method: 'POST',
body: {
accountOwner: form.accountOwner,
accountIban: form.accountIban,
declarationAccepted: form.declarationAccepted,
},
})
if (!response) {
toast.error('Deine Angaben konnten nicht gespeichert werden. Bitte versuche es später erneut.')
return
}
// Feldbezogene Fehler kommen mit Status 200 als `error_types` zurück -- der HttpClient des
// Projekts verwirft Antworten mit Fehlerstatus.
if (response.status !== 'success') {
Object.keys(response.error_types ?? {}).forEach((key) => {
if (key in errors) errors[key] = response.error_types[key]
})
toast.error(response.message ?? 'Bitte prüfe deine Angaben.')
return
}
toast.success(response.message)
state.value = 'accepted'
} finally {
saving.value = false
}
}
</script>
<template>
<AppLayout title="Rückerstattung">
<shadowed-box style="max-width: 640px; margin: 60px auto; padding: 24px;">
<template v-if="state === 'unavailable'">
<h2>Rückerstattung</h2>
<p class="hint">{{ props.message }}</p>
</template>
<template v-else>
<h2>Rückerstattung deines Teilnahmebeitrags</h2>
<p>
Hallo {{ props.name }}, für deine Abmeldung von der Veranstaltung
<strong>{{ props.eventTitle }}</strong> wurde eine Rückerstattung freigegeben.
</p>
<table class="summary">
<tr>
<th>Betrag</th>
<td><strong>{{ props.amount }}</strong></td>
</tr>
<tr>
<th>Grund</th>
<td>{{ props.reason }}</td>
</tr>
<tr v-if="props.reasonNote">
<th>Anmerkung</th>
<td>{{ props.reasonNote }}</td>
</tr>
</table>
<template v-if="state === 'accepted'">
<p 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 }}
</p>
</template>
<template v-else>
<p class="hint">
Der Betrag steht fest und lässt sich hier nicht ändern. Hast du dazu Fragen, wende
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.
-->
<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" />
<!-- 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' }}
</button>
</template>
</form>
</template>
</template>
</shadowed-box>
</AppLayout>
</template>
<style scoped>
h2 {
margin-bottom: 16px;
}
h3 {
margin: 24px 0 12px;
}
.hint {
margin: 16px 0;
padding: 10px 12px;
border-left: 3px solid #f5c400;
background-color: #fffef5;
font-size: 0.9rem;
color: #4b5563;
}
.summary {
border-collapse: collapse;
margin: 20px 0;
}
.summary th {
text-align: left;
padding: 6px 24px 6px 0;
color: #555;
font-weight: normal;
white-space: nowrap;
}
.summary td {
padding: 6px 0;
}
.field {
margin-bottom: 16px;
}
.field label {
display: block;
margin-bottom: 4px;
font-size: 0.9rem;
color: #4b5563;
}
.field .form-input {
width: 100%;
}
.declaration {
display: flex;
align-items: flex-start;
gap: 8px;
margin: 20px 0 8px;
font-size: 0.9rem;
line-height: 1.5;
}
.declaration input {
margin-top: 3px;
flex-shrink: 0;
}
.declaration :deep(label) {
cursor: pointer;
}
</style>
+3 -1
View File
@@ -17,7 +17,9 @@ Route::middleware(IdentifyTenant::class)->group(function () {
route::get('/logout', LogOutController::class); route::get('/logout', LogOutController::class);
route::post('/login', [LoginController::class, 'doLogin']); route::post('/login', [LoginController::class, 'doLogin']);
route::get('/login', [LoginController::class, 'loginForm']); // Benannt, weil Laravels `auth`-Middleware nicht angemeldete Zugriffe auf die Route `login`
// umleitet -- ohne den Namen endet jeder Gast-Zugriff auf eine geschützte Route in einem 500.
route::get('/login', [LoginController::class, 'loginForm'])->name('login');
Route::middleware(['auth'])->group(function () { Route::middleware(['auth'])->group(function () {
Route::post('/logout', [LogoutController::class, 'logout']); Route::post('/logout', [LogoutController::class, 'logout']);
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Enumerations;
use App\Scopes\CommonModel;
/**
* Gründe für die Erstattung eines Teilnahmebeitrags -- DB-gestützt (analog {@see TaxExemptionReason}),
* damit Label und der auf dem Beleg ausgewiesene Text zentral pflegbar sind.
*
* @property string $slug
* @property string $name
* @property string|null $document_text
* @property bool $requires_note
* @property int $sort_order
*/
class RefundReason extends CommonModel
{
public const string SICKNESS = 'sickness';
public const string EVENT_CANCELLED = 'event_cancelled';
public const string OTHER = 'other';
protected $table = 'refund_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 „Grund" steht. Bei einem Grund, der einen Freitext verlangt,
* ist der hinterlegte Text der 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();
}
}
@@ -156,14 +156,18 @@ abstract class AbstractEventPaymentModule implements EventPaymentModule
/** /**
* Template-Method: Der gemeinsame Rechnungs-Rumpf wird hier gebaut, der variierende Schlusssatz * Template-Method: Der gemeinsame Rechnungs-Rumpf wird hier gebaut, der variierende Schlusssatz
* kommt aus {@see invoiceClosingStatement()} des jeweiligen Moduls. * kommt aus {@see invoiceClosingStatement()} des jeweiligen Moduls.
*
* `$request->amount` ist der noch offene Betrag. Ist nichts mehr offen, gilt unabhängig von der
* Zahlungsart derselbe Satz -- eine Zahlungsaufforderung wäre dann schlicht falsch.
*/ */
public function createInvoice(CreateInvoiceRequest $request): CreateInvoiceResponse public function createInvoice(CreateInvoiceRequest $request): CreateInvoiceResponse
{ {
$response = new CreateInvoiceResponse(); $response = new CreateInvoiceResponse();
// TODO: In einer Folge-Iteration den gemeinsamen Rumpf (Betrag, Leistung, Teilnehmerdaten) befüllen
// und an die Invoice-Domain anbinden.
$response->success = true; $response->success = true;
$response->closingStatement = $this->invoiceClosingStatement($request);
$response->closingStatement = $request->amount->getAmount() <= 0
? 'Der Betrag ist bereits vollständig beglichen — vielen Dank.'
: $this->invoiceClosingStatement($request);
return $response; return $response;
} }
@@ -171,6 +175,8 @@ abstract class AbstractEventPaymentModule implements EventPaymentModule
/** /**
* Der je Zahlungsart variierende Schlusssatz der Rechnung * Der je Zahlungsart variierende Schlusssatz der Rechnung
* ("Bitte überweise bis ..." / "wird abgebucht ..." / "wurde per PayPal beglichen"). * ("Bitte überweise bis ..." / "wird abgebucht ..." / "wurde per PayPal beglichen").
*
* Wird nur bei tatsächlich offenem Betrag aufgerufen.
*/ */
abstract protected function invoiceClosingStatement(CreateInvoiceRequest $request): string; abstract protected function invoiceClosingStatement(CreateInvoiceRequest $request): string;
} }
@@ -106,7 +106,24 @@ class AccountTransferPaymentModule extends AbstractEventPaymentModule implements
protected function invoiceClosingStatement(CreateInvoiceRequest $request): string protected function invoiceClosingStatement(CreateInvoiceRequest $request): string
{ {
// TODO: In einer Folge-Iteration ausformulieren (z.B. "Bitte überweise bis zum ... auf IBAN ..."). $config = $request->configuration;
return ''; $deadline = $request->event->registration_final_end?->format('d.m.Y');
$sentence = $deadline !== null
? sprintf('Bitte überweise %s bis zum %s auf folgendes Konto:', $request->amount->toString(), $deadline)
: sprintf('Bitte überweise %s auf folgendes Konto:', $request->amount->toString());
$lines = [
'Kontoinhaber*in: ' . (string) ($config['account_owner'] ?? ''),
'IBAN: ' . (string) ($config['iban'] ?? ''),
];
if (($config['bic'] ?? '') !== '') {
$lines[] = 'BIC: ' . (string) $config['bic'];
}
$lines[] = 'Verwendungszweck: ' . (string) $request->participant->payment_purpose;
return $sentence . '<br />' . implode('<br />', array_map(e(...), $lines));
} }
} }
@@ -59,6 +59,9 @@ class UndefinedPaymentModule extends AbstractEventPaymentModule
protected function invoiceClosingStatement(CreateInvoiceRequest $request): string protected function invoiceClosingStatement(CreateInvoiceRequest $request): string
{ {
return ''; return sprintf(
'Bitte halte den Betrag von %s in bar am ersten Tag der Veranstaltung bereit.',
$request->amount->toString()
);
} }
} }
@@ -0,0 +1,73 @@
<?php
namespace App\Mail\ParticipantRefundMails;
use App\Models\EventParticipant;
use App\Models\ParticipantRefund;
use App\Support\Iban;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
/**
* Bestätigt dem Teili die erfassten Angaben und liefert den Beleg als PDF mit.
*
* Der Beleg wird nicht hier erzeugt, sondern übergeben: er entsteht einmal in
* {@see \App\Domains\ParticipantRefund\Actions\AcceptRefund\AcceptRefundCommand} und geht an beide
* Empfänger. Scheitert die Erzeugung, geht die Mail ohne Anhang raus statt gar nicht.
*/
class RefundAcceptedMail extends Mailable
{
public function __construct(
private EventParticipant $participant,
private ParticipantRefund $refund,
private ?string $pdfContent = null,
private ?string $pdfFilename = null,
) {
}
public function envelope(): Envelope
{
return new Envelope(
subject: sprintf(
'Deine Angaben zur Rückerstattung für %s',
$this->participant->event()->first()->name
),
);
}
public function content(): Content
{
$event = $this->participant->event()->first();
return new Content(
view: 'emails.events.refund_accepted',
with: [
'name' => $this->participant->getNicename(),
'eventTitle' => $event->name,
'eventEmail' => $event->email,
'amount' => $this->refund->amount?->toString() ?? '0,00 Euro',
'reason' => $this->refund->reasonLabel(),
'accountOwner' => $this->refund->account_owner,
'accountIban' => Iban::format((string) $this->refund->account_iban),
'hasDocument' => $this->pdfContent !== null,
],
);
}
/**
* @return array<int, Attachment>
*/
public function attachments(): array
{
if ($this->pdfContent === null) {
return [];
}
return [
Attachment::fromData(fn (): string => $this->pdfContent, $this->pdfFilename ?? 'Rueckerstattung.pdf')
->withMime('application/pdf'),
];
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Mail\ParticipantRefundMails;
use App\Models\EventParticipant;
use App\Models\ParticipantRefund;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
/**
* Fordert den Teili auf, seine Bankverbindung für die freigegebene Erstattung zu hinterlegen.
*/
class RefundReleasedMail extends Mailable
{
public function __construct(
private EventParticipant $participant,
private ParticipantRefund $refund,
) {
}
public function envelope(): Envelope
{
return new Envelope(
subject: sprintf(
'Rückerstattung deines Beitrags für die Veranstaltung %s',
$this->participant->event()->first()->name
),
);
}
public function content(): Content
{
$event = $this->participant->event()->first();
return new Content(
view: 'emails.events.refund_released',
with: [
'name' => $this->participant->getNicename(),
'eventTitle' => $event->name,
'eventEmail' => $event->email,
'amount' => $this->refund->amount?->toString() ?? '0,00 Euro',
'reason' => $this->refund->reasonLabel(),
'reasonNote' => $this->refund->reason_note,
// Absolute URL: der Link muss aus jedem Postfach heraus funktionieren.
'link' => url('/rueckerstattung/' . $this->refund->token),
],
);
}
/**
* @return array<int, Attachment>
*/
public function attachments(): array
{
return [];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Middleware;
use App\Providers\AuthCheckProvider;
use Closure;
/**
* Nur für Hauptadministrator*innen.
*
* Abgegrenzt von {@see AdminRoleMiddleware}, die zusätzlich `ROLE_GROUP_LEADER` durchlässt: die
* Dokumentvorlagen gelten app-weit für alle Mandanten, das darf keine Gruppenleitung ändern.
*/
class MainAdminRoleMiddleware
{
public function handle($request, Closure $next)
{
if (!auth()->check()) {
return redirect('/login')->with('message', 'Du musst eingeloggt sein.');
}
// Bewusst `isMainAdministrator()` statt `getUserRole()`: geprüft wird `user_role_main`, nicht die
// auf einem Sub-Tenant abgeleitete Rolle.
if (!new AuthCheckProvider()->isMainAdministrator()) {
return redirect('/admin')->with('message', 'Du bist dazu nicht berechtigt.');
}
return $next($request);
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Models;
use App\Scopes\CommonModel;
/**
* Ein Bild für die Dokumentvorlagen, referenziert als `{asset:name}`.
*
* Liegt in der Datenbank und nicht im Dateisystem, damit ein Release es nicht überschreibt und es mit
* jedem Dump mitwandert. `data` hält den base64-Payload, der für das PDF ohnehin als Data-URI gebraucht
* wird.
*
* Die Namen vergibt die verwaltende Person selbst -- es gibt keine fachlich vorbelegten Slots.
*
* @property string $name
* @property string|null $label
* @property string $mime
* @property string $data
*/
class DocumentAsset extends CommonModel
{
protected $table = 'document_assets';
protected $fillable = [
'name',
'label',
'mime',
'data',
];
/** Fertige Data-URI zum direkten Einsetzen in ein `src`-Attribut. */
public function toDataUri(): string
{
return sprintf('data:%s;base64,%s', $this->mime, $this->data);
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Models;
use App\Scopes\CommonModel;
use Illuminate\Database\Eloquent\Collection;
/**
* Ein Block einer Dokumentvorlage. Bewusst `CommonModel` (kein `SiteScope`): die Vorlage gilt app-weit,
* tenant-spezifisch sind nur die eingesetzten Werte.
*
* @property string $document_type
* @property string $block
* @property string|null $content
* @property int $sort_order
* @property bool $editable
*/
class DocumentTemplate extends CommonModel
{
public const string TYPE_PARTICIPANT_INVOICE = 'participant_invoice';
public const string TYPE_PARTICIPANT_REFUND = 'participant_refund';
/** Seitengerüst -- enthält die `{block:...}`-Platzhalter und bestimmt damit die Anordnung. */
public const string BLOCK_LAYOUT = 'layout';
/** CSS des Dokuments. */
public const string BLOCK_STYLE = 'style';
/** Der Inhaltsblock. Bei der Rechnung generiert und gesperrt, beim Erstattungsbeleg pflegbar. */
public const string BLOCK_BODY = 'body';
protected $table = 'document_templates';
protected $fillable = [
'document_type',
'block',
'content',
'sort_order',
'editable',
];
protected $casts = [
'sort_order' => 'integer',
'editable' => 'boolean',
];
/**
* Alle Blöcke einer Dokumentart, nach Block-Slug adressierbar.
*
* @return Collection<string, self>
*/
public static function forType(string $documentType): Collection
{
return self::where('document_type', $documentType)
->orderBy('sort_order')
->get()
->keyBy('block');
}
}
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace App\Models;
use App\Domains\ParticipantInvoice\ParticipantInvoiceTokens;
use App\Domains\ParticipantRefund\ParticipantRefundTokens;
/**
* Was die Vorlagen-Verwaltung über eine Dokumentart wissen muss: wie sie heißt, welche Platzhalter es
* gibt und wie die Blöcke im Formular beschriftet sind.
*
* Die eine Stelle, an der eine neue Dokumentart eingetragen wird -- Controller und Formular lesen von
* hier und kennen selbst keine Dokumentart mehr.
*/
final class DocumentTypeCatalog
{
/** Blöcke, die Layout-HTML bzw. CSS enthalten und deshalb im Quelltext-Editor gepflegt werden. */
public const array SOURCE_BLOCKS = [
DocumentTemplate::BLOCK_LAYOUT,
DocumentTemplate::BLOCK_STYLE,
];
/**
* Die Beschriftungen der Blöcke, die jede Dokumentart hat -- Seitengerüst, Gestaltung und der
* Briefkopf des Verbands.
*
* @var array<string, string>
*/
private const array COMMON_BLOCK_LABELS = [
DocumentTemplate::BLOCK_LAYOUT => 'Seitengerüst',
DocumentTemplate::BLOCK_STYLE => 'Gestaltung (CSS)',
'header_sender_return' => 'Rücksendezeile',
'header_recipient' => 'Empfängeranschrift',
'emblem' => 'Emblem',
'logo' => 'Logo',
'sender_data' => 'Absenderangaben',
'subject' => 'Betreff und Referenzdaten',
];
/**
* @return array<string, array{label: string, tokens: class-string, blockLabels: array<string, string>}>
*/
public static function all(): array
{
return [
DocumentTemplate::TYPE_PARTICIPANT_INVOICE => [
'label' => 'Teilnahmerechnung',
'tokens' => ParticipantInvoiceTokens::class,
'blockLabels' => self::COMMON_BLOCK_LABELS + [
DocumentTemplate::BLOCK_BODY => 'Rechnungsinhalt',
'footer' => 'Grußformel und Fußnote',
],
],
DocumentTemplate::TYPE_PARTICIPANT_REFUND => [
'label' => 'Erstattungsbeleg',
'tokens' => ParticipantRefundTokens::class,
'blockLabels' => self::COMMON_BLOCK_LABELS + [
DocumentTemplate::BLOCK_BODY => 'Erklärung und Angaben zur Erstattung',
'footer' => 'Fußbereich',
],
],
];
}
public static function has(string $documentType): bool
{
return array_key_exists($documentType, self::all());
}
/** Die Dokumentart, oder null wenn sie nicht im Katalog steht. */
public static function get(string $documentType): ?array
{
return self::all()[$documentType] ?? null;
}
public static function default(): string
{
return DocumentTemplate::TYPE_PARTICIPANT_INVOICE;
}
public static function blockLabel(string $documentType, string $block): string
{
return self::get($documentType)['blockLabels'][$block] ?? $block;
}
/**
* Platzhalter-Gruppen der Dokumentart -- für die Liste im Formular.
*
* @return array<string, array<string, mixed>>
*/
public static function tokenGroups(string $documentType): array
{
$tokens = self::get($documentType)['tokens'] ?? null;
return $tokens === null ? [] : $tokens::groups();
}
/**
* Beispielwerte der Dokumentart -- für die Vorschau.
*
* @return array<string, string>
*/
public static function sampleTokens(string $documentType): array
{
$tokens = self::get($documentType)['tokens'] ?? null;
return $tokens === null ? [] : $tokens::sample();
}
/**
* Die Auswahl für den Umschalter im Formular.
*
* @return array<int, array{value: string, label: string}>
*/
public static function options(): array
{
$options = [];
foreach (self::all() as $type => $definition) {
$options[] = ['value' => $type, 'label' => $definition['label']];
}
return $options;
}
}
+2
View File
@@ -45,6 +45,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* @property float $support_flat * @property float $support_flat
* @property int $alcoholics_age * @property int $alcoholics_age
* @property boolean $archived * @property boolean $archived
* @property string|null $invoice_key
*/ */
class Event extends InstancedModel class Event extends InstancedModel
{ {
@@ -90,6 +91,7 @@ class Event extends InstancedModel
'participation_options', 'participation_options',
'addons', 'addons',
'invoice_key',
]; ];
protected $casts = [ protected $casts = [
+6
View File
@@ -26,12 +26,15 @@ class EventParticipant extends InstancedModel
'event_id', 'event_id',
'user_id', 'user_id',
'identifier', 'identifier',
'invoice_sequence',
'firstname', 'firstname',
'lastname', 'lastname',
'nickname', 'nickname',
'participation_type', 'participation_type',
'fee_type',
'sibling_reduction',
'local_group', 'local_group',
'birthday', 'birthday',
@@ -91,6 +94,9 @@ class EventParticipant extends InstancedModel
'amount' => AmountCast::class, 'amount' => AmountCast::class,
'amount_paid' => AmountCast::class, 'amount_paid' => AmountCast::class,
'payment_options' => 'array', 'payment_options' => 'array',
'invoice_sequence' => 'integer',
'sibling_reduction' => 'boolean',
]; ];
/* /*
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace App\Models;
use App\Casts\AmountCast;
use App\Enumerations\RefundReason;
use App\Scopes\InstancedModel;
use App\ValueObjects\Amount;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Ein Erstattungsvorgang zu einer Anmeldung.
*
* @property int $id
* @property string $tenant
* @property int $event_id
* @property int $event_participant_id
* @property string $token
* @property string $status
* @property Amount|null $amount
* @property string|null $reason
* @property string|null $reason_note
* @property string|null $account_owner
* @property string|null $account_iban
* @property int|null $released_by
* @property \Illuminate\Support\Carbon|null $released_at
* @property \Illuminate\Support\Carbon|null $accepted_at
* @property \Illuminate\Support\Carbon|null $cancelled_at
*/
class ParticipantRefund extends InstancedModel
{
/** Freigegeben, wartet auf die Bankverbindung des Teilis. */
public const string STATUS_PENDING = 'pending';
/** Der Teili hat bestätigt, der Beleg ist erstellt. Ab hier unveränderlich. */
public const string STATUS_ACCEPTED = 'accepted';
/** Von der Aktionsleitung abgebrochen, bevor der Teili bestätigt hat. */
public const string STATUS_CANCELLED = 'cancelled';
protected $table = 'participant_refunds';
protected $fillable = [
'tenant',
'event_id',
'event_participant_id',
'token',
'status',
'amount',
'reason',
'reason_note',
'account_owner',
'account_iban',
'released_by',
'released_at',
'accepted_at',
'cancelled_at',
];
protected $casts = [
'amount' => AmountCast::class,
'released_at' => 'datetime',
'accepted_at' => 'datetime',
'cancelled_at' => 'datetime',
];
public function participant(): BelongsTo
{
return $this->belongsTo(EventParticipant::class, 'event_participant_id');
}
public function event(): BelongsTo
{
return $this->belongsTo(Event::class);
}
/**
* Der Grund als Stammdatensatz. Nicht `reason()`, weil das die Spalte `reason` verdecken würde.
*/
public function reasonRelation(): BelongsTo
{
return $this->belongsTo(RefundReason::class, 'reason', 'slug');
}
public function isPending(): bool
{
return $this->status === self::STATUS_PENDING;
}
public function isAccepted(): bool
{
return $this->status === self::STATUS_ACCEPTED;
}
/** Der auf dem Beleg auszuweisende Grundtext -- bei Freitext-Gründen der Text der Aktionsleitung. */
public function reasonText(): string
{
return $this->reasonRelation()->first()?->documentText($this->reason_note) ?? '';
}
public function reasonLabel(): string
{
return (string) ($this->reasonRelation()->first()?->name ?? '');
}
}
+38
View File
@@ -3,6 +3,7 @@
namespace App\Models; namespace App\Models;
use App\Scopes\CommonModel; use App\Scopes\CommonModel;
use App\Support\Text;
/** /**
* @property string $slug * @property string $slug
@@ -12,6 +13,14 @@ use App\Scopes\CommonModel;
* @property string $account_name * @property string $account_name
* @property string $account_iban * @property string $account_iban
* @property string $account_bic * @property string $account_bic
* @property string|null $invoice_sender_name
* @property string|null $address_1
* @property string|null $address_2
* @property string|null $address_3
* @property string|null $phone
* @property string|null $tax_number
* @property string|null $vat_id
* @property string|null $invoice_prefix
* @property string $city * @property string $city
* @property string $postcode * @property string $postcode
* @property boolean $download_exports * @property boolean $download_exports
@@ -29,16 +38,42 @@ use App\Scopes\CommonModel;
*/ */
class Tenant extends CommonModel class Tenant extends CommonModel
{ {
/**
* Ohne ausdrückliche Angabe ist das Präfix der Rechnungsnummer der großgeschriebene Slug
* (`wm` -> `WM`). Hier und nicht als DB-Default, weil er sich aus einer anderen Spalte ableitet.
*/
protected static function booted(): void
{
static::creating(static function (self $tenant): void {
$tenant->invoice_prefix ??= strtoupper((string) $tenant->slug);
});
}
public static function getTempDirectory() : string { public static function getTempDirectory() : string {
return app('tenant')->slug . '/temp-data/'; return app('tenant')->slug . '/temp-data/';
} }
/**
* Bezeichnung des Rechnungsstellers.
*
* `name` ist ein internes Kürzel ("Wilde Möhre"); auf einer Rechnung steht die vollständige
* Bezeichnung mit Rechtsform. Ohne eigene Angabe bleibt es beim Namen des Mandanten.
*/
public function invoiceSenderName() : string {
return Text::nullIfBlank($this->invoice_sender_name) ?? (string) $this->name;
}
public const PRIMARY_TENANT_NAME = 'LV'; public const PRIMARY_TENANT_NAME = 'LV';
protected $fillable = [ protected $fillable = [
'slug', 'slug',
'name', 'name',
'invoice_sender_name',
'address_1',
'address_2',
'address_3',
'email', 'email',
'email_finance', 'email_finance',
'phone',
'url', 'url',
'account_name', 'account_name',
'account_iban', 'account_iban',
@@ -57,6 +92,9 @@ class Tenant extends CommonModel
'tax_exemption_reason', 'tax_exemption_reason',
'tax_exemption_note', 'tax_exemption_note',
'vat_pricing_mode', 'vat_pricing_mode',
'tax_number',
'vat_id',
'invoice_prefix',
]; ];
protected $casts = [ protected $casts = [
@@ -0,0 +1,156 @@
<?php
namespace App\Providers;
use App\Models\DocumentAsset;
use App\Models\DocumentTemplate;
use Illuminate\Support\Facades\Log;
/**
* Setzt ein Dokument aus den in der Datenbank gepflegten Vorlagenblöcken zusammen.
*
* Ablauf: `layout` bildet das Seitengerüst und enthält `{block:...}`-Platzhalter; darin werden die
* einzelnen Blöcke eingesetzt, anschließend Bilder und Werte. Das Ergebnis wandert in ein dünnes
* Blade-Gerüst, das selbst kein Layout enthält.
*
* WICHTIG: Vorlageninhalt kommt aus der Datenbank und wird von einem Admin-Formular befüllt. Er wird
* ausschließlich per `strtr()` bzw. `preg_replace_callback()` ersetzt und NIEMALS durch `Blade::render()`
* oder `eval` geschickt -- sonst wäre das Formular ein Weg zur Codeausführung auf dem Server.
*/
class DocumentTemplateRenderProvider
{
/** @var array<string, string> */
private array $blocks;
/**
* @param array<string, string> $overrides Blockinhalte, die den gespeicherten Stand ersetzen -- für die
* Vorschau in der Vorlagen-Verwaltung, damit ungespeicherte
* Änderungen sichtbar werden.
*/
public function __construct(private readonly string $documentType, array $overrides = [])
{
$stored = DocumentTemplate::forType($this->documentType)
->map(fn(DocumentTemplate $block): string => (string) $block->content)
->all();
$this->blocks = array_merge($stored, array_map(strval(...), $overrides));
}
/**
* @param array<string, string> $tokens Platzhalter ohne geschweifte Klammern, z.B. ['invoice_number' => '...']
*/
public function render(array $tokens): string
{
$html = $this->blockContent(DocumentTemplate::BLOCK_LAYOUT);
$html = $this->insertBlocks($html);
$html = $this->insertAssets($html);
$html = $this->applyConditionals($html, $tokens);
$html = $this->insertTokens($html, $tokens);
$style = $this->stripBareDataUris($this->insertTokens(
$this->insertAssets($this->blockContent(DocumentTemplate::BLOCK_STYLE)),
$tokens
));
return view('pdfs.document', [
'title' => $tokens['document_title'] ?? '',
'style' => $style,
'content' => $html,
])->render();
}
/**
* Entfernt Data-URIs, die nicht in `url(...)` bzw. Anführungszeichen stehen.
*
* dompdf lagert Data-URIs im CSS nur dann in interne Blobs aus, wenn ihnen `(`, `"` oder `'`
* vorausgeht (siehe Stylesheet::_parse_css). Ein bar im CSS stehendes Data-URI bleibt als Rohtext
* liegen, und die anschließende Ruleset-Regex `[^{]*{[^}]*}` scannt für jede Startposition durch
* das gesamte Base64 -- quadratische Laufzeit. Bei einem eingebetteten Logo sind das Minuten, und
* unter PHP-FPM stirbt der Worker am Zeitlimit: die Anfrage endet in einem 502.
*
* Gültiges CSS ist so ein Data-URI ohnehin nicht. Es wird deshalb entfernt und weitergerendert,
* statt das Dokument scheitern zu lassen -- wer eine Rechnung braucht, hat die Vorlage nicht
* kaputt gemacht. Die Warnung im Log sorgt dafür, dass der Zustand trotzdem auffällt.
*/
private function stripBareDataUris(string $css): string
{
// Das Semikolon gehört zum Data-URI selbst ("data:image/png;base64,..."), darf hier also nicht
// begrenzen -- sonst bliebe der Base64-Rumpf stehen und der Parser bremst weiter.
$cleaned = preg_replace('/(?<![("\'])data:[^\s}\)\'"]+/', '', $css);
if ($cleaned !== $css) {
Log::warning('Dokumentvorlage: Data-URI ausserhalb von url("...") im CSS entfernt.', [
'document_type' => $this->documentType,
'block' => DocumentTemplate::BLOCK_STYLE,
]);
}
return $cleaned;
}
/** Ersetzt `{block:name}` durch den jeweiligen Blockinhalt. Leere oder fehlende Blöcke fallen weg. */
private function insertBlocks(string $html): string
{
return preg_replace_callback(
'/\{block:([a-z0-9_-]+)}/i',
fn(array $match): string => $this->blockContent($match[1]),
$html
);
}
/** Ersetzt `{asset:name}` durch die Data-URI des Bildes. Unbekannte Namen werden zu einem Leerstring. */
private function insertAssets(string $html): string
{
if (!str_contains($html, '{asset:')) {
return $html;
}
$assets = DocumentAsset::all()->keyBy('name');
return preg_replace_callback(
'/\{asset:([a-z0-9_-]+)}/i',
static fn(array $match): string => $assets->get($match[1])?->toDataUri() ?? '',
$html
);
}
/**
* Wertet `{if:token}...{/if:token}` aus: der Abschnitt bleibt nur stehen, wenn der Platzhalter einen
* Wert hat. Ohne das stünden auf der Rechnung leere Zeilen, hängende Trenner und Beschriftungen ohne
* Wert ("Steuernummer: "), sobald ein optionales Feld beim Tenant nicht gepflegt ist.
*
* Verschachtelte Bedingungen werden nicht unterstützt -- für die Vorlagen hier reicht eine Ebene.
*
* @param array<string, string> $tokens
*/
private function applyConditionals(string $html, array $tokens): string
{
return preg_replace_callback(
'/\{if:([a-z0-9_]+)}(.*?)\{\/if:\1}/is',
static fn(array $match): string => trim((string) ($tokens[$match[1]] ?? '')) === '' ? '' : $match[2],
$html
);
}
/**
* Ersetzt die Wert-Platzhalter. Unbekannte Platzhalter bleiben unangetastet stehen -- das macht beim
* Pflegen der Vorlage sofort sichtbar, dass ein Name nicht stimmt.
*
* @param array<string, string> $tokens
*/
private function insertTokens(string $html, array $tokens): string
{
$replacements = [];
foreach ($tokens as $name => $value) {
$replacements['{' . $name . '}'] = (string) $value;
}
return strtr($html, $replacements);
}
private function blockContent(string $block): string
{
return $this->blocks[$block] ?? '';
}
}
+11
View File
@@ -4,6 +4,7 @@ namespace App\Providers;
use App\Enumerations\EatingHabit; use App\Enumerations\EatingHabit;
use App\Enumerations\InvoiceType; use App\Enumerations\InvoiceType;
use App\Enumerations\RefundReason;
use App\Enumerations\UserRole; use App\Enumerations\UserRole;
use App\Models\AvailablePaymentMethod; use App\Models\AvailablePaymentMethod;
use App\Models\Tenant; use App\Models\Tenant;
@@ -23,10 +24,14 @@ class GlobalDataProvider {
$this->user = auth()->user(); $this->user = auth()->user();
$canAccessAdmin = false; $canAccessAdmin = false;
$isMainAdmin = false;
if (null !== $this->user) { if (null !== $this->user) {
$authCheck = new AuthCheckProvider(); $authCheck = new AuthCheckProvider();
$effectiveRole = $authCheck->getUserRole(); $effectiveRole = $authCheck->getUserRole();
$canAccessAdmin = in_array($effectiveRole, [UserRole::USER_ROLE_ADMIN, UserRole::USER_ROLE_GROUP_LEADER], true); $canAccessAdmin = in_array($effectiveRole, [UserRole::USER_ROLE_ADMIN, UserRole::USER_ROLE_GROUP_LEADER], true);
// Steuert nur die Sichtbarkeit app-weiter Einstellungen im Menü; abgesichert wird über
// MainAdminRoleMiddleware.
$isMainAdmin = $authCheck->isMainAdministrator($this->user);
} }
return response()->json([ return response()->json([
@@ -37,6 +42,7 @@ class GlobalDataProvider {
'version' => config('app.version'), 'version' => config('app.version'),
'currentEvent' => $this->getCurrentEventData(), 'currentEvent' => $this->getCurrentEventData(),
'canAccessAdmin' => $canAccessAdmin, 'canAccessAdmin' => $canAccessAdmin,
'isMainAdmin' => $isMainAdmin,
]); ]);
} }
@@ -184,6 +190,11 @@ class GlobalDataProvider {
return $activeUsers; return $activeUsers;
} }
/** Auswahl der Erstattungsgründe für den Dialog „Beitrag erstatten". */
public function getRefundReasons() : JsonResponse {
return response()->json(RefundReason::options());
}
public function getEventSettingData(Request $request) : JsonResponse { public function getEventSettingData(Request $request) : JsonResponse {
return response()->json( return response()->json(
[ [
@@ -0,0 +1,41 @@
<?php
namespace App\Repositories;
use App\Models\EventParticipant;
use App\Models\ParticipantRefund;
class ParticipantRefundRepository
{
/** Der offene Vorgang einer Anmeldung -- es kann höchstens einen geben. */
public function openFor(EventParticipant $participant): ?ParticipantRefund
{
return ParticipantRefund::where('event_participant_id', $participant->id)
->where('status', ParticipantRefund::STATUS_PENDING)
->first();
}
/**
* Der für die Anzeige maßgebliche Vorgang: der offene, sonst der zuletzt bestätigte. Abgebrochene
* Vorgänge bleiben außen vor -- für die Aktionsleitung sieht die Anmeldung danach aus wie vorher.
*/
public function currentFor(EventParticipant $participant): ?ParticipantRefund
{
return ParticipantRefund::where('event_participant_id', $participant->id)
->whereIn('status', [ParticipantRefund::STATUS_PENDING, ParticipantRefund::STATUS_ACCEPTED])
->orderByDesc('id')
->first();
}
/**
* Der Vorgang zu einem öffentlichen Link.
*
* Der Token ist die einzige Autorisierung -- dasselbe Modell wie bei /print-girocode/{identifier}.
* Der Mandant kommt über den globalen SiteScope aus dem Host der Anfrage: ein Token einer anderen
* Instanz findet hier nichts.
*/
public function getByToken(string $token): ?ParticipantRefund
{
return ParticipantRefund::where('token', $token)->first();
}
}
@@ -8,6 +8,7 @@ use App\Enumerations\ParticipationType;
use App\Models\AvailablePaymentMethod; use App\Models\AvailablePaymentMethod;
use App\Models\EventParticipant; use App\Models\EventParticipant;
use App\Models\PaymentMethod; use App\Models\PaymentMethod;
use App\Repositories\ParticipantRefundRepository;
use App\ValueObjects\Age; use App\ValueObjects\Age;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
@@ -71,6 +72,13 @@ class EventParticipantResource extends JsonResource
'email_1' => $this->resource->email_1, 'email_1' => $this->resource->email_1,
'amountPaid' => ['value' => $this->resource->amount_paid, 'readable' => $this->resource->amount_paid?->toString() ?? '0,00 Euro', 'short' => $this->resource->amount_paid?->getFormattedAmount() ?? '0,00'], 'amountPaid' => ['value' => $this->resource->amount_paid, 'readable' => $this->resource->amount_paid?->toString() ?? '0,00 Euro', 'short' => $this->resource->amount_paid?->getFormattedAmount() ?? '0,00'],
'amountExpected' => ['value' => $this->resource->amount, 'readable' => $this->resource->amount?->toString() ?? '0,00 Euro', 'short' => $this->resource->amount?->getFormattedAmount() ?? '0,00'], 'amountExpected' => ['value' => $this->resource->amount, 'readable' => $this->resource->amount?->toString() ?? '0,00 Euro', 'short' => $this->resource->amount?->getFormattedAmount() ?? '0,00'],
// Numerisch, damit das Frontend rechnen bzw. auf "kostenlos" prüfen kann -- `value` oben ist
// ein Amount-Objekt und serialisiert nicht.
'amountExpectedValue' => $this->resource->amount?->getAmount() ?? 0.0,
'amountPaidValue' => $this->resource->amount_paid?->getAmount() ?? 0.0,
// Der laufende bzw. bestätigte Erstattungsvorgang -- null, wenn keiner existiert oder
// der letzte abgebrochen wurde.
'refund' => $this->refund($request),
'alcoholicsAllowed' => new Age($this->resource->birthday)->getAge() >= $event->alcoholics_age, 'alcoholicsAllowed' => new Age($this->resource->birthday)->getAge() >= $event->alcoholics_age,
'localGroupPostcode' => $this->resource->localGroup()->first()?->postcode ?? '00000', 'localGroupPostcode' => $this->resource->localGroup()->first()?->postcode ?? '00000',
'localGroupCity' => $this->resource->localGroup()->first()?->city ?? '00000', 'localGroupCity' => $this->resource->localGroup()->first()?->city ?? '00000',
@@ -103,4 +111,17 @@ class EventParticipantResource extends JsonResource
] ]
); );
} }
/**
* Der für die Anzeige maßgebliche Erstattungsvorgang.
*
* Abgebrochene Vorgänge bleiben außen vor: für die Aktionsleitung soll die Anmeldung danach
* aussehen wie vor der Freigabe.
*/
private function refund($request): ?array
{
$refund = new ParticipantRefundRepository()->currentFor($this->resource);
return $refund?->toResource()->toArray($request);
}
} }
+4 -4
View File
@@ -6,6 +6,7 @@ use App\Enumerations\ParticipationFeeType;
use App\Enumerations\ParticipationType; use App\Enumerations\ParticipationType;
use App\Enumerations\VatPricingMode; use App\Enumerations\VatPricingMode;
use App\Models\Event; use App\Models\Event;
use App\Support\DateRange;
use App\ValueObjects\Amount; use App\ValueObjects\Amount;
use DateTime; use DateTime;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -20,7 +21,7 @@ class EventResource extends JsonResource{
public function toArray(Request $request) : array public function toArray(Request $request) : array
{ {
$duration = $this->event->end_date->diff($this->event->start_date)->days + 1; $duration = DateRange::inclusiveDays($this->event->start_date, $this->event->end_date);
$returnArray = [ $returnArray = [
'id' => $this->event->id, 'id' => $this->event->id,
@@ -352,8 +353,7 @@ class EventResource extends JsonResource{
$basicFee = $basicFee->multiply($this->getMultiplier()); $basicFee = $basicFee->multiply($this->getMultiplier());
if ($this->event->pay_per_day) { if ($this->event->pay_per_day) {
$days = $arrival->diff($departure)->days + 1; $basicFee = $basicFee->multiply(DateRange::inclusiveDays($arrival, $departure));
$basicFee = $basicFee->multiply($days);
} }
if ($hasSibling && $this->event->sibling_reduction) { if ($hasSibling && $this->event->sibling_reduction) {
@@ -380,7 +380,7 @@ class EventResource extends JsonResource{
*/ */
public function resolveAddons(array $selectedKeys, DateTime $arrival, DateTime $departure): array public function resolveAddons(array $selectedKeys, DateTime $arrival, DateTime $departure): array
{ {
$days = $arrival->diff($departure)->days + 1; $days = DateRange::inclusiveDays($arrival, $departure);
$addsVat = $this->event->tax_liable && $this->event->vat_pricing_mode === VatPricingMode::AddOn->value; $addsVat = $this->event->tax_liable && $this->event->vat_pricing_mode === VatPricingMode::AddOn->value;
$items = []; $items = [];
@@ -0,0 +1,37 @@
<?php
namespace App\Resources;
use App\Models\ParticipantRefund;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* Der Erstattungsvorgang für das Frontend.
*
* Bewusst NICHT `$this->resource->toArray()` als Basis wie in {@see EventParticipantResource}: die
* Bankverbindung darf nur dorthin, wo sie hingehört (Beleg und Auszahlung), nicht in jede
* Teilnehmerliste. Deshalb werden die Felder hier einzeln aufgeführt.
*/
class ParticipantRefundResource extends JsonResource
{
public function __construct(ParticipantRefund $refund)
{
parent::__construct($refund);
}
public function toArray($request): array
{
return [
'token' => $this->resource->token,
'status' => $this->resource->status,
'amount' => $this->resource->amount?->toString() ?? '0,00 Euro',
'amountValue' => $this->resource->amount?->getAmount() ?? 0.0,
'reason' => $this->resource->reason,
'reasonLabel' => $this->resource->reasonLabel(),
'reasonNote' => $this->resource->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'),
];
}
}
+3
View File
@@ -12,6 +12,7 @@ use App\Repositories\EventParticipantRepository;
use App\Repositories\EventRepository; use App\Repositories\EventRepository;
use App\Repositories\InvoiceRepository; use App\Repositories\InvoiceRepository;
use App\Repositories\PageTextRepository; use App\Repositories\PageTextRepository;
use App\Repositories\ParticipantRefundRepository;
use App\Repositories\UserRepository; use App\Repositories\UserRepository;
abstract class CommonController { abstract class CommonController {
@@ -24,6 +25,7 @@ abstract class CommonController {
protected InvoiceRepository $invoices; protected InvoiceRepository $invoices;
protected EventRepository $events; protected EventRepository $events;
protected EventParticipantRepository $eventParticipants; protected EventParticipantRepository $eventParticipants;
protected ParticipantRefundRepository $participantRefunds;
protected EstimatesRepository $estimates; protected EstimatesRepository $estimates;
protected AdminUserRepository $adminUsers; protected AdminUserRepository $adminUsers;
protected AdminTenantRepository $adminTenants; protected AdminTenantRepository $adminTenants;
@@ -36,6 +38,7 @@ abstract class CommonController {
$this->invoices = new InvoiceRepository(); $this->invoices = new InvoiceRepository();
$this->events = new EventRepository(); $this->events = new EventRepository();
$this->eventParticipants = new EventParticipantRepository(); $this->eventParticipants = new EventParticipantRepository();
$this->participantRefunds = new ParticipantRefundRepository();
$this->estimates = new EstimatesRepository(); $this->estimates = new EstimatesRepository();
$this->adminUsers = new AdminUserRepository(); $this->adminUsers = new AdminUserRepository();
$this->adminTenants = new AdminTenantRepository(); $this->adminTenants = new AdminTenantRepository();
+28
View File
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Support;
use DateTimeInterface;
/**
* Zustandslose Helfer für Zeiträume.
*/
final class DateRange
{
/**
* Anzahl Tage eines Zeitraums, bei dem beide Enden mitzählen -- die Anwesenheitstage einer
* Teilnahme also, bei der An- und Abreisetag beide zählen. Ein eintägiger Zeitraum ergibt 1.
*
* Die Reihenfolge der Argumente spielt keine Rolle, `DateInterval::days` liefert den Betrag.
*
* Achtung: Für die Förderabrechnung gilt eine andere Regel -- dort werden Nächte gezählt
* (siehe `presenceDaysSupport` in {@see \App\Resources\EventParticipantResource}). Dieser Helfer
* ist dafür nicht zuständig.
*/
public static function inclusiveDays(DateTimeInterface $from, DateTimeInterface $to): int
{
return $from->diff($to)->days + 1;
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace App\Support;
/**
* Zustandslose Helfer für IBANs.
*
* Geprüft wird nach ISO 13616 bzw. ISO 7064 (Mod 97-10): Struktur, Länge des Landes und die Prüfziffer.
* Die Prüfziffer ist der wichtige Teil -- sie fängt Zahlendreher und Tippfehler ab, die sonst erst beim
* Rückläufer der Bank auffallen würden. Auf ein Konto, dessen IBAN nur strukturell stimmt, überweist man
* im Zweifel Geld an eine fremde Person.
*/
final class Iban
{
/**
* Länge der IBAN je Ländercode. Vollständig für den SEPA-Raum; alles darüber hinaus fällt auf die
* generische Längenprüfung zurück (siehe isValid()).
*
* @var array<string, int>
*/
private const array LENGTHS = [
'AD' => 24, 'AT' => 20, 'BE' => 16, 'BG' => 22, 'CH' => 21, 'CY' => 28, 'CZ' => 24,
'DE' => 22, 'DK' => 18, 'EE' => 20, 'ES' => 24, 'FI' => 18, 'FR' => 27, 'GB' => 22,
'GI' => 23, 'GR' => 27, 'HR' => 21, 'HU' => 28, 'IE' => 22, 'IS' => 26, 'IT' => 27,
'LI' => 21, 'LT' => 20, 'LU' => 20, 'LV' => 21, 'MC' => 27, 'MT' => 31, 'NL' => 18,
'NO' => 15, 'PL' => 28, 'PT' => 25, 'RO' => 24, 'SE' => 24, 'SI' => 19, 'SK' => 24,
'SM' => 27, 'VA' => 22,
];
/** Leerzeichen raus, Großbuchstaben -- die kanonische Form, die gespeichert wird. */
public static function normalize(string $iban): string
{
return strtoupper(preg_replace('/\s+/', '', $iban) ?? '');
}
public static function isValid(string $iban): bool
{
$iban = self::normalize($iban);
if (preg_match('/^[A-Z]{2}[0-9]{2}[A-Z0-9]{10,30}$/', $iban) !== 1) {
return false;
}
$expected = self::LENGTHS[substr($iban, 0, 2)] ?? null;
if ($expected !== null && strlen($iban) !== $expected) {
return false;
}
return self::checksum($iban) === 1;
}
/** In Vierergruppen -- die Schreibweise auf Belegen und Formularen. */
public static function format(string $iban): string
{
return trim(chunk_split(self::normalize($iban), 4, ' '));
}
/**
* Mod 97-10: die ersten vier Zeichen ans Ende, Buchstaben durch ihre Position + 9 ersetzen
* (A = 10 Z = 35), das Ergebnis modulo 97. Eine gültige IBAN ergibt 1.
*
* Der Rest wird stellenweise fortgeschrieben, weil die Zahl sonst jeden Integer sprengt.
*/
private static function checksum(string $iban): int
{
$rearranged = substr($iban, 4) . substr($iban, 0, 4);
$remainder = 0;
foreach (str_split($rearranged) as $char) {
$value = ctype_digit($char) ? $char : (string) (ord($char) - 55);
foreach (str_split($value) as $digit) {
$remainder = ($remainder * 10 + (int) $digit) % 97;
}
}
return $remainder;
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Support;
/**
* Zustandslose Helfer rund um Texteingaben.
*/
final class Text
{
/**
* Leergelassene Eingaben als NULL, sonst getrimmt.
*
* Optionale Felder aus Formularen kommen als Leerstring statt als NULL an. In der Datenbank
* gespeichert würden sie später als "vorhanden, aber leer" gelten -- im Briefkopf einer Rechnung
* etwa als leere Zeile oder als Beschriftung ohne Wert.
*
* Laravels `blank()` erkennt auch reine Whitespace-Eingaben.
*/
public static function nullIfBlank(?string $value): ?string
{
return blank($value) ? null : trim($value);
}
}
+14 -1
View File
@@ -1,6 +1,19 @@
<script setup> <script setup>
import Editor from '@tinymce/tinymce-vue'; import Editor from '@tinymce/tinymce-vue';
const props = defineProps({
/**
* TinyMCE schreibt URLs in href/src standardmässig um (absolut <-> relativ). Wo Platzhalter wie
* {asset:logo} in einem src stehen, zerstört das den Platzhalter -- dort wird die Umschreibung
* abgeschaltet. Standard bleibt TinyMCEs eigener Standard, damit sich für die übrigen
* Einsatzorte nichts ändert.
*/
convertUrls: {
type: Boolean,
default: true,
},
})
const model = defineModel() const model = defineModel()
</script> </script>
@@ -19,7 +32,7 @@ const model = defineModel()
language: 'de', language: 'de',
language_url: '/tinymce/langs/de.js', language_url: '/tinymce/langs/de.js',
ui_mode: 'split', ui_mode: 'split',
convert_urls: props.convertUrls,
}" }"
/> />
</template> </template>
Regular → Executable
View File
+4
View File
@@ -57,6 +57,10 @@
"@php artisan config:clear --ansi", "@php artisan config:clear --ansi",
"@php artisan test" "@php artisan test"
], ],
"test:coverage": [
"@php artisan config:clear --ansi",
"@php -d pcov.enabled=1 vendor/bin/phpunit --coverage-html storage/coverage --coverage-text"
],
"post-autoload-dump": [ "post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi" "@php artisan package:discover --ansi"
@@ -1,20 +1,28 @@
<?php <?php
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/** /**
* Setzt den Standard-Befreiungsgrund neuer Tenants auf Jugendhilfe (§ 4 Nr. 25 Buchst. a). Der Wert * Setzt den Standard-Befreiungsgrund neuer Tenants auf Jugendhilfe (§ 4 Nr. 25 Buchst. a). Der Wert
* existiert in tax_exemption_reasons, der FK bleibt gültig. Bestehende Zeilen bleiben unverändert. * existiert in tax_exemption_reasons, der FK bleibt gültig. Bestehende Zeilen bleiben unverändert.
*
* Über `change()` statt rohem `ALTER TABLE ... SET DEFAULT`, weil sqlite das nicht kennt und die
* Testsuite auf sqlite läuft.
*/ */
return new class extends Migration { return new class extends Migration {
public function up(): void public function up(): void
{ {
DB::statement("ALTER TABLE tenants ALTER COLUMN tax_exemption_reason SET DEFAULT 'ustg_4_25a'"); Schema::table('tenants', function (Blueprint $table) {
$table->string('tax_exemption_reason')->nullable()->default('ustg_4_25a')->change();
});
} }
public function down(): void public function down(): void
{ {
DB::statement('ALTER TABLE tenants ALTER COLUMN tax_exemption_reason DROP DEFAULT'); Schema::table('tenants', function (Blueprint $table) {
$table->string('tax_exemption_reason')->nullable()->default(null)->change();
});
} }
}; };
@@ -0,0 +1,55 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Ergänzt die für eine Rechnung nach § 14 Abs. 4 UStG fehlenden Angaben des Rechnungsstellers
* (vollständige Anschrift, Steuernummer bzw. USt-IdNr.) sowie das Kürzel für den Nummernkreis.
*
* Die Adressfelder heißen wie die des Teilnehmers (`event_participants.address_1/2`), damit
* Absender- und Empfängerblock der Rechnungsvorlage gleich aufgebaut sind.
*/
return new class extends Migration {
public function up(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->string('address_1')->nullable()->after('name');
$table->string('address_2')->nullable()->after('address_1');
$table->string('address_3')->nullable()->after('address_2');
$table->string('phone')->nullable()->after('email_finance');
$table->string('tax_number')->nullable()->after('vat_pricing_mode');
$table->string('vat_id')->nullable()->after('tax_number');
$table->string('invoice_prefix')->nullable()->after('vat_id');
});
// Bestands-Tenants bekommen den großgeschriebenen Slug als Default-Präfix (wm -> WM).
foreach (DB::table('tenants')->select('id', 'slug')->get() as $tenant) {
DB::table('tenants')
->where('id', $tenant->id)
->update(['invoice_prefix' => strtoupper($tenant->slug)]);
}
Schema::table('tenants', function (Blueprint $table) {
$table->unique('invoice_prefix');
});
}
public function down(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->dropUnique(['invoice_prefix']);
$table->dropColumn([
'address_1',
'address_2',
'address_3',
'phone',
'tax_number',
'vat_id',
'invoice_prefix',
]);
});
}
};
@@ -0,0 +1,108 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Friert bei Event-Anlage den Rechnungssteller und den Event-Teil der Rechnungsnummer ein -- analog zur
* bereits bestehenden USt-Grundlage (`2026_08_06_160010_add_tax_snapshot_to_events`).
*
* ACHTUNG: Das hier erzeugte Format ist überholt -- `2026_09_02_140030_compact_invoice_key_format`
* entfernt die Trenner zwischen Jahr, Monat und Veranstaltungsnummer (`WM-V-20260701`). Diese
* Migration bleibt unverändert, weil sie den damaligen Stand abbildet.
*
* `invoice_key` hat die Form `WM-V-2026-07-01` (Tenant-Präfix, Dokumentart, Jahr, Monat, laufende Nummer
* der Veranstaltung dieses Tenants im Monat). Er muss eingefroren werden, weil Tenant-Präfix und
* `start_date` später änderbar sind -- eine bereits herausgegebene Rechnung würde sonst zu einer anderen
* Nummer gehören.
*/
return new class extends Migration {
public function up(): void
{
Schema::table('events', function (Blueprint $table) {
$table->string('invoice_key')->nullable()->unique();
$table->string('invoice_sender_name')->nullable();
$table->string('invoice_sender_address_1')->nullable();
$table->string('invoice_sender_address_2')->nullable();
$table->string('invoice_sender_address_3')->nullable();
$table->string('invoice_sender_postcode')->nullable();
$table->string('invoice_sender_city')->nullable();
$table->string('invoice_sender_email')->nullable();
$table->string('invoice_sender_phone')->nullable();
$table->string('invoice_sender_tax_number')->nullable();
$table->string('invoice_sender_vat_id')->nullable();
});
$this->backfill();
}
/**
* Bestandsevents nachträglich bestücken: Absenderdaten aus dem heutigen Tenant, `invoice_key` je
* Tenant und Monat nach `start_date`, dann `id` durchnummeriert.
*/
private function backfill(): void
{
$tenants = DB::table('tenants')->get()->keyBy('slug');
$counters = [];
$events = DB::table('events')
->select('id', 'tenant', 'start_date')
->orderBy('start_date')
->orderBy('id')
->get();
foreach ($events as $event) {
$tenant = $tenants->get($event->tenant);
if ($tenant === null || $event->start_date === null) {
continue;
}
$month = date('Y-m', strtotime($event->start_date));
$bucket = $event->tenant . '|' . $month;
$counters[$bucket] = ($counters[$bucket] ?? 0) + 1;
DB::table('events')->where('id', $event->id)->update([
// $month ist bereits "2026-07" -> ergibt "WM-V-2026-07-01"
'invoice_key' => sprintf(
'%s-V-%s-%s',
$tenant->invoice_prefix,
$month,
str_pad((string) $counters[$bucket], 2, '0', STR_PAD_LEFT)
),
'invoice_sender_name' => $tenant->name,
'invoice_sender_address_1' => $tenant->address_1,
'invoice_sender_address_2' => $tenant->address_2,
'invoice_sender_address_3' => $tenant->address_3,
'invoice_sender_postcode' => $tenant->postcode,
'invoice_sender_city' => $tenant->city,
'invoice_sender_email' => $tenant->email,
'invoice_sender_phone' => $tenant->phone,
'invoice_sender_tax_number' => $tenant->tax_number,
'invoice_sender_vat_id' => $tenant->vat_id,
]);
}
}
public function down(): void
{
Schema::table('events', function (Blueprint $table) {
$table->dropUnique(['invoice_key']);
$table->dropColumn([
'invoice_key',
'invoice_sender_name',
'invoice_sender_address_1',
'invoice_sender_address_2',
'invoice_sender_address_3',
'invoice_sender_postcode',
'invoice_sender_city',
'invoice_sender_email',
'invoice_sender_phone',
'invoice_sender_tax_number',
'invoice_sender_vat_id',
]);
});
}
};
@@ -0,0 +1,61 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Drei Angaben, die für die Anmelde-Rechnung gebraucht werden:
*
* - `invoice_sequence` -- die Position des Teilis in der Veranstaltung, bildet den letzten Block der
* Rechnungsnummer. Wird persistiert und nicht zur Laufzeit gezählt, damit die Nummer stabil bleibt,
* wenn sich jemand abmeldet.
* - `fee_type` / `sibling_reduction` -- flossen bisher in den Preis ein, ohne gespeichert zu werden.
* Ohne sie ließe sich der ausgewiesene Tagessatz nicht korrekt darstellen (siehe
* CreateParticipantInvoiceCommand).
*/
return new class extends Migration {
public function up(): void
{
Schema::table('event_participants', function (Blueprint $table) {
$table->unsignedInteger('invoice_sequence')->nullable()->after('identifier');
$table->string('fee_type')->nullable()->after('participation_type');
$table->boolean('sibling_reduction')->default(false)->after('fee_type');
});
$this->backfillSequences();
Schema::table('event_participants', function (Blueprint $table) {
$table->unique(['event_id', 'invoice_sequence']);
});
}
/** Bestandsanmeldungen je Event nach `id` durchnummerieren. */
private function backfillSequences(): void
{
$counters = [];
$participants = DB::table('event_participants')
->select('id', 'event_id')
->orderBy('event_id')
->orderBy('id')
->get();
foreach ($participants as $participant) {
$counters[$participant->event_id] = ($counters[$participant->event_id] ?? 0) + 1;
DB::table('event_participants')
->where('id', $participant->id)
->update(['invoice_sequence' => $counters[$participant->event_id]]);
}
}
public function down(): void
{
Schema::table('event_participants', function (Blueprint $table) {
$table->dropUnique(['event_id', 'invoice_sequence']);
$table->dropColumn(['invoice_sequence', 'fee_type', 'sibling_reduction']);
});
}
};
@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Vorlage für generierte Dokumente (aktuell: Anmelde-Rechnung), zerlegt in einzeln pflegbare Blöcke.
*
* Bewusst app-weit und ohne Tenant-Spalte (Model erbt `CommonModel`, also kein `SiteScope`) -- es gibt
* eine Vorlage für alle Tenants, tenant-spezifisch sind nur die eingesetzten Werte. Vorbild ist
* `page_texts`.
*
* Der Inhalt liegt in der Datenbank statt im Blade, damit ein Release ihn nicht überschreibt.
*/
return new class extends Migration {
public function up(): void
{
Schema::create('document_templates', function (Blueprint $table) {
$table->id();
$table->string('document_type');
$table->string('block');
$table->longText('content')->nullable();
$table->integer('sort_order')->default(1);
$table->boolean('editable')->default(true);
$table->timestamps();
$table->unique(['document_type', 'block']);
});
}
public function down(): void
{
Schema::dropIfExists('document_templates');
}
};
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Bilder für die Dokumentvorlagen (Logo, Emblem, ...), referenziert als `{asset:name}`.
*
* Die Bilder liegen in der Datenbank und nicht im Dateisystem: ein Release ist ein `git checkout`,
* alles unter `public/` und `resources/` wird dabei überschrieben. Die Datenbank fasst ein Release
* nicht an, und die Bilder wandern automatisch mit jedem Dump mit. Für das PDF werden sie ohnehin als
* Data-URI eingebettet, `data` wird also direkt so verwendet, wie es gespeichert ist.
*
* Die Namen vergibt die verwaltende Person selbst -- es gibt keine fachlich vorbelegten Slots.
*/
return new class extends Migration {
public function up(): void
{
Schema::create('document_assets', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('label')->nullable();
$table->string('mime');
$table->longText('data');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('document_assets');
}
};
@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Eigener Absendername für Rechnungen.
*
* `tenants.name` ist ein internes Kürzel ("Wilde Möhre", "Landesunmittelbare Mitglieder"). Auf einer
* Rechnung muss dagegen die vollständige Bezeichnung des Rechnungsstellers stehen, üblicherweise
* inklusive Rechtsform. Bleibt das Feld leer, wird weiterhin `name` verwendet.
*/
return new class extends Migration {
public function up(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->string('invoice_sender_name')->nullable()->after('name');
});
}
public function down(): void
{
Schema::table('tenants', function (Blueprint $table) {
$table->dropColumn('invoice_sender_name');
});
}
};
@@ -0,0 +1,51 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Nimmt den Absender-Snapshot vom Event zurück.
*
* Der Absender einer Rechnung ist der Mandant, nicht die Veranstaltung. Eingefroren gehörten diese
* Angaben nie: eine Korrektur am Absendernamen oder an der Anschrift hätte sonst auf keiner
* bestehenden Veranstaltung gewirkt -- und damit auf keiner Rechnung, die zu ihr erzeugt wird.
*
* Eingefroren bleibt, was tatsächlich historisch ist: `events.invoice_key` (der Nummernkreis) und
* die Steuergrundlage (`tax_liable`, `vat_rate`, `vat_pricing_mode`, `tax_exemption_*`) -- sie
* beschreibt, wie der Preis zustande kam, und darf sich rückwirkend nicht ändern.
*
* Angelegt wurden die Spalten in `2026_08_27_140020_add_invoice_snapshot_to_events`; die bleibt
* unangetastet, weil sie zusätzlich `invoice_key` anlegt.
*/
return new class extends Migration {
/** @var array<int, string> */
private const array COLUMNS = [
'invoice_sender_name',
'invoice_sender_address_1',
'invoice_sender_address_2',
'invoice_sender_address_3',
'invoice_sender_postcode',
'invoice_sender_city',
'invoice_sender_email',
'invoice_sender_phone',
'invoice_sender_tax_number',
'invoice_sender_vat_id',
];
public function up(): void
{
Schema::table('events', function (Blueprint $table) {
$table->dropColumn(self::COLUMNS);
});
}
public function down(): void
{
Schema::table('events', function (Blueprint $table) {
foreach (self::COLUMNS as $column) {
$table->string($column)->nullable();
}
});
}
};

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