2
0

contact.service.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import { DataSource, Repository } from 'typeorm';
  2. import { Contact } from './contact.entity';
  3. import { logger } from '@/server/utils/logger';
  4. export class ContactService {
  5. private repository: Repository<Contact>;
  6. constructor(dataSource: DataSource) {
  7. this.repository = dataSource.getRepository(Contact);
  8. }
  9. async findAll(page: number = 1, pageSize: number = 10, customerId?: number) {
  10. logger.api('Fetching contacts with pagination - page: %d, pageSize: %d, customerId: %s',
  11. page, pageSize, customerId);
  12. const where: any = { isDeleted: 0 };
  13. if (customerId) {
  14. where.customerId = customerId;
  15. }
  16. const [data, total] = await this.repository.findAndCount({
  17. skip: (page - 1) * pageSize,
  18. take: pageSize,
  19. where,
  20. order: { updatedAt: 'DESC' }
  21. });
  22. return {
  23. data,
  24. pagination: {
  25. total,
  26. current: page,
  27. pageSize
  28. }
  29. };
  30. }
  31. async findOne(id: number) {
  32. logger.api('Fetching contact with id: %d', id);
  33. const contact = await this.repository.findOne({
  34. where: { id, isDeleted: 0 }
  35. });
  36. if (!contact) {
  37. logger.error('Contact not found with id: %d', id);
  38. throw new Error('联系人不存在');
  39. }
  40. return contact;
  41. }
  42. async create(contactData: Partial<Contact>) {
  43. logger.api('Creating new contact: %o', contactData);
  44. const contact = this.repository.create({
  45. ...contactData,
  46. createdAt: new Date(),
  47. updatedAt: new Date(),
  48. isDeleted: 0
  49. });
  50. return this.repository.save(contact);
  51. }
  52. async update(id: number, contactData: Partial<Contact>) {
  53. logger.api('Updating contact with id: %d, data: %o', id, contactData);
  54. // Check if contact exists
  55. await this.findOne(id);
  56. await this.repository.update(id, {
  57. ...contactData,
  58. updatedAt: new Date()
  59. });
  60. return this.findOne(id);
  61. }
  62. async remove(id: number) {
  63. logger.api('Deleting contact with id: %d', id);
  64. // Check if contact exists
  65. await this.findOne(id);
  66. // Soft delete
  67. await this.repository.update(id, {
  68. isDeleted: 1,
  69. updatedAt: new Date()
  70. });
  71. return { success: true };
  72. }
  73. }