Compare commits

...

3 commits
v1.0.1 ... main

Author SHA1 Message Date
9a418d5465 Kleinanzeigen 1.3.0: einheitliche Werkzeugleiste mit Listenansicht
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-06 19:57:17 +00:00
2be070eb67 Kleinanzeigen 1.2.0: Detailseite im einheitlichen Seitenkopf
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 04:19:02 +00:00
2129e9a5c6 Kleinanzeigen 1.1.0: Schnittstelle für die App
- /api/v1/kleinanzeigen: Liste mit Filtern, meta, meine, Anzeige, Formular,
  aufgeben/speichern mit Fotos, löschen, verlängern/erledigt/reserviert,
  Merkliste, Kontakt (Chat mit conversation_id oder E-Mail), Melden, Fotos mit Token
- Foto-Adressen zeigen bei API-Aufrufen auf die API

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-27 20:11:15 +00:00
15 changed files with 355 additions and 57 deletions

View file

@ -22,6 +22,25 @@ Voraussetzung: Inhaus **0.39.0** oder neuer. Optional: Plugin *Nachrichten* für
3. Unter **Rollen** das Recht **„Kleinanzeigen freigeben und moderieren“** vergeben. Ohne solche Rolle geht die Freigabe
an die Administration.
## Schnittstelle für die App
Unter `/api/v1/kleinanzeigen/…` (Token nötig), dieselben Regeln wie im Portal (neue und geänderte Anzeigen
gehen in die Freigabe):
| Methode | Pfad | Zweck |
|---|---|---|
| GET | `/?q=&typ=&kategorie=&sortierung=&merkliste=1&page=` | sichtbare Anzeigen (24 je Seite) |
| GET | `meta` | Arten, Kategorien, `max_photos`, eigener Ort, Zahl eigener bzw. wartender Anzeigen |
| GET | `meine` | eigene Anzeigen mit Status und Hinweis der Moderation |
| GET | `{id}`, `{id}/bearbeiten` | Anzeige / Werte zum Bearbeiten |
| POST | `/`, `{id}` | aufgeben / speichern (multipart: `photos[]`, `remove_photos[]`) |
| DELETE | `{id}` | löschen |
| POST | `{id}/verlaengern`, `{id}/erledigt`, `{id}/reserviert` | eigene Anzeige verwalten |
| POST / DELETE | `{id}/merken` | Merkliste |
| POST | `{id}/kontakt {message}` | Nachricht: `via: chat` mit `conversation_id` (Chat-Plugin) oder `via: mail` |
| POST | `{id}/melden {reason}` | an die Moderation melden |
| GET | `bilder/{id}/{thumb\|full}` | Fotos (Adressen in API-Antworten zeigen hierher) |
## Entwicklung
```bash

2
dist/assets/style-BD4vSwmw.css vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2
dist/inhaus.json vendored
View file

@ -9,6 +9,6 @@
"widgets/Latest": "widgets/Latest.js"
},
"css": [
"assets/style-CAm2qtFB.css"
"assets/style-BD4vSwmw.css"
]
}

2
dist/pages/Index.js vendored

File diff suppressed because one or more lines are too long

2
dist/pages/Show.js vendored

File diff suppressed because one or more lines are too long

View file

@ -1,13 +1,13 @@
{
"slug": "kleinanzeigen",
"name": "Kleinanzeigen",
"version": "1.0.1",
"version": "1.3.0",
"description": "Kleinanzeigen von Kolleginnen und Kollegen für Kolleginnen und Kollegen: verkaufen, verschenken, suchen, tauschen – mit Fotos, Merkliste und Freigabe durch die Moderation. Kontakt über das Chat-Plugin oder per E-Mail.",
"author": "Loheide",
"namespace": "Inhaus\\Plugins\\Kleinanzeigen\\",
"class": "Inhaus\\Plugins\\Kleinanzeigen\\KleinanzeigenPlugin",
"requires": {
"core": ">=0.39.1",
"core": ">=0.61.0",
"php": ">=8.3"
},
"update_url": "https://git.loheide.cloud/api/v1/repos/friloo/inhaus-plugin-kleinanzeigen/releases/latest"

View file

@ -1,8 +1,8 @@
<script setup>
import { ref, watch } from 'vue';
import { watch } from 'vue';
import { Link, router, usePage } from '@inertiajs/vue3';
import { Heart, ListChecks, Plus, Search, ShieldCheck, ShoppingBag } from '@lucide/vue';
import { AppLayout, Button, EmptyState, PageHeader, toast } from '@inhaus/ui';
import { Heart, ListChecks, Plus, ShieldCheck, ShoppingBag } from '@lucide/vue';
import { AppLayout, Button, EmptyState, ListToolbar, PageHeader, toast, useListView } from '@inhaus/ui';
import ListingCard from '../components/ListingCard.vue';
const props = defineProps({
@ -19,12 +19,7 @@ const props = defineProps({
const page = usePage();
watch(() => page.props.flash?.status, (status) => status && toast.success(status), { immediate: true });
const query = ref(props.filters.q);
let timer;
watch(query, (value) => {
clearTimeout(timer);
timer = setTimeout(() => apply({ q: value }), 350);
});
const view = useListView('kleinanzeigen', 'grid');
function apply(changes) {
const params = { ...props.filters, ...changes };
@ -48,16 +43,6 @@ const sorts = { neu: 'Neueste zuerst', preis: 'Preis aufsteigend', 'preis-ab': '
<div class="ih:grid ih:gap-6 ih:lg:grid-cols-[15rem_minmax(0,1fr)]">
<aside class="ih:grid ih:content-start ih:gap-5">
<div class="ih:relative">
<Search class="ih:pointer-events-none ih:absolute ih:top-1/2 ih:left-2.5 ih:size-4 ih:-translate-y-1/2 ih:text-muted-foreground" />
<input v-model="query" type="search" placeholder="Suchen" aria-label="Anzeigen durchsuchen" class="ih:h-10 ih:w-full ih:rounded-md ih:border ih:border-input ih:bg-card ih:pr-3 ih:pl-8 ih:text-sm ih:shadow-xs ih:focus-visible:ring-3 ih:focus-visible:ring-ring/30 ih:focus-visible:outline-none" />
</div>
<nav aria-label="Art" class="ih:flex ih:flex-wrap ih:gap-1.5">
<button type="button" class="ih:rounded-full ih:border ih:px-3 ih:py-1 ih:text-[13px]" :class="!filters.typ ? 'ih:border-brand ih:bg-brand ih:text-brand-foreground' : 'ih:bg-card ih:hover:bg-accent'" :aria-pressed="!filters.typ" @click="apply({ typ: null })">Alle</button>
<button v-for="(label, key) in types" :key="key" type="button" class="ih:rounded-full ih:border ih:px-3 ih:py-1 ih:text-[13px]" :class="filters.typ === key ? 'ih:border-brand ih:bg-brand ih:text-brand-foreground' : 'ih:bg-card ih:hover:bg-accent'" :aria-pressed="filters.typ === key" @click="apply({ typ: key })">{{ label }}</button>
</nav>
<nav aria-label="Kategorien" class="ih:hidden ih:lg:block">
<h2 class="ih:mb-1.5 ih:text-xs ih:font-semibold ih:tracking-wider ih:text-muted-foreground ih:uppercase">Kategorien</h2>
<ul class="ih:grid ih:gap-0.5 ih:text-sm">
@ -76,19 +61,44 @@ const sorts = { neu: 'Neueste zuerst', preis: 'Preis aufsteigend', 'preis-ab': '
</aside>
<section class="ih:min-w-0">
<div class="ih:mb-4 ih:flex ih:flex-wrap ih:items-center ih:gap-3">
<p class="ih:flex-1 ih:text-sm ih:text-muted-foreground">{{ pagination.total }} {{ pagination.total === 1 ? 'Anzeige' : 'Anzeigen' }}</p>
<button type="button" class="ih:inline-flex ih:items-center ih:gap-1.5 ih:rounded-md ih:border ih:px-3 ih:py-1.5 ih:text-sm" :class="filters.merkliste ? 'ih:border-brand ih:bg-brand-soft ih:text-brand-text' : 'ih:bg-card ih:hover:bg-accent'" :aria-pressed="filters.merkliste" @click="apply({ merkliste: filters.merkliste ? null : 1 })">
<ListToolbar
:filters="[{ value: null, label: 'Alle' }, ...Object.entries(types).map(([value, label]) => ({ value, label }))]"
:filter="filters.typ || null"
filter-label="Art"
:search="filters.q ?? ''"
search-placeholder="Anzeigen durchsuchen"
:sorts="Object.entries(sorts).map(([value, label]) => ({ value, label }))"
:sort="filters.sortierung || 'neu'"
v-model:view="view"
@update:filter="(value) => apply({ typ: value })"
@update:search="(value) => apply({ q: value })"
@update:sort="(value) => apply({ sortierung: value })"
>
<button type="button" class="ih:inline-flex ih:h-9 ih:items-center ih:gap-1.5 ih:rounded-full ih:border ih:px-3 ih:text-sm" :class="filters.merkliste ? 'ih:border-brand ih:bg-brand-soft ih:text-brand-text' : 'ih:bg-card ih:hover:bg-accent'" :aria-pressed="!!filters.merkliste" @click="apply({ merkliste: filters.merkliste ? null : 1 })">
<Heart class="ih:size-4" :class="filters.merkliste ? 'ih:fill-current' : ''" /> Merkliste
</button>
<select class="ih:h-9 ih:rounded-md ih:border ih:bg-card ih:px-2 ih:text-sm" aria-label="Sortierung" :value="filters.sortierung" @change="apply({ sortierung: $event.target.value })">
<option v-for="(label, key) in sorts" :key="key" :value="key">{{ label }}</option>
</select>
</div>
</ListToolbar>
<p class="ih:-mt-2 ih:mb-3 ih:text-sm ih:text-muted-foreground">{{ pagination.total }} {{ pagination.total === 1 ? 'Anzeige' : 'Anzeigen' }}</p>
<div v-if="listings.length" class="ih:grid ih:grid-cols-2 ih:gap-3 ih:sm:gap-4 ih:md:grid-cols-3 ih:xl:grid-cols-4">
<div v-if="listings.length && view === 'grid'" class="ih:grid ih:grid-cols-2 ih:gap-3 ih:sm:gap-4 ih:md:grid-cols-3 ih:xl:grid-cols-4">
<ListingCard v-for="listing in listings" :key="listing.id" :listing="listing" />
</div>
<ul v-else-if="listings.length" class="ih:divide-y ih:rounded-lg ih:border ih:bg-card">
<li v-for="listing in listings" :key="listing.id">
<Link :href="listing.url" class="ih:flex ih:items-center ih:gap-3 ih:px-4 ih:py-2.5 ih:hover:bg-accent/60">
<span class="ih:grid ih:size-14 ih:shrink-0 ih:place-items-center ih:overflow-hidden ih:rounded-md ih:bg-muted">
<img v-if="listing.thumb_url" :src="listing.thumb_url" alt="" class="ih:size-full ih:object-cover" />
<ShoppingBag v-else class="ih:size-5 ih:text-muted-foreground" />
</span>
<span class="ih:grid ih:min-w-0 ih:flex-1">
<span class="ih:text-xs ih:text-muted-foreground">{{ listing.type_label }} · {{ listing.category_label }}<template v-if="listing.reserved"> · reserviert</template></span>
<span class="ih:truncate ih:font-medium">{{ listing.title }}</span>
<span v-if="listing.location" class="ih:truncate ih:text-xs ih:text-muted-foreground">{{ listing.location }}</span>
</span>
<span v-if="listing.price" class="ih:shrink-0 ih:font-semibold ih:text-brand-text">{{ listing.price }}</span>
</Link>
</li>
</ul>
<div v-else class="ih:rounded-lg ih:border ih:bg-card">
<EmptyState :icon="ShoppingBag" :title="filters.q || filters.typ || filters.kategorie || filters.merkliste ? 'Keine passenden Anzeigen' : 'Noch keine Anzeigen'" text="Etwas übrig oder auf der Suche? Geben Sie die erste Anzeige auf." />
</div>

View file

@ -2,7 +2,7 @@
import { computed, ref, watch } from 'vue';
import { Link, router, useForm, usePage } from '@inertiajs/vue3';
import { CalendarDays, ChevronLeft, ChevronRight, Flag, Heart, ImageOff, LoaderCircle, Mail, MapPin, MessageCircle, PencilLine, Phone, ShieldCheck, Trash2 } from '@lucide/vue';
import { AppLayout, Button, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, PersonAvatar, Textarea, formatDate, toast } from '@inhaus/ui';
import { AppLayout, Button, PageHeader, Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, PersonAvatar, Textarea, formatDate, toast } from '@inhaus/ui';
import ListingCard from '../components/ListingCard.vue';
const props = defineProps({
@ -45,13 +45,20 @@ const statusNote = computed(() => ({
<template>
<AppLayout :title="l.title">
<div class="ih:mb-4 ih:flex ih:items-center ih:justify-between ih:gap-3">
<Link href="/kleinanzeigen" class="ih:inline-flex ih:items-center ih:gap-1 ih:text-sm ih:font-medium ih:text-muted-foreground ih:hover:text-foreground"><ChevronLeft class="ih:size-4" /> Alle Kleinanzeigen</Link>
<div class="ih:flex ih:gap-2">
<PageHeader :title="l.title" :breadcrumbs="[{ label: 'Kleinanzeigen', href: '/kleinanzeigen' }]">
<template #description>
<span class="ih:flex ih:flex-wrap ih:items-center ih:gap-2 ih:text-xs">
<span class="ih:rounded ih:bg-brand-soft ih:px-2 ih:py-0.5 ih:font-semibold ih:text-brand-text">{{ l.type_label }}</span>
<span>{{ l.category_label }}</span>
<span v-if="l.reserved" class="ih:rounded ih:bg-foreground ih:px-2 ih:py-0.5 ih:font-semibold ih:text-background">Reserviert</span>
<span v-if="l.price" class="ih:text-base ih:font-semibold ih:text-brand-text">{{ l.price }}</span>
</span>
</template>
<template v-if="l.own || l.can_moderate" #actions>
<Button v-if="l.own" variant="outline" size="sm" as-child><Link :href="`/kleinanzeigen/${l.id}/bearbeiten`"><PencilLine /> Bearbeiten</Link></Button>
<Button v-if="l.own || l.can_moderate" variant="ghost" size="sm" class="ih:text-destructive ih:hover:text-destructive" @click="remove"><Trash2 /> Löschen</Button>
</div>
</div>
<Button variant="ghost" size="sm" class="ih:text-destructive ih:hover:text-destructive" @click="remove"><Trash2 /> Löschen</Button>
</template>
</PageHeader>
<p v-if="statusNote" class="ih:mb-4 ih:rounded-md ih:border ih:bg-muted ih:px-4 ih:py-3 ih:text-sm">
{{ statusNote }}<template v-if="l.review_note"> Hinweis: {{ l.review_note }}</template>
@ -78,14 +85,7 @@ const statusNote = computed(() => ({
</section>
<section class="ih:rounded-xl ih:border ih:bg-card ih:p-5 ih:sm:p-6">
<div class="ih:flex ih:flex-wrap ih:items-center ih:gap-2 ih:text-xs">
<span class="ih:rounded ih:bg-brand-soft ih:px-2 ih:py-0.5 ih:font-semibold ih:text-brand-text">{{ l.type_label }}</span>
<span class="ih:text-muted-foreground">{{ l.category_label }}</span>
<span v-if="l.reserved" class="ih:rounded ih:bg-foreground ih:px-2 ih:py-0.5 ih:font-semibold ih:text-background">Reserviert</span>
</div>
<h1 class="ih:mt-2 ih:text-2xl ih:font-semibold ih:tracking-tight ih:text-balance">{{ l.title }}</h1>
<p v-if="l.price" class="ih:mt-1 ih:text-xl ih:font-semibold ih:text-brand-text">{{ l.price }}</p>
<dl class="ih:mt-4 ih:flex ih:flex-wrap ih:gap-x-6 ih:gap-y-2 ih:text-sm ih:text-muted-foreground">
<dl class="ih:flex ih:flex-wrap ih:gap-x-6 ih:gap-y-2 ih:text-sm ih:text-muted-foreground">
<div v-if="l.location" class="ih:flex ih:items-center ih:gap-1.5"><dt class="ih:sr-only">Ort</dt><MapPin class="ih:size-4" aria-hidden="true" /><dd>{{ l.location }}</dd></div>
<div v-if="l.published_at" class="ih:flex ih:items-center ih:gap-1.5"><dt class="ih:sr-only">Eingestellt</dt><CalendarDays class="ih:size-4" aria-hidden="true" /><dd>seit {{ formatDate(l.published_at) }}</dd></div>
</dl>

23
routes/api.php Normal file
View file

@ -0,0 +1,23 @@
<?php
use Illuminate\Support\Facades\Route;
use Inhaus\Plugins\Kleinanzeigen\Http\Controllers\ApiController;
// /api/v1/kleinanzeigen … für die Inhaus-App (Token nötig) – dieselben Regeln wie im Portal
Route::prefix('kleinanzeigen')->name('kleinanzeigen.app.')->group(function () {
Route::get('/', [ApiController::class, 'list'])->name('index');
Route::get('/meta', [ApiController::class, 'meta'])->name('meta');
Route::get('/meine', [ApiController::class, 'own'])->name('mine');
Route::post('/', [ApiController::class, 'publish'])->middleware('throttle:10,60')->name('store');
Route::get('/bilder/{image}/{size}', [ApiController::class, 'image'])->whereIn('size', ['thumb', 'full'])->name('image');
Route::get('/{listing}', [ApiController::class, 'detail'])->whereNumber('listing')->name('show');
Route::get('/{listing}/bearbeiten', [ApiController::class, 'form'])->whereNumber('listing')->name('edit');
Route::post('/{listing}', [ApiController::class, 'save'])->whereNumber('listing')->name('update'); // POST wegen Fotos
Route::delete('/{listing}', [ApiController::class, 'remove'])->whereNumber('listing')->name('destroy');
Route::post('/{listing}/{action}', [ApiController::class, 'action'])->whereNumber('listing')->whereIn('action', ['verlaengern', 'erledigt', 'reserviert'])->name('action');
Route::post('/{listing}/merken', [ApiController::class, 'favor'])->name('favorite');
Route::delete('/{listing}/merken', [ApiController::class, 'favor'])->name('unfavorite');
Route::post('/{listing}/kontakt', [ApiController::class, 'message'])->middleware('throttle:20,60')->name('contact');
Route::post('/{listing}/melden', [ApiController::class, 'flag'])->middleware('throttle:10,60')->name('report');
});

View file

@ -0,0 +1,196 @@
<?php
namespace Inhaus\Plugins\Kleinanzeigen\Http\Controllers;
use App\Search\GlobalSearch;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
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;
/**
* Schnittstelle für die Inhaus-App (/api/v1/kleinanzeigen …) – dieselben Regeln wie im Portal
* (Prüfung, Fotos und Freigabe stammen aus dem ListingController).
*/
class ApiController extends ListingController
{
/** Kategorien, Arten und eigene Zahlen – für Filter und Formular */
public function meta(Request $request): JsonResponse
{
$user = $request->user();
return response()->json([
'types' => Listing::TYPES,
'categories' => Listing::CATEGORIES,
'max_photos' => Photos::MAX,
'default_location' => $user->location,
'mine' => Listing::query()->where('user_id', $user->id)->whereIn('status', ['pending', 'active'])->count(),
'pending' => $user->can('kleinanzeigen.moderate') ? Listing::query()->where('status', 'pending')->count() : null,
]);
}
public function list(Request $request): JsonResponse
{
$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);
$favorites = DB::table('kleinanzeigen_favorites')->where('user_id', $user->id)->pluck('listing_id')->all();
return response()->json([
'data' => collect($listings->items())->map(fn (Listing $l) => Presenter::card($l, $favorites))->all(),
'meta' => ['current_page' => $listings->currentPage(), 'last_page' => $listings->lastPage(), 'total' => $listings->total()],
]);
}
public function detail(Request $request, Listing $listing): JsonResponse
{
$this->ensureVisible($request, $listing);
$listing->load(['images', 'user']);
return response()->json(['data' => Presenter::detail($listing, $request->user(), $this->market)]);
}
/** Eigene Anzeigen mit Stand der Freigabe */
public function own(Request $request): JsonResponse
{
return response()->json([
'data' => 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])->all(),
]);
}
/** Werte zum Bearbeiten (Preis wie im Formular: „12,50“) */
public function form(Request $request, Listing $listing): JsonResponse
{
$this->ensureOwner($request, $listing);
$listing->load('images');
return response()->json(['data' => [
'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.app.image', [$i, 'thumb'])])->all(),
]]);
}
public function publish(Request $request): JsonResponse
{
$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 response()->json(['id' => $listing->id, 'message' => 'Danke! Ihre Anzeige wird geprüft und dann freigeschaltet.'], 201);
}
public function save(Request $request, Listing $listing): JsonResponse
{
$this->ensureOwner($request, $listing);
$listing->fill($this->validated($request, $listing));
$contentChanged = $listing->isDirty(Market::REVIEW_FIELDS);
$listing->save();
$photosChanged = $this->syncPhotos($request, $listing);
if ($listing->status !== 'pending' && $listing->status !== 'done' && ($contentChanged || $photosChanged || $listing->status === 'rejected')) {
$this->market->submitted($listing, $listing->status === 'active');
return response()->json(['id' => $listing->id, 'message' => 'Gespeichert – die Änderungen werden geprüft.']);
}
return response()->json(['id' => $listing->id, 'message' => 'Gespeichert.']);
}
public function remove(Request $request, Listing $listing): JsonResponse
{
abort_unless($listing->user_id === $request->user()->id || $request->user()->can('kleinanzeigen.moderate'), 403);
$this->photos->deleteAll($listing);
$listing->delete();
return response()->json(['message' => 'Anzeige gelöscht.']);
}
/** Verlängern, erledigt, reserviert – liefert die Anzeige neu */
public function action(Request $request, Listing $listing, string $action): JsonResponse
{
$this->ensureOwner($request, $listing);
switch ($action) {
case 'verlaengern':
$this->market->extend($listing);
$message = 'Verlängert bis '.$listing->expires_at->format('d.m.Y').'.';
break;
case 'erledigt':
$listing->forceFill(['status' => 'done', 'reserved' => false])->save();
$message = 'Als erledigt markiert – die Anzeige ist nicht mehr sichtbar.';
break;
default:
$listing->forceFill(['reserved' => ! $listing->reserved])->save();
$message = $listing->reserved ? 'Als reserviert markiert.' : 'Wieder verfügbar.';
}
return response()->json(['message' => $message, 'data' => Presenter::card($listing->load('images'))]);
}
public function favor(Request $request, Listing $listing): JsonResponse
{
$this->ensureVisible($request, $listing);
$request->isMethod('delete')
? $listing->favoritedBy()->detach($request->user()->id)
: $listing->favoritedBy()->syncWithoutDetaching([$request->user()->id => ['created_at' => now()]]);
return response()->json(['favorite' => ! $request->isMethod('delete')]);
}
/** Kontakt: über den Chat (die App öffnet dann das Gespräch), sonst per E-Mail */
public function message(Request $request, Listing $listing): JsonResponse
{
$response = $this->contact($request, $listing);
$conversation = preg_match('#/chat/(\d+)$#', $response->getTargetUrl(), $m) ? (int) $m[1] : null;
return response()->json($conversation
? ['via' => 'chat', 'conversation_id' => $conversation, 'message' => 'Nachricht im Chat gesendet.']
: ['via' => 'mail', 'message' => 'Nachricht gesendet – die Antwort kommt per E-Mail.']);
}
public function flag(Request $request, Listing $listing): JsonResponse
{
$this->report($request, $listing);
return response()->json(['message' => 'Danke für den Hinweis – die Moderation sieht es sich an.']);
}
}

View file

@ -26,7 +26,7 @@ use Symfony\Component\HttpFoundation\StreamedResponse;
class ListingController extends Controller
{
public function __construct(private readonly Market $market, private readonly Photos $photos) {}
public function __construct(protected readonly Market $market, protected readonly Photos $photos) {}
public function index(Request $request): Response
{
@ -252,7 +252,7 @@ class ListingController extends Controller
/**
* @return array<string, mixed>
*/
private function validated(Request $request, ?Listing $listing): array
protected function validated(Request $request, ?Listing $listing): array
{
$data = $request->validate([
'type' => ['required', Rule::in(array_keys(Listing::TYPES))],
@ -286,7 +286,7 @@ class ListingController extends Controller
}
/** Fotos entfernen bzw. hinzufügen – true, wenn sich etwas geändert hat */
private function syncPhotos(Request $request, Listing $listing): bool
protected function syncPhotos(Request $request, Listing $listing): bool
{
$changed = false;
@ -309,13 +309,13 @@ class ListingController extends Controller
return $changed;
}
private function ensureVisible(Request $request, Listing $listing): void
protected 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
protected function ensureOwner(Request $request, Listing $listing): void
{
abort_unless($listing->user_id === $request->user()->id, 403);
}

View file

@ -8,6 +8,12 @@ use Inhaus\Plugins\Kleinanzeigen\Models\ListingImage;
class Presenter
{
/** Fotos: die App lädt mit ihrem Token über die API, der Browser über die Sitzung */
private static function imageRoute(): string
{
return request()->is('api/*') ? 'kleinanzeigen.app.image' : 'kleinanzeigen.image';
}
/**
* @return array<string, mixed>
*/
@ -27,7 +33,7 @@ class Presenter
'status' => $listing->status,
'status_label' => Listing::STATUSES[$listing->status] ?? $listing->status,
'reserved' => $listing->reserved,
'thumb_url' => $cover ? route('kleinanzeigen.image', [$cover, 'thumb']) : null,
'thumb_url' => $cover ? route(self::imageRoute(), [$cover, 'thumb']) : null,
'images' => $listing->images->count(),
'favorite' => in_array($listing->id, $favorites, true),
'published_at' => $listing->published_at?->toIso8601String(),
@ -53,8 +59,8 @@ class Presenter
'review_note' => $own || $viewer->can('kleinanzeigen.moderate') ? $listing->review_note : null,
'photos' => $listing->images->map(fn (ListingImage $i) => [
'id' => $i->id,
'url' => route('kleinanzeigen.image', [$i, 'full']),
'thumb_url' => route('kleinanzeigen.image', [$i, 'thumb']),
'url' => route(self::imageRoute(), [$i, 'full']),
'thumb_url' => route(self::imageRoute(), [$i, 'thumb']),
'width' => $i->width,
'height' => $i->height,
])->values()->all(),

View file

@ -7,6 +7,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Inertia\Testing\AssertableInertia as Assert;
use Inhaus\Plugins\Kleinanzeigen\Models\Listing;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
/**
@ -56,5 +57,10 @@ class ChatContactTest extends TestCase
$this->actingAs($seller)->getJson('/chat/api/gespraeche/'.basename($location).'/nachrichten')->assertOk()
->assertJsonPath('messages.0.body', "Zu deiner Anzeige „Sofa“:\n".route('kleinanzeigen.show', $listing)."\n\nKann ich es Samstag holen?");
// App: dasselbe Gespräch, die App öffnet es direkt
Sanctum::actingAs($buyer);
$this->postJson("/api/v1/kleinanzeigen/{$listing->id}/kontakt", ['message' => 'Und Sonntag?'])->assertOk()
->assertJsonPath('via', 'chat')->assertJsonPath('conversation_id', (int) basename($location));
}
}

View file

@ -14,6 +14,7 @@ use Inertia\Testing\AssertableInertia as Assert;
use Inhaus\Plugins\Kleinanzeigen\Mail\ContactMessage;
use Inhaus\Plugins\Kleinanzeigen\Market;
use Inhaus\Plugins\Kleinanzeigen\Models\Listing;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
/**
@ -149,4 +150,41 @@ class KleinanzeigenTest extends TestCase
$this->assertSame('active', $old->fresh()->status);
$this->assertTrue($old->fresh()->expires_at->isAfter(now()->addDays(29)));
}
public function test_app_api_with_token(): void
{
Notification::fake();
Mail::fake();
$seller = User::factory()->create();
$buyer = User::factory()->create();
Sanctum::actingAs($seller);
$id = $this->post('/api/v1/kleinanzeigen', [...$this->payload(), 'photos' => [UploadedFile::fake()->image('rad.jpg', 800, 600)]], ['Accept' => 'application/json'])
->assertCreated()->json('id');
$this->getJson('/api/v1/kleinanzeigen/meine')->assertJsonPath('data.0.status', 'pending');
$this->getJson("/api/v1/kleinanzeigen/{$id}/bearbeiten")->assertJsonPath('data.price', '45,50');
Sanctum::actingAs($buyer);
$this->getJson("/api/v1/kleinanzeigen/{$id}")->assertNotFound();
$this->getJson('/api/v1/kleinanzeigen')->assertJsonCount(0, 'data');
app(Market::class)->approve(Listing::query()->findOrFail($id), $this->moderator);
$thumb = $this->getJson('/api/v1/kleinanzeigen?q=fahrrad')->assertJsonCount(1, 'data')->json('data.0.thumb_url');
$this->assertStringContainsString('/api/v1/kleinanzeigen/bilder/', $thumb);
$this->get($thumb)->assertOk();
$this->getJson("/api/v1/kleinanzeigen/{$id}")->assertJsonPath('data.contact', 'mail')->assertJsonPath('data.seller.id', $seller->id);
$this->postJson("/api/v1/kleinanzeigen/{$id}/merken")->assertJsonPath('favorite', true);
$this->getJson('/api/v1/kleinanzeigen?merkliste=1')->assertJsonCount(1, 'data');
$this->postJson("/api/v1/kleinanzeigen/{$id}/kontakt", ['message' => 'Noch zu haben?'])->assertOk()->assertJsonPath('via', 'mail');
Mail::assertQueued(ContactMessage::class);
$this->postJson("/api/v1/kleinanzeigen/{$id}/reserviert")->assertForbidden();
Sanctum::actingAs($seller);
$this->postJson("/api/v1/kleinanzeigen/{$id}/reserviert")->assertJsonPath('data.reserved', true);
$this->post("/api/v1/kleinanzeigen/{$id}", $this->payload(['title' => 'Kinderfahrrad 24 Zoll']), ['Accept' => 'application/json'])
->assertJsonPath('message', 'Gespeichert – die Änderungen werden geprüft.');
$this->postJson("/api/v1/kleinanzeigen/{$id}/erledigt")->assertJsonPath('data.status', 'done');
$this->deleteJson("/api/v1/kleinanzeigen/{$id}")->assertOk();
$this->assertNull(Listing::query()->find($id));
}
}