322 lines
15 KiB
PHP
322 lines
15 KiB
PHP
<?php
|
||
|
||
namespace Inhaus\Plugins\Kleinanzeigen\Http\Controllers;
|
||
|
||
use App\Http\Controllers\Controller;
|
||
use App\Notifications\PortalNotification;
|
||
use App\Search\GlobalSearch;
|
||
use Illuminate\Http\RedirectResponse;
|
||
use Illuminate\Http\Request;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Mail;
|
||
use Illuminate\Support\Facades\Notification;
|
||
use Illuminate\Support\Facades\Storage;
|
||
use Illuminate\Support\Str;
|
||
use Illuminate\Validation\Rule;
|
||
use Inertia\Inertia;
|
||
use Inertia\Response;
|
||
use Inhaus\Plugins\Chat\Chat;
|
||
use Inhaus\Plugins\Kleinanzeigen\Mail\ContactMessage;
|
||
use Inhaus\Plugins\Kleinanzeigen\Market;
|
||
use Inhaus\Plugins\Kleinanzeigen\Models\Listing;
|
||
use Inhaus\Plugins\Kleinanzeigen\Models\ListingImage;
|
||
use Inhaus\Plugins\Kleinanzeigen\Photos;
|
||
use Inhaus\Plugins\Kleinanzeigen\Presenter;
|
||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||
|
||
class ListingController extends Controller
|
||
{
|
||
public function __construct(private readonly Market $market, private readonly Photos $photos) {}
|
||
|
||
public function index(Request $request): Response
|
||
{
|
||
$data = $request->validate([
|
||
'q' => ['nullable', 'string', 'max:100'],
|
||
'typ' => ['nullable', Rule::in(array_keys(Listing::TYPES))],
|
||
'kategorie' => ['nullable', Rule::in(array_keys(Listing::CATEGORIES))],
|
||
'sortierung' => ['nullable', Rule::in(['neu', 'preis', 'preis-ab'])],
|
||
'merkliste' => ['nullable', 'boolean'],
|
||
]);
|
||
$user = $request->user();
|
||
|
||
$query = Listing::query()->visible()->with('images')
|
||
->when($data['typ'] ?? null, fn ($q, $type) => $q->where('type', $type))
|
||
->when($data['kategorie'] ?? null, fn ($q, $category) => $q->where('category', $category))
|
||
->when($request->boolean('merkliste'), fn ($q) => $q->whereHas('favoritedBy', fn ($f) => $f->whereKey($user->id)));
|
||
|
||
if (filled($data['q'] ?? null)) {
|
||
GlobalSearch::whereTerms($query, ['title', 'description', 'location'], $data['q']);
|
||
}
|
||
|
||
match ($data['sortierung'] ?? 'neu') {
|
||
'preis' => $query->orderByRaw('price_cents IS NULL')->orderBy('price_cents'),
|
||
'preis-ab' => $query->orderByDesc('price_cents'),
|
||
default => $query->latest('published_at'),
|
||
};
|
||
|
||
$listings = $query->paginate(24)->withQueryString();
|
||
$favorites = DB::table('kleinanzeigen_favorites')->where('user_id', $user->id)->pluck('listing_id')->all();
|
||
|
||
return Inertia::render('kleinanzeigen::Index', [
|
||
'listings' => collect($listings->items())->map(fn (Listing $l) => Presenter::card($l, $favorites))->all(),
|
||
'pagination' => ['current' => $listings->currentPage(), 'last' => $listings->lastPage(), 'prev' => $listings->previousPageUrl(), 'next' => $listings->nextPageUrl(), 'total' => $listings->total()],
|
||
'filters' => ['q' => $data['q'] ?? '', 'typ' => $data['typ'] ?? null, 'kategorie' => $data['kategorie'] ?? null, 'sortierung' => $data['sortierung'] ?? 'neu', 'merkliste' => $request->boolean('merkliste')],
|
||
'types' => Listing::TYPES,
|
||
'categories' => Listing::CATEGORIES,
|
||
'counts' => Listing::query()->visible()->selectRaw('category, count(*) as c')->groupBy('category')->pluck('c', 'category'),
|
||
'pending' => $user->can('kleinanzeigen.moderate') ? Listing::query()->where('status', 'pending')->count() : null,
|
||
'mine' => Listing::query()->where('user_id', $user->id)->whereIn('status', ['pending', 'active'])->count(),
|
||
]);
|
||
}
|
||
|
||
public function show(Request $request, Listing $listing): Response
|
||
{
|
||
$this->ensureVisible($request, $listing);
|
||
$listing->load(['images', 'user']);
|
||
|
||
return Inertia::render('kleinanzeigen::Show', [
|
||
'listing' => Presenter::detail($listing, $request->user(), $this->market),
|
||
'more' => Listing::query()->visible()->with('images')->whereKeyNot($listing->id)
|
||
->where(fn ($q) => $q->where('user_id', $listing->user_id)->orWhere('category', $listing->category))
|
||
->orderByRaw('user_id = ? DESC', [$listing->user_id])->latest('published_at')->limit(4)->get()
|
||
->map(fn (Listing $l) => Presenter::card($l))->all(),
|
||
]);
|
||
}
|
||
|
||
public function mine(Request $request): Response
|
||
{
|
||
return Inertia::render('kleinanzeigen::Mine', [
|
||
'listings' => Listing::query()->where('user_id', $request->user()->id)->with('images')->withCount('favoritedBy')
|
||
->orderByRaw("FIELD(status, 'pending', 'rejected', 'active', 'expired', 'done')")->latest('updated_at')->get()
|
||
->map(fn (Listing $l) => [...Presenter::card($l), 'review_note' => $l->review_note, 'favorites' => $l->favorited_by_count, 'edit_url' => route('kleinanzeigen.edit', $l)])->all(),
|
||
]);
|
||
}
|
||
|
||
public function create(): Response
|
||
{
|
||
return $this->editor(null);
|
||
}
|
||
|
||
public function edit(Request $request, Listing $listing): Response
|
||
{
|
||
$this->ensureOwner($request, $listing);
|
||
|
||
return $this->editor($listing->load('images'));
|
||
}
|
||
|
||
public function store(Request $request): RedirectResponse
|
||
{
|
||
$data = $this->validated($request, null);
|
||
$listing = Listing::query()->create([...$data, 'user_id' => $request->user()->id, 'status' => 'pending']);
|
||
$this->syncPhotos($request, $listing);
|
||
$this->market->submitted($listing);
|
||
|
||
return to_route('kleinanzeigen.mine')->with('status', 'Danke! Ihre Anzeige wird geprüft und dann freigeschaltet.');
|
||
}
|
||
|
||
public function update(Request $request, Listing $listing): RedirectResponse
|
||
{
|
||
$this->ensureOwner($request, $listing);
|
||
$data = $this->validated($request, $listing);
|
||
$listing->fill($data);
|
||
$contentChanged = $listing->isDirty(Market::REVIEW_FIELDS);
|
||
$listing->save();
|
||
$photosChanged = $this->syncPhotos($request, $listing);
|
||
|
||
// Inhaltliche Änderungen gehen erneut in die Freigabe
|
||
if ($listing->status !== 'pending' && $listing->status !== 'done' && ($contentChanged || $photosChanged || $listing->status === 'rejected')) {
|
||
$wasActive = $listing->status === 'active';
|
||
$this->market->submitted($listing, $wasActive);
|
||
|
||
return to_route('kleinanzeigen.mine')->with('status', 'Gespeichert – die Änderungen werden geprüft.');
|
||
}
|
||
|
||
return to_route('kleinanzeigen.mine')->with('status', 'Gespeichert.');
|
||
}
|
||
|
||
public function destroy(Request $request, Listing $listing): RedirectResponse
|
||
{
|
||
abort_unless($listing->user_id === $request->user()->id || $request->user()->can('kleinanzeigen.moderate'), 403);
|
||
$this->photos->deleteAll($listing);
|
||
$listing->delete();
|
||
|
||
return to_route($listing->user_id === $request->user()->id ? 'kleinanzeigen.mine' : 'kleinanzeigen.index')->with('status', 'Anzeige gelöscht.');
|
||
}
|
||
|
||
public function extend(Request $request, Listing $listing): RedirectResponse
|
||
{
|
||
$this->ensureOwner($request, $listing);
|
||
$this->market->extend($listing);
|
||
|
||
return back()->with('status', 'Verlängert bis '.$listing->expires_at->format('d.m.Y').'.');
|
||
}
|
||
|
||
public function done(Request $request, Listing $listing): RedirectResponse
|
||
{
|
||
$this->ensureOwner($request, $listing);
|
||
$listing->forceFill(['status' => 'done', 'reserved' => false])->save();
|
||
|
||
return back()->with('status', 'Als erledigt markiert – die Anzeige ist nicht mehr sichtbar.');
|
||
}
|
||
|
||
public function reserve(Request $request, Listing $listing): RedirectResponse
|
||
{
|
||
$this->ensureOwner($request, $listing);
|
||
$listing->forceFill(['reserved' => ! $listing->reserved])->save();
|
||
|
||
return back()->with('status', $listing->reserved ? 'Als reserviert markiert.' : 'Wieder verfügbar.');
|
||
}
|
||
|
||
public function favorite(Request $request, Listing $listing): RedirectResponse
|
||
{
|
||
$this->ensureVisible($request, $listing);
|
||
$request->isMethod('delete')
|
||
? $listing->favoritedBy()->detach($request->user()->id)
|
||
: $listing->favoritedBy()->syncWithoutDetaching([$request->user()->id => ['created_at' => now()]]);
|
||
|
||
return back();
|
||
}
|
||
|
||
/** Kontakt: Direktnachricht im Chat (falls installiert), sonst E-Mail */
|
||
public function contact(Request $request, Listing $listing): RedirectResponse
|
||
{
|
||
$this->ensureVisible($request, $listing);
|
||
$user = $request->user();
|
||
abort_if($listing->user_id === $user->id || ! $listing->user?->is_active, 422);
|
||
$data = $request->validate(['message' => ['required', 'string', 'max:2000']], [], ['message' => 'Nachricht']);
|
||
|
||
if ($this->market->chatAvailable($user, $listing->user)) {
|
||
$chat = app(Chat::class);
|
||
$conversation = $chat->direct($user, $listing->user);
|
||
$chat->send($conversation, $user, "Zu deiner Anzeige „{$listing->title}“:\n".route('kleinanzeigen.show', $listing)."\n\n".trim($data['message']));
|
||
|
||
return redirect('/chat/'.$conversation->id);
|
||
}
|
||
|
||
Mail::to($listing->user)->queue(new ContactMessage($listing, $user, trim($data['message'])));
|
||
|
||
return back()->with('status', 'Nachricht gesendet – die Antwort kommt per E-Mail.');
|
||
}
|
||
|
||
public function report(Request $request, Listing $listing): RedirectResponse
|
||
{
|
||
$this->ensureVisible($request, $listing);
|
||
$data = $request->validate(['reason' => ['required', 'string', 'max:500']], [], ['reason' => 'Grund']);
|
||
|
||
DB::table('kleinanzeigen_reports')->insertOrIgnore([
|
||
'listing_id' => $listing->id, 'user_id' => $request->user()->id, 'reason' => trim($data['reason']), 'created_at' => now(), 'updated_at' => now(),
|
||
]);
|
||
Notification::send($this->market->moderators(), new PortalNotification('Anzeige gemeldet: '.Str::limit($listing->title, 60), Str::limit($data['reason'], 120), route('kleinanzeigen.moderation', absolute: false), 'flag'));
|
||
|
||
return back()->with('status', 'Danke für den Hinweis – die Moderation sieht es sich an.');
|
||
}
|
||
|
||
public function image(Request $request, ListingImage $image, string $size): StreamedResponse
|
||
{
|
||
$listing = $image->listing;
|
||
$this->ensureVisible($request, $listing);
|
||
$path = $size === 'thumb' ? $image->thumb_path : $image->path;
|
||
abort_unless(Storage::disk(Photos::DISK)->exists($path), 404);
|
||
|
||
return Storage::disk(Photos::DISK)->response($path, null, [
|
||
'Content-Type' => 'image/webp',
|
||
'Cache-Control' => 'private, max-age=604800',
|
||
'X-Content-Type-Options' => 'nosniff',
|
||
]);
|
||
}
|
||
|
||
private function editor(?Listing $listing): Response
|
||
{
|
||
return Inertia::render('kleinanzeigen::Editor', [
|
||
'listing' => $listing ? [
|
||
'id' => $listing->id,
|
||
'type' => $listing->type,
|
||
'category' => $listing->category,
|
||
'title' => $listing->title,
|
||
'description' => $listing->description,
|
||
'price' => $listing->price_cents === null ? '' : number_format($listing->price_cents / 100, 2, ',', ''),
|
||
'negotiable' => $listing->negotiable,
|
||
'location' => $listing->location,
|
||
'phone' => $listing->phone,
|
||
'status' => $listing->status,
|
||
'review_note' => $listing->review_note,
|
||
'photos' => $listing->images->map(fn (ListingImage $i) => ['id' => $i->id, 'url' => route('kleinanzeigen.image', [$i, 'thumb'])])->all(),
|
||
] : null,
|
||
'types' => Listing::TYPES,
|
||
'categories' => Listing::CATEGORIES,
|
||
'maxPhotos' => Photos::MAX,
|
||
'defaultLocation' => request()->user()->location,
|
||
]);
|
||
}
|
||
|
||
/**
|
||
* @return array<string, mixed>
|
||
*/
|
||
private function validated(Request $request, ?Listing $listing): array
|
||
{
|
||
$data = $request->validate([
|
||
'type' => ['required', Rule::in(array_keys(Listing::TYPES))],
|
||
'category' => ['required', Rule::in(array_keys(Listing::CATEGORIES))],
|
||
'title' => ['required', 'string', 'max:120'],
|
||
'description' => ['required', 'string', 'max:5000'],
|
||
'price' => ['nullable', 'string', 'max:12', 'regex:/^\d{1,7}([.,]\d{1,2})?$/'],
|
||
'negotiable' => ['boolean'],
|
||
'location' => ['nullable', 'string', 'max:120'],
|
||
'phone' => ['nullable', 'string', 'max:40', 'regex:/^[0-9 +()\/-]+$/'],
|
||
'photos' => ['nullable', 'array', 'max:'.Photos::MAX],
|
||
'photos.*' => ['image', 'mimes:jpg,jpeg,png,webp,gif', 'max:15360'],
|
||
'remove_photos' => ['nullable', 'array'],
|
||
'remove_photos.*' => ['integer'],
|
||
], ['price.regex' => 'Bitte einen Betrag wie 25 oder 12,50 eingeben.', 'phone.regex' => 'Bitte nur Ziffern, Leerzeichen und + ( ) / -.'], [
|
||
'type' => 'Art', 'category' => 'Kategorie', 'title' => 'Titel', 'description' => 'Beschreibung', 'price' => 'Preis', 'photos.*' => 'Foto',
|
||
]);
|
||
|
||
$withPrice = in_array($data['type'], ['sell', 'search'], true) && filled($data['price'] ?? null);
|
||
|
||
return [
|
||
'type' => $data['type'],
|
||
'category' => $data['category'],
|
||
'title' => trim($data['title']),
|
||
'description' => trim($data['description']),
|
||
'price_cents' => $withPrice ? (int) round((float) str_replace(',', '.', $data['price']) * 100) : null,
|
||
'negotiable' => $withPrice && (bool) ($data['negotiable'] ?? false),
|
||
'location' => filled($data['location'] ?? null) ? trim($data['location']) : null,
|
||
'phone' => filled($data['phone'] ?? null) ? trim($data['phone']) : null,
|
||
];
|
||
}
|
||
|
||
/** Fotos entfernen bzw. hinzufügen – true, wenn sich etwas geändert hat */
|
||
private function syncPhotos(Request $request, Listing $listing): bool
|
||
{
|
||
$changed = false;
|
||
|
||
foreach ($listing->images()->whereKey((array) $request->input('remove_photos', []))->get() as $image) {
|
||
$this->photos->delete($image);
|
||
$changed = true;
|
||
}
|
||
|
||
$sort = (int) $listing->images()->max('sort');
|
||
|
||
foreach ((array) $request->file('photos', []) as $file) {
|
||
if ($listing->images()->count() >= Photos::MAX) {
|
||
break;
|
||
}
|
||
|
||
$this->photos->store($listing, $file, ++$sort);
|
||
$changed = true;
|
||
}
|
||
|
||
return $changed;
|
||
}
|
||
|
||
private function ensureVisible(Request $request, Listing $listing): void
|
||
{
|
||
$user = $request->user();
|
||
abort_unless($listing->isVisible() || $listing->user_id === $user->id || $user->can('kleinanzeigen.moderate'), 404);
|
||
}
|
||
|
||
private function ensureOwner(Request $request, Listing $listing): void
|
||
{
|
||
abort_unless($listing->user_id === $request->user()->id, 403);
|
||
}
|
||
}
|