diff --git a/public/assets/images/fonts/LAHZEH-FANUM-BLACK.TTF b/public/assets/images/fonts/LAHZEH-FANUM-BLACK.TTF new file mode 100644 index 0000000..b34fb51 Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-BLACK.TTF differ diff --git a/public/assets/images/fonts/LAHZEH-FANUM-BOLD.TTF b/public/assets/images/fonts/LAHZEH-FANUM-BOLD.TTF new file mode 100644 index 0000000..ff52394 Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-BOLD.TTF differ diff --git a/public/assets/images/fonts/LAHZEH-FANUM-EXTRABOLD.TTF b/public/assets/images/fonts/LAHZEH-FANUM-EXTRABOLD.TTF new file mode 100644 index 0000000..9fb2329 Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-EXTRABOLD.TTF differ diff --git a/public/assets/images/fonts/LAHZEH-FANUM-EXTRALIGHT.TTF b/public/assets/images/fonts/LAHZEH-FANUM-EXTRALIGHT.TTF new file mode 100644 index 0000000..b5568d8 Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-EXTRALIGHT.TTF differ diff --git a/public/assets/images/fonts/LAHZEH-FANUM-LIGHT.TTF b/public/assets/images/fonts/LAHZEH-FANUM-LIGHT.TTF new file mode 100644 index 0000000..fd7f0da Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-LIGHT.TTF differ diff --git a/public/assets/images/fonts/LAHZEH-FANUM-MEDIUM.TTF b/public/assets/images/fonts/LAHZEH-FANUM-MEDIUM.TTF new file mode 100644 index 0000000..a5e7725 Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-MEDIUM.TTF differ diff --git a/public/assets/images/fonts/LAHZEH-FANUM-REGULAR.TTF b/public/assets/images/fonts/LAHZEH-FANUM-REGULAR.TTF new file mode 100644 index 0000000..1a65122 Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-REGULAR.TTF differ diff --git a/public/assets/images/fonts/LAHZEH-FANUM-SEMIBOLD.TTF b/public/assets/images/fonts/LAHZEH-FANUM-SEMIBOLD.TTF new file mode 100644 index 0000000..c2e211f Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-SEMIBOLD.TTF differ diff --git a/public/assets/images/fonts/LAHZEH-FANUM-THIN.TTF b/public/assets/images/fonts/LAHZEH-FANUM-THIN.TTF new file mode 100644 index 0000000..41b6150 Binary files /dev/null and b/public/assets/images/fonts/LAHZEH-FANUM-THIN.TTF differ diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts index ae19abb..7ea7ce5 100644 --- a/src/app/app.routes.ts +++ b/src/app/app.routes.ts @@ -2,6 +2,7 @@ import { Routes } from '@angular/router'; import { HomePage } from './pages/home/home.page'; import { SettingsPage } from './pages/settings/settings.page'; import { LoginPage } from './pages/login/login.page'; +import { ReportsPage } from './pages/reports/reports.page'; import { AuthService } from './services/auth/auth.service'; import { authGuard } from './services/auth/auth.guard'; import { Router } from '@angular/router'; @@ -23,18 +24,24 @@ export const routes: Routes = [ path: 'login', title: 'ورود', component: LoginPage, - // canActivate: [redirectAuthenticated], + canActivate: [redirectAuthenticated], }, { path: '', title: 'دستیار هوشمند', component: HomePage, - // canActivate: [authGuard], + canActivate: [authGuard], }, { path: 'settings', title: 'تنظیمات', component: SettingsPage, - // canActivate: [authGuard], + canActivate: [authGuard], + }, + { + path: 'reports', + title: 'گزارشات', + component: ReportsPage, + canActivate: [authGuard], }, ]; diff --git a/src/app/layout/layout.component.css b/src/app/layout/layout.component.css index 9db9002..d094db9 100644 --- a/src/app/layout/layout.component.css +++ b/src/app/layout/layout.component.css @@ -51,6 +51,7 @@ flex-direction: column; flex: 1; min-width: 0; + margin-right: 72px; transition: margin-right 0.3s ease; } diff --git a/src/app/pages/reports/reports.page.css b/src/app/pages/reports/reports.page.css new file mode 100644 index 0000000..9e87ad1 --- /dev/null +++ b/src/app/pages/reports/reports.page.css @@ -0,0 +1,406 @@ +.reports-page { + min-height: 100%; + padding: 2.25rem 3rem 3.5rem; + display: flex; + flex-direction: column; + gap: 1.5rem; + animation: fadeIn 0.4s ease-out; +} + +.reports-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 1rem; + flex-wrap: wrap; +} + +.reports-title-group { + display: flex; + align-items: center; + gap: 0.875rem; +} + +.reports-title-icon { + display: flex; + align-items: center; + justify-content: center; + width: 44px; + height: 44px; + border-radius: 0.875rem; + background: var(--color-primary) / 12; + color: var(--color-primary); + flex-shrink: 0; +} + +.reports-title { + margin: 0; + font-size: 1.5rem; + font-weight: 700; + color: var(--text-primary); + line-height: 1.3; +} + +.reports-subtitle { + margin: 0.15rem 0 0; + font-size: 0.8125rem; + color: var(--text-muted); +} + +.period-chip { + padding: 0.45rem 0.9rem; + border: 1px solid var(--card-border); + border-radius: 9999px; + background: var(--card-bg); + font-size: 0.75rem; + color: var(--text-secondary); + white-space: nowrap; +} + +.reports-tabs { + display: inline-flex; + align-self: flex-start; + gap: 0.25rem; + padding: 0.3rem; + border: 1px solid var(--card-border); + border-radius: 1rem; + background: var(--sidebar-hover); +} + +.tab-btn { + position: relative; + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.55rem 1.15rem; + border: none; + border-radius: 0.75rem; + background: transparent; + color: var(--text-muted); + font-size: 0.8125rem; + font-weight: 500; + cursor: pointer; + transition: color 0.2s ease, background 0.2s ease; + white-space: nowrap; +} + +.tab-btn:hover { + color: var(--text-primary); +} + +.tab-btn.tab-active { + background: var(--card-bg); + color: var(--color-primary); + box-shadow: 0 4px 14px rgba(15, 23, 42, 0.08); +} + +.tab-indicator { + position: absolute; + bottom: 0.3rem; + left: 50%; + transform: translateX(-50%); + width: 1.5rem; + height: 0.125rem; + border-radius: 9999px; + background: var(--color-primary); + animation: slideIn 0.3s ease-out; +} + +.tab-panel { + display: flex; + flex-direction: column; + gap: 1.25rem; + animation: fadeIn 0.3s ease-out; +} + +.stats-grid { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 1.25rem; +} + +.charts-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1.25rem; +} + +.ai-grid { + display: grid; + grid-template-columns: minmax(0, 5fr) minmax(0, 7fr); + gap: 1.25rem; +} + +.report-card { + padding: 1.25rem 1.4rem; + border: 1px solid var(--card-border); + border-radius: 1.25rem; + background: var(--card-bg); + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.06), 0 2px 10px rgba(0, 0, 0, 0.03); + animation: fadeInUp 0.5s ease-out both; +} + +.report-card:nth-child(1) { animation-delay: 0.03s; } +.report-card:nth-child(2) { animation-delay: 0.06s; } +.report-card:nth-child(3) { animation-delay: 0.09s; } +.report-card:nth-child(4) { animation-delay: 0.12s; } + +.stat-card { + display: flex; + flex-direction: column; + gap: 0.35rem; +} + +.stat-label { + font-size: 0.8125rem; + color: var(--text-muted); +} + +.stat-value { + font-size: 1.75rem; + font-weight: 700; + color: var(--text-primary); + line-height: 1.2; +} + +.stat-hint { + font-size: 0.6875rem; + color: var(--text-muted); +} + +.stat-progress { + height: 6px; + border-radius: 9999px; + background: var(--stat-progress-bg, rgba(100, 116, 139, 0.16)); + overflow: hidden; +} + +.stat-progress-fill { + display: block; + height: 100%; + border-radius: 9999px; + background: var(--color-primary); + transition: width 0.8s cubic-bezier(0.22, 1, 0.36, 1); +} + +.card-header { + margin-bottom: 1.1rem; +} + +.card-title { + margin: 0; + font-size: 1.0625rem; + font-weight: 600; + color: var(--text-primary); +} + +.card-description { + margin: 0.2rem 0 0; + font-size: 0.75rem; + color: var(--text-muted); + line-height: 1.7; +} + +.trend-peak { + display: inline-block; + margin-inline-start: 0.35rem; + color: var(--text-secondary); +} + +.ai-stats { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.9rem 1.25rem; +} + +.ai-stat { + display: flex; + flex-direction: column; + gap: 0.3rem; +} + +.ai-stat-label { + font-size: 0.75rem; + color: var(--text-muted); +} + +.ai-stat-value { + font-size: 1.125rem; + font-weight: 700; + color: var(--text-primary); +} + +.ai-channels { + margin-top: 1.4rem; + padding-top: 1.1rem; + border-top: 1px solid var(--card-border); +} + +.ai-channels-title { + margin: 0 0 0.9rem; + font-size: 0.875rem; + font-weight: 600; + color: var(--text-secondary); +} + +.error-card { + display: flex; + flex-direction: column; + align-items: center; + gap: 0.5rem; + padding: 3rem 1.5rem; + text-align: center; + color: var(--text-muted); +} + +.error-card h2 { + margin: 0.5rem 0 0; + font-size: 1.0625rem; + font-weight: 600; + color: var(--text-primary); +} + +.error-card p { + margin: 0; + font-size: 0.8125rem; +} + +.retry-btn { + margin-top: 0.75rem; + padding: 0.55rem 1.5rem; + border: none; + border-radius: 0.75rem; + background: var(--color-primary); + color: #ffffff; + font-size: 0.8125rem; + font-weight: 500; + cursor: pointer; + transition: opacity 0.2s ease, transform 0.2s ease; +} + +.retry-btn:hover { + opacity: 0.9; + transform: translateY(-1px); +} + +.skeleton-card { + min-height: 132px; +} + +.skeleton { + border-radius: 0.5rem; + background: linear-gradient( + 90deg, + var(--stat-progress-bg, rgba(100, 116, 139, 0.12)) 25%, + rgba(100, 116, 139, 0.05) 37%, + var(--stat-progress-bg, rgba(100, 116, 139, 0.12)) 63% + ); + background-size: 400% 100%; + animation: skeletonShimmer 1.4s ease infinite; +} + +.skeleton-title { + width: 45%; + height: 0.875rem; +} + +.skeleton-value { + width: 30%; + height: 2rem; + margin-top: 0.75rem; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes slideIn { + from { + width: 0; + opacity: 0; + } + to { + width: 1.5rem; + opacity: 1; + } +} + +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(16px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +@keyframes skeletonShimmer { + from { + background-position: 100% 50%; + } + to { + background-position: 0 50%; + } +} + +@media (prefers-reduced-motion: reduce) { + .report-card, + .skeleton { + animation: none; + } +} + +@media (max-width: 1024px) { + .reports-page { + padding: 1.5rem 1.75rem 2.75rem; + } + + .stats-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + .charts-grid, + .ai-grid { + grid-template-columns: minmax(0, 1fr); + } +} + +@media (max-width: 640px) { + .reports-page { + padding: 1.25rem 1.25rem 2.25rem; + } + + .stats-grid { + grid-template-columns: minmax(0, 1fr); + } + + .reports-tabs { + width: 100%; + } + + .tab-btn { + flex: 1; + justify-content: center; + padding: 0.55rem 0.5rem; + } +} + +:host-context([data-bs-theme='dark']) .report-card { + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3), 0 2px 10px rgba(0, 0, 0, 0.2); +} + +:host-context([data-bs-theme='dark']) .stat-progress { + background: rgba(148, 163, 184, 0.2); +} + +:host-context([data-bs-theme='dark']) .skeleton { + background: linear-gradient(90deg, rgba(148, 163, 184, 0.14) 25%, rgba(148, 163, 184, 0.05) 37%, rgba(148, 163, 184, 0.14) 63%); + background-size: 400% 100%; +} diff --git a/src/app/pages/reports/reports.page.html b/src/app/pages/reports/reports.page.html new file mode 100644 index 0000000..584d373 --- /dev/null +++ b/src/app/pages/reports/reports.page.html @@ -0,0 +1,215 @@ +
+
+
+ + + + + + + + +
+

گزارشات

+

مروری بر استفاده از دستیار هوشمند و نتایج پاسخ‌های هوش مصنوعی

+
+
+ @if (summary(); as summary) { + بازه گزارش: {{ summary.periodLabel }} + } +
+ + @if (loading()) { +
+ @for (card of [1, 2, 3, 4]; track card) { +
+
+
+
+ } +
+ } @else if (loadError()) { + + } @else if (data(); as view) { + + + @if (activeTab() === 'questions') { +
+
+
+ تعداد کل سوالات + {{ formatCount(view.summary.totalQuestions) }} + در {{ view.summary.periodLabel }} +
+ +
+ کاربران یکتا + {{ formatCount(view.summary.uniqueUsers) }} + کاربرانی که با دستیار گفتگو کرده‌اند +
+ +
+ پاسخ‌های هوش مصنوعی + {{ formatCount(view.summary.aiAnswered) }} + + {{ formatPercent(aiAnswerRate()) }} از کل سوالات +
+ +
+ ارجاع به کارشناس + {{ formatCount(view.summary.escalatedToAgent) }} + سوالات نیازمند بررسی انسانی +
+
+ +
+
+
+

پرتکرارترین سوالات

+

پرپرسش‌ترین موضوعات کاربران، به ترتیب فراوانی

+
+ +
+ +
+
+

توزیع سوالات

+

سهم هر دسته از کل سوالات مطرح‌شده

+
+ +
+
+
+ } @else { +
+
+
+
+

عملکرد هوش مصنوعی

+

آمار پاسخ‌دهی و کیفیت عملکرد دستیار

+
+ +
+
+ میانگین زمان پاسخ + {{ formatDecimal(view.aiPerformance.avgResponseSeconds) }} ثانیه +
+
+ نرخ موفقیت پاسخ‌ها + {{ formatPercent(view.aiPerformance.successRate) }} + +
+
+ رضایت‌مندی کاربران + {{ formatPercent(view.aiPerformance.satisfactionRate) }} + +
+
+ پاسخ بر پایه سوالات متداول + {{ formatPercent(faqBasedRate()) }} + +
+
+ +
+

پاسخ‌ها بر اساس گونه گفتگو

+ +
+
+ +
+
+

روند استفاده

+

+ تغییرات حجم سوالات در {{ view.summary.periodLabel }} — مجموع + {{ formatCount(trendTotal()) }} سوال + @if (trendPeak(); as peak) { + بیشترین رشد در {{ peak.label }} با {{ formatCount(peak.value) }} سوال + } +

+
+ +
+
+
+ } + } +
diff --git a/src/app/pages/reports/reports.page.spec.ts b/src/app/pages/reports/reports.page.spec.ts new file mode 100644 index 0000000..da73a08 --- /dev/null +++ b/src/app/pages/reports/reports.page.spec.ts @@ -0,0 +1,65 @@ +import { TestBed } from '@angular/core/testing'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { provideAnimations } from '@angular/platform-browser/animations'; +import { provideHttpClient } from '@angular/common/http'; +import { provideRouter } from '@angular/router'; +import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr'; +import { ReportsPage } from './reports.page'; + +describe('ReportsPage', () => { + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [ReportsPage], + providers: [ + provideZonelessChangeDetection(), + provideHttpClient(), + provideRouter([]), + provideAnimations(), + { provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } }, + ], + }).compileComponents(); + }); + + function titles(fixture: { nativeElement: HTMLElement }): (string | undefined)[] { + return Array.from(fixture.nativeElement.querySelectorAll('.card-title')).map((node) => + node.textContent?.trim(), + ); + } + + it('should create the page', () => { + const fixture = TestBed.createComponent(ReportsPage); + expect(fixture.componentInstance).toBeTruthy(); + }); + + it('renders the questions tab by default with its charts', () => { + const fixture = TestBed.createComponent(ReportsPage); + fixture.detectChanges(); + + const element: HTMLElement = fixture.nativeElement; + const tabLabels = Array.from(element.querySelectorAll('.tab-btn')).map((node) => + node.textContent?.trim(), + ); + + expect(element.querySelector('.reports-title')?.textContent?.trim()).toBe('گزارشات'); + expect(tabLabels).toEqual(['پرسش‌های کاربران', 'عملکرد و روند']); + expect(titles(fixture)).toEqual(['پرتکرارترین سوالات', 'توزیع سوالات']); + expect(element.querySelectorAll('.stat-card').length).toBe(4); + expect(element.querySelector('app-bar-chart')).toBeTruthy(); + expect(element.querySelector('app-doughnut-chart')).toBeTruthy(); + expect(element.textContent).toContain('۴,۸۰۲'); + }); + + it('switches to the performance tab with AI and usage reports', () => { + const fixture = TestBed.createComponent(ReportsPage); + fixture.detectChanges(); + + const element = fixture.nativeElement as HTMLElement; + const tabButtons = element.querySelectorAll('.tab-btn'); + (tabButtons[1] as HTMLButtonElement).click(); + fixture.detectChanges(); + + expect(fixture.componentInstance.activeTab()).toBe('performance'); + expect(titles(fixture)).toEqual(['عملکرد هوش مصنوعی', 'روند استفاده']); + expect(fixture.nativeElement.querySelector('app-line-chart')).toBeTruthy(); + }); +}); diff --git a/src/app/services/reports/reports.mock.ts b/src/app/services/reports/reports.mock.ts new file mode 100644 index 0000000..0559589 --- /dev/null +++ b/src/app/services/reports/reports.mock.ts @@ -0,0 +1,88 @@ +import { + AiChannelUsage, + AiPerformance, + CategoryShare, + QuestionSummary, + TopQuestion, + UsageTrendPoint, +} from './reports.types'; + +const TREND_DAYS = 30; + +/** Deterministic pseudo-random source so mock data stays stable across reloads and tests. */ +function seededNoise(seed: number): number { + const value = Math.sin(seed * 12.9898) * 43758.5453; + return Math.abs(value - Math.floor(value)); +} + +function buildTrend(): UsageTrendPoint[] { + const points: UsageTrendPoint[] = []; + const today = new Date(); + + for (let offset = TREND_DAYS - 1; offset >= 0; offset--) { + const date = new Date(today); + date.setDate(today.getDate() - offset); + + const weekday = date.getDay(); + const isWeekend = weekday === 4 || weekday === 5; + const noise = seededNoise(offset + 1); + + // Recent campaign window lifts the last two weeks. + const campaign = offset <= 14 ? 9 : 0; + const base = isWeekend ? 34 : 58; + + const count = Math.round(base + noise * 22 - (isWeekend ? 12 : 0) + campaign); + + points.push({ + label: date.toLocaleDateString('fa-IR', { day: 'numeric', month: 'long' }), + count, + }); + } + + return points; +} + +export const MOCK_TOP_QUESTIONS: TopQuestion[] = [ + { id: 'q1', text: 'چگونه رمز عبور حساب کاربری خود را بازیابی کنم؟', count: 142, category: 'حساب کاربری' }, + { id: 'q2', text: 'ساعات کاری پشتیبانی در چه ساعتی است؟', count: 128, category: 'پشتیبانی' }, + { id: 'q3', text: 'برای دریافت فاکتور رسمی چگونه اقدام کنم؟', count: 97, category: 'پرداخت و فاکتور' }, + { id: 'q4', text: 'آیا ارسال به شهرستان‌ها امکان‌پذیر است؟', count: 88, category: 'سفارش و ارسال' }, + { id: 'q5', text: 'چگونه سفارش خود را پیگیری کنم؟', count: 76, category: 'سفارش و ارسال' }, + { id: 'q6', text: 'هزینه ارسال چگونه محاسبه می‌شود؟', count: 61, category: 'سفارش و ارسال' }, + { id: 'q7', text: 'شرایط مرجوع کردن کالا چیست؟', count: 54, category: 'پشتیبانی' }, + { id: 'q8', text: 'آیا امکان پرداخت اقساطی وجود دارد؟', count: 47, category: 'پرداخت و فاکتور' }, +]; + +export const MOCK_QUESTION_SUMMARY: QuestionSummary = { + totalQuestions: 4802, + uniqueUsers: 1736, + aiAnswered: 4318, + escalatedToAgent: 484, + periodLabel: '۳۰ روز گذشته', +}; + +export const MOCK_CATEGORY_SHARES: CategoryShare[] = [ + { category: 'حساب کاربری', count: 1265 }, + { category: 'سفارش و ارسال', count: 1148 }, + { category: 'پرداخت و فاکتور', count: 862 }, + { category: 'پشتیبانی', count: 668 }, + { category: 'محصولات', count: 479 }, + { category: 'سایر', count: 380 }, +]; + +export const MOCK_USAGE_TREND: UsageTrendPoint[] = buildTrend(); + +export const MOCK_AI_CHANNELS: AiChannelUsage[] = [ + { label: 'گفتگوی متنی', count: 3622 }, + { label: 'گفتگوی صوتی', count: 1180 }, +]; + +export const MOCK_AI_PERFORMANCE: AiPerformance = { + totalResponses: 4802, + faqBasedResponses: 3553, + avgResponseSeconds: 1.8, + successRate: 91, + satisfactionRate: 87, + escalationRate: 10, + channels: MOCK_AI_CHANNELS, +}; diff --git a/src/app/services/reports/reports.service.spec.ts b/src/app/services/reports/reports.service.spec.ts new file mode 100644 index 0000000..78aa62c --- /dev/null +++ b/src/app/services/reports/reports.service.spec.ts @@ -0,0 +1,83 @@ +import { TestBed } from '@angular/core/testing'; +import { provideZonelessChangeDetection } from '@angular/core'; +import { provideAnimations } from '@angular/platform-browser/animations'; +import { provideHttpClient } from '@angular/common/http'; +import { provideRouter } from '@angular/router'; +import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr'; +import { firstValueFrom } from 'rxjs'; +import { ReportsService } from './reports.service'; + +describe('ReportsService', () => { + let service: ReportsService; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideZonelessChangeDetection(), + provideHttpClient(), + provideRouter([]), + provideAnimations(), + { provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } }, + ], + }); + service = TestBed.inject(ReportsService); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); + + it('returns top questions ranked by frequency', async () => { + const questions = await firstValueFrom(service.getTopQuestions()); + + expect(questions.length).toBeGreaterThan(0); + const counts = questions.map((question) => question.count); + expect([...counts].sort((a, b) => b - a)).toEqual(counts); + }); + + it('returns a question summary whose parts stay within the total', async () => { + const summary = await firstValueFrom(service.getQuestionSummary()); + + expect(summary.totalQuestions).toBeGreaterThan(0); + expect(summary.aiAnswered + summary.escalatedToAgent).toBeLessThanOrEqual( + summary.totalQuestions, + ); + }); + + it('returns category shares summing up to the total question count', async () => { + const categories = await firstValueFrom(service.getCategoryDistribution()); + const summary = await firstValueFrom(service.getQuestionSummary()); + const total = categories.reduce((sum, category) => sum + category.count, 0); + + expect(total).toBe(summary.totalQuestions); + }); + + it('returns a 30 point usage trend with valid labels', async () => { + const trend = await firstValueFrom(service.getUsageTrend()); + + expect(trend).toHaveLength(30); + trend.forEach((point) => { + expect(point.label).toBeTruthy(); + expect(point.count).toBeGreaterThan(0); + }); + }); + + it('returns AI performance stats with bounded rates', async () => { + const performance = await firstValueFrom(service.getAiPerformance()); + + expect(performance.totalResponses).toBeGreaterThan(0); + expect(performance.channels.length).toBeGreaterThan(0); + expect(performance.successRate).toBeLessThanOrEqual(100); + expect(performance.satisfactionRate).toBeLessThanOrEqual(100); + }); + + it('returns a complete overview combining every report', async () => { + const overview = await firstValueFrom(service.getOverview()); + + expect(overview.topQuestions.length).toBeGreaterThan(0); + expect(overview.categories.length).toBeGreaterThan(0); + expect(overview.trend).toHaveLength(30); + expect(overview.summary.totalQuestions).toBeGreaterThan(0); + expect(overview.aiPerformance.totalResponses).toBeGreaterThan(0); + }); +}); diff --git a/src/app/services/reports/reports.service.ts b/src/app/services/reports/reports.service.ts new file mode 100644 index 0000000..f16824a --- /dev/null +++ b/src/app/services/reports/reports.service.ts @@ -0,0 +1,72 @@ +import { Injectable, inject } from '@angular/core'; +import { map, Observable, of } from 'rxjs'; +import { HttpService } from '../http-request/http.service'; +import { + AiPerformance, + CategoryShare, + QuestionSummary, + ReportsView, + TopQuestion, + UsageTrendPoint, +} from './reports.types'; +import { + MOCK_AI_PERFORMANCE, + MOCK_CATEGORY_SHARES, + MOCK_QUESTION_SUMMARY, + MOCK_TOP_QUESTIONS, + MOCK_USAGE_TREND, +} from './reports.mock'; + +@Injectable({ + providedIn: 'root', +}) +export class ReportsService { + private readonly http = inject(HttpService); + + /** Flip to false once the backend report endpoints are deployed. */ + private readonly useMockData = true; + + getTopQuestions(limit = 8): Observable { + return this.request('reports/top-questions', { limit }, MOCK_TOP_QUESTIONS); + } + + getQuestionSummary(): Observable { + return this.request('reports/questions-summary', {}, MOCK_QUESTION_SUMMARY); + } + + getCategoryDistribution(): Observable { + return this.request( + 'reports/questions-distribution', + {}, + MOCK_CATEGORY_SHARES, + ); + } + + getUsageTrend(days = 30): Observable { + return this.request('reports/usage-trend', { days }, MOCK_USAGE_TREND); + } + + getAiPerformance(): Observable { + return this.request('reports/ai-performance', {}, MOCK_AI_PERFORMANCE); + } + + getOverview(): Observable { + return this.request('reports/overview', {}, { + topQuestions: MOCK_TOP_QUESTIONS, + summary: MOCK_QUESTION_SUMMARY, + categories: MOCK_CATEGORY_SHARES, + trend: MOCK_USAGE_TREND, + aiPerformance: MOCK_AI_PERFORMANCE, + }); + } + + private request(endpoint: string, params: Record, fallback: T): Observable { + if (this.useMockData) { + return of(fallback); + } + + return this.http + .get(endpoint, { params, skipToast: true, skipHasErrorCheck: true }) + .pipe(map((response) => response.result)); + } +} diff --git a/src/app/services/reports/reports.types.ts b/src/app/services/reports/reports.types.ts new file mode 100644 index 0000000..1b43ac7 --- /dev/null +++ b/src/app/services/reports/reports.types.ts @@ -0,0 +1,47 @@ +export interface TopQuestion { + id: string; + text: string; + count: number; + category: string; +} + +export interface QuestionSummary { + totalQuestions: number; + uniqueUsers: number; + aiAnswered: number; + escalatedToAgent: number; + periodLabel: string; +} + +export interface CategoryShare { + category: string; + count: number; +} + +export interface UsageTrendPoint { + label: string; + count: number; +} + +export interface AiChannelUsage { + label: string; + count: number; +} + +export interface AiPerformance { + totalResponses: number; + faqBasedResponses: number; + avgResponseSeconds: number; + successRate: number; + satisfactionRate: number; + escalationRate: number; + channels: AiChannelUsage[]; +} + +export interface ReportsView { + topQuestions: TopQuestion[]; + summary: QuestionSummary; + categories: CategoryShare[]; + trend: UsageTrendPoint[]; + aiPerformance: AiPerformance; +} diff --git a/src/app/shared/ui/charts/bar-chart.component.css b/src/app/shared/ui/charts/bar-chart.component.css new file mode 100644 index 0000000..e28f58b --- /dev/null +++ b/src/app/shared/ui/charts/bar-chart.component.css @@ -0,0 +1,137 @@ +.bar-chart { + display: flex; + flex-direction: column; + gap: 1.1rem; + margin: 0; + padding: 0; + list-style: none; +} + +.bar-row { + position: relative; +} + +.bar-head { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.75rem; + margin-bottom: 0.4rem; +} + +.bar-label { + font-size: 0.8125rem; + color: var(--text-secondary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bar-metrics { + display: flex; + align-items: baseline; + gap: 0.5rem; + flex-shrink: 0; +} + +.bar-value { + font-size: 0.8125rem; + font-weight: 600; + color: var(--text-primary); +} + +.bar-share { + font-size: 0.6875rem; + color: var(--text-muted); +} + +.bar-track { + position: relative; + height: 12px; + border-radius: 9999px; + background: var(--bar-track-bg, rgba(100, 116, 139, 0.16)); + cursor: default; +} + +.bar-fill { + height: 100%; + border-radius: 9999px; + background: var(--bar-color); + transform-origin: right center; + animation: barGrow 0.7s cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.bar-tooltip { + position: absolute; + bottom: calc(100% + 8px); + z-index: 20; + display: flex; + flex-direction: column; + gap: 0.15rem; + min-width: max-content; + max-width: 260px; + padding: 0.55rem 0.75rem; + border: 1px solid var(--card-border); + border-radius: 0.75rem; + background: var(--surface-bg); + box-shadow: 0 12px 32px rgba(15, 23, 42, 0.18); + transform: translateX(50%); + pointer-events: none; + animation: fadeIn 0.15s ease-out; +} + +.bar-tooltip-title { + font-size: 0.8125rem; + font-weight: 600; + color: var(--text-primary); + line-height: 1.5; +} + +.bar-tooltip-row { + font-size: 0.75rem; + color: var(--text-secondary); +} + +.bar-tooltip-hint { + font-size: 0.6875rem; + color: var(--text-muted); +} + +.chart-empty { + padding: 2.5rem 1rem; + text-align: center; + font-size: 0.875rem; + color: var(--text-muted); +} + +@keyframes barGrow { + from { + transform: scaleX(0); + } + to { + transform: scaleX(1); + } +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .bar-fill { + animation: none; + } +} + +:host-context([data-bs-theme='dark']) .bar-track { + background: rgba(148, 163, 184, 0.22); +} + +:host-context([data-bs-theme='dark']) .bar-tooltip { + box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5); +} diff --git a/src/app/shared/ui/charts/bar-chart.component.html b/src/app/shared/ui/charts/bar-chart.component.html new file mode 100644 index 0000000..d03b533 --- /dev/null +++ b/src/app/shared/ui/charts/bar-chart.component.html @@ -0,0 +1,42 @@ +@if (items().length) { +
    + @for (item of items(); track item.label; let index = $index) { +
  • +
    + {{ item.label }} + + {{ format(item.value) }} + {{ share(item.value) }} + +
    + +
    +
    +
    + + @if (activeIndex() === index) { + + } +
  • + } +
+} @else { +

{{ emptyText() }}

+} diff --git a/src/app/shared/ui/charts/bar-chart.component.ts b/src/app/shared/ui/charts/bar-chart.component.ts new file mode 100644 index 0000000..7dec773 --- /dev/null +++ b/src/app/shared/ui/charts/bar-chart.component.ts @@ -0,0 +1,57 @@ +import { ChangeDetectionStrategy, Component, computed, input, signal } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { formatCount, formatPercent } from '../../utils/format.util'; + +export interface BarChartItem { + label: string; + value: number; + color: string; + hint?: string; +} + +@Component({ + selector: 'app-bar-chart', + standalone: true, + imports: [CommonModule], + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './bar-chart.component.html', + styleUrl: './bar-chart.component.css', +}) +export class BarChartComponent { + readonly items = input.required(); + readonly valueSuffix = input(''); + readonly emptyText = input('داده‌ای برای نمایش نیست'); + readonly ariaLabel = input('نمودار میله‌ای'); + + readonly activeIndex = signal(null); + readonly tooltipX = signal(0); + + readonly total = computed(() => this.items().reduce((sum, item) => sum + item.value, 0)); + readonly max = computed(() => { + const values = this.items().map((item) => item.value); + return values.length ? Math.max(...values) : 0; + }); + + barWidth(value: number): string { + return this.max() > 0 ? `${(value / this.max()) * 100}%` : '0%'; + } + + share(value: number): string { + return this.total() > 0 ? formatPercent((value / this.total()) * 100) : '۰٪'; + } + + format(value: number): string { + return `${formatCount(value)}${this.valueSuffix()}`; + } + + onTrackMove(index: number, event: MouseEvent): void { + const track = event.currentTarget as HTMLElement; + const rect = track.getBoundingClientRect(); + this.tooltipX.set(event.clientX - rect.left); + this.activeIndex.set(index); + } + + onTrackLeave(): void { + this.activeIndex.set(null); + } +} diff --git a/src/app/shared/ui/charts/doughnut-chart.component.css b/src/app/shared/ui/charts/doughnut-chart.component.css new file mode 100644 index 0000000..b5de1f0 --- /dev/null +++ b/src/app/shared/ui/charts/doughnut-chart.component.css @@ -0,0 +1,181 @@ +.doughnut-wrapper { + display: flex; + flex-direction: column; + align-items: center; + gap: 1.25rem; +} + +.doughnut-chart { + position: relative; + width: 200px; + height: 200px; + flex-shrink: 0; +} + +.doughnut-svg { + width: 100%; + height: 100%; +} + +.doughnut-base { + fill: none; + stroke: var(--doughnut-base-bg, rgba(100, 116, 139, 0.14)); + stroke-width: 22; +} + +.doughnut-segment { + fill: none; + stroke-width: 22; + stroke-linecap: butt; + cursor: default; + transition: stroke-width 0.2s ease, opacity 0.2s ease; + animation: doughnutDraw 0.8s cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.doughnut-segment-active { + stroke-width: 27; +} + +.doughnut-center { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.15rem; + pointer-events: none; + text-align: center; + padding: 0 2.2rem; +} + +.doughnut-center-value { + font-size: 1.5rem; + font-weight: 700; + color: var(--text-primary); + line-height: 1.2; +} + +.doughnut-center-caption { + font-size: 0.6875rem; + color: var(--text-muted); + line-height: 1.4; +} + +.doughnut-legend { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.5rem 1rem; + width: 100%; + margin: 0; + padding: 0; + list-style: none; +} + +.legend-item { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.35rem 0.5rem; + border-radius: 0.5rem; + font-size: 0.75rem; + color: var(--text-secondary); + transition: background 0.2s ease; + cursor: default; +} + +.legend-item-active, +.legend-item:hover { + background: var(--sidebar-hover); +} + +.legend-dot { + width: 0.625rem; + height: 0.625rem; + border-radius: 50%; + flex-shrink: 0; +} + +.legend-label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.legend-value { + margin-inline-start: auto; + font-weight: 600; + color: var(--text-primary); +} + +.legend-percent { + min-width: 2.75rem; + text-align: end; + color: var(--text-muted); +} + +.chart-tooltip { + position: absolute; + z-index: 20; + display: flex; + flex-direction: column; + gap: 0.15rem; + min-width: max-content; + max-width: 240px; + padding: 0.55rem 0.75rem; + border: 1px solid var(--card-border); + border-radius: 0.75rem; + background: var(--surface-bg); + box-shadow: 0 12px 32px rgba(15, 23, 42, 0.18); + transform: translate(50%, -110%); + pointer-events: none; + animation: tooltipFade 0.15s ease-out; +} + +.chart-tooltip-title { + font-size: 0.8125rem; + font-weight: 600; + color: var(--text-primary); +} + +.chart-tooltip-row { + font-size: 0.75rem; + color: var(--text-secondary); +} + +.chart-empty { + padding: 2.5rem 1rem; + text-align: center; + font-size: 0.875rem; + color: var(--text-muted); +} + +@keyframes doughnutDraw { + from { + opacity: 0; + stroke-dasharray: 0 377; + } +} + +@keyframes tooltipFade { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .doughnut-segment { + animation: none; + } +} + +:host-context([data-bs-theme='dark']) .doughnut-base { + stroke: rgba(148, 163, 184, 0.18); +} + +:host-context([data-bs-theme='dark']) .chart-tooltip { + box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5); +} diff --git a/src/app/shared/ui/charts/doughnut-chart.component.html b/src/app/shared/ui/charts/doughnut-chart.component.html new file mode 100644 index 0000000..d66e816 --- /dev/null +++ b/src/app/shared/ui/charts/doughnut-chart.component.html @@ -0,0 +1,61 @@ +@if (segments().length) { +
+ + +
    + @for (arc of arcs(); track arc.label; let index = $index) { +
  • + + {{ arc.label }} + {{ formatValue(arc.value) }} + {{ formatShare(arc.value) }} +
  • + } +
+
+} @else { +

{{ emptyText() }}

+} diff --git a/src/app/shared/ui/charts/doughnut-chart.component.ts b/src/app/shared/ui/charts/doughnut-chart.component.ts new file mode 100644 index 0000000..17c2aec --- /dev/null +++ b/src/app/shared/ui/charts/doughnut-chart.component.ts @@ -0,0 +1,95 @@ +import { ChangeDetectionStrategy, Component, computed, input, signal } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { formatCount, formatPercent } from '../../utils/format.util'; + +export interface DoughnutSegment { + label: string; + value: number; + color: string; +} + +interface DoughnutArc extends DoughnutSegment { + dashArray: string; + dashOffset: number; + percent: number; +} + +const RADIUS = 60; +const CIRCUMFERENCE = 2 * Math.PI * RADIUS; +const SEGMENT_GAP = 3; + +@Component({ + selector: 'app-doughnut-chart', + standalone: true, + imports: [CommonModule], + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './doughnut-chart.component.html', + styleUrl: './doughnut-chart.component.css', +}) +export class DoughnutChartComponent { + readonly segments = input.required(); + readonly centerLabel = input('کل سوالات'); + readonly emptyText = input('داده‌ای برای نمایش نیست'); + readonly ariaLabel = input('نمودار دایره‌ای'); + + readonly activeIndex = signal(null); + readonly tooltipX = signal(0); + readonly tooltipY = signal(0); + + readonly total = computed(() => this.segments().reduce((sum, segment) => sum + segment.value, 0)); + + readonly arcs = computed(() => { + const total = this.total(); + let cumulative = 0; + + return this.segments().map((segment) => { + const fraction = total > 0 ? segment.value / total : 0; + const dashLength = Math.max(fraction * CIRCUMFERENCE - SEGMENT_GAP, 0); + + const arc: DoughnutArc = { + ...segment, + dashArray: `${dashLength} ${CIRCUMFERENCE}`, + dashOffset: -cumulative, + percent: fraction * 100, + }; + + cumulative += fraction * CIRCUMFERENCE; + return arc; + }); + }); + + readonly centerValue = computed(() => { + const active = this.activeIndex(); + if (active === null) return this.formatValue(this.total()); + return this.arcs()[active] ? this.formatValue(this.arcs()[active].value) : '۰'; + }); + + readonly centerCaption = computed(() => { + const active = this.activeIndex(); + if (active === null) return this.centerLabel(); + const arc = this.arcs()[active]; + return arc ? `${arc.label} — ${formatPercent(arc.percent)}` : this.centerLabel(); + }); + + formatValue(value: number): string { + return formatCount(value); + } + + formatShare(value: number): string { + return this.total() > 0 ? formatPercent((value / this.total()) * 100) : '۰٪'; + } + + onSegmentEnter(index: number, event: MouseEvent): void { + const host = (event.currentTarget as Element).closest('.doughnut-chart') as HTMLElement | null; + if (host) { + const rect = host.getBoundingClientRect(); + this.tooltipX.set(event.clientX - rect.left); + this.tooltipY.set(event.clientY - rect.top); + } + this.activeIndex.set(index); + } + + onSegmentLeave(): void { + this.activeIndex.set(null); + } +} diff --git a/src/app/shared/ui/charts/line-chart.component.css b/src/app/shared/ui/charts/line-chart.component.css new file mode 100644 index 0000000..eb4ddc0 --- /dev/null +++ b/src/app/shared/ui/charts/line-chart.component.css @@ -0,0 +1,137 @@ +.line-chart { + position: relative; + width: 100%; +} + +.line-svg { + width: 100%; + height: auto; + overflow: visible; +} + +.line-grid line { + stroke: var(--line-grid-color, rgba(100, 116, 139, 0.18)); + stroke-width: 1; + stroke-dasharray: 4 6; +} + +.line-tick-label { + font-size: 6px; + fill: var(--text-muted); +} + +.line-x-label { + font-size: 6px; + fill: var(--text-muted); +} + +.line-area { + animation: areaFade 0.8s ease-out both; +} + +.line-path { + stroke-dasharray: 2000; + animation: lineDraw 1.1s cubic-bezier(0.22, 1, 0.36, 1) both; +} + +.line-hit-area { + fill: transparent; + cursor: default; +} + +.line-point { + fill: var(--surface-bg); + stroke: var(--color-primary); + stroke-width: 2; + transition: r 0.15s ease; +} + +.line-point-active { + r: 4; + fill: var(--color-primary); +} + +.line-guide { + stroke: var(--color-primary); + stroke-width: 1.5; + stroke-dasharray: 3 4; + opacity: 0.7; + animation: fadeIn 0.15s ease-out; +} + +.chart-tooltip { + position: absolute; + z-index: 20; + display: flex; + flex-direction: column; + gap: 0.15rem; + min-width: max-content; + padding: 0.55rem 0.75rem; + border: 1px solid var(--card-border); + border-radius: 0.75rem; + background: var(--surface-bg); + box-shadow: 0 12px 32px rgba(15, 23, 42, 0.18); + transform: translate(50%, -110%); + pointer-events: none; + animation: fadeIn 0.15s ease-out; +} + +.chart-tooltip-title { + font-size: 0.8125rem; + font-weight: 600; + color: var(--text-primary); +} + +.chart-tooltip-row { + font-size: 0.75rem; + color: var(--text-secondary); +} + +.chart-empty { + padding: 2.5rem 1rem; + text-align: center; + font-size: 0.875rem; + color: var(--text-muted); +} + +@keyframes lineDraw { + from { + stroke-dashoffset: 2000; + } + to { + stroke-dashoffset: 0; + } +} + +@keyframes areaFade { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .line-path, + .line-area { + animation: none; + } +} + +:host-context([data-bs-theme='dark']) .line-grid line { + stroke: rgba(148, 163, 184, 0.2); +} + +:host-context([data-bs-theme='dark']) .chart-tooltip { + box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5); +} diff --git a/src/app/shared/ui/charts/line-chart.component.html b/src/app/shared/ui/charts/line-chart.component.html new file mode 100644 index 0000000..df6fe1d --- /dev/null +++ b/src/app/shared/ui/charts/line-chart.component.html @@ -0,0 +1,88 @@ +@if (points().length) { + +} @else { +

{{ emptyText() }}

+} diff --git a/src/app/shared/ui/charts/line-chart.component.ts b/src/app/shared/ui/charts/line-chart.component.ts new file mode 100644 index 0000000..746734b --- /dev/null +++ b/src/app/shared/ui/charts/line-chart.component.ts @@ -0,0 +1,124 @@ +import { ChangeDetectionStrategy, Component, computed, input, signal } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { formatCount } from '../../utils/format.util'; + +export interface LinePoint { + label: string; + value: number; +} + +interface LineGeometryPoint extends LinePoint { + x: number; + y: number; + showLabel: boolean; +} + +const WIDTH = 720; +const HEIGHT = 260; +const PADDING = { top: 26, right: 52, bottom: 36, left: 10 }; +const TICK_COUNT = 4; + +@Component({ + selector: 'app-line-chart', + standalone: true, + imports: [CommonModule], + changeDetection: ChangeDetectionStrategy.OnPush, + templateUrl: './line-chart.component.html', + styleUrl: './line-chart.component.css', +}) +export class LineChartComponent { + readonly points = input.required(); + readonly seriesLabel = input('تعداد سوالات'); + readonly unitLabel = input('سوال'); + readonly emptyText = input('داده‌ای برای نمایش نیست'); + readonly ariaLabel = input('نمودار روند'); + readonly gradientId = input('lineAreaGradient'); + + readonly activeIndex = signal(null); + readonly tooltipX = signal(0); + readonly tooltipY = signal(0); + + readonly plotWidth = WIDTH - PADDING.left - PADDING.right; + readonly plotHeight = HEIGHT - PADDING.top - PADDING.bottom; + readonly viewBox = `0 0 ${WIDTH} ${HEIGHT}`; + readonly plotRight = WIDTH - PADDING.right; + readonly plotTop = PADDING.top; + readonly baseline = HEIGHT - PADDING.bottom; + + readonly maxValue = computed(() => { + const values = this.points().map((point) => point.value); + return values.length ? Math.max(...values) : 0; + }); + + readonly niceMax = computed(() => { + const max = this.maxValue(); + if (max <= 0) return 1; + const magnitude = Math.pow(10, Math.floor(Math.log10(max))); + return Math.ceil(max / magnitude) * magnitude; + }); + + readonly ticks = computed(() => { + const max = this.niceMax(); + return Array.from({ length: TICK_COUNT + 1 }, (_, index) => (max / TICK_COUNT) * index); + }); + + readonly geometry = computed(() => { + const points = this.points(); + const max = this.niceMax(); + const lastIndex = Math.max(points.length - 1, 1); + const labelStep = Math.max(Math.ceil(points.length / 6), 1); + + return points.map((point, index) => { + // RTL: oldest point on the right, newest on the left. + const x = WIDTH - PADDING.right - (index / lastIndex) * this.plotWidth; + const y = PADDING.top + (1 - point.value / max) * this.plotHeight; + + return { ...point, x, y, showLabel: index % labelStep === 0 || index === points.length - 1 }; + }); + }); + + readonly linePath = computed(() => + this.geometry() + .map((point, index) => `${index === 0 ? 'M' : 'L'}${point.x} ${point.y}`) + .join(' '), + ); + + readonly areaPath = computed(() => { + const points = this.geometry(); + if (points.length === 0) return ''; + const first = points[0]; + const last = points[points.length - 1]; + const baseline = HEIGHT - PADDING.bottom; + return `M${first.x} ${first.y} ${points + .slice(1) + .map((point) => `L${point.x} ${point.y}`) + .join(' ')} L${last.x} ${baseline} L${first.x} ${baseline} Z`; + }); + + readonly activePoint = computed(() => { + const index = this.activeIndex(); + return index === null ? null : (this.geometry()[index] ?? null); + }); + + formatValue(value: number): string { + return formatCount(value); + } + + tickY(tick: number): number { + return this.plotTop + (1 - tick / this.niceMax()) * this.plotHeight; + } + + onPointEnter(index: number, event: MouseEvent): void { + const host = (event.currentTarget as Element).closest('.line-chart') as HTMLElement | null; + if (host) { + const rect = host.getBoundingClientRect(); + this.tooltipX.set(event.clientX - rect.left); + this.tooltipY.set(event.clientY - rect.top); + } + this.activeIndex.set(index); + } + + onPointLeave(): void { + this.activeIndex.set(null); + } +} diff --git a/src/app/shared/ui/sidebar/sidebar.component.css b/src/app/shared/ui/sidebar/sidebar.component.css index 517402a..4b8faee 100644 --- a/src/app/shared/ui/sidebar/sidebar.component.css +++ b/src/app/shared/ui/sidebar/sidebar.component.css @@ -178,7 +178,7 @@ border-radius: 0.5rem; color: var(--sidebar-muted); text-decoration: none; - font-size: 1rem; + font-size: 0.875rem; font-weight: 500; transition: background 0.2s; } diff --git a/src/app/shared/utils/format.util.ts b/src/app/shared/utils/format.util.ts new file mode 100644 index 0000000..80b9231 --- /dev/null +++ b/src/app/shared/utils/format.util.ts @@ -0,0 +1,20 @@ +const PERSIAN_DIGITS = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']; + +export function toPersianDigits(value: string | number): string { + return String(value).replace(/\d/g, (digit) => PERSIAN_DIGITS[Number(digit)]); +} + +/** 4802 -> «۴,۸۰۲» */ +export function formatCount(value: number): string { + return toPersianDigits(Math.round(value).toLocaleString('en-US')); +} + +/** 1.8 -> «۱٫۸» */ +export function formatDecimal(value: number, fractionDigits = 1): string { + return toPersianDigits(value.toFixed(fractionDigits)).replace('.', '٫'); +} + +/** 91 -> «۹۱٪» */ +export function formatPercent(value: number): string { + return `${toPersianDigits(Math.round(value))}٪`; +} diff --git a/tailwind.config.js b/tailwind.config.js index 440343c..da154b8 100644 --- a/tailwind.config.js +++ b/tailwind.config.js @@ -54,7 +54,7 @@ module.exports = { }, }, fontFamily: { - sans: ['Vazir', 'sans-serif'], + sans: ['Lahze', 'sans-serif'], }, }, },