| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- import { DataSource, Repository } from 'typeorm';
- import { Contact } from './contact.entity';
- import { logger } from '@/server/utils/logger';
- export class ContactService {
- private repository: Repository<Contact>;
- constructor(dataSource: DataSource) {
- this.repository = dataSource.getRepository(Contact);
- }
- async findAll(page: number = 1, pageSize: number = 10, customerId?: number) {
- logger.api('Fetching contacts with pagination - page: %d, pageSize: %d, customerId: %s',
- page, pageSize, customerId);
-
- const where: any = { isDeleted: 0 };
- if (customerId) {
- where.customerId = customerId;
- }
-
- const [data, total] = await this.repository.findAndCount({
- skip: (page - 1) * pageSize,
- take: pageSize,
- where,
- order: { updatedAt: 'DESC' }
- });
-
- return {
- data,
- pagination: {
- total,
- current: page,
- pageSize
- }
- };
- }
- async findOne(id: number) {
- logger.api('Fetching contact with id: %d', id);
-
- const contact = await this.repository.findOne({
- where: { id, isDeleted: 0 }
- });
-
- if (!contact) {
- logger.error('Contact not found with id: %d', id);
- throw new Error('联系人不存在');
- }
-
- return contact;
- }
- async create(contactData: Partial<Contact>) {
- logger.api('Creating new contact: %o', contactData);
-
- const contact = this.repository.create({
- ...contactData,
- createdAt: new Date(),
- updatedAt: new Date(),
- isDeleted: 0
- });
-
- return this.repository.save(contact);
- }
- async update(id: number, contactData: Partial<Contact>) {
- logger.api('Updating contact with id: %d, data: %o', id, contactData);
-
- // Check if contact exists
- await this.findOne(id);
-
- await this.repository.update(id, {
- ...contactData,
- updatedAt: new Date()
- });
-
- return this.findOne(id);
- }
- async remove(id: number) {
- logger.api('Deleting contact with id: %d', id);
-
- // Check if contact exists
- await this.findOne(id);
-
- // Soft delete
- await this.repository.update(id, {
- isDeleted: 1,
- updatedAt: new Date()
- });
-
- return { success: true };
- }
- }
|