Dev 4.8.0 #15

Merged
th.guenther merged 11 commits from dev-4.8.0 into main 2026-09-04 09:29:57 +02:00
79 changed files with 4303 additions and 75 deletions
Showing only changes of commit 9c4c28e566 - Show all commits
@@ -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;
use App\Support\Text;
class UpdateTenantContactAction
{
public function __construct(private UpdateTenantContactRequest $request)
@@ -15,8 +17,14 @@ class UpdateTenantContactAction
$this->request->tenant->update([
'email' => $this->request->email,
'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,
'city' => $this->request->city,
'phone' => Text::nullIfBlank($this->request->phone),
]);
$response->success = true;
@@ -12,6 +12,14 @@ class UpdateTenantContactRequest
public string $emailFinance,
public string $postcode,
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;
use App\Enumerations\VatPricingMode;
use App\Models\Tenant;
use App\Support\Text;
class UpdateTenantTaxAction
{
@@ -14,14 +16,23 @@ class UpdateTenantTaxAction
{
$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) {
$this->request->tenant->update([
$this->request->tenant->update($this->withInvoiceDetails([
'tax_liable' => true,
'vat_rate' => $this->clampVatRate($this->request->vatRate),
'vat_pricing_mode' => $this->request->vatPricingMode->value,
'tax_exemption_reason' => null,
'tax_exemption_note' => null,
]);
], $prefix));
$response->success = true;
$response->message = 'Steuerinformationen wurden gespeichert.';
@@ -45,13 +56,13 @@ class UpdateTenantTaxAction
return $response;
}
$this->request->tenant->update([
$this->request->tenant->update($this->withInvoiceDetails([
'tax_liable' => false,
'vat_rate' => 0,
'vat_pricing_mode' => VatPricingMode::Inclusive->value,
'tax_exemption_reason' => $reason->slug,
'tax_exemption_note' => $reason->requires_note ? $note : null,
]);
], $prefix));
$response->success = true;
$response->message = 'Steuerinformationen wurden gespeichert.';
@@ -63,4 +74,31 @@ class UpdateTenantTaxAction
{
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 ?string $exemptionNote,
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,56 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Domains\ParticipantInvoice\ParticipantInvoiceTokens;
use App\Models\DocumentAsset;
use App\Models\DocumentTemplate;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
class DocumentTemplatesGetController extends CommonController
{
/** Blöcke, die Layout-HTML bzw. CSS enthalten und deshalb im Quelltext-Editor gepflegt werden. */
private const array SOURCE_BLOCKS = [
DocumentTemplate::BLOCK_LAYOUT,
DocumentTemplate::BLOCK_STYLE,
];
private const array 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',
DocumentTemplate::BLOCK_BODY => 'Rechnungsinhalt',
'footer' => 'Grußformel und Fußnote',
];
public function __invoke(): JsonResponse
{
$blocks = DocumentTemplate::forType(DocumentTemplate::TYPE_PARTICIPANT_INVOICE)
->values()
->map(fn(DocumentTemplate $block): array => [
'block' => $block->block,
'label' => self::BLOCK_LABELS[$block->block] ?? $block->block,
'content' => (string) $block->content,
'editable' => $block->editable,
'source' => in_array($block->block, self::SOURCE_BLOCKS, true),
]);
return response()->json([
'blocks' => $blocks,
'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' => ParticipantInvoiceTokens::groups(),
]);
}
}
@@ -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,30 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Domains\ParticipantInvoice\ParticipantInvoiceTokens;
use App\Models\DocumentTemplate;
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
{
$html = new DocumentTemplateRenderProvider(
DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
(array) $request->input('blocks', []),
)->render(ParticipantInvoiceTokens::sample());
return response(PdfGenerateAndDownloadProvider::fromHtml($html, 'portrait'), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="vorschau.pdf"',
]);
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Domains\Admin\Controllers;
use App\Domains\Admin\Actions\UpdateDocumentTemplate\UpdateDocumentTemplateAction;
use App\Domains\Admin\Actions\UpdateDocumentTemplate\UpdateDocumentTemplateRequest;
use App\Models\DocumentTemplate;
use App\Scopes\CommonController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class DocumentTemplatesUpdateController extends CommonController
{
public function __invoke(Request $request): JsonResponse
{
$action = new UpdateDocumentTemplateAction(new UpdateDocumentTemplateRequest(
documentType: DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
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([
'email' => $tenant->email,
'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,
'city' => $tenant->city,
'saveEndpoint' => '/api/v1/admin/tenants/' . $slug . '/contact',
@@ -20,6 +20,11 @@ class ManagedTenantContactUpdateController extends CommonController
emailFinance: $request->input('email_finance'),
postcode: $request->input('postcode'),
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();
@@ -20,6 +20,11 @@ class ManagedTenantTaxGetController extends CommonController
'tax_exemption_reason' => $tenant->tax_exemption_reason,
'tax_exemption_note' => $tenant->tax_exemption_note,
'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(),
'pricing_modes' => VatPricingMode::options(),
'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(),
exemptionNote: $request->input('tax_exemption_note'),
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();
@@ -13,6 +13,13 @@ class TenantContactGetController extends CommonController
return response()->json([
'email' => $this->tenant->email,
'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,
'city' => $this->tenant->city,
'saveEndpoint' => '/api/v1/admin/tenant/contact',
@@ -18,6 +18,11 @@ class TenantContactUpdateController extends CommonController
emailFinance: $request->input('email_finance'),
postcode: $request->input('postcode'),
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();
@@ -18,6 +18,11 @@ class TenantTaxGetController extends CommonController
'tax_exemption_reason' => $this->tenant->tax_exemption_reason,
'tax_exemption_note' => $this->tenant->tax_exemption_note,
'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(),
'pricing_modes' => VatPricingMode::options(),
'saveEndpoint' => '/api/v1/admin/tenant/tax',
@@ -21,6 +21,10 @@ class TenantTaxUpdateController extends CommonController
exemptionReason: TaxExemptionReason::where('slug', $request->input('tax_exemption_reason'))->first(),
exemptionNote: $request->input('tax_exemption_note'),
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();
+18
View File
@@ -1,5 +1,10 @@
<?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\ManagedTenantContactUpdateController;
use App\Domains\Admin\Controllers\ManagedTenantGdprGetController;
@@ -34,6 +39,7 @@ use App\Domains\Admin\Controllers\UserUpdateController;
use App\Middleware\AdminRoleMiddleware;
use App\Middleware\IdentifyTenant;
use App\Middleware\LvOnlyMiddleware;
use App\Middleware\MainAdminRoleMiddleware;
use Illuminate\Support\Facades\Route;
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);
});
// 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::prefix('api/v1/admin/tenants')->group(function () {
Route::get('/list', TenantListApiController::class);
+7
View File
@@ -1,6 +1,7 @@
<?php
use App\Domains\Admin\Controllers\AdminDashboardController;
use App\Domains\Admin\Controllers\DocumentTemplatesPageController;
use App\Domains\Admin\Controllers\TenantEditPageController;
use App\Domains\Admin\Controllers\TenantListPageController;
use App\Domains\Admin\Controllers\TenantPageController;
@@ -8,6 +9,7 @@ use App\Domains\Admin\Controllers\UserListPageController;
use App\Middleware\AdminRoleMiddleware;
use App\Middleware\IdentifyTenant;
use App\Middleware\LvOnlyMiddleware;
use App\Middleware\MainAdminRoleMiddleware;
use Illuminate\Support\Facades\Route;
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('/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::get('/tenants', TenantListPageController::class);
Route::get('/tenants/{slug}', TenantEditPageController::class);
@@ -0,0 +1,618 @@
<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({})
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 data = await request('/api/v1/admin/document-templates', {method: 'GET'})
if (!data) {
toast.error('Die Vorlage konnte nicht geladen werden.')
return
}
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()
}
/** 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: {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({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="Rechnungsvorlage">
<shadowed-box style="width: 95%; margin: 20px auto; padding: 20px;">
<p class="intro">
Die Vorlage gilt für <strong>alle Mandanten</strong>; die eingesetzten Werte kommen je
Rechnung aus dem jeweiligen Mandanten. Sie liegt in der Datenbank und wird von einem
Update nicht überschrieben.
</p>
<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 der Rechnung 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;
}
.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 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({
invoice_sender_name: props.data.invoice_sender_name ?? '',
email: props.data.email ?? '',
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 ?? '',
city: props.data.city ?? '',
})
@@ -39,16 +47,49 @@ async function save() {
<template>
<div v-if="!editing">
<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 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>Ort:</th><td>{{ form.city }}</td></tr>
</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>
</div>
<div v-else>
<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>
<th>Email:</th>
<td><input type="email" v-model="form.email" class="form-input" /></td>
@@ -57,6 +98,27 @@ async function save() {
<th>Email Schatzmeister*in:</th>
<td><input type="email" v-model="form.email_finance" class="form-input" /></td>
</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>
<th>Postleitzahl:</th>
<td><input type="text" v-model="form.postcode" class="form-input" /></td>
@@ -101,6 +163,22 @@ async function save() {
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 {
margin-top: 15px;
padding: 8px 20px;
@@ -29,8 +29,15 @@ const form = ref({
tax_exemption_reason: props.data.tax_exemption_reason ?? '',
tax_exemption_note: props.data.tax_exemption_note ?? '',
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 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_note: form.value.tax_exemption_note,
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>
<td>{{ invoiceHint }}</td>
</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>
<button class="btn-edit" @click="editing = true">Bearbeiten</button>
</div>
@@ -152,6 +174,42 @@ async function save() {
<th>Rechnungshinweis</th>
<td class="hint-preview">{{ invoiceHint }}</td>
</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>
<div class="btn-group">
<button class="btn-save" @click="save">Speichern</button>
@@ -195,6 +253,25 @@ async function save() {
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 {
margin-top: 15px;
padding: 8px 20px;
+3 -14
View File
@@ -2,11 +2,6 @@
use App\Domains\CostUnit\Controllers\CreateController;
use App\Domains\CostUnit\Controllers\ListController;
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 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\EventLocalGroups;
use App\RelationModels\EventPaymentMethods;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
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([
'tenant' => app('tenant')->slug,
'tenant' => $tenant->slug,
'name' => $this->request->name,
'identifier' => Str::random(10),
'location' => $this->request->location,
@@ -49,13 +55,23 @@ class CreateEventCommand {
'support_flat' => 0,
// Umsatzsteuerliche Grundlage bei Anlage einfrieren (unveränderlich), damit Preisermittlung und
// spätere Rechnungen von späteren Tenant-Änderungen unberührt bleiben.
'tax_liable' => app('tenant')->tax_liable,
'vat_rate' => app('tenant')->vat_rate,
'vat_pricing_mode' => app('tenant')->vat_pricing_mode,
'tax_exemption_reason' => app('tenant')->tax_exemption_reason,
'tax_exemption_note' => app('tenant')->tax_exemption_note,
'tax_liable' => $tenant->tax_liable,
'vat_rate' => $tenant->vat_rate,
'vat_pricing_mode' => $tenant->vat_pricing_mode,
'tax_exemption_reason' => $tenant->tax_exemption_reason,
'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) {
EventEatingHabits::create([
'event_id' => $event->id,
@@ -90,4 +106,35 @@ class CreateEventCommand {
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\EventPaymentModules\EventPaymentModuleRegistry;
use App\ValueObjects\Age;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SignUpCommand {
@@ -43,15 +44,21 @@ class SignUpCommand {
$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,
'user_id' => $this->request->user_id,
'identifier' => Str::random(10),
'invoice_sequence' => $this->nextInvoiceSequence(),
'firstname' => $this->request->firstname,
'lastname' => $this->request->lastname,
'nickname' => $this->request->nickname,
'participation_type' => $this->request->participationType,
'fee_type' => $this->request->feeType,
'sibling_reduction' => $this->request->siblingReduction,
'local_group' => $this->request->localGroup->slug,
'birthday' => $this->request->birthday,
'address_1' => $this->request->address_1,
@@ -92,13 +99,38 @@ class SignUpCommand {
]
);
$this->persistParticipationOptions($response->participant, $participationOptionRows);
$this->persistAddons($response->participant);
$this->persistParticipationOptions($participant, $participationOptionRows);
$this->persistAddons($participant);
return $participant;
});
$response->success = true;
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
* Rechnung. Die Beträge sind bereits in der Controller-Auflösung (`resolveAddons`) berechnet, inkl. USt.
@@ -50,6 +50,10 @@ class SignUpRequest {
public array $participationOptions = [],
/** Aufgelöste Zusätze (Event-Addons): je Eintrag [ key, title, price, flat, days, amount ]. */
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['participationOptions'] ?? []),
$addonResolution['items'],
$registrationData['beitrag'],
$siblingReduction,
);
$signupCommand = new SignUpCommand($signupRequest);
@@ -1,7 +1,11 @@
<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 DialableTelephoneNumber from "../../../../Views/Components/DialableTelephoneNumber.vue";
import {useAjax} from "../../../../../resources/js/components/ajaxHandler.js";
const {download} = useAjax();
const staticProps = defineProps({
editMode: Boolean,
@@ -146,6 +150,31 @@ function enableEditMode() {
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() {
emit('saveParticipant', { ...form });
close();
@@ -457,6 +486,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="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 class="button" @click="close">Schließen</button>
@@ -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);
});
});
});
+3 -1
View File
@@ -17,7 +17,9 @@ Route::middleware(IdentifyTenant::class)->group(function () {
route::get('/logout', LogOutController::class);
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::post('/logout', [LogoutController::class, 'logout']);
@@ -156,14 +156,18 @@ abstract class AbstractEventPaymentModule implements EventPaymentModule
/**
* Template-Method: Der gemeinsame Rechnungs-Rumpf wird hier gebaut, der variierende Schlusssatz
* 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
{
$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->closingStatement = $this->invoiceClosingStatement($request);
$response->closingStatement = $request->amount->getAmount() <= 0
? 'Der Betrag ist bereits vollständig beglichen — vielen Dank.'
: $this->invoiceClosingStatement($request);
return $response;
}
@@ -171,6 +175,8 @@ abstract class AbstractEventPaymentModule implements EventPaymentModule
/**
* Der je Zahlungsart variierende Schlusssatz der Rechnung
* ("Bitte überweise bis ..." / "wird abgebucht ..." / "wurde per PayPal beglichen").
*
* Wird nur bei tatsächlich offenem Betrag aufgerufen.
*/
abstract protected function invoiceClosingStatement(CreateInvoiceRequest $request): string;
}
@@ -106,7 +106,24 @@ class AccountTransferPaymentModule extends AbstractEventPaymentModule implements
protected function invoiceClosingStatement(CreateInvoiceRequest $request): string
{
// TODO: In einer Folge-Iteration ausformulieren (z.B. "Bitte überweise bis zum ... auf IBAN ...").
return '';
$config = $request->configuration;
$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
{
return '';
return sprintf(
'Bitte halte den Betrag von %s in bar am ersten Tag der Veranstaltung bereit.',
$request->amount->toString()
);
}
}
@@ -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);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?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';
/** 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 generierte Teil (Positionstabelle, Summen, Schlusssatz) -- nicht editierbar. */
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');
}
}
+2
View File
@@ -45,6 +45,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* @property float $support_flat
* @property int $alcoholics_age
* @property boolean $archived
* @property string|null $invoice_key
*/
class Event extends InstancedModel
{
@@ -90,6 +91,7 @@ class Event extends InstancedModel
'participation_options',
'addons',
'invoice_key',
];
protected $casts = [
+6
View File
@@ -26,12 +26,15 @@ class EventParticipant extends InstancedModel
'event_id',
'user_id',
'identifier',
'invoice_sequence',
'firstname',
'lastname',
'nickname',
'participation_type',
'fee_type',
'sibling_reduction',
'local_group',
'birthday',
@@ -91,6 +94,9 @@ class EventParticipant extends InstancedModel
'amount' => AmountCast::class,
'amount_paid' => AmountCast::class,
'payment_options' => 'array',
'invoice_sequence' => 'integer',
'sibling_reduction' => 'boolean',
];
/*
+38
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Scopes\CommonModel;
use App\Support\Text;
/**
* @property string $slug
@@ -12,6 +13,14 @@ use App\Scopes\CommonModel;
* @property string $account_name
* @property string $account_iban
* @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 $postcode
* @property boolean $download_exports
@@ -29,16 +38,42 @@ use App\Scopes\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 {
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';
protected $fillable = [
'slug',
'name',
'invoice_sender_name',
'address_1',
'address_2',
'address_3',
'email',
'email_finance',
'phone',
'url',
'account_name',
'account_iban',
@@ -57,6 +92,9 @@ class Tenant extends CommonModel
'tax_exemption_reason',
'tax_exemption_note',
'vat_pricing_mode',
'tax_number',
'vat_id',
'invoice_prefix',
];
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] ?? '';
}
}
+5
View File
@@ -23,10 +23,14 @@ class GlobalDataProvider {
$this->user = auth()->user();
$canAccessAdmin = false;
$isMainAdmin = false;
if (null !== $this->user) {
$authCheck = new AuthCheckProvider();
$effectiveRole = $authCheck->getUserRole();
$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([
@@ -37,6 +41,7 @@ class GlobalDataProvider {
'version' => config('app.version'),
'currentEvent' => $this->getCurrentEventData(),
'canAccessAdmin' => $canAccessAdmin,
'isMainAdmin' => $isMainAdmin,
]);
}
@@ -71,6 +71,9 @@ class EventParticipantResource extends JsonResource
'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'],
'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,
'alcoholicsAllowed' => new Age($this->resource->birthday)->getAge() >= $event->alcoholics_age,
'localGroupPostcode' => $this->resource->localGroup()->first()?->postcode ?? '00000',
'localGroupCity' => $this->resource->localGroup()->first()?->city ?? '00000',
+4 -4
View File
@@ -6,6 +6,7 @@ use App\Enumerations\ParticipationFeeType;
use App\Enumerations\ParticipationType;
use App\Enumerations\VatPricingMode;
use App\Models\Event;
use App\Support\DateRange;
use App\ValueObjects\Amount;
use DateTime;
use Illuminate\Http\Request;
@@ -20,7 +21,7 @@ class EventResource extends JsonResource{
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 = [
'id' => $this->event->id,
@@ -352,8 +353,7 @@ class EventResource extends JsonResource{
$basicFee = $basicFee->multiply($this->getMultiplier());
if ($this->event->pay_per_day) {
$days = $arrival->diff($departure)->days + 1;
$basicFee = $basicFee->multiply($days);
$basicFee = $basicFee->multiply(DateRange::inclusiveDays($arrival, $departure));
}
if ($hasSibling && $this->event->sibling_reduction) {
@@ -380,7 +380,7 @@ class EventResource extends JsonResource{
*/
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;
$items = [];
+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;
}
}
+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>
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()
</script>
@@ -19,7 +32,7 @@ const model = defineModel()
language: 'de',
language_url: '/tinymce/langs/de.js',
ui_mode: 'split',
convert_urls: props.convertUrls,
}"
/>
</template>
@@ -1,20 +1,28 @@
<?php
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
* 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 {
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
{
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();
}
});
}
};
@@ -0,0 +1,42 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
/**
* Entfernt die Trenner zwischen Jahr, Monat und Veranstaltungsnummer im Rechnungsschlüssel.
*
* vorher WM-V-2026-07-01 -> Rechnungsnummer WM-V-2026-07-01-0005
* nachher WM-V-20260701 -> Rechnungsnummer WM-V-20260701-0005
*
* Die Rechnungsnummer selbst wird nirgends gespeichert, sondern bei jedem Abruf aus `invoice_key`
* und `event_participants.invoice_sequence` zusammengesetzt. Die Umstellung hier wirkt daher
* unmittelbar auf alle Rechnungen; alte und neue Veranstaltungen bleiben im selben Format.
*/
return new class extends Migration {
public function up(): void
{
$this->rewrite('/^(.*-V-)(\d{4})-(\d{2})-(\d{2})$/', '$1$2$3$4');
}
public function down(): void
{
$this->rewrite('/^(.*-V-)(\d{4})(\d{2})(\d{2})$/', '$1$2-$3-$4');
}
private function rewrite(string $pattern, string $replacement): void
{
$events = DB::table('events')
->select('id', 'invoice_key')
->whereNotNull('invoice_key')
->get();
foreach ($events as $event) {
$rewritten = preg_replace($pattern, $replacement, (string) $event->invoice_key);
if ($rewritten !== null && $rewritten !== $event->invoice_key) {
DB::table('events')->where('id', $event->id)->update(['invoice_key' => $rewritten]);
}
}
}
};
File diff suppressed because one or more lines are too long
+5
View File
@@ -113,6 +113,11 @@ const props = defineProps({
<a href="/admin/users" @click="closeSidebar">Benutzer*innen</a>
</li>
</ul>
<ul class="nav-links" v-if="globalProps.isMainAdmin">
<li>
<a href="/admin/document-templates" @click="closeSidebar">Rechnungsvorlage</a>
</li>
</ul>
</nav>
</div>
+18
View File
@@ -0,0 +1,18 @@
{{--
Dünnes Gerüst für aus der Datenbank zusammengesetzte Dokumente. Enthält bewusst kein Layout --
das steckt in den Vorlagenblöcken (`document_templates`), damit ein Release es nicht überschreibt.
$style und $content sind bereits fertig ersetztes HTML aus dem DocumentTemplateRenderProvider und
werden hier nur ausgegeben, nicht als Blade ausgewertet.
--}}
<!DOCTYPE html>
<html lang="de">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>{{ $title }}</title>
<style>{!! $style !!}</style>
</head>
<body>
{!! $content !!}
</body>
</html>
+20 -15
View File
@@ -11,21 +11,26 @@ use App\Providers\GlobalDataProvider;
use Illuminate\Support\Facades\Route;
require_once __DIR__ . '/../app/Domains/Dashboard/Routes/web.php';
require_once __DIR__ . '/../app/Domains/Dashboard/Routes/api.php';
require_once __DIR__ . '/../app/Domains/UserManagement/Routes/web.php';
require_once __DIR__ . '/../app/Domains/UserManagement/Routes/api.php';
require_once __DIR__ . '/../app/Domains/CostUnit/Routes/web.php';
require_once __DIR__ . '/../app/Domains/CostUnit/Routes/api.php';
require_once __DIR__ . '/../app/Domains/Invoice/Routes/web.php';
require_once __DIR__ . '/../app/Domains/Invoice/Routes/api.php';
require_once __DIR__ . '/../app/Domains/Event/Routes/web.php';
require_once __DIR__ . '/../app/Domains/Event/Routes/api.php';
require_once __DIR__ . '/../app/Domains/Budget/Routes/web.php';
require_once __DIR__ . '/../app/Domains/Budget/Routes/api.php';
require_once __DIR__ . '/../app/Domains/Legal/Routes/web.php';
require_once __DIR__ . '/../app/Domains/Admin/Routes/web.php';
require_once __DIR__ . '/../app/Domains/Admin/Routes/api.php';
// Bewusst `require` und nicht `require_once`: Diese Datei wird einmal pro Anfrage geladen, in der
// Testsuite aber einmal je Test (die Anwendung wird zwischen Tests neu aufgebaut). Mit `require_once`
// wäre die zweite Registrierung ein No-op und ab dem zweiten Test einer Klasse fehlten sämtliche
// Domain-Routen -- jeder HTTP-Test liefe dann in einen 404.
require __DIR__ . '/../app/Domains/Dashboard/Routes/web.php';
require __DIR__ . '/../app/Domains/Dashboard/Routes/api.php';
require __DIR__ . '/../app/Domains/UserManagement/Routes/web.php';
require __DIR__ . '/../app/Domains/UserManagement/Routes/api.php';
require __DIR__ . '/../app/Domains/CostUnit/Routes/web.php';
require __DIR__ . '/../app/Domains/CostUnit/Routes/api.php';
require __DIR__ . '/../app/Domains/Invoice/Routes/web.php';
require __DIR__ . '/../app/Domains/Invoice/Routes/api.php';
require __DIR__ . '/../app/Domains/Event/Routes/web.php';
require __DIR__ . '/../app/Domains/Event/Routes/api.php';
require __DIR__ . '/../app/Domains/ParticipantInvoice/Routes/api.php';
require __DIR__ . '/../app/Domains/Budget/Routes/web.php';
require __DIR__ . '/../app/Domains/Budget/Routes/api.php';
require __DIR__ . '/../app/Domains/Legal/Routes/web.php';
require __DIR__ . '/../app/Domains/Admin/Routes/web.php';
require __DIR__ . '/../app/Domains/Admin/Routes/api.php';
Route::get('/LKvDUqWl', function () {
+215
View File
@@ -0,0 +1,215 @@
<?php
namespace Tests\Feature;
use App\Enumerations\UserRole;
use App\Models\DocumentAsset;
use App\Models\DocumentTemplate;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
/**
* Die Vorlagen gelten app-weit für alle Mandanten -- Zugriff deshalb nur für Hauptadministrator*innen.
*/
class DocumentTemplateAdminTest extends TestCase
{
use RefreshDatabase;
private Tenant $tenant;
protected function setUp(): void
{
parent::setUp();
// Bewusst kein LV-Tenant: dort leitet AuthCheckProvider die Rolle aus `user_role_main` ab, sodass
// sich eine Gruppenleitung gar nicht erst darstellen ließe.
$this->tenant = Tenant::create([
'slug' => 'wm',
'name' => 'Wilde Möhre',
'email' => 'wm@example.com',
'email_finance' => 'wm-f@example.com',
'url' => parse_url(config('app.url'), PHP_URL_HOST),
'account_name' => 'Wilde Möhre e.V.',
'account_iban' => 'DE00',
'account_bic' => 'XY',
'city' => 'Stadt',
'postcode' => '00000',
'is_active_local_group' => true,
'has_active_instance' => true,
]);
app()->instance('tenant', $this->tenant);
// `users.user_role_main` und `user_role_local_group` sind Fremdschlüssel auf `user_roles`.
foreach ([UserRole::USER_ROLE_ADMIN, UserRole::USER_ROLE_GROUP_LEADER, UserRole::USER_ROLE_USER] as $role) {
UserRole::create(['slug' => $role, 'name' => $role]);
}
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => DocumentTemplate::BLOCK_LAYOUT,
'content' => '<div>{block:footer}</div>',
'sort_order' => 10,
]);
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => 'footer',
'content' => 'alt',
'sort_order' => 20,
]);
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => DocumentTemplate::BLOCK_BODY,
'content' => '{positions_table}',
'sort_order' => 30,
'editable' => false,
]);
}
private function makeUser(string $mainRole, string $localRole = UserRole::USER_ROLE_USER): User
{
return User::create([
'username' => $mainRole . '-' . uniqid() . '@example.com',
'email' => $mainRole . '-' . uniqid() . '@example.com',
'firstname' => 'Test',
'lastname' => 'Person',
'password' => bcrypt('secret'),
'local_group' => $this->tenant->slug,
'user_role_main' => $mainRole,
'user_role_local_group' => $localRole,
'active' => true,
]);
}
public function test_group_leaders_cannot_reach_the_templates(): void
{
$this->actingAs($this->makeUser(UserRole::USER_ROLE_USER, UserRole::USER_ROLE_GROUP_LEADER));
$this->get('/admin/document-templates')->assertRedirect('/admin');
$this->getJson('/api/v1/admin/document-templates')->assertRedirect('/admin');
}
public function test_main_administrators_can_read_the_templates(): void
{
$this->actingAs($this->makeUser(UserRole::USER_ROLE_ADMIN));
$response = $this->getJson('/api/v1/admin/document-templates');
$response->assertOk();
$response->assertJsonPath('blocks.1.block', 'footer');
$response->assertJsonPath('blocks.1.editable', true);
// Der generierte Block wird angezeigt, aber als nicht editierbar gekennzeichnet.
$response->assertJsonPath('blocks.2.editable', false);
}
public function test_saving_leaves_generated_blocks_untouched(): void
{
$this->actingAs($this->makeUser(UserRole::USER_ROLE_ADMIN));
$this->postJson('/api/v1/admin/document-templates', [
'blocks' => [
'footer' => 'neu',
DocumentTemplate::BLOCK_BODY => 'manipuliert',
'gibtesnicht' => 'egal',
],
])->assertOk()->assertJsonPath('status', 'success');
$blocks = DocumentTemplate::forType(DocumentTemplate::TYPE_PARTICIPANT_INVOICE);
$this->assertSame('neu', $blocks['footer']->content);
$this->assertSame('{positions_table}', $blocks[DocumentTemplate::BLOCK_BODY]->content);
}
public function test_a_bare_asset_placeholder_in_the_css_is_refused(): void
{
$this->actingAs($this->makeUser(UserRole::USER_ROLE_ADMIN));
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => DocumentTemplate::BLOCK_STYLE,
'content' => '.a { color: red; }',
'sort_order' => 15,
]);
$response = $this->postJson('/api/v1/admin/document-templates', [
'blocks' => [
DocumentTemplate::BLOCK_STYLE => '.a { color: red; }{asset:logo}',
'footer' => 'neu',
],
]);
$response->assertOk()->assertJsonPath('status', 'error');
$this->assertStringContainsString('url("{asset:logo}")', $response->json('message'));
// Nichts gespeichert -- auch nicht der unbedenkliche Block.
$blocks = DocumentTemplate::forType(DocumentTemplate::TYPE_PARTICIPANT_INVOICE);
$this->assertSame('.a { color: red; }', $blocks[DocumentTemplate::BLOCK_STYLE]->content);
$this->assertSame('alt', $blocks['footer']->content);
}
public function test_an_asset_inside_url_is_accepted_in_the_css(): void
{
$this->actingAs($this->makeUser(UserRole::USER_ROLE_ADMIN));
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => DocumentTemplate::BLOCK_STYLE,
'content' => '',
'sort_order' => 15,
]);
$this->postJson('/api/v1/admin/document-templates', [
'blocks' => [DocumentTemplate::BLOCK_STYLE => '.a { background: url("{asset:logo}"); }'],
])->assertOk()->assertJsonPath('status', 'success');
$this->assertStringContainsString(
'url("{asset:logo}")',
DocumentTemplate::where('block', DocumentTemplate::BLOCK_STYLE)->first()->content
);
}
public function test_preview_renders_unsaved_content(): void
{
$this->actingAs($this->makeUser(UserRole::USER_ROLE_ADMIN));
$response = $this->post('/api/v1/admin/document-templates/preview', [
'blocks' => ['footer' => 'noch nicht gespeichert'],
]);
$response->assertOk();
$response->assertHeader('Content-Type', 'application/pdf');
// Der gespeicherte Stand bleibt unberührt.
$this->assertSame('alt', DocumentTemplate::where('block', 'footer')->first()->content);
}
public function test_assets_still_used_in_the_template_are_kept(): void
{
$this->actingAs($this->makeUser(UserRole::USER_ROLE_ADMIN));
DocumentAsset::create(['name' => 'logo', 'mime' => 'image/png', 'data' => 'QUJD']);
DocumentTemplate::where('block', 'footer')->update(['content' => '<img src="{asset:logo}" />']);
$this->deleteJson('/api/v1/admin/document-templates/assets/logo')
->assertOk()
->assertJsonPath('status', 'error');
$this->assertNotNull(DocumentAsset::where('name', 'logo')->first());
}
public function test_unused_assets_can_be_deleted(): void
{
$this->actingAs($this->makeUser(UserRole::USER_ROLE_ADMIN));
DocumentAsset::create(['name' => 'altbestand', 'mime' => 'image/png', 'data' => 'QUJD']);
$this->deleteJson('/api/v1/admin/document-templates/assets/altbestand')
->assertOk()
->assertJsonPath('status', 'success');
$this->assertNull(DocumentAsset::where('name', 'altbestand')->first());
}
}
+26 -8
View File
@@ -2,18 +2,36 @@
namespace Tests\Feature;
// use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
use RefreshDatabase;
$response->assertStatus(200);
/**
* Rauchtest über den Anfrage-Stack: die Anwendung ist mandantenfähig, ohne passenden Tenant zum Host
* beantwortet {@see \App\Middleware\IdentifyTenant} jede Anfrage mit 404. Mit passendem Tenant kommt
* die Anfrage durch und wird als Gast erwartungsgemäß zum Login geleitet.
*/
public function test_the_application_redirects_guests_to_the_login(): void
{
Tenant::create([
'slug' => 'tv',
'name' => 'Test',
'email' => 't@example.com',
'email_finance' => 'finance@example.com',
'url' => parse_url(config('app.url'), PHP_URL_HOST),
'account_name' => 'Test e.V.',
'account_iban' => 'DE00',
'account_bic' => 'XY',
'city' => 'Stadt',
'postcode' => '00000',
'is_active_local_group' => true,
'has_active_instance' => true,
]);
$this->get('/')->assertRedirect('/login');
}
}
+215
View File
@@ -0,0 +1,215 @@
<?php
namespace Tests\Feature;
use App\Domains\Event\Actions\CreateEvent\CreateEventCommand;
use App\Domains\Event\Actions\CreateEvent\CreateEventRequest;
use App\Domains\Event\Actions\SignUp\SignUpCommand;
use App\Domains\Event\Actions\SignUp\SignUpRequest;
use App\Enumerations\EatingHabit;
use App\Enumerations\EfzStatus;
use App\Enumerations\FirstAidPermission;
use App\Enumerations\ParticipationFeeType;
use App\Enumerations\ParticipationType;
use App\Enumerations\SwimmingPermission;
use App\Models\Event;
use App\Models\PaymentMethod;
use App\Models\Tenant;
use App\ValueObjects\Amount;
use DateTime;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
/**
* Die Rechnungsnummer wird nirgends gespeichert, sondern aus `events.invoice_key` und
* `event_participants.invoice_sequence` zusammengesetzt. Beide Bausteine müssen deshalb stabil sein.
*/
class InvoiceNumberingTest extends TestCase
{
use RefreshDatabase;
private Tenant $wildeMoehre;
protected function setUp(): void
{
parent::setUp();
$this->wildeMoehre = $this->makeTenant('wm', 'Wilde Möhre');
DB::table('participation_fee_types')->insert(['slug' => 'fixed', 'name' => 'Fix']);
EatingHabit::create(['slug' => EatingHabit::EATING_HABIT_VEGAN, 'name' => 'Vegan']);
EatingHabit::create(['slug' => EatingHabit::EATING_HABIT_VEGETARIAN, 'name' => 'Vegetarisch']);
ParticipationType::create(['slug' => ParticipationType::PARTICIPATION_TYPE_PARTICIPANT, 'name' => 'Teilnehmende']);
PaymentMethod::create(['slug' => PaymentMethod::PAYMENT_ACCOUNT_TRANSACTION]);
EfzStatus::create(['slug' => EfzStatus::EFZ_STATUS_NOT_CHECKED, 'name' => 'Nicht geprüft']);
EfzStatus::create(['slug' => EfzStatus::EFZ_STATUS_NOT_REQUIRED, 'name' => 'Nicht erforderlich']);
SwimmingPermission::create(['slug' => SwimmingPermission::SWIMMING_PERMISSION_ALLOWED, 'name' => 'Darf baden', 'short' => 'Erteilt']);
FirstAidPermission::create(['slug' => FirstAidPermission::FIRST_AID_PERMISSION_ALLOWED, 'name' => 'Zugestimmt', 'description' => '']);
app()->instance('tenant', $this->wildeMoehre);
}
/**
* `create()` liefert nur die übergebenen Attribute zurück; die DB-Defaults (u.a. `tax_liable`) stehen
* erst nach dem Neuladen bereit -- so, wie der Tenant im Betrieb aus der IdentifyTenant-Middleware kommt.
*/
private function makeTenant(string $slug, string $name): Tenant
{
return Tenant::create([
'slug' => $slug,
'name' => $name,
'address_1' => 'Musterweg 1',
'email' => $slug . '@example.com',
'email_finance' => $slug . '-f@example.com',
'url' => $slug . '.test.local',
'account_name' => $name,
'account_iban' => 'DE00',
'account_bic' => 'XY',
'city' => 'Stadt',
'postcode' => '00000',
'invoice_prefix' => strtoupper($slug),
'is_active_local_group' => true,
'has_active_instance' => true,
])->fresh();
}
private function createEvent(string $begin, string $name = 'Lager'): Event
{
$response = new CreateEventCommand(new CreateEventRequest(
name: $name,
location: 'Ort',
postalCode: '00000',
email: 'e@example.com',
begin: new DateTime($begin),
end: new DateTime($begin),
earlyBirdEnd: new DateTime('2026-01-01'),
registrationFinalEnd: new DateTime('2026-01-02'),
earlyBirdEndAmountIncrease: 0,
participationFeeType: ParticipationFeeType::where('slug', 'fixed')->first(),
accountOwner: 'Owner',
accountIban: 'DE00',
payPerDay: false,
))->execute();
$this->assertTrue($response->success);
return $response->event->fresh();
}
/*
|--------------------------------------------------------------------------
| Event-Teil der Nummer
|--------------------------------------------------------------------------
*/
public function test_events_of_the_same_month_are_numbered_consecutively(): void
{
$this->assertSame('WM-V-20260701', $this->createEvent('2026-07-16')->invoice_key);
$this->assertSame('WM-V-20260702', $this->createEvent('2026-07-24')->invoice_key);
// Anderer Monat, eigene Zählung.
$this->assertSame('WM-V-20260801', $this->createEvent('2026-08-03')->invoice_key);
}
public function test_each_tenant_counts_for_itself(): void
{
$this->createEvent('2026-07-16');
app()->instance('tenant', $this->makeTenant('sn', 'Sachsen'));
$this->assertSame('SN-V-20260701', $this->createEvent('2026-07-18')->invoice_key);
}
public function test_invoice_key_survives_moving_the_event_to_another_month(): void
{
$event = $this->createEvent('2026-07-16');
$event->update(['start_date' => '2026-11-05', 'end_date' => '2026-11-07']);
// Eingefroren: eine bereits herausgegebene Rechnung gehört sonst plötzlich zu einer anderen Nummer.
$this->assertSame('WM-V-20260701', $event->fresh()->invoice_key);
}
public function test_new_tenants_default_to_their_uppercased_slug(): void
{
$tenant = Tenant::create([
'slug' => 'fen',
'name' => 'Fen',
'email' => 'fen@example.com',
'email_finance' => 'fen-f@example.com',
'url' => 'fen.test.local',
'account_name' => 'Fen',
'account_iban' => 'DE00',
'account_bic' => 'XY',
'city' => 'Stadt',
'postcode' => '00000',
'is_active_local_group' => true,
'has_active_instance' => true,
])->fresh();
// Ohne gesetztes Präfix greift der Migrations-Default: der großgeschriebene Slug.
$this->assertSame('FEN', $tenant->invoice_prefix);
app()->instance('tenant', $tenant);
$this->assertSame('FEN-V-20260701', $this->createEvent('2026-07-16')->invoice_key);
}
/*
|--------------------------------------------------------------------------
| Teilnehmer-Teil der Nummer
|--------------------------------------------------------------------------
*/
private function signUp(Event $event, string $firstname): void
{
$response = new SignUpCommand(new SignUpRequest(
$event, null, $firstname, 'Muster', null, ParticipationType::PARTICIPATION_TYPE_PARTICIPANT,
$this->wildeMoehre, new DateTime('2000-01-01'), 'Weg 1', null, '00000', 'Stadt',
strtolower($firstname) . '@example.com', '123', null, null, null, null, null, null, null,
'vegan', null, null, false, false, false, false, false,
new DateTime('2026-07-16'), new DateTime('2026-07-16'), 0, 0, null,
new Amount(50.0, 'Euro'), PaymentMethod::PAYMENT_ACCOUNT_TRANSACTION,
))->execute();
$this->assertTrue($response->success, $response->message ?? '');
}
public function test_sequences_are_handed_out_in_order(): void
{
$event = $this->createEvent('2026-07-16');
$this->signUp($event, 'Ada');
$this->signUp($event, 'Bo');
$this->signUp($event, 'Cem');
$this->assertSame([1, 2, 3], $event->participants()->orderBy('id')->pluck('invoice_sequence')->all());
}
public function test_signing_off_does_not_shift_later_sequences(): void
{
$event = $this->createEvent('2026-07-16');
$this->signUp($event, 'Ada');
$this->signUp($event, 'Bo');
// Abmeldung: der Datensatz bleibt bestehen, die Nummer damit vergeben.
$event->participants()->orderBy('id')->first()->update(['unregistered_at' => '2026-07-01']);
$this->signUp($event, 'Cem');
$this->assertSame(3, $event->participants()->orderBy('id')->get()->last()->invoice_sequence);
}
public function test_sequences_are_per_event(): void
{
$first = $this->createEvent('2026-07-16', 'Erstes');
$second = $this->createEvent('2026-07-24', 'Zweites');
$this->signUp($first, 'Ada');
$this->signUp($second, 'Bo');
$this->assertSame(1, $first->participants()->first()->invoice_sequence);
$this->assertSame(1, $second->participants()->first()->invoice_sequence);
}
}
+630
View File
@@ -0,0 +1,630 @@
<?php
namespace Tests\Feature;
use App\Domains\ParticipantInvoice\Actions\CreateParticipantInvoice\CreateParticipantInvoiceCommand;
use App\Domains\ParticipantInvoice\Actions\CreateParticipantInvoice\CreateParticipantInvoiceRequest;
use App\Domains\ParticipantInvoice\ParticipantInvoiceTokens;
use App\Enumerations\EfzStatus;
use App\Enumerations\TaxExemptionReason;
use App\Enumerations\UserRole;
use App\Models\DocumentAsset;
use App\Models\DocumentTemplate;
use App\Models\Event;
use App\Models\EventParticipant;
use App\Models\PaymentMethod;
use App\Models\Tenant;
use App\Models\User;
use App\Providers\DocumentTemplateRenderProvider;
use App\RelationModels\EventParticipationFee;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use ReflectionMethod;
use Tests\TestCase;
class ParticipantInvoiceTest extends TestCase
{
use RefreshDatabase;
private Tenant $tenant;
protected function setUp(): void
{
parent::setUp();
$this->tenant = Tenant::create([
'slug' => 'wm',
'name' => 'Wilde Möhre',
'address_1' => 'Musterweg 1',
'email' => 't@example.com',
'email_finance' => 'finance@example.com',
// Muss dem Host der Testanfragen entsprechen, sonst weist IdentifyTenant sie mit 404 ab.
'url' => parse_url(config('app.url'), PHP_URL_HOST),
'account_name' => 'Test e.V.',
'account_iban' => 'DE00',
'account_bic' => 'XY',
'city' => 'Stadt',
'postcode' => '00000',
'invoice_prefix' => 'WM',
'is_active_local_group' => true,
'has_active_instance' => true,
]);
app()->instance('tenant', $this->tenant);
DB::table('participation_types')->insert(['slug' => 'participant', 'name' => 'Teilnehmer']);
DB::table('participation_fee_types')->insert(['slug' => 'fixed', 'name' => 'Fix']);
PaymentMethod::create(['slug' => PaymentMethod::PAYMENT_ACCOUNT_TRANSACTION]);
PaymentMethod::create(['slug' => PaymentMethod::PAYMENT_NOT_DEFINED]);
EfzStatus::create(['slug' => EfzStatus::EFZ_STATUS_NOT_REQUIRED, 'name' => 'Nicht erforderlich']);
$this->seedTemplate();
}
/** Minimale Vorlage: alles, was die Tests brauchen, in einem Block. */
private function seedTemplate(): void
{
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => DocumentTemplate::BLOCK_LAYOUT,
'content' => '<div>{block:subject}{block:body}</div>',
'sort_order' => 10,
]);
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => DocumentTemplate::BLOCK_STYLE,
'content' => 'body { font-size: 10pt; }',
'sort_order' => 20,
]);
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => 'subject',
'content' => '<h1>Rechnung {invoice_number}</h1><p>{invoice_date} / {service_period}</p>',
'sort_order' => 30,
]);
DocumentTemplate::create([
'document_type' => DocumentTemplate::TYPE_PARTICIPANT_INVOICE,
'block' => DocumentTemplate::BLOCK_BODY,
'content' => '{positions_table}{summary_table}<div>{closing_statement}</div>',
'sort_order' => 40,
'editable' => false,
]);
}
private function makeEvent(array $attributes = []): Event
{
$fee = EventParticipationFee::create([
'tenant' => $this->tenant->slug,
'type' => 'participant',
'name' => 'Sippe',
'description' => null,
'amount_standard' => 60.0,
'amount_reduced' => null,
'amount_solidarity' => null,
]);
return Event::create(array_merge([
'tenant' => $this->tenant->slug,
'name' => 'Sommerlager',
'identifier' => 'evt-' . uniqid(),
'location' => 'Ort',
'postal_code' => '00000',
'email' => 'e@example.com',
'start_date' => '2026-07-16',
'end_date' => '2026-07-20',
'early_bird_end' => '2026-06-20',
'registration_final_end' => '2026-07-01',
'early_bird_end_amount_increase' => 0,
'account_owner' => 'Owner',
'account_iban' => 'DE00',
'participation_fee_type' => 'fixed',
'participation_fee_1' => $fee->id,
'pay_per_day' => true,
'pay_direct' => false,
'tax_liable' => false,
'vat_rate' => 0,
'vat_pricing_mode' => 'inclusive',
'invoice_key' => 'WM-V-20260701',
], $attributes));
}
private function makeParticipant(Event $event, array $attributes = []): EventParticipant
{
return $event->participants()->create(array_merge([
'tenant' => $this->tenant->slug,
'identifier' => 'p-' . uniqid(),
'invoice_sequence' => 5,
'firstname' => 'Mika',
'lastname' => 'Muster',
'participation_type' => 'participant',
'fee_type' => 'standard',
'sibling_reduction' => false,
'local_group' => $this->tenant->slug,
'birthday' => '2000-01-01',
'address_1' => 'Beispielstraße 3',
'postcode' => '11111',
'city' => 'Beispielstadt',
'email_1' => 'mika@example.com',
'phone_1' => '0170 0000000',
'arrival_date' => '2026-07-16',
'departure_date' => '2026-07-20',
'arrival_eating' => 1,
'departure_eating' => 1,
'amount' => 300.0,
'payment_purpose' => 'Sommerlager',
'payment_method' => PaymentMethod::PAYMENT_ACCOUNT_TRANSACTION,
'efz_status' => EfzStatus::EFZ_STATUS_NOT_REQUIRED,
], $attributes));
}
/** @return array<int, array<string, mixed>> */
private function lines(EventParticipant $participant): array
{
$command = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant));
return new ReflectionMethod($command, 'buildLines')->invoke($command);
}
/*
|--------------------------------------------------------------------------
| Positionen
|--------------------------------------------------------------------------
*/
public function test_fee_line_is_derived_from_amount_and_split_per_day(): void
{
$lines = $this->lines($this->makeParticipant($this->makeEvent()));
$this->assertCount(1, $lines);
$this->assertSame('Teilnahme Sommerlager in Gruppe Sippe (Standardbeitrag)', $lines[0]['description']);
$this->assertSame(5.0, $lines[0]['quantity']);
$this->assertEqualsWithDelta(60.0, $lines[0]['unitPrice'], 0.001);
$this->assertEqualsWithDelta(300.0, $lines[0]['amount'], 0.001);
}
public function test_addons_are_own_lines_and_reduce_the_fee_share(): void
{
$event = $this->makeEvent();
$participant = $this->makeParticipant($event, ['amount' => 345.0]);
$participant->selectedAddons()->create([
'tenant' => $this->tenant->slug,
'event_id' => $event->id,
'addon_key' => 'shirt',
'title' => 'T-Shirt',
'price' => 45.0,
'flat' => true,
'days' => 1,
'amount' => 45.0,
]);
$lines = $this->lines($participant->fresh());
$this->assertCount(2, $lines);
// Beitragsanteil = amount - Zusätze, nicht neu berechnet.
$this->assertEqualsWithDelta(300.0, $lines[0]['amount'], 0.001);
$this->assertSame('T-Shirt', $lines[1]['description']);
$this->assertEqualsWithDelta(45.0, $lines[1]['amount'], 0.001);
$this->assertEqualsWithDelta(345.0, array_sum(array_column($lines, 'amount')), 0.001);
}
public function test_sibling_reduction_shows_full_day_rate_and_a_discount_line(): void
{
$participant = $this->makeParticipant($this->makeEvent(), [
'sibling_reduction' => true,
'amount' => 150.0,
]);
$lines = $this->lines($participant);
$this->assertCount(2, $lines);
// Der ausgewiesene Tagessatz ist der echte (60 €), nicht der halbierte.
$this->assertEqualsWithDelta(60.0, $lines[0]['unitPrice'], 0.001);
$this->assertEqualsWithDelta(300.0, $lines[0]['amount'], 0.001);
$this->assertSame('Geschwisterermäßigung 50 %', $lines[1]['description']);
$this->assertEqualsWithDelta(-150.0, $lines[1]['amount'], 0.001);
// Die Summe bleibt der tatsächlich zu zahlende Betrag.
$this->assertEqualsWithDelta(150.0, array_sum(array_column($lines, 'amount')), 0.001);
}
public function test_legacy_registration_without_fee_type_still_adds_up(): void
{
$participant = $this->makeParticipant($this->makeEvent(), [
'fee_type' => null,
'sibling_reduction' => false,
]);
$lines = $this->lines($participant);
$this->assertSame('Teilnahme Sommerlager in Gruppe Sippe', $lines[0]['description']);
$this->assertEqualsWithDelta(300.0, array_sum(array_column($lines, 'amount')), 0.001);
}
public function test_uneven_day_rate_falls_back_to_a_single_line(): void
{
// 637,50 auf 4 Tage ergibt 159,375 -- gerundet würde 4 x 159,38 = 637,52 ergeben. Eine Rechnung,
// die sich nicht nachrechnen lässt, wäre unbrauchbar, also entfällt die Aufteilung.
$participant = $this->makeParticipant($this->makeEvent(), [
'amount' => 637.5,
'departure_date' => '2026-07-19',
]);
$lines = $this->lines($participant);
$this->assertSame(1.0, $lines[0]['quantity']);
$this->assertEqualsWithDelta(637.5, $lines[0]['unitPrice'], 0.001);
$this->assertEqualsWithDelta(637.5, $lines[0]['amount'], 0.001);
}
/*
|--------------------------------------------------------------------------
| Umsatzsteuer
|--------------------------------------------------------------------------
*/
/** @return array{net: float, vat: float} */
private function splitVat(EventParticipant $participant, float $gross): array
{
$command = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant));
return new ReflectionMethod($command, 'splitVat')->invoke($command, $gross);
}
public function test_vat_is_extracted_identically_in_both_pricing_modes(): void
{
$inclusive = $this->makeParticipant($this->makeEvent([
'tax_liable' => true,
'vat_rate' => 19,
'vat_pricing_mode' => 'inclusive',
]));
$addOn = $this->makeParticipant($this->makeEvent([
'tax_liable' => true,
'vat_rate' => 19,
'vat_pricing_mode' => 'add_on',
'invoice_key' => 'WM-V-20260702',
]));
// Gespeichert ist immer der finale Brutto-Betrag -- für die Rechnung spielt der Preismodus
// deshalb keine Rolle mehr.
$this->assertEquals($this->splitVat($inclusive, 119.0), $this->splitVat($addOn, 119.0));
$this->assertEqualsWithDelta(19.0, $this->splitVat($inclusive, 119.0)['vat'], 0.001);
$this->assertEqualsWithDelta(100.0, $this->splitVat($inclusive, 119.0)['net'], 0.001);
}
public function test_without_tax_liability_no_vat_is_shown_but_the_legal_note_is(): void
{
// Die Befreiungsgründe kommen bereits aus der Migration, inklusive ihres Pflichthinweises.
$reason = TaxExemptionReason::find(TaxExemptionReason::USTG_4_25A);
$participant = $this->makeParticipant($this->makeEvent([
'tax_liable' => false,
'tax_exemption_reason' => $reason->slug,
]));
$command = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant));
$summary = new ReflectionMethod($command, 'renderSummary')->invoke($command, 300.0);
$this->assertStringNotContainsString('USt.', $summary);
$this->assertStringContainsString($reason->invoice_text, $summary);
}
/*
|--------------------------------------------------------------------------
| Zahlungs-Schlusssatz
|--------------------------------------------------------------------------
*/
private function closingStatement(EventParticipant $participant): string
{
$command = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant));
return new ReflectionMethod($command, 'closingStatement')->invoke($command);
}
public function test_open_amount_is_requested_by_transfer(): void
{
$statement = $this->closingStatement($this->makeParticipant($this->makeEvent()));
$this->assertStringContainsString('Bitte überweise', $statement);
}
public function test_cash_payment_asks_for_the_amount_on_site(): void
{
$participant = $this->makeParticipant($this->makeEvent(), [
'payment_method' => PaymentMethod::PAYMENT_NOT_DEFINED,
]);
$this->assertStringContainsString(
'in bar am ersten Tag der Veranstaltung bereit',
$this->closingStatement($participant)
);
}
public function test_fully_paid_participant_is_not_asked_to_pay_again(): void
{
$participant = $this->makeParticipant($this->makeEvent(), ['amount_paid' => 300.0]);
$statement = $this->closingStatement($participant);
$this->assertStringContainsString('bereits vollständig beglichen', $statement);
$this->assertStringNotContainsString('Bitte überweise', $statement);
}
/*
|--------------------------------------------------------------------------
| Rechnungsnummer und Dokument
|--------------------------------------------------------------------------
*/
public function test_invoice_number_is_deterministic(): void
{
$participant = $this->makeParticipant($this->makeEvent(), ['invoice_sequence' => 5]);
$first = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant))->execute();
$second = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant->fresh()))->execute();
$this->assertTrue($first->success);
$this->assertSame('WM-V-20260701-0005', $first->invoiceNumber);
$this->assertSame($first->invoiceNumber, $second->invoiceNumber);
$this->assertSame('Rechnung-WM-V-20260701-0005.pdf', $first->filename);
$this->assertStringStartsWith('%PDF', $first->pdfContent);
}
public function test_the_endpoint_delivers_the_pdf_as_a_download(): void
{
$participant = $this->makeParticipant($this->makeEvent(), ['invoice_sequence' => 5]);
$this->actingAs($this->makeLeader());
$response = $this->get('/api/v1/participant-invoice/' . $participant->identifier);
$response->assertOk();
$response->assertHeader('Content-Type', 'application/pdf');
$response->assertHeader('Content-Disposition', 'attachment; filename="Rechnung-WM-V-20260701-0005.pdf"');
}
public function test_the_endpoint_is_closed_to_guests(): void
{
$participant = $this->makeParticipant($this->makeEvent());
$this->get('/api/v1/participant-invoice/' . $participant->identifier)->assertRedirect('/login');
}
private function makeLeader(): User
{
foreach ([UserRole::USER_ROLE_ADMIN, UserRole::USER_ROLE_GROUP_LEADER, UserRole::USER_ROLE_USER] as $role) {
UserRole::firstOrCreate(['slug' => $role], ['name' => $role]);
}
return User::create([
'username' => 'leitung@example.com',
'email' => 'leitung@example.com',
'firstname' => 'Leitung',
'lastname' => 'Person',
'password' => bcrypt('secret'),
'local_group' => $this->tenant->slug,
'user_role_main' => UserRole::USER_ROLE_USER,
'user_role_local_group' => UserRole::USER_ROLE_GROUP_LEADER,
'active' => true,
]);
}
public function test_service_period_collapses_for_single_day_events(): void
{
$singleDay = $this->makeParticipant($this->makeEvent([
'start_date' => '2027-01-01',
'end_date' => '2027-01-01',
]));
$multiDay = $this->makeParticipant($this->makeEvent([
'start_date' => '2027-01-06',
'end_date' => '2027-01-08',
'invoice_key' => 'WM-V-20270102',
]));
$period = static fn(EventParticipant $p): string => new ReflectionMethod(
$command = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($p)),
'servicePeriod'
)->invoke($command);
$this->assertSame('01.01.2027', $period($singleDay));
$this->assertSame('06.01.2027 08.01.2027', $period($multiDay));
}
/*
|--------------------------------------------------------------------------
| Vorlage
|--------------------------------------------------------------------------
*/
public function test_empty_blocks_disappear(): void
{
DocumentTemplate::where('block', 'subject')->update(['content' => '']);
$html = new DocumentTemplateRenderProvider(DocumentTemplate::TYPE_PARTICIPANT_INVOICE)
->render(['positions_table' => 'POS', 'summary_table' => '', 'closing_statement' => '']);
$this->assertStringNotContainsString('Rechnung', $html);
$this->assertStringNotContainsString('{block:', $html);
$this->assertStringContainsString('POS', $html);
}
public function test_template_content_is_never_evaluated_as_blade(): void
{
// Der Inhalt kommt aus einem Admin-Formular. Würde er durch Blade laufen, wäre das Formular ein
// Weg zur Codeausführung auf dem Server.
DocumentTemplate::where('block', 'subject')->update([
'content' => '<p>{{ 7*7 }} @php echo "ausgefuehrt"; @endphp</p>',
]);
$html = new DocumentTemplateRenderProvider(DocumentTemplate::TYPE_PARTICIPANT_INVOICE)->render([]);
// Beides bleibt wörtlich stehen -- nichts davon wird ausgewertet.
$this->assertStringContainsString('{{ 7*7 }}', $html);
$this->assertStringContainsString('@php echo "ausgefuehrt"; @endphp', $html);
$this->assertStringNotContainsString('49', $html);
$this->assertStringNotContainsString('>ausgefuehrt<', $html);
}
public function test_a_bare_data_uri_is_stripped_from_the_css(): void
{
// dompdf lagert Data-URIs im CSS nur aus, wenn ihnen ( " oder ' vorausgeht. Ein bar stehendes
// bleibt liegen und treibt seinen Parser in quadratische Laufzeit -- unter FPM stirbt der
// Worker am Zeitlimit und die Anfrage endet in einem 502.
DocumentAsset::create(['name' => 'logo', 'mime' => 'image/png', 'data' => 'RUlORFJVQ0s']);
DocumentTemplate::where('block', DocumentTemplate::BLOCK_STYLE)->update([
'content' => '.a { color: red; }{asset:logo}{asset:logo}',
]);
$html = new DocumentTemplateRenderProvider(DocumentTemplate::TYPE_PARTICIPANT_INVOICE)->render([]);
$this->assertStringContainsString('.a { color: red; }', $html);
$this->assertStringNotContainsString('data:image/png', $html);
// Entscheidend ist der Rumpf: das Semikolon gehört zum Data-URI. Eine Begrenzung, die dort
// aufhört, entfernt nur den Präfix und lässt das Base64 stehen -- der Parser bremst weiter.
$this->assertStringNotContainsString('RUlORFJVQ0s', $html);
$this->assertStringNotContainsString('base64', $html);
}
public function test_a_data_uri_inside_url_is_kept_in_the_css(): void
{
DocumentAsset::create(['name' => 'logo', 'mime' => 'image/png', 'data' => 'QUJD']);
DocumentTemplate::where('block', DocumentTemplate::BLOCK_STYLE)->update([
'content' => '.a { background: url("{asset:logo}"); }',
]);
$html = new DocumentTemplateRenderProvider(DocumentTemplate::TYPE_PARTICIPANT_INVOICE)->render([]);
// Korrekt eingebettet ist es für dompdf kein Problem und bleibt erhalten.
$this->assertStringContainsString('url("data:image/png;base64,QUJD")', $html);
}
public function test_unknown_asset_resolves_to_nothing(): void
{
DocumentAsset::create([
'name' => 'logo',
'mime' => 'image/png',
'data' => 'QUJD',
]);
DocumentTemplate::where('block', 'subject')->update([
'content' => '<img src="{asset:logo}" /><img src="{asset:gibtesnicht}" />',
]);
$html = new DocumentTemplateRenderProvider(DocumentTemplate::TYPE_PARTICIPANT_INVOICE)->render([]);
$this->assertStringContainsString('src="data:image/png;base64,QUJD"', $html);
$this->assertStringContainsString('src=""', $html);
$this->assertStringNotContainsString('{asset:', $html);
}
/*
|--------------------------------------------------------------------------
| Rechnungssteller
|--------------------------------------------------------------------------
*/
private function senderName(EventParticipant $participant): string
{
$command = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant));
return new ReflectionMethod($command, 'buildTokens')
->invoke($command, 'WM-V-20260701-0005', [], 300.0)['sender_name'];
}
public function test_without_an_own_entry_the_tenant_name_is_the_sender(): void
{
$participant = $this->makeParticipant($this->makeEvent());
$this->assertSame('Wilde Möhre', $this->senderName($participant));
}
public function test_an_own_invoice_sender_name_wins(): void
{
$this->tenant->update(['invoice_sender_name' => 'BdP Landesverband Sachsen e.V.']);
$participant = $this->makeParticipant($this->makeEvent());
$this->assertSame('BdP Landesverband Sachsen e.V.', $this->senderName($participant->fresh()));
}
public function test_a_blank_entry_falls_back_to_the_tenant_name(): void
{
// Aus dem Formular kommt ein Leerstring, nicht null.
$this->tenant->update(['invoice_sender_name' => ' ']);
$participant = $this->makeParticipant($this->makeEvent());
$this->assertSame('Wilde Möhre', $this->senderName($participant->fresh()));
}
public function test_correcting_the_sender_reaches_existing_events(): void
{
// Der Fall, der vorher nicht funktioniert hat: der Absender wurde bei der Event-Anlage
// eingefroren, eine spätere Korrektur wirkte deshalb auf bestehende Veranstaltungen nie.
$participant = $this->makeParticipant($this->makeEvent());
$this->tenant->update([
'invoice_sender_name' => 'BdP Landesverband Sachsen e.V.',
'address_1' => 'Bernhard-Göring-Str. 152',
]);
$command = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant->fresh()));
$tokens = new ReflectionMethod($command, 'buildTokens')
->invoke($command, 'WM-V-20260701-0005', [], 300.0);
$this->assertSame('BdP Landesverband Sachsen e.V.', $tokens['sender_name']);
$this->assertSame('Bernhard-Göring-Str. 152', $tokens['sender_address_1']);
}
public function test_the_tax_basis_stays_frozen_on_the_event(): void
{
// Gegenprobe zur Abgrenzung: die Steuergrundlage erklärt, wie der Preis zustande kam, und
// folgt dem Mandanten ausdrücklich NICHT.
$event = $this->makeEvent(['tax_liable' => true, 'vat_rate' => 19]);
$this->tenant->update(['tax_liable' => false, 'vat_rate' => 0]);
$this->assertTrue($event->fresh()->tax_liable);
$this->assertSame(19, $event->fresh()->vat_rate);
}
public function test_token_catalogue_matches_what_the_command_actually_provides(): void
{
// Der Katalog speist die Platzhalter-Liste und die Vorschau in der Vorlagen-Verwaltung. Liefe er
// gegenüber dem Command auseinander, würde die Verwaltung Platzhalter anbieten, die auf der echten
// Rechnung leer bleiben -- oder umgekehrt welche verschweigen.
$participant = $this->makeParticipant($this->makeEvent());
$command = new CreateParticipantInvoiceCommand(new CreateParticipantInvoiceRequest($participant));
$actual = array_keys(
new ReflectionMethod($command, 'buildTokens')->invoke($command, 'WM-V-20260701-0005', [], 300.0)
);
sort($actual);
$documented = ParticipantInvoiceTokens::names();
sort($documented);
$this->assertSame($documented, $actual);
}
public function test_conditional_sections_drop_when_the_value_is_missing(): void
{
DocumentTemplate::where('block', 'subject')->update([
'content' => '{if:sender_phone}Telefon: {sender_phone}{/if:sender_phone}'
. '{if:sender_city}Ort: {sender_city}{/if:sender_city}',
]);
$html = new DocumentTemplateRenderProvider(DocumentTemplate::TYPE_PARTICIPANT_INVOICE)
->render(['sender_phone' => '', 'sender_city' => 'Stadt']);
$this->assertStringNotContainsString('Telefon:', $html);
$this->assertStringContainsString('Ort: Stadt', $html);
}
}
+6 -2
View File
@@ -80,11 +80,15 @@ class TenantTaxInformationTest extends TestCase
public function test_invalid_exemption_reason_fails(): void
{
// Neue Tenants tragen den DB-Default (Jugendhilfe); verglichen wird deshalb gegen den Stand
// vor der Aktion, nicht gegen null.
$before = $this->tenant->fresh()->tax_exemption_reason;
$response = $this->runAction(taxLiable: false, vatRate: 0, reason: 'not_a_reason');
$this->assertFalse($response->success);
// Unbekannter Slug wird nicht aufgelöst (null) → kein Speichern, Wert bleibt unverändert.
$this->assertNull($this->tenant->fresh()->tax_exemption_reason);
// Unbekannter Slug wird nicht aufgelöst → kein Speichern, Wert bleibt unverändert.
$this->assertSame($before, $this->tenant->fresh()->tax_exemption_reason);
}
public function test_custom_reason_requires_note(): void
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace Tests\Unit;
use App\Support\DateRange;
use DateTime;
use PHPUnit\Framework\TestCase;
class DateRangeTest extends TestCase
{
public function test_a_single_day_counts_as_one(): void
{
$day = new DateTime('2026-07-16');
$this->assertSame(1, DateRange::inclusiveDays($day, $day));
}
public function test_both_ends_are_counted(): void
{
// An- und Abreisetag zählen beide mit.
$this->assertSame(2, DateRange::inclusiveDays(new DateTime('2026-07-16'), new DateTime('2026-07-17')));
$this->assertSame(5, DateRange::inclusiveDays(new DateTime('2026-07-16'), new DateTime('2026-07-20')));
}
public function test_the_order_of_the_arguments_does_not_matter(): void
{
$early = new DateTime('2026-07-16');
$late = new DateTime('2026-07-20');
$this->assertSame(
DateRange::inclusiveDays($early, $late),
DateRange::inclusiveDays($late, $early)
);
}
public function test_month_and_year_boundaries_are_handled(): void
{
$this->assertSame(3, DateRange::inclusiveDays(new DateTime('2026-07-30'), new DateTime('2026-08-01')));
$this->assertSame(3, DateRange::inclusiveDays(new DateTime('2026-12-31'), new DateTime('2027-01-02')));
// 2028 ist ein Schaltjahr.
$this->assertSame(2, DateRange::inclusiveDays(new DateTime('2028-02-28'), new DateTime('2028-02-29')));
}
}
@@ -55,10 +55,9 @@ class EventPaymentModuleRegistryTest extends TestCase
// Überweisung: keine payer-seitigen Eingaben.
$this->assertSame([], (new AccountTransferPaymentModule())->getParticipantOptions());
// Sonstiges: exemplarische Teilnehmer-Eingaben (Betrag + Passend-Checkbox).
$undefined = (new UndefinedPaymentModule())->getParticipantOptions();
$this->assertSame(['amount_brought', 'has_exact_amount'], array_column($undefined, 'name'));
$this->assertSame('checkbox', $undefined[1]['type']);
// Sonstiges (Barzahlung vor Ort): ebenfalls keine payer-seitigen Eingaben -- die Zahlungsart
// beschreibt sich allein über den vom Veranstalter gepflegten Freitext.
$this->assertSame([], (new UndefinedPaymentModule())->getParticipantOptions());
}
public function test_participant_option_helpers(): void
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace Tests\Unit;
use App\Support\Text;
use PHPUnit\Framework\TestCase;
class TextTest extends TestCase
{
public function test_blank_input_becomes_null(): void
{
// Optionale Formularfelder kommen als Leerstring an, nicht als null.
$this->assertNull(Text::nullIfBlank(null));
$this->assertNull(Text::nullIfBlank(''));
$this->assertNull(Text::nullIfBlank(' '));
$this->assertNull(Text::nullIfBlank("\t\n"));
}
public function test_content_is_kept_and_trimmed(): void
{
$this->assertSame('Musterweg 1', Text::nullIfBlank(' Musterweg 1 '));
$this->assertSame('WM', Text::nullIfBlank('WM'));
}
public function test_a_zero_is_content_not_emptiness(): void
{
// "0" ist falsy -- eine naive Prüfung mit `empty()` würde die Angabe verschlucken.
$this->assertSame('0', Text::nullIfBlank('0'));
}
}