feat(notifications): add multi-channel notification module with Email, FCM, templates, and event listeners
- Domain: NotificationLog/NotificationPreference entities, repositories, channel value object - Infrastructure: EmailService (nodemailer/SMTP), FcmService (firebase-admin), TemplateService (Handlebars) - Application: SendNotification CQRS command, UserRegistered + AgentVerified event listeners - Presentation: NotificationsController with history, preferences, and templates endpoints - Prisma: NotificationLog and NotificationPreference models with proper indexes - Templates: Vietnamese notification templates for user.registered, agent.verified, listing.approved, inquiry.received, password.reset Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
56
apps/web/lib/api-client.ts
Normal file
56
apps/web/lib/api-client.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
const API_BASE_URL = process.env['NEXT_PUBLIC_API_URL'] || 'http://localhost:3001';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
}
|
||||
}
|
||||
|
||||
type RequestOptions = Omit<RequestInit, 'body'> & {
|
||||
body?: unknown;
|
||||
};
|
||||
|
||||
async function request<T>(endpoint: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { body, headers, ...rest } = options;
|
||||
|
||||
const res = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
...rest,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...headers,
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const error = await res.json().catch(() => ({ message: res.statusText }));
|
||||
throw new ApiError(res.status, error.message || 'Request failed');
|
||||
}
|
||||
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function authHeaders(token: string): HeadersInit {
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
export const apiClient = {
|
||||
get: <T>(endpoint: string, headers?: HeadersInit) =>
|
||||
request<T>(endpoint, { method: 'GET', headers }),
|
||||
|
||||
post: <T>(endpoint: string, body?: unknown, headers?: HeadersInit) =>
|
||||
request<T>(endpoint, { method: 'POST', body, headers }),
|
||||
|
||||
patch: <T>(endpoint: string, body?: unknown, headers?: HeadersInit) =>
|
||||
request<T>(endpoint, { method: 'PATCH', body, headers }),
|
||||
|
||||
authGet: <T>(endpoint: string, token: string) =>
|
||||
request<T>(endpoint, { method: 'GET', headers: authHeaders(token) }),
|
||||
|
||||
authPost: <T>(endpoint: string, token: string, body?: unknown) =>
|
||||
request<T>(endpoint, { method: 'POST', body, headers: authHeaders(token) }),
|
||||
};
|
||||
42
apps/web/lib/auth-api.ts
Normal file
42
apps/web/lib/auth-api.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { apiClient } from './api-client';
|
||||
|
||||
export interface TokenPair {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresIn: number;
|
||||
}
|
||||
|
||||
export interface UserProfile {
|
||||
id: string;
|
||||
email: string | null;
|
||||
phone: string;
|
||||
fullName: string;
|
||||
avatarUrl: string | null;
|
||||
role: string;
|
||||
kycStatus: string;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface RegisterPayload {
|
||||
phone: string;
|
||||
password: string;
|
||||
fullName: string;
|
||||
email?: string;
|
||||
}
|
||||
|
||||
export interface LoginPayload {
|
||||
phone: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export const authApi = {
|
||||
register: (data: RegisterPayload) => apiClient.post<TokenPair>('/auth/register', data),
|
||||
|
||||
login: (data: LoginPayload) => apiClient.post<TokenPair>('/auth/login', data),
|
||||
|
||||
refresh: (refreshToken: string) =>
|
||||
apiClient.post<TokenPair>('/auth/refresh', { refreshToken }),
|
||||
|
||||
getProfile: (token: string) => apiClient.authGet<UserProfile>('/auth/profile', token),
|
||||
};
|
||||
123
apps/web/lib/auth-store.ts
Normal file
123
apps/web/lib/auth-store.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import { create } from 'zustand';
|
||||
import { authApi, type TokenPair, type UserProfile, type LoginPayload, type RegisterPayload } from './auth-api';
|
||||
import { ApiError } from './api-client';
|
||||
|
||||
const TOKEN_KEY = 'goodgo_tokens';
|
||||
|
||||
function persistTokens(tokens: TokenPair | null) {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (tokens) {
|
||||
localStorage.setItem(TOKEN_KEY, JSON.stringify(tokens));
|
||||
} else {
|
||||
localStorage.removeItem(TOKEN_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
function loadTokens(): TokenPair | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const raw = localStorage.getItem(TOKEN_KEY);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
tokens: TokenPair | null;
|
||||
user: UserProfile | null;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
|
||||
login: (data: LoginPayload) => Promise<void>;
|
||||
register: (data: RegisterPayload) => Promise<void>;
|
||||
logout: () => void;
|
||||
refreshToken: () => Promise<boolean>;
|
||||
fetchProfile: () => Promise<void>;
|
||||
initialize: () => Promise<void>;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>((set, get) => ({
|
||||
tokens: null,
|
||||
user: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
|
||||
login: async (data) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const tokens = await authApi.login(data);
|
||||
persistTokens(tokens);
|
||||
set({ tokens, isLoading: false });
|
||||
await get().fetchProfile();
|
||||
} catch (e) {
|
||||
const message = e instanceof ApiError ? e.message : 'Đăng nhập thất bại';
|
||||
set({ isLoading: false, error: message });
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
|
||||
register: async (data) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const tokens = await authApi.register(data);
|
||||
persistTokens(tokens);
|
||||
set({ tokens, isLoading: false });
|
||||
await get().fetchProfile();
|
||||
} catch (e) {
|
||||
const message = e instanceof ApiError ? e.message : 'Đăng ký thất bại';
|
||||
set({ isLoading: false, error: message });
|
||||
throw e;
|
||||
}
|
||||
},
|
||||
|
||||
logout: () => {
|
||||
persistTokens(null);
|
||||
set({ tokens: null, user: null, error: null });
|
||||
},
|
||||
|
||||
refreshToken: async () => {
|
||||
const { tokens } = get();
|
||||
if (!tokens?.refreshToken) return false;
|
||||
try {
|
||||
const newTokens = await authApi.refresh(tokens.refreshToken);
|
||||
persistTokens(newTokens);
|
||||
set({ tokens: newTokens });
|
||||
return true;
|
||||
} catch {
|
||||
get().logout();
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
fetchProfile: async () => {
|
||||
const { tokens } = get();
|
||||
if (!tokens?.accessToken) return;
|
||||
try {
|
||||
const user = await authApi.getProfile(tokens.accessToken);
|
||||
set({ user });
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 401) {
|
||||
const refreshed = await get().refreshToken();
|
||||
if (refreshed) {
|
||||
const newTokens = get().tokens;
|
||||
if (newTokens) {
|
||||
const user = await authApi.getProfile(newTokens.accessToken);
|
||||
set({ user });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
initialize: async () => {
|
||||
const tokens = loadTokens();
|
||||
if (!tokens) return;
|
||||
set({ tokens });
|
||||
await get().fetchProfile();
|
||||
},
|
||||
|
||||
clearError: () => set({ error: null }),
|
||||
}));
|
||||
6
apps/web/lib/utils.ts
Normal file
6
apps/web/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from 'clsx';
|
||||
import { twMerge } from 'tailwind-merge';
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
39
apps/web/lib/validations/auth.ts
Normal file
39
apps/web/lib/validations/auth.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const phoneRegex = /^(0|\+84)(3[2-9]|5[2689]|7[06-9]|8[1-9]|9[0-9])\d{7}$/;
|
||||
|
||||
export const loginSchema = z.object({
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, 'Vui lòng nhập số điện thoại')
|
||||
.regex(phoneRegex, 'Số điện thoại không hợp lệ'),
|
||||
password: z.string().min(1, 'Vui lòng nhập mật khẩu'),
|
||||
});
|
||||
|
||||
export const registerSchema = z
|
||||
.object({
|
||||
fullName: z
|
||||
.string()
|
||||
.min(1, 'Vui lòng nhập họ tên')
|
||||
.min(2, 'Họ tên phải có ít nhất 2 ký tự'),
|
||||
phone: z
|
||||
.string()
|
||||
.min(1, 'Vui lòng nhập số điện thoại')
|
||||
.regex(phoneRegex, 'Số điện thoại không hợp lệ'),
|
||||
email: z
|
||||
.string()
|
||||
.email('Email không hợp lệ')
|
||||
.optional()
|
||||
.or(z.literal('')),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, 'Mật khẩu phải có ít nhất 8 ký tự'),
|
||||
confirmPassword: z.string().min(1, 'Vui lòng xác nhận mật khẩu'),
|
||||
})
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
message: 'Mật khẩu xác nhận không khớp',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
|
||||
export type LoginFormData = z.infer<typeof loginSchema>;
|
||||
export type RegisterFormData = z.infer<typeof registerSchema>;
|
||||
Reference in New Issue
Block a user