| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- import { GenericCrudService } from '@d8d/shared-crud';
- import { DataSource, Repository, Like, Not } from 'typeorm';
- import { Channel } from '../entities/channel.entity';
- export class ChannelService extends GenericCrudService<Channel> {
- constructor(dataSource: DataSource) {
- super(dataSource, Channel);
- }
- /**
- * 创建渠道 - 覆盖父类方法,添加名称唯一性检查
- */
- async create(data: Partial<Channel>, userId?: string | number): Promise<Channel> {
- // 检查渠道名称是否已存在
- if (data.channelName) {
- const existingChannel = await this.repository.findOne({
- where: { channelName: data.channelName }
- });
- if (existingChannel) {
- throw new Error('渠道名称已存在');
- }
- }
- // 设置默认值
- const channelData = {
- contactPerson: '',
- contactPhone: '',
- channelType: '',
- description: '',
- ...data,
- status: 1,
- createTime: new Date(),
- updateTime: new Date()
- };
- return super.create(channelData, userId);
- }
- /**
- * 更新渠道 - 覆盖父类方法,添加存在性和名称重复检查
- */
- async update(id: number, data: Partial<Channel>, userId?: string | number): Promise<Channel | null> {
- // 检查渠道是否存在
- const channel = await this.repository.findOne({ where: { channelId: id } });
- if (!channel) {
- throw new Error('渠道不存在');
- }
- // 检查渠道名称是否与其他渠道重复
- if (data.channelName && data.channelName !== channel.channelName) {
- const existingChannel = await this.repository.findOne({
- where: { channelName: data.channelName, channelId: Not(id) }
- });
- if (existingChannel) {
- throw new Error('渠道名称已存在');
- }
- }
- // 设置更新时间
- const updateData = {
- ...data,
- updateTime: new Date()
- };
- return super.update(id, updateData, userId);
- }
- /**
- * 删除渠道 - 覆盖父类方法,改为软删除(设置status为0)
- */
- async delete(id: number, userId?: string | number): Promise<boolean> {
- // 改为软删除:设置status为0
- const result = await this.repository.update(id, { status: 0 });
- return result.affected === 1;
- }
- /**
- * 获取所有渠道(分页) - 自定义方法,返回源服务的格式
- */
- async findAll(skip?: number, take?: number): Promise<{ data: Channel[], total: number }> {
- const [data, total] = await this.repository.findAndCount({
- skip: skip ?? 0,
- take: take ?? 10,
- order: { channelId: 'DESC' }
- });
- return { data, total };
- }
- /**
- * 按名称搜索渠道 - 自定义方法
- */
- async searchByName(name: string, skip?: number, take?: number): Promise<{ data: Channel[], total: number }> {
- const [data, total] = await this.repository.findAndCount({
- where: {
- channelName: Like(`%${name}%`)
- },
- skip: skip ?? 0,
- take: take ?? 10,
- order: { channelId: 'DESC' }
- });
- return { data, total };
- }
- /**
- * 获取单个渠道 - 自定义方法
- */
- async findOne(channelId: number): Promise<Channel | null> {
- return this.repository.findOne({ where: { channelId } });
- }
- }
|