Add business.

This commit is contained in:
2026-05-21 17:59:14 +03:30
parent 4bc6c003f3
commit ebae7687af
11 changed files with 456 additions and 54 deletions
+1
View File
@@ -1 +1,2 @@
VITE_API_URL=https://api.montime.ir
VITE_ASSETS_URL=https://api.montime.ir
+16
View File
@@ -1,7 +1,9 @@
import { api } from './client';
import { apiFormData } from './client';
import type {
AssignOwnerPayload,
Business,
BusinessImage,
CreateBusinessPayload,
UpdateBusinessPayload,
} from './types';
@@ -45,3 +47,17 @@ export function assignBusinessOwner(id: string, payload: AssignOwnerPayload) {
body: JSON.stringify(payload),
});
}
export function uploadBusinessImages(businessId: string, files: File[]) {
const form = new FormData();
for (const file of files) {
form.append('files', file);
}
return apiFormData<BusinessImage[]>(`/businesses/${businessId}/images`, form);
}
export function deleteBusinessImage(businessId: string, imageId: string) {
return api<{ success: true }>(`/businesses/${businessId}/images/${imageId}`, {
method: 'DELETE',
});
}
+24
View File
@@ -55,4 +55,28 @@ export async function api<T>(path: string, options: ApiOptions = {}): Promise<T>
return res.json() as Promise<T>;
}
export async function apiFormData<T>(path: string, form: FormData): Promise<T> {
const token = getApiToken();
const headers: Record<string, string> = {};
if (token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(`${baseUrl}${path}`, {
method: 'POST',
headers,
body: form,
});
if (!res.ok) {
const body = (await res.json().catch(() => null)) as
| { message?: string | string[] }
| null;
const msg = Array.isArray(body?.message)
? body.message.join(', ')
: body?.message ?? res.statusText;
throw new ApiError(res.status, msg);
}
return res.json() as Promise<T>;
}
export { TOKEN_KEY };
+10
View File
@@ -19,6 +19,15 @@ export type BusinessCategory = {
updatedAt?: string;
};
export type BusinessImage = {
id: string;
businessId: string;
url: string;
originalName: string | null;
sortOrder: number;
isCover: boolean;
};
export type Business = {
id: string;
title: string;
@@ -32,6 +41,7 @@ export type Business = {
categoryId: string;
ownerId: string | null;
category?: BusinessCategory;
images?: BusinessImage[];
owner?: User | null;
createdAt?: string;
updatedAt?: string;
@@ -0,0 +1,133 @@
<template>
<div class="space-y-3">
<label class="block text-sm font-medium text-muted">تصاویر کسب‌وکار</label>
<p class="text-xs text-muted">حداکثر ۱۰ تصویر — هر کدام تا ۵ مگابایت (JPG, PNG, WebP)</p>
<div v-if="existing.length" class="grid grid-cols-3 gap-2">
<div
v-for="img in existing"
:key="img.id"
class="relative aspect-square overflow-hidden rounded-xl border border-border bg-surface-3"
>
<img :src="uploadUrl(img.url)" :alt="img.originalName ?? ''" class="h-full w-full object-cover" />
<span
v-if="img.isCover"
class="absolute left-1 top-1 rounded bg-brand-600/90 px-1.5 py-0.5 text-[10px] text-white"
>
کاور
</span>
<button
type="button"
class="absolute bottom-1 left-1 right-1 rounded-lg bg-black/60 py-1 text-xs text-white"
:disabled="deletingId === img.id"
@click="emit('remove-existing', img.id)"
>
حذف
</button>
</div>
</div>
<div v-if="pendingPreviews.length" class="grid grid-cols-3 gap-2">
<div
v-for="(src, idx) in pendingPreviews"
:key="idx"
class="relative aspect-square overflow-hidden rounded-xl border border-dashed border-brand-500/50"
>
<img :src="src" alt="" class="h-full w-full object-cover" />
<button
type="button"
class="absolute bottom-1 left-1 right-1 rounded-lg bg-black/60 py-1 text-xs text-white"
@click="removePending(idx)"
>
حذف
</button>
</div>
</div>
<label
class="flex cursor-pointer flex-col items-center justify-center rounded-xl border border-dashed border-border bg-surface-3 px-4 py-6 text-sm text-muted transition hover:border-brand-500/50 hover:bg-brand-500/5"
>
<span class="text-2xl">📷</span>
<span class="mt-2">افزودن تصویر</span>
<input
type="file"
accept="image/jpeg,image/png,image/webp,image/gif"
multiple
class="hidden"
@change="onPick"
/>
</label>
</div>
</template>
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue';
import type { BusinessImage } from '@/api/types';
import { uploadUrl } from '@/utils/media';
const props = defineProps<{
existing: BusinessImage[];
deletingId?: string | null;
}>();
const emit = defineEmits<{
'remove-existing': [imageId: string];
'pending-change': [files: File[]];
}>();
const pendingFiles = ref<File[]>([]);
const pendingPreviews = ref<string[]>([]);
function revokeAll() {
for (const url of pendingPreviews.value) {
URL.revokeObjectURL(url);
}
}
function syncPending() {
emit('pending-change', [...pendingFiles.value]);
}
function onPick(e: Event) {
const input = e.target as HTMLInputElement;
const picked = Array.from(input.files ?? []);
input.value = '';
if (!picked.length) return;
const total = props.existing.length + pendingFiles.value.length + picked.length;
if (total > 10) {
alert('حداکثر ۱۰ تصویر مجاز است.');
return;
}
for (const file of picked) {
pendingFiles.value.push(file);
pendingPreviews.value.push(URL.createObjectURL(file));
}
syncPending();
}
function removePending(index: number) {
URL.revokeObjectURL(pendingPreviews.value[index]);
pendingFiles.value.splice(index, 1);
pendingPreviews.value.splice(index, 1);
syncPending();
}
watch(
() => props.existing.length,
() => syncPending(),
);
onBeforeUnmount(revokeAll);
defineExpose({
clearPending() {
revokeAll();
pendingFiles.value = [];
pendingPreviews.value = [];
syncPending();
},
getPendingFiles: () => [...pendingFiles.value],
});
</script>
+58
View File
@@ -0,0 +1,58 @@
<template>
<article class="overflow-hidden rounded-2xl border border-border bg-surface-2 transition hover:border-brand-500/40 hover:shadow-md">
<div class="relative aspect-[16/10] bg-surface-3">
<img
v-if="cover"
:src="cover"
:alt="business.title"
class="h-full w-full object-cover"
loading="lazy"
/>
<div
v-else
class="flex h-full w-full items-center justify-center text-4xl text-muted/50"
>
🏪
</div>
<AppBadge
class="absolute left-2 top-2"
:tone="business.isActive ? 'success' : 'warning'"
>
{{ activeLabel(business.isActive) }}
</AppBadge>
</div>
<div class="p-3">
<h3 class="truncate font-semibold text-text">{{ business.title }}</h3>
<p v-if="business.category" class="mt-0.5 truncate text-xs text-muted">
{{ business.category.title }}
</p>
<p v-if="ownerText" class="mt-1 truncate text-xs text-muted">{{ ownerText }}</p>
<div v-if="$slots.actions" class="mt-3 grid gap-1" :class="actionGridClass">
<slot name="actions" />
</div>
</div>
</article>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import type { Business } from '@/api/types';
import AppBadge from '@/components/ui/AppBadge.vue';
import { activeLabel } from '@/utils/format';
import { businessCoverUrl } from '@/utils/media';
const props = defineProps<{
business: Business;
ownerText?: string | null;
actionCols?: number;
}>();
const cover = computed(() => businessCoverUrl(props.business.images));
const actionGridClass = computed(() => {
const cols = props.actionCols ?? 3;
return cols === 2 ? 'grid-cols-2' : 'grid-cols-3';
});
</script>
+59
View File
@@ -0,0 +1,59 @@
<template>
<RouterLink
:to="to"
class="group relative overflow-hidden rounded-2xl border border-border bg-surface-2 p-4 transition hover:border-brand-500/50 hover:shadow-md"
>
<div
class="pointer-events-none absolute -left-6 -top-6 h-20 w-20 rounded-full opacity-40 blur-2xl transition group-hover:opacity-60"
:class="accentClass"
/>
<div class="relative flex items-start justify-between gap-2">
<div>
<p class="text-xs font-medium text-muted">{{ label }}</p>
<p class="mt-2 text-3xl font-bold tracking-tight text-text">{{ value }}</p>
</div>
<span
class="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-lg"
:class="iconWrapClass"
>
{{ icon }}
</span>
</div>
</RouterLink>
</template>
<script setup lang="ts">
import { computed } from 'vue';
const props = defineProps<{
label: string;
value: number | string;
icon: string;
to: string;
tone?: 'amber' | 'emerald' | 'sky' | 'violet' | 'rose';
}>();
const tone = computed(() => props.tone ?? 'amber');
const accentClass = computed(() => {
const map = {
amber: 'bg-brand-500/30',
emerald: 'bg-emerald-500/30',
sky: 'bg-sky-500/30',
violet: 'bg-violet-500/30',
rose: 'bg-rose-500/30',
};
return map[tone.value];
});
const iconWrapClass = computed(() => {
const map = {
amber: 'bg-brand-500/15 text-brand-700 dark:text-brand-500',
emerald: 'bg-emerald-500/15 text-emerald-700 dark:text-emerald-400',
sky: 'bg-sky-500/15 text-sky-700 dark:text-sky-400',
violet: 'bg-violet-500/15 text-violet-700 dark:text-violet-400',
rose: 'bg-rose-500/15 text-rose-700 dark:text-rose-400',
};
return map[tone.value];
});
</script>
+21
View File
@@ -0,0 +1,21 @@
/** Base URL for uploaded files (empty = same origin /uploads via Vite proxy). */
const assetsBase = (import.meta.env.VITE_ASSETS_URL ?? '').replace(/\/$/, '');
export function uploadUrl(path: string | null | undefined): string {
if (!path) return '';
if (path.startsWith('http://') || path.startsWith('https://')) return path;
const rel = path.startsWith('/uploads/')
? path
: path.startsWith('/')
? path
: `/uploads/${path}`;
return assetsBase ? `${assetsBase}${rel}` : rel;
}
export function businessCoverUrl(
images?: { url: string; isCover?: boolean }[] | null,
): string | null {
if (!images?.length) return null;
const cover = images.find((i) => i.isCover) ?? images[0];
return uploadUrl(cover?.url) || null;
}
+61 -26
View File
@@ -30,26 +30,14 @@
کسب‌وکاری یافت نشد.
</EmptyState>
<ul v-else class="mt-4 space-y-2">
<li
<div v-else class="mt-4 grid grid-cols-1 gap-3 sm:grid-cols-2">
<BusinessListCard
v-for="biz in businesses"
:key="biz.id"
class="rounded-2xl border border-border bg-surface-2 p-4"
:business="biz"
:owner-text="ownerLabel(biz)"
>
<div class="flex items-start justify-between gap-2">
<div class="min-w-0 flex-1">
<p class="font-semibold text-text">{{ biz.title }}</p>
<p class="mt-0.5 text-xs text-muted" dir="ltr">{{ biz.slug }}</p>
<p v-if="biz.category" class="mt-1 text-xs text-muted">{{ biz.category.title }}</p>
<div class="mt-2 flex flex-wrap gap-2">
<AppBadge :tone="biz.isActive ? 'success' : 'warning'">
{{ activeLabel(biz.isActive) }}
</AppBadge>
<AppBadge v-if="ownerLabel(biz)" tone="default">{{ ownerLabel(biz) }}</AppBadge>
</div>
</div>
</div>
<div class="mt-3 grid grid-cols-3 gap-1">
<template #actions>
<AppButton variant="ghost" class="!w-auto px-2 text-xs" @click="openEdit(biz)">
ویرایش
</AppButton>
@@ -59,9 +47,9 @@
<AppButton variant="danger" class="!w-auto px-2 text-xs" @click="onDelete(biz)">
حذف
</AppButton>
</div>
</li>
</ul>
</template>
</BusinessListCard>
</div>
<!-- Create / Edit -->
<AppModal
@@ -90,6 +78,14 @@
<input v-model="form.isActive" type="checkbox" class="rounded border-border" />
فعال
</label>
<BusinessImageUpload
ref="imageUploadRef"
:existing="editingBusiness?.images ?? []"
:deleting-id="deletingImageId"
@remove-existing="onRemoveImage"
/>
<AppButton type="submit" :loading="saving">ذخیره</AppButton>
</form>
</AppModal>
@@ -126,13 +122,17 @@ import {
assignBusinessOwner,
createBusiness,
deleteBusiness,
deleteBusinessImage,
fetchBusiness,
fetchBusinesses,
updateBusiness,
uploadBusinessImages,
} from '@/api/businesses';
import { fetchUsers } from '@/api/users';
import type { Business, BusinessCategory, User } from '@/api/types';
import { ApiError } from '@/api/client';
import AppBadge from '@/components/ui/AppBadge.vue';
import BusinessImageUpload from '@/components/admin/BusinessImageUpload.vue';
import BusinessListCard from '@/components/admin/BusinessListCard.vue';
import AppButton from '@/components/ui/AppButton.vue';
import AppInput from '@/components/ui/AppInput.vue';
import AppModal from '@/components/ui/AppModal.vue';
@@ -141,7 +141,6 @@ import AppTextarea from '@/components/ui/AppTextarea.vue';
import EmptyState from '@/components/ui/EmptyState.vue';
import PageHeader from '@/components/ui/PageHeader.vue';
import AdminLayout from '@/layouts/AdminLayout.vue';
import { activeLabel } from '@/utils/format';
import { isValidIranMobile, normalizeIranMobile } from '@/utils/mobile';
import { isValidSlug, slugify } from '@/utils/slug';
@@ -161,6 +160,9 @@ const slugTouched = ref(false);
const assignOpen = ref(false);
const assignTarget = ref<Business | null>(null);
const editingBusiness = ref<Business | null>(null);
const imageUploadRef = ref<InstanceType<typeof BusinessImageUpload> | null>(null);
const deletingImageId = ref<string | null>(null);
const form = ref({
title: '',
@@ -231,7 +233,9 @@ function openCreate() {
return;
}
editingId.value = null;
editingBusiness.value = null;
slugTouched.value = false;
imageUploadRef.value?.clearPending();
form.value = {
title: '',
slug: '',
@@ -246,9 +250,15 @@ function openCreate() {
formOpen.value = true;
}
function openEdit(biz: Business) {
async function openEdit(biz: Business) {
editingId.value = biz.id;
slugTouched.value = true;
try {
editingBusiness.value = await fetchBusiness(biz.id);
} catch {
editingBusiness.value = biz;
}
imageUploadRef.value?.clearPending();
form.value = {
title: biz.title,
slug: biz.slug,
@@ -265,6 +275,23 @@ function openEdit(biz: Business) {
function closeForm() {
formOpen.value = false;
editingBusiness.value = null;
imageUploadRef.value?.clearPending();
}
async function onRemoveImage(imageId: string) {
if (!editingId.value) return;
deletingImageId.value = imageId;
error.value = '';
try {
await deleteBusinessImage(editingId.value, imageId);
editingBusiness.value = await fetchBusiness(editingId.value);
await load();
} catch (e) {
error.value = e instanceof ApiError ? e.message : 'خطا در حذف تصویر';
} finally {
deletingImageId.value = null;
}
}
function maybeSlug() {
@@ -295,8 +322,9 @@ async function onSaveBusiness() {
const lng = parseCoord(form.value.longitude);
try {
if (editingId.value) {
await updateBusiness(editingId.value, {
let businessId = editingId.value;
if (businessId) {
await updateBusiness(businessId, {
title: form.value.title.trim(),
slug: form.value.slug.trim(),
categoryId: form.value.categoryId,
@@ -308,7 +336,7 @@ async function onSaveBusiness() {
isActive: form.value.isActive,
});
} else {
await createBusiness({
const created = await createBusiness({
title: form.value.title.trim(),
slug: form.value.slug.trim(),
categoryId: form.value.categoryId,
@@ -319,7 +347,14 @@ async function onSaveBusiness() {
longitude: lng,
isActive: form.value.isActive,
});
businessId = created.id;
}
const pending = imageUploadRef.value?.getPendingFiles() ?? [];
if (businessId && pending.length > 0) {
await uploadBusinessImages(businessId, pending);
}
closeForm();
await load();
} catch (e) {
+68 -28
View File
@@ -1,6 +1,16 @@
<template>
<AdminLayout>
<PageHeader title="داشبورد" subtitle="خلاصه وضعیت سیستم" />
<section
class="relative overflow-hidden rounded-2xl border border-brand-500/25 bg-gradient-to-br from-brand-500/15 via-surface-2 to-surface-2 p-5"
>
<div class="relative">
<p class="text-sm text-muted">خوش آمدید</p>
<h1 class="mt-1 text-xl font-bold text-text">
{{ auth.user?.fullName ?? 'سوپر ادمین' }}
</h1>
<p class="mt-1 text-sm text-muted" dir="ltr">{{ auth.user?.mobile }}</p>
</div>
</section>
<p v-if="error" class="mt-4 rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-600">
{{ error }}
@@ -8,23 +18,46 @@
<div v-if="loading" class="mt-6 text-sm text-muted">در حال بارگذاری…</div>
<div v-else class="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<RouterLink
v-for="card in cards"
:key="card.label"
:to="card.to"
class="rounded-2xl border border-border bg-surface-2 p-4 transition hover:border-brand-500/50"
>
<p class="text-xs text-muted">{{ card.label }}</p>
<p class="mt-1 text-2xl font-bold text-text">{{ card.value }}</p>
</RouterLink>
</div>
<template v-else>
<div class="mt-6 grid grid-cols-2 gap-3 lg:grid-cols-3">
<StatCard
v-for="card in statCards"
:key="card.label"
:label="card.label"
:value="card.value"
:icon="card.icon"
:to="card.to"
:tone="card.tone"
/>
</div>
<div v-if="auth.user" class="mt-6 rounded-2xl border border-border bg-surface-2 p-4 text-sm">
<p class="text-xs text-muted">ورود شما</p>
<p class="mt-1 font-medium" dir="ltr">{{ auth.user.mobile }}</p>
<p class="mt-1 text-muted">{{ auth.user.fullName ?? 'بدون نام' }}</p>
</div>
<section class="mt-8">
<div class="mb-3 flex items-center justify-between">
<h2 class="text-base font-bold text-text">آخرین کسب‌وکارها</h2>
<RouterLink to="/businesses" class="text-sm text-brand-700 dark:text-brand-500">
همه
</RouterLink>
</div>
<EmptyState v-if="recentBusinesses.length === 0">
هنوز کسب‌وکاری ثبت نشده.
<RouterLink to="/businesses" class="mt-2 inline-block text-brand-700">
افزودن کسب‌وکار
</RouterLink>
</EmptyState>
<div v-else class="grid grid-cols-2 gap-3">
<RouterLink
v-for="biz in recentBusinesses"
:key="biz.id"
to="/businesses"
class="block"
>
<BusinessListCard :business="biz" />
</RouterLink>
</div>
</section>
</template>
</AdminLayout>
</template>
@@ -34,14 +67,18 @@ import { fetchBookings } from '@/api/bookings';
import { fetchCategories } from '@/api/business-categories';
import { fetchBusinesses } from '@/api/businesses';
import { fetchUsers } from '@/api/users';
import type { Business } from '@/api/types';
import { ApiError } from '@/api/client';
import PageHeader from '@/components/ui/PageHeader.vue';
import BusinessListCard from '@/components/admin/BusinessListCard.vue';
import StatCard from '@/components/admin/StatCard.vue';
import EmptyState from '@/components/ui/EmptyState.vue';
import AdminLayout from '@/layouts/AdminLayout.vue';
import { useAuthStore } from '@/stores/auth';
const auth = useAuthStore();
const loading = ref(true);
const error = ref('');
const businesses = ref<Business[]>([]);
const counts = ref({
businesses: 0,
activeBusinesses: 0,
@@ -50,31 +87,34 @@ const counts = ref({
categories: 0,
});
const cards = computed(() => [
{ label: 'کسب‌وکارها', value: counts.value.businesses, to: '/businesses' },
{ label: 'کسب‌وکار فعال', value: counts.value.activeBusinesses, to: '/businesses' },
{ label: 'رزروها', value: counts.value.bookings, to: '/bookings' },
{ label: 'کاربران', value: counts.value.users, to: '/users' },
{ label: 'دسته‌ها', value: counts.value.categories, to: '/categories' },
const statCards = computed(() => [
{ label: 'کسب‌وکار', value: counts.value.businesses, icon: '🏪', to: '/businesses', tone: 'amber' as const },
{ label: 'فعال', value: counts.value.activeBusinesses, icon: '✓', to: '/businesses', tone: 'emerald' as const },
{ label: 'رزرو', value: counts.value.bookings, icon: '📅', to: '/bookings', tone: 'sky' as const },
{ label: 'کاربر', value: counts.value.users, icon: '👥', to: '/users', tone: 'violet' as const },
{ label: 'دسته', value: counts.value.categories, icon: '📁', to: '/categories', tone: 'rose' as const },
]);
const recentBusinesses = computed(() => businesses.value.slice(0, 6));
onMounted(async () => {
try {
const [businesses, users, categories, bookingList] = await Promise.all([
const [bizList, users, categories, bookingList] = await Promise.all([
fetchBusinesses(),
fetchUsers(),
fetchCategories(),
fetchBookings().catch(() => []),
]);
businesses.value = bizList;
counts.value = {
businesses: businesses.length,
activeBusinesses: businesses.filter((b) => b.isActive).length,
businesses: bizList.length,
activeBusinesses: bizList.filter((b) => b.isActive).length,
bookings: bookingList.length,
users: users.length,
categories: categories.length,
};
} catch (e) {
error.value = e instanceof ApiError ? e.message : 'خطا در بارگذاری آمار';
error.value = e instanceof ApiError ? e.message : 'خطا در بارگذاری';
} finally {
loading.value = false;
}
+5
View File
@@ -20,6 +20,11 @@ export default defineConfig({
secure: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
'/uploads': {
target: API_TARGET,
changeOrigin: true,
secure: true,
},
},
},
});