import type { ArticleSummary, ScanHistoryPoint, WeeklyReportResponse, } from '../../../service/visibility/visibility.interface'; import { getWeeklyReport, listArticles, listBrands, listScans, } from '../../../service/visibility/visibility.service'; import { getCurrentWeekIso } from '../../visibility/helpers'; /** What HQ's canvases read about the brand. */ export interface HomeWeek { brandId: string; /** This week's report, or null until this week's scan has written one. */ report: WeeklyReportResponse | null; /** The scan history, newest first. */ scans: ScanHistoryPoint[]; articles: ArticleSummary[]; } /** * Read the week for HQ: this week's report, the scan history and the content. * Each read stands on its own, so a week whose report is not written yet * (every Monday until its scan lands) still shows the scans and the content. * * @param {string} clientId - Merchant client id. * @param {string} token - Merchant JWT. * @returns {Promise} The week, or null when there is no brand. */ export const loadHomeWeek = async ( clientId: string, token: string ): Promise => { const brands = await listBrands(clientId, token); const brandId: string = brands.brands?.[0]?.brand_id ?? ''; if (!brandId) return null; const [report, history, contents] = await Promise.all([ getWeeklyReport(clientId, token, brandId, getCurrentWeekIso()).catch( () => null ), listScans(clientId, token, brandId).catch(() => null), listArticles(clientId, token, { brand_id: brandId }).catch(() => null), ]); return { brandId, report, // The endpoint sorts ascending; the canvases read scans[0] as the latest, // so the window is turned around once here rather than at each reader. scans: [...(history?.history ?? [])].reverse(), articles: contents?.articles ?? [], }; };