diff --git a/DESIGN.md b/DESIGN.md index 832174c..a57a1e9 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -132,6 +132,7 @@ The approved Persian-first baseline remains authoritative where the shipped arti | Version | Date | Decision | | ------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 0.13.0 | 2026-08-22 | Replaced equal upcoming-event cards with an RTL shared-baseline priority histogram and ranked evidence cards. Three positive integer shares descend from physical right and total ۱۰۰٪; visible copy distinguishes planning priority from growth probability. Historical occasion evidence takes precedence over onboarding-profile signals, with explicit source and promote/prepare/caution labels. | | 0.12.0 | 2026-08-22 | Replaced the Transactions table with a period-scoped operational-health dashboard: four status KPIs, an absolute-count distribution chart, a 100% composition trend, keyboard inspection, and visible semantic data-table alternatives. Status colors are fixed to blue Paid/awaiting verification, emerald Verified/final, rose Failed, and amber Reversed. | | 0.11.1 | 2026-08-21 | Hardened narrow-screen shell, calendar, and chart behavior: the navbar uses the compact authentication-screen brand mark while the opened mobile drawer carries the full typographic wordmark and the only terminal selector, exact-period fields cannot overlap, payment charts keep their readable width with horizontal scrolling, and the growth teaser gains an action-blue emphasis with a restrained reduced-motion-safe pulse. | | 0.11.0 | 2026-08-21 | Added the feature-gated AI growth analyst: a cache-first 90-day forecast view with count/amount modes, P10–P90 uncertainty band, keyboard and tabular alternatives, evidence-linked Persian campaign guidance, preserved-content refresh states, and restrained semantic opportunity/risk styling. | @@ -311,6 +312,14 @@ The Transactions page contains no rows or drill-down links. Its primary chart us The fee page gives the circular share chart a large physical-right column while three numeric KPI cards stack in the adjacent column. Peer progress bars move from rose through amber and sky to emerald as the direction-adjusted percentile improves. Retry guidance uses amber, sky, or emerald surfaces and changes its supportive sentence at tested recovery/sample thresholds. +### Event Planning Priority + +The growth page ranks up to three upcoming occasions in one shared-baseline histogram. Rank 1 is the physical-right column in RTL; all available columns remain side by side on phones because their relative heights are the comparison. Column height maps literally to an integer planning-priority share, and the visible percentages total ۱۰۰٪. When only one or two candidates exist, a visible note names that limited set and the chart divides attention only among those events. A nearby clarification says these values allocate planning attention and are not growth probabilities. + +The histogram is the section's single visual signature: rank 1 uses the primary data color, while ranks 2 and 3 use progressively quieter mixtures of the same token and the nested surface. It uses no gradient, floating shadow, or decorative motion. Height changes may transition for 240ms and become immediate under reduced motion. Rank, title, percentage, total, and an ordered screen-reader description make the chart understandable without color or pointer interaction. + +Evidence cards stack beneath the compact chart on phones and form up to three physical-right-to-left columns from the medium breakpoint. Each card shows the event range, reason, explicit stance, and one source badge: «بر پایه تجربه شما» or «بر پایه شناخت کسب‌وکار». Historical cards show the previous occasion range, observation count, paid-session uplift, and amount uplift. Profile-grounded cards show onboarding-derived category, niche, or channel signals; if none are available, they say that only general profile context was used. Typed history-unavailable codes are translated into natural Persian. A visible warning identifies deterministic `PARTIAL` copy. Success, action, or warning accents reinforce the written promote, prepare, or caution stance and never replace it. + ## Do's and Don'ts ### Do: diff --git a/docs/GROWTH-ANALYST-UX-SPEC.md b/docs/GROWTH-ANALYST-UX-SPEC.md index 2bbc367..babfb52 100644 --- a/docs/GROWTH-ANALYST-UX-SPEC.md +++ b/docs/GROWTH-ANALYST-UX-SPEC.md @@ -12,8 +12,14 @@ - Header states the 90-day horizon starts after the latest complete dataset date. A daily `به‌روزرسانی تحلیل` action shows `nextRefreshAt`, loading, and typed rate-limit feedback. - Render a responsive, keyboard-accessible forecast chart with count/amount mode, hover/focus points, P10–P90 band, axes/units, chart summary, and a non-visual data alternative. - Show historical wins, up to five upcoming opportunities, up to three gentle low-period warnings, and a peer card when permitted. +- Rank up to three upcoming events as a shared-baseline priority histogram. Rank 1 is the physical-right column in RTL. Each column's literal height equals its integer planning-priority percentage; the displayed percentages are positive, descend by rank, and total exactly `100`. When only one or two relevant candidates exist, say so explicitly and divide the total only among the available candidates. +- State visibly that event priority is a relative planning allocation, not a probability of growth or guaranteed demand. Repeat rank and percentage in text so height and color are never the only carriers of meaning. +- Pair the compact histogram with one evidence card per displayed event. On desktop, up to three cards form RTL columns aligned by rank; on mobile, the compact histogram keeps its shared baseline and evidence cards stack for readable analysis. +- Prefer evidence from the merchant's matching prior occasion window. Show the prior start/end dates, observation count, paid-session uplift, amount uplift, and an explicit promote, prepare, or caution stance. Material decline must produce a visible caution recommendation. +- When matching historical evidence is unavailable, ground the explanation in onboarding profile signals. Show the matched category, niche, or sales-channel signals and, when provided, the reason history was unavailable. +- Label every event explanation as either `بر پایه تجربه شما` or `بر پایه شناخت کسب‌وکار`. The label must agree with both deterministic evidence and the recommendation's `insightBasis`. - Each brief contains server-rendered timing/range/evidence plus validated AI headline, interpretation, offer/message suggestion, one preparation step, confidence, and limitation. -- `PARTIAL` keeps deterministic charts/cards and explains that the written AI interpretation was unavailable. `LOW` keeps the forecast visible with an explicit limited-history or high-variance warning. `INSUFFICIENT_DATA` is reserved for scopes with no historical observations. `FAILED` offers safe retry without hiding an older successful report. +- `PARTIAL` keeps deterministic charts/cards and visibly explains that the written AI interpretation was unavailable. `INSUFFICIENT_EVENT_CANDIDATES` additionally states the exact number of available events instead of implying that three were ranked. `LOW` keeps the forecast visible with an explicit limited-history or high-variance warning. `INSUFFICIENT_DATA` is reserved for scopes with no historical observations. `FAILED` offers safe retry without hiding an older successful report. - Motion is restrained, supports reduced motion, and does not block reading. All interactive targets are at least 44 px. ## Copy rules @@ -21,11 +27,25 @@ - Use natural professional Persian, Persian `ی`/`ک`, appropriate نیم‌فاصله, Persian digits, and Rial. - Keep tone constructive: describe opportunity, preparation, and uncertainty; do not shame the merchant or claim guaranteed outcomes. - Every recommendation visibly cites its deterministic evidence card. AI is labeled advisory. +- Event reasons explain why the occasion is relevant to this merchant and must not turn planning priority into a forecast claim. - No chat, notifications, campaign execution, user memory, provider/model names, token usage, or internal failure details appear in merchant UI. +## Event priority contract + +- `occasionKey` is the stable identity used to join an upcoming occurrence to prior occurrences; `eventVariant` is one of `PRIMARY`, `CAMPAIGN_WINDOW`, or `OPERATIONAL_WINDOW` and distinguishes materially different variants without changing that identity. +- `HISTORICAL` is preferred whenever matching prior-window evidence is eligible. `BUSINESS_PROFILE` is used only when that evidence is unavailable. +- `historicalEvidence` contains deterministic dates, sample size, basis-point uplifts, and material-win/material-decline flags. AI copy may interpret these values but may not invent or alter them. +- `profileEvidence.matchedSignals` contains onboarding-derived evidence and may be empty. Empty signals produce truthful general-profile copy rather than invented alignment chips. `historyUnavailableReason` is an optional typed code and is always translated to natural Persian; raw backend codes never appear. +- Deterministic events form a discriminated evidence union: `HISTORICAL` requires `historicalEvidence`, while `BUSINESS_PROFILE` requires `profileEvidence`. Recommendation basis must match the deterministic event basis; mismatched recommendation copy is discarded rather than overriding evidence authority. +- `priorityPercent` is an integer from `1` to `98`. A valid AI recommendation collection contains exactly three items, is sorted descending, and totals exactly `100`; reports with fewer candidates omit AI copy and use the explicit limited-candidate `PARTIAL` state. +- Upcoming-event filtering compares inclusive calendar dates in `Asia/Tehran`, so an event remains visible through its entire `endDate` in the merchant calendar. +- `stance` is one of `PROMOTE`, `PREPARE`, or `CAUTION`; color always appears with its Persian text label. + ## Acceptance - Works at 360, 768, 1024, and wide desktop widths in light/dark RTL layouts. +- The event chart keeps three readable columns at 360 px, places rank 1 physically right, and exposes an equivalent ordered text alternative to assistive technology. +- Event evidence and reasons are visible without hover or pointer interaction, and histogram height transitions are removed under `prefers-reduced-motion`. - All job, cache, refresh, partial, insufficient, unauthorized, and recoverable error states are accessible and tested. - Generated OpenAPI types are used; no handwritten duplicate growth DTOs or browser secrets exist. - Cached navigation performs no generation request. Manual retry remains available while the current scope has no persisted AI-written summary; after one exists, refresh is limited once per merchant per Tehran day. diff --git a/src/lib/api/schema.d.ts b/src/lib/api/schema.d.ts index 822e5f4..e4d0e52 100644 --- a/src/lib/api/schema.d.ts +++ b/src/lib/api/schema.d.ts @@ -907,19 +907,73 @@ export interface components { expectedAmountRial: components["schemas"]["GrowthRange"]; historicalEvidenceId: string; }; - GrowthUpcomingEvent: { + GrowthHistoricalEventEvidence: { + /** Format: date-time */ + priorStartDate: string; + /** Format: date-time */ + priorEndDate: string; + /** @description Number of eligible comparison windows used to establish the baseline. */ + observationCount: number; + /** Format: int64 */ + paidSessionUpliftBps: number; + /** Format: int64 */ + amountUpliftBps: number; + materialWin: boolean; + materialDecline: boolean; + }; + GrowthProfileEventEvidence: { + matchedSignals: string[]; + historyUnavailableReason?: components["schemas"]["GrowthHistoryUnavailableReason"]; + }; + /** @enum {string} */ + GrowthHistoryUnavailableReason: "INSUFFICIENT_BASELINE_OBSERVATIONS" | "INSUFFICIENT_BASELINE_SESSIONS" | "INSUFFICIENT_HISTORY" | "INCOMPLETE_EVENT_WINDOW" | "INSUFFICIENT_COHORT" | "TERMINAL_SCOPE_UNSUPPORTED"; + GrowthUpcomingEventCommon: { evidenceId: string; eventId: string; + occasionKey: string; + /** @enum {string} */ + eventVariant: "PRIMARY" | "CAMPAIGN_WINDOW" | "OPERATIONAL_WINDOW"; eventTitleFa: string; /** Format: date-time */ date: string; + /** Format: date-time */ + endDate: string; eventType: string; officialHoliday: boolean; merchantCategories: string[]; behavioralChannels: string[]; }; + GrowthUpcomingHistoricalEvent: components["schemas"]["GrowthUpcomingEventCommon"] & { + /** @enum {string} */ + insightBasis: "HISTORICAL"; + historicalEvidence: components["schemas"]["GrowthHistoricalEventEvidence"]; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + insightBasis: "HISTORICAL"; + }; + GrowthUpcomingProfileEvent: components["schemas"]["GrowthUpcomingEventCommon"] & { + /** @enum {string} */ + insightBasis: "BUSINESS_PROFILE"; + profileEvidence: components["schemas"]["GrowthProfileEventEvidence"]; + } & { + /** + * @description discriminator enum property added by openapi-typescript + * @enum {string} + */ + insightBasis: "BUSINESS_PROFILE"; + }; + GrowthUpcomingEvent: components["schemas"]["GrowthUpcomingHistoricalEvent"] | components["schemas"]["GrowthUpcomingProfileEvent"]; + /** @description Exactly three recommendations are returned in descending priority order. Their positive integer priorityPercent values sum to 100. */ GrowthEventRecommendation: { evidenceId: string; + priorityPercent: number; + /** @enum {string} */ + stance: "PROMOTE" | "PREPARE" | "CAUTION"; + /** @enum {string} */ + insightBasis: "HISTORICAL" | "BUSINESS_PROFILE"; relevanceReason: string; }; GrowthRisk: { @@ -977,6 +1031,7 @@ export interface components { category: string; niches: string[]; salesChannels: string[]; + businessDescriptions?: string[]; }; }; GrowthReport: { @@ -991,6 +1046,7 @@ export interface components { horizonDays: 90; deterministicEvidence?: components["schemas"]["GrowthEvidence"]; aiCopy?: { + /** @description Ranked in descending priorityPercent order; the three percentages sum to exactly 100. */ eventRecommendations: components["schemas"]["GrowthEventRecommendation"][]; }; failureCode?: string; diff --git a/src/lib/components/GrowthEventImpactChart.svelte b/src/lib/components/GrowthEventImpactChart.svelte index c78d6d3..1e9861f 100644 --- a/src/lib/components/GrowthEventImpactChart.svelte +++ b/src/lib/components/GrowthEventImpactChart.svelte @@ -1,53 +1,314 @@ {#if visibleEvents.length} -
- {#each visibleEvents as event (event.evidenceId)} -
-

رویداد پیش رو

-

{event.eventTitleFa}

-

{formatDateOnly(event.date)}

-

{event.relevanceReason}

-
- {/each} +
+ {#if isPartial} +
+

نسخهٔ موقت تحلیل

+

+ {visibleEvents.length < 3 + ? 'رویدادهای مرتبط کافی برای رتبه‌بندی کامل پیدا نشد؛ موارد موجود به‌صورت موقت نمایش داده می‌شوند.' + : 'متن تفسیری هوشمند این نوبت آماده نشد؛ اولویت‌های زیر از شواهد موجود ساخته شده‌اند.'} +

+
+ {/if} + + {#if visibleEvents.length < 3} +
+ تنها {formatValue(visibleEvents.length)} رویداد مرتبط در بازهٔ بررسی پیدا شد؛ سهم‌های نمایش‌داده‌شده فقط + میان همین موارد تقسیم شده‌اند. +
+ {/if} + +
+ +

+ این درصد، سهم اولویت برای برنامه‌ریزی است؛ نه احتمال رشد فروش. جمع + {visibleEvents.length === 3 ? 'سه اولویت' : `اولویت‌های ${formatValue(visibleEvents.length)} رویداد`} + ۱۰۰٪ است. +

+
+ +
+
+ نمودار ستونی رتبه‌بندی رویدادها؛ ارتفاع هر ستون برابر سهم آن رویداد از اولویت برنامه‌ریزی است. +
+ +
+ {#each visibleEvents as event (event.evidenceId)} +
+ رتبه {formatValue(event.rank)} +

{event.eventTitleFa}

+
+ {/each} +
+

+ جمع اولویت‌ها: {formatValue(priorityTotal)}٪ +

+
    + {#each visibleEvents as event (event.evidenceId)} +
  1. + رتبه {formatValue(event.rank)}، {event.eventTitleFa}، {formatValue(event.priorityPercent)} درصد از + اولویت برنامه‌ریزی. +
  2. + {/each} +
+
+ +
+ {#each visibleEvents as event (event.evidenceId)} +
+
+
+

+ رتبه {formatValue(event.rank)} · {formatValue(event.priorityPercent)}٪ +

+

{event.eventTitleFa}

+
+ + {event.insightBasis === 'HISTORICAL' ? 'بر پایه تجربه شما' : 'بر پایه شناخت کسب‌وکار'} + +
+ +

+ زمان رویداد: {dateRange(event.date, event.endDate)} +

+

{stanceLabels[event.stance]}

+

{event.relevanceReason}

+ + {#if event.insightBasis === 'HISTORICAL' && event.historicalEvidence} +
+

دوره مشابه قبلی

+

+ {dateRange(event.historicalEvidence.priorStartDate, event.historicalEvidence.priorEndDate)} · + {formatValue(event.historicalEvidence.observationCount)} بازه مقایسه‌شده +

+
+
+
تعداد پرداخت موفق
+
+ {movement(event.historicalEvidence.paidSessionUpliftBps)} +
+
+
+
مبلغ فروش
+
{movement(event.historicalEvidence.amountUpliftBps)}
+
+
+
+ {:else if event.insightBasis === 'BUSINESS_PROFILE' && event.profileEvidence} +
+

نشانه‌های مرتبط در پروفایل شما

+ {#if event.profileEvidence.matchedSignals.length} +
    + {#each event.profileEvidence.matchedSignals as signal (signal)} +
  • {signal}
  • + {/each} +
+ {:else} +

+ این پیشنهاد با شناخت کلی ثبت‌شده از کسب‌وکار شما تنظیم شده است؛ نشانهٔ جزئی‌تری برای نمایش + وجود ندارد. +

+ {/if} + {#if event.profileEvidence.historyUnavailableReason} +

+ دلیل استفاده از پروفایل: {historyUnavailableCopy( + event.profileEvidence.historyUnavailableReason, + )} +

+ {/if} +
+ {/if} +
+ {/each} +
{:else}
@@ -55,3 +316,64 @@

با به‌روزرسانی تقویم، این بخش دوباره بررسی می‌شود.

{/if} + + diff --git a/src/lib/components/GrowthEventImpactChart.test.ts b/src/lib/components/GrowthEventImpactChart.test.ts index 6aa9c1a..abd9d91 100644 --- a/src/lib/components/GrowthEventImpactChart.test.ts +++ b/src/lib/components/GrowthEventImpactChart.test.ts @@ -1,97 +1,274 @@ -import { cleanup, render, screen } from '@testing-library/svelte'; +import { cleanup, render, screen, within } from '@testing-library/svelte'; import { afterEach, describe, expect, it } from 'vitest'; import GrowthEventImpactChart from './GrowthEventImpactChart.svelte'; const events = [ { - evidenceId: 'event-1', - eventId: 'event-1', - eventTitleFa: 'نوروز', - date: '2027-03-21T00:00:00Z', - eventType: 'SEASONAL', - officialHoliday: false, - merchantCategories: [], - behavioralChannels: [], - }, - { - evidenceId: 'event-2', - eventId: 'event-2', - eventTitleFa: 'شب یلدا', - date: '2026-12-21T00:00:00Z', - eventType: 'CULTURAL', - officialHoliday: false, - merchantCategories: [], - behavioralChannels: [], - }, - { - evidenceId: 'event-3', - eventId: 'event-3', + evidenceId: 'event-black-friday', + eventId: 'black-friday-2026', + occasionKey: 'BLACK_FRIDAY', + eventVariant: 'CAMPAIGN_WINDOW' as const, eventTitleFa: 'بلک‌فرایدی', date: '2026-11-27T00:00:00Z', + endDate: '2026-11-29T23:59:59Z', eventType: 'COMMERCIAL', officialHoliday: false, - merchantCategories: [], - behavioralChannels: [], + merchantCategories: ['فروشگاه آنلاین'], + behavioralChannels: ['ONLINE'], + insightBasis: 'HISTORICAL' as const, + historicalEvidence: { + priorStartDate: '2025-11-28T00:00:00Z', + priorEndDate: '2025-11-30T23:59:59Z', + observationCount: 6, + paidSessionUpliftBps: 2450, + amountUpliftBps: 3180, + materialWin: true, + materialDecline: false, + }, }, { - evidenceId: 'event-4', - eventId: 'event-4', + evidenceId: 'event-yalda', + eventId: 'yalda-2026', + occasionKey: 'YALDA', + eventVariant: 'PRIMARY' as const, + eventTitleFa: 'شب یلدا', + date: '2026-12-21T00:00:00Z', + endDate: '2026-12-21T23:59:59Z', + eventType: 'CULTURAL', + officialHoliday: false, + merchantCategories: ['فروشگاه آنلاین'], + behavioralChannels: ['ONLINE'], + insightBasis: 'BUSINESS_PROFILE' as const, + profileEvidence: { + matchedSignals: ['فروش آنلاین', 'محصول هدیه‌پذیر'], + historyUnavailableReason: 'INSUFFICIENT_HISTORY' as const, + }, + }, + { + evidenceId: 'event-cyber-monday', + eventId: 'cyber-monday-2026', + occasionKey: 'CYBER_MONDAY', + eventVariant: 'OPERATIONAL_WINDOW' as const, eventTitleFa: 'سایبرماندی', date: '2026-11-30T00:00:00Z', + endDate: '2026-11-30T23:59:59Z', eventType: 'COMMERCIAL', officialHoliday: false, - merchantCategories: [], - behavioralChannels: [], + merchantCategories: ['فروشگاه آنلاین'], + behavioralChannels: ['ONLINE'], + insightBasis: 'HISTORICAL' as const, + historicalEvidence: { + priorStartDate: '2025-12-01T00:00:00Z', + priorEndDate: '2025-12-01T23:59:59Z', + observationCount: 5, + paidSessionUpliftBps: -1340, + amountUpliftBps: -2080, + materialWin: false, + materialDecline: true, + }, + }, +]; + +const recommendations = [ + { + evidenceId: 'event-black-friday', + priorityPercent: 52, + stance: 'PROMOTE' as const, + insightBasis: 'HISTORICAL' as const, + relevanceReason: 'فروش موفق پارسال نشان می‌دهد پیشنهاد زودهنگام می‌تواند دوباره تقاضا را جذب کند.', + }, + { + evidenceId: 'event-yalda', + priorityPercent: 31, + stance: 'PREPARE' as const, + insightBasis: 'BUSINESS_PROFILE' as const, + relevanceReason: 'محصولات هدیه‌پذیر شما با خریدهای مناسبتی شب یلدا هم‌خوانی دارند.', + }, + { + evidenceId: 'event-cyber-monday', + priorityPercent: 17, + stance: 'CAUTION' as const, + insightBasis: 'HISTORICAL' as const, + relevanceReason: 'افت مبلغ فروش در دوره قبل، اجرای محدود و کنترل موجودی را منطقی‌تر می‌کند.', }, ]; afterEach(cleanup); describe('GrowthEventImpactChart', () => { - it('uses AI rank order and shows each grounded relevance reason', () => { + it('renders a ranked three-column priority histogram whose percentages total 100', () => { + render(GrowthEventImpactChart, { + props: { events, recommendations, now: new Date('2026-08-21T00:00:00Z') }, + }); + + const chart = screen.getByRole('figure', { name: 'نمودار اولویت برنامه‌ریزی سه رویداد پیش رو' }); + const bars = within(chart).getAllByTestId('priority-bar'); + expect(bars).toHaveLength(3); + expect(bars[0].getAttribute('style')).toContain('--priority: 52'); + expect(bars[1].getAttribute('style')).toContain('--priority: 31'); + expect(bars[2].getAttribute('style')).toContain('--priority: 17'); + expect(within(chart).getByText('۵۲٪')).not.toBeNull(); + expect(within(chart).getByText('رتبه ۱')).not.toBeNull(); + expect(within(chart).getByText('رتبه ۲')).not.toBeNull(); + expect(within(chart).getByText('رتبه ۳')).not.toBeNull(); + expect(within(chart).getByText(/جمع اولویت‌ها: ۱۰۰٪/)).not.toBeNull(); + expect(screen.getByText(/این درصد، سهم اولویت برای برنامه‌ریزی است؛ نه احتمال رشد فروش/)).not.toBeNull(); + }); + + it('shows deterministic historical evidence and a clear positive stance', () => { + render(GrowthEventImpactChart, { + props: { events, recommendations, now: new Date('2026-08-21T00:00:00Z') }, + }); + + const card = screen.getByRole('article', { name: 'رتبه ۱: بلک‌فرایدی' }); + expect(card.textContent).toContain('بر پایه تجربه شما'); + expect(card.textContent).toContain('پیشنهاد: ترویج'); + expect(card.textContent).toContain('۶ بازه مقایسه‌شده'); + expect(card.textContent).toContain('تعداد پرداخت موفق ۲۴٫۵٪ افزایش'); + expect(card.textContent).toContain('مبلغ فروش ۳۱٫۸٪ افزایش'); + expect(card.textContent).toContain(recommendations[0].relevanceReason); + expect(card.textContent).toContain('دوره مشابه قبلی'); + }); + + it('uses onboarding profile signals when matching historical data is unavailable', () => { + render(GrowthEventImpactChart, { + props: { events, recommendations, now: new Date('2026-08-21T00:00:00Z') }, + }); + + const card = screen.getByRole('article', { name: 'رتبه ۲: شب یلدا' }); + expect(card.textContent).toContain('بر پایه شناخت کسب‌وکار'); + expect(card.textContent).toContain('پیشنهاد: آماده‌سازی'); + expect(card.textContent).toContain('فروش آنلاین'); + expect(card.textContent).toContain('محصول هدیه‌پذیر'); + expect(card.textContent).toContain('هنوز سابقهٔ کافی برای این مناسبت ثبت نشده است.'); + expect(card.textContent).not.toContain('INSUFFICIENT_HISTORY'); + expect(card.textContent).toContain(recommendations[1].relevanceReason); + }); + + it('uses truthful general profile copy when no matched signal is available', () => { + const profileEvent = events[1]; + if (profileEvent.insightBasis !== 'BUSINESS_PROFILE') throw new Error('Expected profile-backed fixture'); + + render(GrowthEventImpactChart, { + props: { + events: [ + { ...profileEvent, profileEvidence: { ...profileEvent.profileEvidence, matchedSignals: [] } }, + ], + now: new Date('2026-08-21T00:00:00Z'), + }, + }); + + const card = screen.getByRole('article', { name: 'رتبه ۱: شب یلدا' }); + expect(card.textContent).toContain('شناخت کلی ثبت‌شده از کسب‌وکار شما'); + expect(screen.queryByRole('list', { name: 'نشانه‌های مرتبط کسب‌وکار' })).toBeNull(); + }); + + it('states a caution recommendation when prior performance materially declined', () => { + render(GrowthEventImpactChart, { + props: { events, recommendations, now: new Date('2026-08-21T00:00:00Z') }, + }); + + const card = screen.getByRole('article', { name: 'رتبه ۳: سایبرماندی' }); + expect(card.textContent).toContain('پیشنهاد: با احتیاط'); + expect(card.textContent).toContain('تعداد پرداخت موفق ۱۳٫۴٪ کاهش'); + expect(card.textContent).toContain('مبلغ فروش ۲۰٫۸٪ کاهش'); + }); + + it('keeps a grounded 100-percent fallback when written recommendations are unavailable', () => { + render(GrowthEventImpactChart, { + props: { events, now: new Date('2026-08-21T00:00:00Z') }, + }); + + const chart = screen.getByRole('figure', { name: 'نمودار اولویت برنامه‌ریزی سه رویداد پیش رو' }); + expect(within(chart).getByText(/جمع اولویت‌ها: ۱۰۰٪/)).not.toBeNull(); + expect(within(chart).getAllByTestId('priority-bar')[0].getAttribute('style')).toContain('--priority: 34'); + expect(screen.getByRole('article', { name: 'رتبه ۱: بلک‌فرایدی' }).textContent).toContain( + 'رفتار پرداخت در دوره مشابه قبلی', + ); + }); + + it('omits past events without leaving an inaccessible chart', () => { + render(GrowthEventImpactChart, { + props: { + events: [{ ...events[0], date: '2026-08-20T00:00:00Z', endDate: '2026-08-20T16:00:00Z' }], + recommendations: [recommendations[0]], + now: new Date('2026-08-21T00:00:00Z'), + }, + }); + + expect(screen.queryByRole('figure')).toBeNull(); + expect(screen.getByRole('status').textContent).toContain('رویداد مرتبطی در تقویم بررسی‌شده پیدا نشد'); + }); + + it('keeps an event visible through its inclusive Tehran end date', () => { + render(GrowthEventImpactChart, { + props: { + events: [{ ...events[0], date: '2026-08-21T00:00:00Z', endDate: '2026-08-21T00:00:00Z' }], + now: new Date('2026-08-21T15:00:00Z'), + }, + }); + + expect(screen.getByRole('figure', { name: 'نمودار اولویت برنامه‌ریزی ۱ رویداد پیش رو' })).not.toBeNull(); + }); + + it.each([ + [1, '۱', [100]], + [2, '۲', [50, 50]], + ])('truthfully normalizes %i available candidate(s)', (count, persianCount, expectedShares) => { + render(GrowthEventImpactChart, { + props: { events: events.slice(0, count), now: new Date('2026-08-21T00:00:00Z') }, + }); + + const chart = screen.getByRole('figure', { + name: `نمودار اولویت برنامه‌ریزی ${persianCount} رویداد پیش رو`, + }); + expect(within(chart).getAllByTestId('priority-bar')).toHaveLength(count); + expectedShares.forEach((share, index) => { + expect(within(chart).getAllByTestId('priority-bar')[index].getAttribute('style')).toContain( + `--priority: ${share}`, + ); + }); + expect(screen.getByText(new RegExp(`تنها ${persianCount} رویداد مرتبط`))).not.toBeNull(); + expect(screen.queryByText(/جمع سه اولویت/)).toBeNull(); + expect(within(chart).getByText(/جمع اولویت‌ها: ۱۰۰٪/)).not.toBeNull(); + }); + + it('keeps deterministic evidence authoritative when recommendation basis disagrees', () => { render(GrowthEventImpactChart, { props: { events, recommendations: [ - { evidenceId: 'event-1', relevanceReason: 'زمان مناسبی برای آماده‌سازی پیشنهادهای فروش است.' }, - { evidenceId: 'event-3', relevanceReason: 'این رویداد با فروش آنلاین کسب‌وکار مرتبط است.' }, - { evidenceId: 'event-2', relevanceReason: 'این مناسبت برای برنامه‌ریزی پیام‌رسانی مناسب است.' }, + { ...recommendations[0], insightBasis: 'BUSINESS_PROFILE' as const }, + recommendations[1], + recommendations[2], ], now: new Date('2026-08-21T00:00:00Z'), }, }); - const cards = screen.getAllByRole('listitem'); - expect(cards).toHaveLength(3); - expect(cards[0]).toHaveTextContent('نوروز'); - expect(cards[0]).toHaveTextContent('زمان مناسبی برای آماده‌سازی پیشنهادهای فروش است.'); - expect(cards[1]).toHaveTextContent('بلک‌فرایدی'); + const card = screen.getByRole('article', { name: 'رتبه ۱: بلک‌فرایدی' }); + expect(card.textContent).toContain('بر پایه تجربه شما'); + expect(card.textContent).toContain('دوره مشابه قبلی'); }); - it('falls back to the first three upcoming reviewed events when AI is unavailable', () => { - render(GrowthEventImpactChart, { props: { events, now: new Date('2026-08-21T00:00:00Z') } }); - - expect(screen.getAllByRole('listitem')).toHaveLength(3); - expect(screen.getByText('بلک‌فرایدی')).not.toBeNull(); - expect( - screen.getAllByText('این مناسبت در تقویم بررسی‌شده به‌عنوان رویدادی مرتبط با کسب‌وکار ثبت شده است.'), - ).toHaveLength(3); - expect(screen.queryByText('نوروز')).toBeNull(); - }); - - it('does not render events that are already in the past', () => { + it('shows a visible partial notice when AI prose fell back', () => { render(GrowthEventImpactChart, { - props: { - events: [ - { ...events[0], evidenceId: 'past', eventTitleFa: 'رویداد گذشته', date: '2026-08-20T00:00:00Z' }, - events[2], - ], - now: new Date('2026-08-21T00:00:00Z'), - }, + props: { events, recommendations, isPartial: true, now: new Date('2026-08-21T00:00:00Z') }, }); - expect(screen.queryByText('رویداد گذشته')).toBeNull(); - expect(screen.getByText('بلک‌فرایدی')).not.toBeNull(); + expect(screen.getByRole('status', { name: 'تحلیل تکمیلی موقت' }).textContent).toContain( + 'متن تفسیری هوشمند این نوبت آماده نشد', + ); + }); + + it('explains a sparse partial result without blaming AI availability', () => { + render(GrowthEventImpactChart, { + props: { events: events.slice(0, 1), isPartial: true, now: new Date('2026-08-21T00:00:00Z') }, + }); + + const notice = screen.getByRole('status', { name: 'تحلیل تکمیلی موقت' }); + expect(notice.textContent).toContain('رویدادهای مرتبط کافی برای رتبه‌بندی کامل پیدا نشد'); + expect(notice.textContent).not.toContain('متن تفسیری هوشمند این نوبت آماده نشد'); }); }); diff --git a/src/lib/components/GrowthPage.svelte b/src/lib/components/GrowthPage.svelte index 5060722..a802bff 100644 --- a/src/lib/components/GrowthPage.svelte +++ b/src/lib/components/GrowthPage.svelte @@ -823,13 +823,16 @@ > {/if}
- +
- سه رویداد پیش رو + اولویت رویدادهای پیش رو

- سه مناسبت مرتبط با فعالیت شما، بر پایه تقویم بررسی‌شده و اولویت‌بندی هوشمند، نمایش داده می‌شوند. + سه مناسبت نزدیک، بر پایه تجربه دوره‌های مشابه یا نشانه‌های ثبت‌شده در پروفایل کسب‌وکار شما + رتبه‌بندی شده‌اند.