( projectId: string, startDate: Date, endDate: Date )
| 197 | } |
| 198 | |
| 199 | export async function syncGscData( |
| 200 | projectId: string, |
| 201 | startDate: Date, |
| 202 | endDate: Date |
| 203 | ): Promise<void> { |
| 204 | const conn = await db.gscConnection.findUniqueOrThrow({ |
| 205 | where: { projectId }, |
| 206 | }); |
| 207 | |
| 208 | if (!conn.siteUrl) { |
| 209 | throw new Error('No GSC site URL configured for this project'); |
| 210 | } |
| 211 | |
| 212 | const accessToken = await getGscAccessToken(projectId); |
| 213 | const start = formatDate(startDate); |
| 214 | const end = formatDate(endDate); |
| 215 | const syncedAt = nowString(); |
| 216 | |
| 217 | // 1. Daily totals — authoritative numbers for overview chart |
| 218 | const dailyRows = await queryGscSearchAnalytics( |
| 219 | accessToken, |
| 220 | conn.siteUrl, |
| 221 | start, |
| 222 | end, |
| 223 | ['date'] |
| 224 | ); |
| 225 | |
| 226 | if (dailyRows.length > 0) { |
| 227 | await originalCh.insert({ |
| 228 | table: 'gsc_daily', |
| 229 | values: dailyRows.map((row) => ({ |
| 230 | project_id: projectId, |
| 231 | date: row.keys[0] ?? '', |
| 232 | clicks: row.clicks, |
| 233 | impressions: row.impressions, |
| 234 | ctr: row.ctr, |
| 235 | position: row.position, |
| 236 | synced_at: syncedAt, |
| 237 | })), |
| 238 | format: 'JSONEachRow', |
| 239 | }); |
| 240 | } |
| 241 | |
| 242 | // 2. Per-page breakdown |
| 243 | const pageRows = await queryGscSearchAnalytics( |
| 244 | accessToken, |
| 245 | conn.siteUrl, |
| 246 | start, |
| 247 | end, |
| 248 | ['date', 'page'] |
| 249 | ); |
| 250 | |
| 251 | if (pageRows.length > 0) { |
| 252 | await originalCh.insert({ |
| 253 | table: 'gsc_pages_daily', |
| 254 | values: pageRows.map((row) => ({ |
| 255 | project_id: projectId, |
| 256 | date: row.keys[0] ?? '', |
no test coverage detected