|
| 1 | +using Microsoft.EntityFrameworkCore; |
| 2 | +using web.Data; |
| 3 | +using web.Models; |
| 4 | + |
| 5 | +namespace web.Services; |
| 6 | + |
| 7 | +public class VisitorProfileService : IVisitorProfileService |
| 8 | +{ |
| 9 | + private readonly ApplicationDbContext _context; |
| 10 | + |
| 11 | + public VisitorProfileService(ApplicationDbContext context) |
| 12 | + { |
| 13 | + _context = context ?? throw new ArgumentNullException(nameof(context)); |
| 14 | + } |
| 15 | + |
| 16 | + public async Task<VisitorProfile?> GetVisitorProfileByEmailAsync(string email) |
| 17 | + { |
| 18 | + if (string.IsNullOrWhiteSpace(email)) |
| 19 | + { |
| 20 | + return null; |
| 21 | + } |
| 22 | + return await _context.VisitorProfiles.FindAsync(email); |
| 23 | + } |
| 24 | + |
| 25 | + public async Task<VisitorProfile> CreateOrUpdateVisitorProfileAsync(VisitorProfile visitorProfile) |
| 26 | + { |
| 27 | + if (string.IsNullOrWhiteSpace(visitorProfile.Email)) |
| 28 | + { |
| 29 | + throw new ArgumentException("Email cannot be null or empty", nameof(visitorProfile)); |
| 30 | + } |
| 31 | + |
| 32 | + var existing = await _context.VisitorProfiles.FindAsync(visitorProfile.Email); |
| 33 | + if (existing != null) |
| 34 | + { |
| 35 | + // 更新現有記錄 |
| 36 | + existing.Name = visitorProfile.Name; |
| 37 | + existing.Company = visitorProfile.Company; |
| 38 | + existing.Phone = visitorProfile.Phone; |
| 39 | + existing.Cid = visitorProfile.Cid; |
| 40 | + existing.UpdatedAt = DateTime.UtcNow; |
| 41 | + if (visitorProfile.ExpiresAt.HasValue) |
| 42 | + { |
| 43 | + existing.ExpiresAt = visitorProfile.ExpiresAt; |
| 44 | + } |
| 45 | + await _context.SaveChangesAsync(); |
| 46 | + return existing; |
| 47 | + } |
| 48 | + else |
| 49 | + { |
| 50 | + // 創建新記錄 |
| 51 | + visitorProfile.CreatedAt = DateTime.UtcNow; |
| 52 | + visitorProfile.UpdatedAt = DateTime.UtcNow; |
| 53 | + _context.VisitorProfiles.Add(visitorProfile); |
| 54 | + await _context.SaveChangesAsync(); |
| 55 | + return visitorProfile; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + public async Task<bool> DeleteVisitorProfileAsync(string email) |
| 60 | + { |
| 61 | + if (string.IsNullOrWhiteSpace(email)) |
| 62 | + { |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + var visitorProfile = await _context.VisitorProfiles.FindAsync(email); |
| 67 | + if (visitorProfile == null) |
| 68 | + { |
| 69 | + return false; |
| 70 | + } |
| 71 | + |
| 72 | + _context.VisitorProfiles.Remove(visitorProfile); |
| 73 | + await _context.SaveChangesAsync(); |
| 74 | + return true; |
| 75 | + } |
| 76 | +} |
| 77 | + |
0 commit comments