feat(reports): implement reports page and data visualization components

Implement a comprehensive reports dashboard including user question
summaries, AI performance metrics, and usage trends. This includes
the creation of several reusable chart components and supporting
services.

- Add `ReportsPage` with tabbed navigation for questions and performance
- Implement `ReportsService` with mock data support for rapid development
- Create reusable UI components: `BarChartComponent`, `DoughnutChartComponent`, and `LineChartComponent`
- Add `format.util.ts` for Persian digit and number formatting
- Integrate 'Lahze' font family and add font assets
- Add unit tests for `ReportsPage` and `ReportsService`
This commit is contained in:
Peyman Honarjoo
2026-10-09 17:48:18 +03:30
parent 72e7d0a007
commit 0b5a882ecb
30 changed files with 1931 additions and 5 deletions
+10 -3
View File
@@ -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],
},
];
+1
View File
@@ -51,6 +51,7 @@
flex-direction: column;
flex: 1;
min-width: 0;
margin-right: 72px;
transition: margin-right 0.3s ease;
}
+406
View File
@@ -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%;
}
+215
View File
@@ -0,0 +1,215 @@
<div class="reports-page">
<header class="reports-header">
<div class="reports-title-group">
<span class="reports-title-icon">
<svg
width="22"
height="22"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M4 4v16h16" />
<path d="M8 20V11" />
<path d="M12.5 20V6" />
<path d="M17 20V9" />
</svg>
</span>
<div>
<h1 class="reports-title">گزارشات</h1>
<p class="reports-subtitle">مروری بر استفاده از دستیار هوشمند و نتایج پاسخ‌های هوش مصنوعی</p>
</div>
</div>
@if (summary(); as summary) {
<span class="period-chip">بازه گزارش: {{ summary.periodLabel }}</span>
}
</header>
@if (loading()) {
<div class="stats-grid">
@for (card of [1, 2, 3, 4]; track card) {
<div class="report-card skeleton-card">
<div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-value"></div>
</div>
}
</div>
} @else if (loadError()) {
<div class="report-card error-card" role="alert">
<svg
width="40"
height="40"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4M12 16h.01" />
</svg>
<h2>دریافت گزارشات ممکن نشد</h2>
<p>ارتباط با سرور برقرار نشد. لطفاً دوباره تلاش کنید.</p>
<button type="button" class="retry-btn" (click)="retry()">تلاش مجدد</button>
</div>
} @else if (data(); as view) {
<nav class="reports-tabs" role="tablist" aria-label="بخش‌های گزارشات">
@for (tab of tabs; track tab.id) {
<button
type="button"
class="tab-btn"
role="tab"
[class.tab-active]="activeTab() === tab.id"
[attr.aria-selected]="activeTab() === tab.id"
(click)="selectTab(tab.id)"
>
<svg
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path [attr.d]="tab.icon" />
</svg>
<span>{{ tab.label }}</span>
@if (activeTab() === tab.id) {
<span class="tab-indicator"></span>
}
</button>
}
</nav>
@if (activeTab() === 'questions') {
<div class="tab-panel" role="tabpanel">
<div class="stats-grid">
<section class="report-card stat-card">
<span class="stat-label">تعداد کل سوالات</span>
<strong class="stat-value">{{ formatCount(view.summary.totalQuestions) }}</strong>
<span class="stat-hint">در {{ view.summary.periodLabel }}</span>
</section>
<section class="report-card stat-card">
<span class="stat-label">کاربران یکتا</span>
<strong class="stat-value">{{ formatCount(view.summary.uniqueUsers) }}</strong>
<span class="stat-hint">کاربرانی که با دستیار گفتگو کرده‌اند</span>
</section>
<section class="report-card stat-card">
<span class="stat-label">پاسخ‌های هوش مصنوعی</span>
<strong class="stat-value">{{ formatCount(view.summary.aiAnswered) }}</strong>
<div class="stat-progress" aria-hidden="true">
<span class="stat-progress-fill" [style.width.%]="aiAnswerRate()"></span>
</div>
<span class="stat-hint">{{ formatPercent(aiAnswerRate()) }} از کل سوالات</span>
</section>
<section class="report-card stat-card">
<span class="stat-label">ارجاع به کارشناس</span>
<strong class="stat-value">{{ formatCount(view.summary.escalatedToAgent) }}</strong>
<span class="stat-hint">سوالات نیازمند بررسی انسانی</span>
</section>
</div>
<div class="charts-grid">
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">پرتکرارترین سوالات</h2>
<p class="card-description">پرپرسش‌ترین موضوعات کاربران، به ترتیب فراوانی</p>
</div>
<app-bar-chart
[items]="topQuestions()"
ariaLabel="نمودار میله‌ای پرتکرارترین سوالات کاربران"
/>
</section>
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">توزیع سوالات</h2>
<p class="card-description">سهم هر دسته از کل سوالات مطرح‌شده</p>
</div>
<app-doughnut-chart
[segments]="categories()"
centerLabel="کل سوالات"
ariaLabel="نمودار دایره‌ای توزیع سوالات بر اساس دسته"
/>
</section>
</div>
</div>
} @else {
<div class="tab-panel" role="tabpanel">
<div class="ai-grid">
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">عملکرد هوش مصنوعی</h2>
<p class="card-description">آمار پاسخ‌دهی و کیفیت عملکرد دستیار</p>
</div>
<div class="ai-stats">
<div class="ai-stat">
<span class="ai-stat-label">میانگین زمان پاسخ</span>
<strong class="ai-stat-value">{{ formatDecimal(view.aiPerformance.avgResponseSeconds) }} ثانیه</strong>
</div>
<div class="ai-stat">
<span class="ai-stat-label">نرخ موفقیت پاسخ‌ها</span>
<strong class="ai-stat-value">{{ formatPercent(view.aiPerformance.successRate) }}</strong>
<div class="stat-progress" aria-hidden="true">
<span class="stat-progress-fill" [style.width.%]="view.aiPerformance.successRate"></span>
</div>
</div>
<div class="ai-stat">
<span class="ai-stat-label">رضایت‌مندی کاربران</span>
<strong class="ai-stat-value">{{ formatPercent(view.aiPerformance.satisfactionRate) }}</strong>
<div class="stat-progress" aria-hidden="true">
<span class="stat-progress-fill" [style.width.%]="view.aiPerformance.satisfactionRate"></span>
</div>
</div>
<div class="ai-stat">
<span class="ai-stat-label">پاسخ بر پایه سوالات متداول</span>
<strong class="ai-stat-value">{{ formatPercent(faqBasedRate()) }}</strong>
<div class="stat-progress" aria-hidden="true">
<span class="stat-progress-fill" [style.width.%]="faqBasedRate()"></span>
</div>
</div>
</div>
<div class="ai-channels">
<h3 class="ai-channels-title">پاسخ‌ها بر اساس گونه گفتگو</h3>
<app-bar-chart
[items]="channels()"
valueSuffix=" پاسخ"
ariaLabel="نمودار میله‌ای پاسخ‌ها بر اساس گونه گفتگو"
/>
</div>
</section>
<section class="report-card chart-card">
<div class="card-header">
<h2 class="card-title">روند استفاده</h2>
<p class="card-description">
تغییرات حجم سوالات در {{ view.summary.periodLabel }} — مجموع
{{ formatCount(trendTotal()) }} سوال
@if (trendPeak(); as peak) {
<span class="trend-peak">بیشترین رشد در {{ peak.label }} با {{ formatCount(peak.value) }} سوال</span>
}
</p>
</div>
<app-line-chart
[points]="trend()"
seriesLabel="تعداد سوالات"
gradientId="reportsUsageTrend"
ariaLabel="نمودار خطی روند حجم سوالات در گذر زمان"
/>
</section>
</div>
</div>
}
}
</div>
@@ -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();
});
});
+88
View File
@@ -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,
};
@@ -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);
});
});
@@ -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<TopQuestion[]> {
return this.request<TopQuestion[]>('reports/top-questions', { limit }, MOCK_TOP_QUESTIONS);
}
getQuestionSummary(): Observable<QuestionSummary> {
return this.request<QuestionSummary>('reports/questions-summary', {}, MOCK_QUESTION_SUMMARY);
}
getCategoryDistribution(): Observable<CategoryShare[]> {
return this.request<CategoryShare[]>(
'reports/questions-distribution',
{},
MOCK_CATEGORY_SHARES,
);
}
getUsageTrend(days = 30): Observable<UsageTrendPoint[]> {
return this.request<UsageTrendPoint[]>('reports/usage-trend', { days }, MOCK_USAGE_TREND);
}
getAiPerformance(): Observable<AiPerformance> {
return this.request<AiPerformance>('reports/ai-performance', {}, MOCK_AI_PERFORMANCE);
}
getOverview(): Observable<ReportsView> {
return this.request<ReportsView>('reports/overview', {}, {
topQuestions: MOCK_TOP_QUESTIONS,
summary: MOCK_QUESTION_SUMMARY,
categories: MOCK_CATEGORY_SHARES,
trend: MOCK_USAGE_TREND,
aiPerformance: MOCK_AI_PERFORMANCE,
});
}
private request<T>(endpoint: string, params: Record<string, unknown>, fallback: T): Observable<T> {
if (this.useMockData) {
return of(fallback);
}
return this.http
.get<T>(endpoint, { params, skipToast: true, skipHasErrorCheck: true })
.pipe(map((response) => response.result));
}
}
+47
View File
@@ -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;
}
@@ -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);
}
@@ -0,0 +1,42 @@
@if (items().length) {
<ul class="bar-chart" role="list" [attr.aria-label]="ariaLabel()">
@for (item of items(); track item.label; let index = $index) {
<li class="bar-row">
<div class="bar-head">
<span class="bar-label" [title]="item.label">{{ item.label }}</span>
<span class="bar-metrics">
<span class="bar-value">{{ format(item.value) }}</span>
<span class="bar-share">{{ share(item.value) }}</span>
</span>
</div>
<div
class="bar-track"
[style.--bar-color]="item.color"
(mouseenter)="onTrackMove(index, $event)"
(mousemove)="onTrackMove(index, $event)"
(mouseleave)="onTrackLeave()"
>
<div class="bar-fill" [style.width]="barWidth(item.value)"></div>
</div>
@if (activeIndex() === index) {
<div
class="bar-tooltip"
role="tooltip"
[style.inset-inline-start]="tooltipX() + 'px'"
>
<strong class="bar-tooltip-title">{{ item.label }}</strong>
<span class="bar-tooltip-row">تعداد: {{ format(item.value) }}</span>
<span class="bar-tooltip-row">سهم: {{ share(item.value) }}</span>
@if (item.hint) {
<span class="bar-tooltip-hint">{{ item.hint }}</span>
}
</div>
}
</li>
}
</ul>
} @else {
<p class="chart-empty">{{ emptyText() }}</p>
}
@@ -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<BarChartItem[]>();
readonly valueSuffix = input<string>('');
readonly emptyText = input<string>('داده‌ای برای نمایش نیست');
readonly ariaLabel = input<string>('نمودار میله‌ای');
readonly activeIndex = signal<number | null>(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);
}
}
@@ -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);
}
@@ -0,0 +1,61 @@
@if (segments().length) {
<div class="doughnut-wrapper">
<div class="doughnut-chart" role="img" [attr.aria-label]="ariaLabel()">
<svg viewBox="0 0 160 160" class="doughnut-svg">
<circle class="doughnut-base" cx="80" cy="80" [attr.r]="60" />
<g transform="rotate(-90 80 80)">
@for (arc of arcs(); track arc.label; let index = $index) {
<circle
class="doughnut-segment"
[class.doughnut-segment-active]="activeIndex() === index"
[style.stroke]="arc.color"
[style.stroke-dasharray]="arc.dashArray"
[style.stroke-dashoffset]="arc.dashOffset"
cx="80"
cy="80"
r="60"
(mouseenter)="onSegmentEnter(index, $event)"
(mouseleave)="onSegmentLeave()"
/>
}
</g>
</svg>
<div class="doughnut-center" aria-hidden="true">
<span class="doughnut-center-value">{{ centerValue() }}</span>
<span class="doughnut-center-caption">{{ centerCaption() }}</span>
</div>
@if (activeIndex() !== null) {
<div
class="chart-tooltip"
role="tooltip"
[style.inset-inline-start]="tooltipX() + 'px'"
[style.top]="tooltipY() + 'px'"
>
<strong class="chart-tooltip-title">{{ arcs()[activeIndex()!].label }}</strong>
<span class="chart-tooltip-row">تعداد: {{ formatValue(arcs()[activeIndex()!].value) }}</span>
<span class="chart-tooltip-row">سهم: {{ formatShare(arcs()[activeIndex()!].value) }}</span>
</div>
}
</div>
<ul class="doughnut-legend" role="list">
@for (arc of arcs(); track arc.label; let index = $index) {
<li
class="legend-item"
[class.legend-item-active]="activeIndex() === index"
(mouseenter)="activeIndex.set(index)"
(mouseleave)="activeIndex.set(null)"
>
<span class="legend-dot" [style.background]="arc.color"></span>
<span class="legend-label">{{ arc.label }}</span>
<span class="legend-value">{{ formatValue(arc.value) }}</span>
<span class="legend-percent">{{ formatShare(arc.value) }}</span>
</li>
}
</ul>
</div>
} @else {
<p class="chart-empty">{{ emptyText() }}</p>
}
@@ -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<DoughnutSegment[]>();
readonly centerLabel = input<string>('کل سوالات');
readonly emptyText = input<string>('داده‌ای برای نمایش نیست');
readonly ariaLabel = input<string>('نمودار دایره‌ای');
readonly activeIndex = signal<number | null>(null);
readonly tooltipX = signal(0);
readonly tooltipY = signal(0);
readonly total = computed(() => this.segments().reduce((sum, segment) => sum + segment.value, 0));
readonly arcs = computed<DoughnutArc[]>(() => {
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);
}
}
@@ -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);
}
@@ -0,0 +1,88 @@
@if (points().length) {
<div class="line-chart" role="img" [attr.aria-label]="ariaLabel()">
<svg [attr.viewBox]="viewBox" class="line-svg" preserveAspectRatio="xMidYMid meet">
<defs>
<linearGradient [attr.id]="gradientId()" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="var(--color-primary)" stop-opacity="0.32" />
<stop offset="100%" stop-color="var(--color-primary)" stop-opacity="0.02" />
</linearGradient>
</defs>
@for (tick of ticks(); track tick) {
<g class="line-grid">
<line
[attr.x1]="10"
[attr.y1]="tickY(tick)"
[attr.x2]="plotRight"
[attr.y2]="tickY(tick)"
/>
<text
class="line-tick-label"
[attr.x]="plotRight + 8"
[attr.y]="tickY(tick) + 4"
>{{ formatValue(tick) }}</text>
</g>
}
<path class="line-area" [attr.d]="areaPath()" [attr.fill]="'url(#' + gradientId() + ')'" />
<path
class="line-path"
[attr.d]="linePath()"
fill="none"
stroke="var(--color-primary)"
stroke-width="2.5"
stroke-linecap="round"
stroke-linejoin="round"
/>
@for (point of geometry(); track point.label; let index = $index) {
<g class="line-point-group">
@if (point.showLabel) {
<text class="line-x-label" [attr.x]="point.x" [attr.y]="baseline + 18" text-anchor="middle">
{{ point.label }}
</text>
}
<circle
class="line-hit-area"
[attr.cx]="point.x"
[attr.cy]="point.y"
r="14"
(mouseenter)="onPointEnter(index, $event)"
(mouseleave)="onPointLeave()"
/>
<circle
class="line-point"
[class.line-point-active]="activeIndex() === index"
[attr.cx]="point.x"
[attr.cy]="point.y"
r="2.5"
/>
</g>
}
@if (activePoint()) {
<line
class="line-guide"
[attr.x1]="activePoint()!.x"
[attr.y1]="plotTop"
[attr.x2]="activePoint()!.x"
[attr.y2]="baseline"
/>
}
</svg>
@if (activePoint()) {
<div
class="chart-tooltip"
role="tooltip"
[style.inset-inline-start]="tooltipX() + 'px'"
[style.top]="tooltipY() + 'px'"
>
<strong class="chart-tooltip-title">{{ activePoint()!.label }}</strong>
<span class="chart-tooltip-row">{{ seriesLabel() }}: {{ formatValue(activePoint()!.value) }} {{ unitLabel() }}</span>
</div>
}
</div>
} @else {
<p class="chart-empty">{{ emptyText() }}</p>
}
@@ -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<LinePoint[]>();
readonly seriesLabel = input<string>('تعداد سوالات');
readonly unitLabel = input<string>('سوال');
readonly emptyText = input<string>('داده‌ای برای نمایش نیست');
readonly ariaLabel = input<string>('نمودار روند');
readonly gradientId = input<string>('lineAreaGradient');
readonly activeIndex = signal<number | null>(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<LineGeometryPoint[]>(() => {
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<LineGeometryPoint | null>(() => {
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);
}
}
@@ -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;
}
+20
View File
@@ -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))}٪`;
}