Files
tgex-backend/src/usecase/external_channel/create_external_channel.py
Artem Tsyrulnikov af32e2a507 feat: add workspace
2025-12-13 22:09:55 +03:00

54 lines
1.8 KiB
Python

import logging
import uuid
from typing import TYPE_CHECKING
from src import domain, dto
if TYPE_CHECKING:
from .. import Usecase
log = logging.getLogger(__name__)
async def create_external_channel(
self: 'Usecase', input: dto.CreateExternalChannelInput, user_id: uuid.UUID, workspace_id: uuid.UUID
) -> dto.ExternalChannelOutput:
await self.ensure_workspace_access(workspace_id, user_id)
existing_channel = await self.database.get_external_channel(workspace_id, telegram_id=input.telegram_id)
if existing_channel:
raise domain.ExternalChannelAlreadyExists(input.telegram_id)
for target_id in input.target_channel_ids:
target_channel = await self.database.get_target_channel(workspace_id, channel_id=target_id)
if not target_channel:
raise domain.TargetChannelNotFound(target_id)
async with self.database.transaction():
channel = domain.ExternalChannel(
telegram_id=input.telegram_id,
title=input.title,
username=input.username,
description=input.description,
subscribers_count=input.subscribers_count,
workspace_id=workspace_id,
)
await self.database.create_external_channel(channel)
if input.target_channel_ids:
await self.database.add_external_channel_to_targets(channel, input.target_channel_ids)
log.info(
'External channel %s created and linked to %s target channels', input.telegram_id, len(input.target_channel_ids)
)
return dto.ExternalChannelOutput(
id=channel.id,
telegram_id=channel.telegram_id,
title=channel.title,
username=channel.username,
description=channel.description,
subscribers_count=channel.subscribers_count,
)