Add Mellat e-payment, videos/instructions CMS, and legacy domain lookup.
Store gateway credentials per business, initiate/verify Mellat at checkout, and resolve old CMS ids from domains in the migrate modal. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
parent
513673a7da
commit
d5e502cf77
@@ -0,0 +1,197 @@
|
||||
import { ContentStatus, VideoProvider } from '@prisma/client';
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
IsArray,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Matches,
|
||||
Min,
|
||||
MinLength,
|
||||
} from 'class-validator';
|
||||
|
||||
export class ListVideosDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
pageSize?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ContentStatus)
|
||||
status?: ContentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(VideoProvider)
|
||||
provider?: VideoProvider;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
categoryId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export class ListPublicVideosDto {
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(1)
|
||||
pageSize?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(VideoProvider)
|
||||
provider?: VideoProvider;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
categoryId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export class CreateVideoDto {
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
titleFa!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
titleEn?: string;
|
||||
|
||||
/** @deprecated use titleFa */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
title?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
abstract?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
descriptionHtml?: string;
|
||||
|
||||
@IsEnum(VideoProvider)
|
||||
videoProvider!: VideoProvider;
|
||||
|
||||
@IsString()
|
||||
@MinLength(10)
|
||||
embedCode!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
categoryId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ContentStatus)
|
||||
status?: ContentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
featuredMediaId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
tags?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
authorId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
export class UpdateVideoDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
titleFa?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
titleEn?: string | null;
|
||||
|
||||
/** @deprecated use titleFa */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
title?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
abstract?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
descriptionHtml?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(VideoProvider)
|
||||
videoProvider?: VideoProvider;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(10)
|
||||
embedCode?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
categoryId?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsEnum(ContentStatus)
|
||||
status?: ContentStatus;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
featuredMediaId?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
tags?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
authorId?: string | null;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@Matches(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
export class CreateVideoCommentDto {
|
||||
@IsString()
|
||||
@MinLength(2)
|
||||
authorName!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
authorEmail?: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
text!: string;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { RequireBusinessPermission } from '../auth/decorators/require-business-permission.decorator';
|
||||
import { BusinessPermissionGuard } from '../auth/guards/business-permission.guard';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { VideosService } from './videos.service';
|
||||
import {
|
||||
CreateVideoCommentDto,
|
||||
CreateVideoDto,
|
||||
ListPublicVideosDto,
|
||||
ListVideosDto,
|
||||
UpdateVideoDto,
|
||||
} from './dto/video.dto';
|
||||
|
||||
@Controller('businesses/:businessId/videos')
|
||||
@UseGuards(JwtAuthGuard, BusinessPermissionGuard)
|
||||
export class VideosController {
|
||||
constructor(private readonly service: VideosService) {}
|
||||
|
||||
@Get()
|
||||
@RequireBusinessPermission('videos.read')
|
||||
list(
|
||||
@Param('businessId') businessId: string,
|
||||
@Query() query: ListVideosDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.service.list(businessId, query, user);
|
||||
}
|
||||
|
||||
@Get(':videoId')
|
||||
@RequireBusinessPermission('videos.read')
|
||||
getOne(
|
||||
@Param('businessId') businessId: string,
|
||||
@Param('videoId') videoId: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.service.getOne(businessId, videoId, user);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@RequireBusinessPermission('videos.create')
|
||||
create(
|
||||
@Param('businessId') businessId: string,
|
||||
@Body() dto: CreateVideoDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.service.create(businessId, dto, user);
|
||||
}
|
||||
|
||||
@Patch(':videoId')
|
||||
@RequireBusinessPermission('videos.update')
|
||||
update(
|
||||
@Param('businessId') businessId: string,
|
||||
@Param('videoId') videoId: string,
|
||||
@Body() dto: UpdateVideoDto,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.service.update(businessId, videoId, dto, user);
|
||||
}
|
||||
|
||||
@Delete(':videoId')
|
||||
@RequireBusinessPermission('videos.delete')
|
||||
remove(
|
||||
@Param('businessId') businessId: string,
|
||||
@Param('videoId') videoId: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.service.remove(businessId, videoId, user);
|
||||
}
|
||||
|
||||
@Get(':videoId/comments')
|
||||
@RequireBusinessPermission('comments.read')
|
||||
listComments(
|
||||
@Param('businessId') businessId: string,
|
||||
@Param('videoId') videoId: string,
|
||||
@CurrentUser() user: AuthUser,
|
||||
) {
|
||||
return this.service.listCommentsAdmin(businessId, videoId, user);
|
||||
}
|
||||
}
|
||||
|
||||
@Controller('tenants/:host/videos')
|
||||
export class PublicVideosController {
|
||||
constructor(private readonly service: VideosService) {}
|
||||
|
||||
@Get()
|
||||
list(@Param('host') host: string, @Query() query: ListPublicVideosDto) {
|
||||
return this.service.listPublic(host, query);
|
||||
}
|
||||
|
||||
@Get(':videoId/comments')
|
||||
listComments(@Param('host') host: string, @Param('videoId') videoId: string) {
|
||||
return this.service.listCommentsPublic(host, videoId);
|
||||
}
|
||||
|
||||
@Post(':videoId/comments')
|
||||
createComment(
|
||||
@Param('host') host: string,
|
||||
@Param('videoId') videoId: string,
|
||||
@Body() dto: CreateVideoCommentDto,
|
||||
) {
|
||||
return this.service.createCommentPublic(host, videoId, dto);
|
||||
}
|
||||
|
||||
@Get(':slug')
|
||||
getBySlug(@Param('host') host: string, @Param('slug') slug: string) {
|
||||
return this.service.getPublicBySlug(host, slug);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { BusinessSettingsModule } from '../business-settings/business-settings.module';
|
||||
import { TenantModule } from '../tenant/tenant.module';
|
||||
import { PublicVideosController, VideosController } from './videos.controller';
|
||||
import { VideosService } from './videos.service';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule, BusinessSettingsModule, TenantModule],
|
||||
controllers: [VideosController, PublicVideosController],
|
||||
providers: [VideosService],
|
||||
})
|
||||
export class VideosModule {}
|
||||
@@ -0,0 +1,825 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ContentStatus,
|
||||
MediaEntityType,
|
||||
Prisma,
|
||||
VideoProvider,
|
||||
} from '@prisma/client';
|
||||
import { AuthUser } from '../auth/auth.types';
|
||||
import { PermissionsService } from '../auth/permissions.service';
|
||||
import { BusinessSettingsService } from '../business-settings/business-settings.service';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { TenantService } from '../tenant/tenant.service';
|
||||
import {
|
||||
CreateVideoCommentDto,
|
||||
CreateVideoDto,
|
||||
ListPublicVideosDto,
|
||||
ListVideosDto,
|
||||
UpdateVideoDto,
|
||||
} from './dto/video.dto';
|
||||
|
||||
function slugify(value: string): string {
|
||||
return (
|
||||
value
|
||||
.toLowerCase()
|
||||
.trim()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '') || 'video'
|
||||
);
|
||||
}
|
||||
|
||||
type VideoWithRelations = Prisma.videosGetPayload<{
|
||||
include: {
|
||||
media: true;
|
||||
author: {
|
||||
select: { id: true; firstName: true; lastName: true; email: true };
|
||||
};
|
||||
};
|
||||
}>;
|
||||
|
||||
const videoInclude = {
|
||||
media: true,
|
||||
author: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
} satisfies Prisma.videosInclude;
|
||||
|
||||
@Injectable()
|
||||
export class VideosService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly tenant: TenantService,
|
||||
private readonly businessSettings: BusinessSettingsService,
|
||||
) {}
|
||||
|
||||
async list(businessIdRaw: string, query: ListVideosDto, actor: AuthUser) {
|
||||
const businessId = BigInt(businessIdRaw);
|
||||
await this.assertPermission(businessId, actor.id, 'videos.read');
|
||||
|
||||
const page = query.page ?? 1;
|
||||
const pageSize = query.pageSize ?? 12;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const where = await this.buildWhere(businessId, query);
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.videos.findMany({
|
||||
where,
|
||||
orderBy: [{ published_at: 'desc' }, { created_at: 'desc' }],
|
||||
skip,
|
||||
take: pageSize,
|
||||
include: videoInclude,
|
||||
}),
|
||||
this.prisma.videos.count({ where }),
|
||||
]);
|
||||
|
||||
const serialized = await Promise.all(
|
||||
items.map((item) => this.serializeVideo(item, { includeComments: true })),
|
||||
);
|
||||
|
||||
return { items: serialized, total, page, pageSize };
|
||||
}
|
||||
|
||||
async getOne(businessIdRaw: string, videoIdRaw: string, actor: AuthUser) {
|
||||
const businessId = BigInt(businessIdRaw);
|
||||
const videoId = BigInt(videoIdRaw);
|
||||
await this.assertPermission(businessId, actor.id, 'videos.read');
|
||||
|
||||
const video = await this.findVideoOrThrow(businessId, videoId);
|
||||
|
||||
return {
|
||||
video: await this.serializeVideo(video, { includeComments: true }),
|
||||
};
|
||||
}
|
||||
|
||||
async create(businessIdRaw: string, dto: CreateVideoDto, actor: AuthUser) {
|
||||
const businessId = BigInt(businessIdRaw);
|
||||
await this.assertPermission(businessId, actor.id, 'videos.create');
|
||||
|
||||
const titleFa = this.resolveTitleFa(dto.titleFa, dto.title);
|
||||
const titleEn = dto.titleEn?.trim() || null;
|
||||
if (!titleFa) {
|
||||
throw new BadRequestException('titleFa is required');
|
||||
}
|
||||
|
||||
const slug = await this.ensureUniqueSlug(
|
||||
businessId,
|
||||
dto.slug ?? slugify(titleEn || titleFa),
|
||||
);
|
||||
|
||||
const status = dto.status ?? ContentStatus.published;
|
||||
const featuredMediaId = dto.featuredMediaId
|
||||
? BigInt(dto.featuredMediaId)
|
||||
: null;
|
||||
|
||||
if (featuredMediaId) {
|
||||
await this.assertMediaBelongsToBusiness(businessId, featuredMediaId);
|
||||
}
|
||||
|
||||
const authorId = dto.authorId ? BigInt(dto.authorId) : actor.id;
|
||||
await this.assertAuthorBelongsToBusiness(businessId, authorId);
|
||||
|
||||
if (dto.categoryId) {
|
||||
await this.assertCategoryBelongsToBusiness(
|
||||
businessId,
|
||||
BigInt(dto.categoryId),
|
||||
);
|
||||
}
|
||||
|
||||
const created = await this.prisma.$transaction(async (tx) => {
|
||||
const video = await tx.videos.create({
|
||||
data: {
|
||||
business_id: businessId,
|
||||
author_id: authorId,
|
||||
title: titleFa,
|
||||
title_fa: titleFa,
|
||||
title_en: titleEn,
|
||||
slug,
|
||||
excerpt: dto.abstract?.trim() || null,
|
||||
content: this.buildContent(dto.descriptionHtml) as Prisma.InputJsonValue,
|
||||
video_provider: dto.videoProvider,
|
||||
embed_code: dto.embedCode.trim(),
|
||||
status,
|
||||
featured_media_id: featuredMediaId,
|
||||
published_at: status === ContentStatus.published ? new Date() : null,
|
||||
metadata: this.buildMetadata(dto.tags) as Prisma.InputJsonValue,
|
||||
},
|
||||
include: videoInclude,
|
||||
});
|
||||
|
||||
if (dto.categoryId) {
|
||||
await tx.categoryAssignment.create({
|
||||
data: {
|
||||
businessId,
|
||||
categoryId: BigInt(dto.categoryId),
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: video.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return video;
|
||||
});
|
||||
|
||||
return {
|
||||
message: 'Video created successfully',
|
||||
video: await this.serializeVideo(created),
|
||||
};
|
||||
}
|
||||
|
||||
async update(
|
||||
businessIdRaw: string,
|
||||
videoIdRaw: string,
|
||||
dto: UpdateVideoDto,
|
||||
actor: AuthUser,
|
||||
) {
|
||||
const businessId = BigInt(businessIdRaw);
|
||||
const videoId = BigInt(videoIdRaw);
|
||||
await this.assertPermission(businessId, actor.id, 'videos.update');
|
||||
|
||||
const existing = await this.prisma.videos.findFirst({
|
||||
where: { id: videoId, business_id: businessId },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundException('Video not found');
|
||||
}
|
||||
|
||||
const nextTitleFa =
|
||||
dto.titleFa !== undefined || dto.title !== undefined
|
||||
? this.resolveTitleFa(dto.titleFa, dto.title)
|
||||
: undefined;
|
||||
|
||||
if (
|
||||
(dto.titleFa !== undefined || dto.title !== undefined) &&
|
||||
!nextTitleFa
|
||||
) {
|
||||
throw new BadRequestException('titleFa is required');
|
||||
}
|
||||
|
||||
let slug = existing.slug;
|
||||
if (dto.slug) {
|
||||
slug = await this.ensureUniqueSlug(businessId, dto.slug, videoId);
|
||||
} else if (nextTitleFa && nextTitleFa !== (existing.title_fa ?? existing.title)) {
|
||||
const slugBase =
|
||||
(dto.titleEn !== undefined
|
||||
? dto.titleEn?.trim() || null
|
||||
: existing.title_en) || nextTitleFa;
|
||||
slug = await this.ensureUniqueSlug(businessId, slugify(slugBase), videoId);
|
||||
}
|
||||
|
||||
let featuredMediaId: bigint | null | undefined = undefined;
|
||||
if (dto.featuredMediaId !== undefined) {
|
||||
if (dto.featuredMediaId === null || dto.featuredMediaId === '') {
|
||||
featuredMediaId = null;
|
||||
} else {
|
||||
featuredMediaId = BigInt(dto.featuredMediaId);
|
||||
await this.assertMediaBelongsToBusiness(businessId, featuredMediaId);
|
||||
}
|
||||
}
|
||||
|
||||
let authorId: bigint | null | undefined = undefined;
|
||||
if (dto.authorId !== undefined) {
|
||||
if (dto.authorId === null || dto.authorId === '') {
|
||||
authorId = null;
|
||||
} else {
|
||||
authorId = BigInt(dto.authorId);
|
||||
await this.assertAuthorBelongsToBusiness(businessId, authorId);
|
||||
}
|
||||
}
|
||||
|
||||
const existingContent = this.asRecord(existing.content);
|
||||
const existingMetadata = this.asRecord(existing.metadata);
|
||||
|
||||
const nextContent = { ...existingContent };
|
||||
if (dto.descriptionHtml !== undefined) {
|
||||
nextContent.html = dto.descriptionHtml ?? '';
|
||||
}
|
||||
|
||||
const nextMetadata = { ...existingMetadata };
|
||||
if (dto.tags !== undefined) {
|
||||
nextMetadata.tags = dto.tags;
|
||||
}
|
||||
|
||||
let publishedAt: Date | null | undefined = undefined;
|
||||
if (dto.status !== undefined) {
|
||||
if (
|
||||
dto.status === ContentStatus.published &&
|
||||
existing.status !== ContentStatus.published
|
||||
) {
|
||||
publishedAt = new Date();
|
||||
}
|
||||
if (dto.status !== ContentStatus.published) {
|
||||
publishedAt = null;
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await this.prisma.$transaction(async (tx) => {
|
||||
const video = await tx.videos.update({
|
||||
where: { id: videoId },
|
||||
data: {
|
||||
...(nextTitleFa !== undefined
|
||||
? { title: nextTitleFa, title_fa: nextTitleFa }
|
||||
: {}),
|
||||
...(dto.titleEn !== undefined
|
||||
? { title_en: dto.titleEn?.trim() || null }
|
||||
: {}),
|
||||
...(dto.abstract !== undefined
|
||||
? { excerpt: dto.abstract?.trim() || null }
|
||||
: {}),
|
||||
...(dto.videoProvider !== undefined
|
||||
? { video_provider: dto.videoProvider }
|
||||
: {}),
|
||||
...(dto.embedCode !== undefined
|
||||
? { embed_code: dto.embedCode.trim() }
|
||||
: {}),
|
||||
...(dto.status !== undefined ? { status: dto.status } : {}),
|
||||
...(featuredMediaId !== undefined
|
||||
? { featured_media_id: featuredMediaId }
|
||||
: {}),
|
||||
...(authorId !== undefined ? { author_id: authorId } : {}),
|
||||
...(publishedAt !== undefined ? { published_at: publishedAt } : {}),
|
||||
slug,
|
||||
content: nextContent as Prisma.InputJsonValue,
|
||||
metadata: nextMetadata as Prisma.InputJsonValue,
|
||||
},
|
||||
include: videoInclude,
|
||||
});
|
||||
|
||||
if (dto.categoryId !== undefined) {
|
||||
await tx.categoryAssignment.deleteMany({
|
||||
where: {
|
||||
businessId,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: videoId,
|
||||
},
|
||||
});
|
||||
|
||||
if (dto.categoryId) {
|
||||
const categoryId = BigInt(dto.categoryId);
|
||||
await this.assertCategoryBelongsToBusiness(businessId, categoryId);
|
||||
await tx.categoryAssignment.create({
|
||||
data: {
|
||||
businessId,
|
||||
categoryId,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: videoId,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return video;
|
||||
});
|
||||
|
||||
return {
|
||||
message: 'Video updated successfully',
|
||||
video: await this.serializeVideo(updated),
|
||||
};
|
||||
}
|
||||
|
||||
async remove(businessIdRaw: string, videoIdRaw: string, actor: AuthUser) {
|
||||
const businessId = BigInt(businessIdRaw);
|
||||
const videoId = BigInt(videoIdRaw);
|
||||
await this.assertPermission(businessId, actor.id, 'videos.delete');
|
||||
|
||||
const existing = await this.prisma.videos.findFirst({
|
||||
where: { id: videoId, business_id: businessId },
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new NotFoundException('Video not found');
|
||||
}
|
||||
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.comment.deleteMany({
|
||||
where: {
|
||||
businessId,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: videoId,
|
||||
},
|
||||
}),
|
||||
this.prisma.categoryAssignment.deleteMany({
|
||||
where: {
|
||||
businessId,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: videoId,
|
||||
},
|
||||
}),
|
||||
this.prisma.videos.delete({ where: { id: videoId } }),
|
||||
]);
|
||||
|
||||
return { message: 'Video deleted successfully' };
|
||||
}
|
||||
|
||||
async listPublic(host: string, query: ListPublicVideosDto) {
|
||||
const business = await this.tenant.resolveBusinessByDomain(host);
|
||||
const businessId = business.id;
|
||||
|
||||
const page = query.page ?? 1;
|
||||
const pageSize = query.pageSize ?? 12;
|
||||
const skip = (page - 1) * pageSize;
|
||||
|
||||
const where = await this.buildWhere(businessId, {
|
||||
...query,
|
||||
status: ContentStatus.published,
|
||||
});
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
this.prisma.videos.findMany({
|
||||
where,
|
||||
orderBy: [{ published_at: 'desc' }, { created_at: 'desc' }],
|
||||
skip,
|
||||
take: pageSize,
|
||||
include: videoInclude,
|
||||
}),
|
||||
this.prisma.videos.count({ where }),
|
||||
]);
|
||||
|
||||
const serialized = await Promise.all(
|
||||
items.map((item) =>
|
||||
this.serializeVideo(item, {
|
||||
includeComments: true,
|
||||
approvedCommentsOnly: true,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return { items: serialized, total, page, pageSize };
|
||||
}
|
||||
|
||||
async getPublicBySlug(host: string, slug: string) {
|
||||
const business = await this.tenant.resolveBusinessByDomain(host);
|
||||
const businessId = business.id;
|
||||
|
||||
const video = await this.prisma.videos.findFirst({
|
||||
where: {
|
||||
business_id: businessId,
|
||||
slug,
|
||||
status: ContentStatus.published,
|
||||
},
|
||||
include: videoInclude,
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
throw new NotFoundException('Video not found');
|
||||
}
|
||||
|
||||
return {
|
||||
video: await this.serializeVideo(video, {
|
||||
includeComments: true,
|
||||
approvedCommentsOnly: true,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async listCommentsPublic(host: string, videoIdRaw: string) {
|
||||
const business = await this.tenant.resolveBusinessByDomain(host);
|
||||
const businessId = business.id;
|
||||
const videoId = BigInt(videoIdRaw);
|
||||
|
||||
await this.assertPublishedVideoExists(businessId, videoId);
|
||||
|
||||
const items = await this.prisma.comment.findMany({
|
||||
where: {
|
||||
businessId,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: videoId,
|
||||
isApproved: true,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { approver: true },
|
||||
});
|
||||
|
||||
return { items: items.map((item) => this.serializeComment(item)) };
|
||||
}
|
||||
|
||||
async createCommentPublic(
|
||||
host: string,
|
||||
videoIdRaw: string,
|
||||
dto: CreateVideoCommentDto,
|
||||
) {
|
||||
const business = await this.tenant.resolveBusinessByDomain(host);
|
||||
const businessId = business.id;
|
||||
const videoId = BigInt(videoIdRaw);
|
||||
|
||||
await this.assertPublishedVideoExists(businessId, videoId);
|
||||
|
||||
const autoApprove =
|
||||
await this.businessSettings.isCommentsAutoApprove(businessId);
|
||||
const approvedAt = autoApprove ? new Date() : null;
|
||||
|
||||
const created = await this.prisma.comment.create({
|
||||
data: {
|
||||
businessId,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: videoId,
|
||||
authorName: dto.authorName.trim(),
|
||||
authorEmail: dto.authorEmail?.trim() || null,
|
||||
text: dto.text.trim(),
|
||||
isApproved: autoApprove,
|
||||
approvedAt,
|
||||
},
|
||||
include: { approver: true },
|
||||
});
|
||||
|
||||
return {
|
||||
comment: this.serializeComment(created),
|
||||
message: autoApprove
|
||||
? 'Comment submitted and is approved'
|
||||
: 'Comment submitted and is pending approval',
|
||||
};
|
||||
}
|
||||
|
||||
async listCommentsAdmin(
|
||||
businessIdRaw: string,
|
||||
videoIdRaw: string,
|
||||
actor: AuthUser,
|
||||
) {
|
||||
const businessId = BigInt(businessIdRaw);
|
||||
const videoId = BigInt(videoIdRaw);
|
||||
await this.assertPermission(businessId, actor.id, 'comments.read');
|
||||
|
||||
const video = await this.prisma.videos.findFirst({
|
||||
where: { id: videoId, business_id: businessId },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
throw new NotFoundException('Video not found');
|
||||
}
|
||||
|
||||
const items = await this.prisma.comment.findMany({
|
||||
where: {
|
||||
businessId,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: videoId,
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: { approver: true },
|
||||
});
|
||||
|
||||
return { items: items.map((item) => this.serializeComment(item)) };
|
||||
}
|
||||
|
||||
private resolveTitleFa(titleFa?: string, title?: string): string {
|
||||
return (titleFa ?? title ?? '').trim();
|
||||
}
|
||||
|
||||
private async buildWhere(
|
||||
businessId: bigint,
|
||||
query: (ListVideosDto | ListPublicVideosDto) & { status?: ContentStatus },
|
||||
): Promise<Prisma.videosWhereInput> {
|
||||
let entityIds: bigint[] | undefined;
|
||||
|
||||
if (query.categoryId) {
|
||||
const assignments = await this.prisma.categoryAssignment.findMany({
|
||||
where: {
|
||||
businessId,
|
||||
categoryId: BigInt(query.categoryId),
|
||||
entityType: MediaEntityType.video,
|
||||
},
|
||||
select: { entityId: true },
|
||||
});
|
||||
|
||||
entityIds = assignments.map((item) => item.entityId);
|
||||
|
||||
if (entityIds.length === 0) {
|
||||
return { id: { in: [] } };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
business_id: businessId,
|
||||
...(query.status ? { status: query.status } : {}),
|
||||
...(query.provider ? { video_provider: query.provider } : {}),
|
||||
...(entityIds ? { id: { in: entityIds } } : {}),
|
||||
...(query.title?.trim()
|
||||
? {
|
||||
OR: [
|
||||
{
|
||||
title_fa: {
|
||||
contains: query.title.trim(),
|
||||
mode: 'insensitive',
|
||||
},
|
||||
},
|
||||
{
|
||||
title_en: {
|
||||
contains: query.title.trim(),
|
||||
mode: 'insensitive',
|
||||
},
|
||||
},
|
||||
{
|
||||
title: { contains: query.title.trim(), mode: 'insensitive' },
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
private async findVideoOrThrow(businessId: bigint, videoId: bigint) {
|
||||
const video = await this.prisma.videos.findFirst({
|
||||
where: { id: videoId, business_id: businessId },
|
||||
include: videoInclude,
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
throw new NotFoundException('Video not found');
|
||||
}
|
||||
|
||||
return video;
|
||||
}
|
||||
|
||||
private async assertPublishedVideoExists(
|
||||
businessId: bigint,
|
||||
videoId: bigint,
|
||||
) {
|
||||
const video = await this.prisma.videos.findFirst({
|
||||
where: {
|
||||
id: videoId,
|
||||
business_id: businessId,
|
||||
status: ContentStatus.published,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!video) {
|
||||
throw new NotFoundException('Video not found');
|
||||
}
|
||||
}
|
||||
|
||||
private async serializeVideo(
|
||||
video: VideoWithRelations,
|
||||
options: {
|
||||
includeComments?: boolean;
|
||||
approvedCommentsOnly?: boolean;
|
||||
} = {},
|
||||
) {
|
||||
const content = this.asRecord(video.content);
|
||||
const metadata = this.asRecord(video.metadata);
|
||||
|
||||
const [categoryAssignment, commentData] = await Promise.all([
|
||||
this.prisma.categoryAssignment.findFirst({
|
||||
where: {
|
||||
businessId: video.business_id,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: video.id,
|
||||
},
|
||||
include: { category: true },
|
||||
}),
|
||||
options.includeComments
|
||||
? this.loadComments(
|
||||
video.business_id,
|
||||
video.id,
|
||||
options.approvedCommentsOnly,
|
||||
)
|
||||
: Promise.resolve({ commentCount: 0, comments: [] }),
|
||||
]);
|
||||
|
||||
return {
|
||||
id: video.id.toString(),
|
||||
businessId: video.business_id.toString(),
|
||||
title: video.title,
|
||||
titleFa: video.title_fa ?? video.title,
|
||||
titleEn: video.title_en,
|
||||
slug: video.slug,
|
||||
abstract: video.excerpt ?? '',
|
||||
descriptionHtml: (content.html as string | undefined) ?? '',
|
||||
videoProvider: video.video_provider,
|
||||
embedCode: video.embed_code,
|
||||
status: video.status,
|
||||
categoryId: categoryAssignment?.categoryId.toString() ?? null,
|
||||
categoryName: categoryAssignment?.category.name ?? '',
|
||||
tags: Array.isArray(metadata.tags) ? (metadata.tags as string[]) : [],
|
||||
authorId: video.author_id?.toString() ?? null,
|
||||
author: video.author
|
||||
? {
|
||||
id: video.author.id.toString(),
|
||||
firstName: video.author.firstName,
|
||||
lastName: video.author.lastName,
|
||||
email: video.author.email,
|
||||
}
|
||||
: null,
|
||||
coverImageUrl: video.media?.publicUrl ?? null,
|
||||
featuredMediaId: video.featured_media_id?.toString() ?? null,
|
||||
commentCount: commentData.commentCount,
|
||||
comments: commentData.comments,
|
||||
publishedAt: video.published_at,
|
||||
createdAt: video.created_at,
|
||||
updatedAt: video.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
private async loadComments(
|
||||
businessId: bigint,
|
||||
videoId: bigint,
|
||||
approvedOnly?: boolean,
|
||||
) {
|
||||
const where: Prisma.CommentWhereInput = {
|
||||
businessId,
|
||||
entityType: MediaEntityType.video,
|
||||
entityId: videoId,
|
||||
...(approvedOnly ? { isApproved: true } : {}),
|
||||
};
|
||||
|
||||
const [commentCount, comments] = await Promise.all([
|
||||
this.prisma.comment.count({ where }),
|
||||
this.prisma.comment.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
take: approvedOnly ? 50 : undefined,
|
||||
include: { approver: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
commentCount,
|
||||
comments: comments.map((item) => this.serializeComment(item)),
|
||||
};
|
||||
}
|
||||
|
||||
private serializeComment(
|
||||
comment: Prisma.CommentGetPayload<{ include: { approver: true } }>,
|
||||
) {
|
||||
return {
|
||||
id: comment.id.toString(),
|
||||
businessId: comment.businessId.toString(),
|
||||
entityType: comment.entityType,
|
||||
entityId: comment.entityId.toString(),
|
||||
authorName: comment.authorName,
|
||||
authorEmail: comment.authorEmail,
|
||||
text: comment.text,
|
||||
isApproved: comment.isApproved,
|
||||
approvedAt: comment.approvedAt,
|
||||
approvedBy: comment.approvedBy?.toString() ?? null,
|
||||
approver: comment.approver
|
||||
? {
|
||||
id: comment.approver.id.toString(),
|
||||
firstName: comment.approver.firstName,
|
||||
lastName: comment.approver.lastName,
|
||||
}
|
||||
: null,
|
||||
createdAt: comment.createdAt,
|
||||
updatedAt: comment.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
private buildContent(descriptionHtml?: string) {
|
||||
return {
|
||||
html: descriptionHtml ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
private buildMetadata(tags?: string[]) {
|
||||
return {
|
||||
tags: tags?.map((tag) => tag.trim()).filter(Boolean) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
private asRecord(value: Prisma.JsonValue): Record<string, unknown> {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
private async assertMediaBelongsToBusiness(
|
||||
businessId: bigint,
|
||||
mediaId: bigint,
|
||||
) {
|
||||
const media = await this.prisma.media.findFirst({
|
||||
where: { id: mediaId, businessId },
|
||||
});
|
||||
if (!media) {
|
||||
throw new BadRequestException('Media not found for this business');
|
||||
}
|
||||
}
|
||||
|
||||
private async assertCategoryBelongsToBusiness(
|
||||
businessId: bigint,
|
||||
categoryId: bigint,
|
||||
) {
|
||||
const category = await this.prisma.category.findFirst({
|
||||
where: {
|
||||
id: categoryId,
|
||||
businessId,
|
||||
entityType: MediaEntityType.video,
|
||||
isActive: true,
|
||||
},
|
||||
});
|
||||
if (!category) {
|
||||
throw new BadRequestException('Video category not found for this business');
|
||||
}
|
||||
}
|
||||
|
||||
private async assertAuthorBelongsToBusiness(
|
||||
businessId: bigint,
|
||||
authorId: bigint,
|
||||
) {
|
||||
const member = await this.prisma.businessUser.findFirst({
|
||||
where: { businessId, userId: authorId },
|
||||
});
|
||||
|
||||
if (!member) {
|
||||
throw new BadRequestException(
|
||||
'Author must be a team member of this business',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async ensureUniqueSlug(
|
||||
businessId: bigint,
|
||||
baseSlug: string,
|
||||
excludeId?: bigint,
|
||||
) {
|
||||
let slug = baseSlug;
|
||||
let suffix = 1;
|
||||
|
||||
while (true) {
|
||||
const existing = await this.prisma.videos.findFirst({
|
||||
where: {
|
||||
business_id: businessId,
|
||||
slug,
|
||||
...(excludeId ? { NOT: { id: excludeId } } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
return slug;
|
||||
}
|
||||
|
||||
suffix += 1;
|
||||
slug = `${baseSlug}-${suffix}`;
|
||||
}
|
||||
}
|
||||
|
||||
private async assertPermission(
|
||||
businessId: bigint,
|
||||
userId: bigint,
|
||||
permission: string,
|
||||
) {
|
||||
const allowed = await this.permissions.hasBusinessPermission(
|
||||
userId,
|
||||
businessId,
|
||||
permission,
|
||||
);
|
||||
|
||||
if (!allowed) {
|
||||
throw new ForbiddenException(
|
||||
`Missing permission: ${permission} for this business`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user