Skip to content

Feat(project): amplitude event 연결#328

Merged
constantly-dev merged 12 commits intodevelopfrom
feat/#327/connect-amplitude-event
Apr 7, 2026
Merged

Feat(project): amplitude event 연결#328
constantly-dev merged 12 commits intodevelopfrom
feat/#327/connect-amplitude-event

Conversation

@constantly-dev
Copy link
Copy Markdown
Member

@constantly-dev constantly-dev commented Apr 6, 2026

📌 Related Issues

관련된 Issue를 태그해주세요. (e.g. - close #25)

📄 Tasks

  • ampli pull을 통해 Viewed_Saved_ContentImpression_Saved_Content 이벤트로 교체
  • @pinback/analytics 패키지에서 ampli 타입 전체 re-export (export type *)
  • 카드 뷰포트 노출 트래킹용 공통 컴포넌트 AnalyticsCardWrapper 추가
  • react-intersection-observeruseInView를 활용해 카드가 뷰포트에 노출될 때 이벤트 발화 (triggerOnce: true)
  • Remind, MyBookmark, JobPins 페이지 카드에 Impression_Saved_Content 이벤트 연결 (bookmark_type으로 탭 구분)
  • ESLint consistent-type-imports 룰 추가 및 저장 시 자동 수정 활성화

⭐ PR Point (To Reviewer)

  • Saved_Shared_Bookmark 이벤트는 dashboard → 외부 사이트 → extension 저장으로 이어지는 크로스 컨텍스트 구조상 신뢰도 있는 트래킹이 어려워 연결하지 않았습니다.
  • Impression_Saved_Contentarticle_id, category_id 프로퍼티는 유저별 내부 ID라 cross-user 집계가 불가능하여 현재 미사용 처리하였습니다.

📷 Screenshot

Summary by CodeRabbit

  • New Features

    • Firebase 알림에 Amplitude 이벤트 전송 추가(백그라운드 알림 발생/클릭 추적)
    • 카드 단위 노출(Impression) 및 클릭 이벤트 수집을 위한 분석 래퍼 도입(북마크·잡핀·리마인더·내북마크)
    • 확장 프로그램의 기사 저장 시 분석 이벤트 전송 추가
  • Refactor

    • TypeScript 타입 전용(import type) 사용 확대(빌드 최적화)
    • ESLint 자동 수정(on save) 및 타입 임포트 규칙 강화

@vercel
Copy link
Copy Markdown

vercel bot commented Apr 6, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
pinback-client-client Ready Ready Preview, Comment Apr 7, 2026 2:09am
pinback-client-landing Ready Ready Preview, Comment Apr 7, 2026 2:09am

@github-actions github-actions bot added the feat 기능 개발하라 개발 달려라 달려 label Apr 6, 2026
@github-actions github-actions bot requested review from jjangminii and jllee000 April 6, 2026 12:53
@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 6, 2026

✅ Storybook chromatic 배포 확인:
🐿️ storybook

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 6, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1ef157e0-cd72-4dc2-8c2a-8db13047c59d

📥 Commits

Reviewing files that changed from the base of the PR and between 1c42161 and 06f757a.

📒 Files selected for processing (2)
  • apps/client/src/pages/jobPins/JobPins.tsx
  • apps/extension/src/pages/MainPop.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/extension/src/pages/MainPop.tsx

Walkthrough

애널리틱스 이벤트(클릭·임프레션·저장) 통합, Amplitude 이벤트/메서드 리팩토링, 여러 파일의 TypeScript 타입 임포트를 type 전용으로 변환하고 VSCode/ESLint 설정을 일부 조정했습니다.

Changes

Cohort / File(s) Summary
Analytics 통합 (클라이언트 UI)
apps/client/src/pages/jobPins/JobPins.tsx, apps/client/src/pages/myBookmark/components/myBookmarkContent/MyBookmarkContent.tsx, apps/client/src/pages/remind/Remind.tsx, apps/extension/src/pages/MainPop.tsx
카드 클릭 시 analytics.track(...) 호출 추가 및 카드들을 AnalyticsCardWrapper로 래핑해 클릭/저장 이벤트를 전송하도록 변경. MyBookmarkContent는 queryClient prop 제거 및 내부에서 useQueryClient() 사용.
AnalyticsCardWrapper 컴포넌트
apps/client/src/shared/components/analyticsCardWrapper/AnalyticsCardWrapper.tsx
뷰포트 진입을 useInView로 감지해 최초 노출 시 analytics.track('Impression_Saved_Content', ...) 호출하는 새 래퍼 컴포넌트 추가.
서비스워커 Amplitude 통합
apps/client/public/firebase-messaging-sw.js
Amplitude API 키와 trackAmplitudeEvent() 헬퍼 추가, 백그라운드 메시지 처리 및 알림 클릭 시 Amplitude 이벤트 전송 로직 삽입(조건부 호스트 체크 포함).
Ampli 이벤트 스키마 리팩토링
packages/analytics/src/ampli/index.ts
이벤트/프로퍼티 이름 및 타입 변경(예: ClickedReminderClickedAlarm, OpenedSavedContentImpressionSavedContent), 새 메서드(clickedAlarm, clickedMyBookmark) 추가 및 일부 뷰 관련 메서드 제거/이름 변경.
패키지 타입 re-export
packages/analytics/index.ts
export type * from './src/ampli'; 추가로 Ampli 타입 공개 재수출.
타입 전용(import type) 리팩토링
여러 위치: apps/client/src/pages/..., apps/client/src/shared/..., apps/extension/..., packages/...
수십 개 파일에서 런타임 바인딩을 제거하기 위해 여러 타입 임포트를 import { type ... }로 변경(런타임 로직 미변경).
ESLint / VSCode 설정 변경
.vscode/settings.json, packages/eslint-config/react-internal.js
VSCode의 save autofix 동작을 변경하고(explicitalways), @typescript-eslint/consistent-type-imports 규칙을 추가해 type 임포트 일관성 강제.
기타 소소한 변경
apps/client/src/shared/utils/fetchOgData.ts, apps/client/src/shared/...
단순 타입 import 변환 및 관련 임포트 정리(런타임 영향 없음).

Sequence Diagram(s)

sequenceDiagram
  participant Browser as Client Browser
  participant UI as App UI (Card)
  participant Analytics as Analytics (ampli)
  participant Router as Navigation

  UI->>Analytics: Impression event on in-view\n("Impression_Saved_Content", bookmark_type)
  UI->>Analytics: Click event on click\n("Clicked_*", {article_id, category_id})
  UI->>Router: open article (window.open)
  Analytics-->>Analytics: enqueue/send event
Loading
sequenceDiagram
  participant SW as ServiceWorker
  participant FCM as Firebase Messaging
  participant Amplitude as Amplitude API
  participant Client as Client (focus/navigation)

  FCM->>SW: onBackgroundMessage(payload)
  SW->>Amplitude: trackAmplitudeEvent('Triggered_Reminder')
  SW->>SW: showNotification(...)
  SW->>SW: notificationclick
  SW->>Amplitude: trackAmplitudeEvent('Clicked_alarm')
  SW->>Client: clients.openWindow(notificationTarget)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

🛠️ Feature, frontend

Suggested reviewers

  • jllee000
  • jjangminii

Poem

🐰 코드 밭을 뛰어다니며 외치네,
클릭과 노출이 춤추는 밤이야.
임프레션도, 알람도, 내 발자국도,
Amplitude가 하나하나 기록하네.
당근 들고 축하한다, 데이터의 향연! 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning 코드 변경사항이 #327의 Amplitude 이벤트 연결 목표를 충족하지만, #25는 Progress 바 구현으로 이 PR과 무관합니다. #25는 이 PR과 무관한 Progress 바 구현 이슈이므로 연결 해제하거나 관련 변경사항을 추가하세요.
Out of Scope Changes check ⚠️ Warning ESLint consistent-type-imports 규칙 추가 및 광범위한 타입 임포트 변환은 #327 범위 밖의 변경사항입니다. 타입 임포트 변환(consistent-type-imports)은 별도 PR로 분리하고, 이 PR은 #327의 Amplitude 이벤트 연결에만 집중하세요.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed PR 제목은 'Feat(project): amplitude event 연결'로 주 변경사항인 Amplitude 이벤트 연결을 명확히 요약합니다.
Description check ✅ Passed PR 설명은 관련 이슈, 작업 내용, 리뷰어 노트를 포함하지만 스크린샷이 누락되었고 일부 섹션이 선택사항임을 고려하면 충분합니다.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/#327/connect-amplitude-event

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/client/src/pages/myBookmark/hooks/useMyBookmarkContentData.ts (1)

8-14: ⚠️ Potential issue | 🟡 Minor

scrollContainerRef의 타입을 RefObject로 변경하세요.

useInfiniteScroll 훅의 타입 정의(line 13)에서 rootRef?: React.RefObject<HTMLElement | null>로 명시하고 있습니다. 실제 사용처(line 33)에서도 rootRef?.current를 읽기만 수행하므로, 파라미터 타입을 MutableRefObject에서 RefObject로 수정하여 타입 계약을 일치시켜야 합니다.

제안 diff 보기
-import { type MutableRefObject } from 'react';
+import { type RefObject } from 'react';
...
-  scrollContainerRef: MutableRefObject<HTMLDivElement | null>;
+  scrollContainerRef: RefObject<HTMLDivElement | null>;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/client/src/pages/myBookmark/hooks/useMyBookmarkContentData.ts` around
lines 8 - 14, The parameter type for scrollContainerRef in the
UseMyBookmarkContentDataParams interface is too broad; change it from
MutableRefObject<HTMLDivElement | null> to React.RefObject<HTMLDivElement |
null> so it matches the useInfiniteScroll signature (rootRef?:
React.RefObject<HTMLElement | null>) and usage where only rootRef?.current is
read; update the import to include React if necessary and adjust any callers to
pass a RefObject.
🧹 Nitpick comments (2)
apps/client/src/shared/components/analyticsCardWrapper/AnalyticsCardWrapper.tsx (1)

27-27: 래퍼 div가 레이아웃에 영향을 줄 수 있습니다.

추가된 <div> 요소가 flex/grid 레이아웃에서 예상치 못한 스타일링 문제를 일으킬 수 있습니다. 필요 시 className prop을 추가하여 스타일 제어가 가능하도록 하는 것을 고려해 주세요.

♻️ 선택적 개선안
 interface AnalyticsCardWrapperProps {
   bookmarkType: ImpressionSavedContentProperties['bookmark_type'];
   children: React.ReactNode;
+  className?: string;
 }
 
 const AnalyticsCardWrapper = ({
   bookmarkType,
   children,
+  className,
 }: AnalyticsCardWrapperProps) => {
   const { ref, inView } = useInView({ threshold: 0.5, triggerOnce: true });
 
   useEffect(() => {
     if (inView) {
       analytics.track('Impression_Saved_Content', {
         bookmark_type: bookmarkType,
       });
     }
   }, [inView, bookmarkType]);
 
-  return <div ref={ref}>{children}</div>;
+  return <div ref={ref} className={className}>{children}</div>;
 };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@apps/client/src/shared/components/analyticsCardWrapper/AnalyticsCardWrapper.tsx`
at line 27, The wrapper div in AnalyticsCardWrapper may disrupt flex/grid
layouts; update the AnalyticsCardWrapper component to accept an optional
className prop (e.g., className?: string) and pass it through to the returned
<div> (alongside the existing ref and children) so consumers can control
layout/styling, ensuring the ref forwarding (ref) remains intact; alternatively
consider using a React.Fragment when no extra DOM node is needed, but if keeping
the div, add and forward className to it.
apps/client/public/firebase-messaging-sw.js (1)

6-21: device_id가 하드코딩되어 사용자 간 이벤트 구분이 불가능합니다.

현재 device_id: 'serviceworker'로 고정되어 있어 모든 사용자의 서비스 워커 이벤트가 동일한 디바이스로 집계됩니다. 이로 인해 개별 사용자 행동 분석이 어려워질 수 있습니다.

가능하다면 IndexedDB나 다른 저장소에서 사용자 ID 또는 디바이스 ID를 가져와 사용하는 것을 고려해 주세요.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/client/public/firebase-messaging-sw.js` around lines 6 - 21, The
trackAmplitudeEvent function currently hardcodes device_id as 'serviceworker' so
events can't be attributed to individual users; update trackAmplitudeEvent to
read a persisted identifier (user ID or device ID) from a storage accessible in
the service worker (e.g., IndexedDB key like 'deviceId' or 'userId') and use
that value for the events.device_id in the payload sent to AMPLITUDE_API_KEY; if
none exists, generate a UUID, persist it to the same storage for future calls,
and use it as the device_id; ensure the fetch body uses that retrieved/generated
identifier instead of the static 'serviceworker'.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/client/src/pages/jobPins/JobPins.tsx`:
- Around line 83-86: The analytics.track call can throw when article.category is
undefined; update the analytics.track('Clicked_Shared_Bookmark', ...) invocation
to defensively access category by using optional chaining or a fallback (e.g.,
String(article.category?.categoryId ?? '')) so category_id is always a string
and no runtime error occurs; locate the analytics.track call in JobPins.tsx and
replace the direct article.category.categoryId access with a safe expression.

In `@apps/extension/src/pages/MainPop.tsx`:
- Around line 217-222: The analytics.track call uses new URL(url).hostname which
can throw and abort the save flow; wrap the hostname extraction in a safe parse
(try/catch or a helper like getHostnameSafe) so that if parsing fails you fall
back to undefined (e.g., const page_domain = safeHostname(url) ?? undefined) and
then call analytics.track({ page_domain, category_id: selected ?? undefined, ...
}) without letting an exception prevent save(...) from being invoked; ensure the
change touches the same analytics.track invocation and that save(...) remains
called even when URL parsing fails.

---

Outside diff comments:
In `@apps/client/src/pages/myBookmark/hooks/useMyBookmarkContentData.ts`:
- Around line 8-14: The parameter type for scrollContainerRef in the
UseMyBookmarkContentDataParams interface is too broad; change it from
MutableRefObject<HTMLDivElement | null> to React.RefObject<HTMLDivElement |
null> so it matches the useInfiniteScroll signature (rootRef?:
React.RefObject<HTMLElement | null>) and usage where only rootRef?.current is
read; update the import to include React if necessary and adjust any callers to
pass a RefObject.

---

Nitpick comments:
In `@apps/client/public/firebase-messaging-sw.js`:
- Around line 6-21: The trackAmplitudeEvent function currently hardcodes
device_id as 'serviceworker' so events can't be attributed to individual users;
update trackAmplitudeEvent to read a persisted identifier (user ID or device ID)
from a storage accessible in the service worker (e.g., IndexedDB key like
'deviceId' or 'userId') and use that value for the events.device_id in the
payload sent to AMPLITUDE_API_KEY; if none exists, generate a UUID, persist it
to the same storage for future calls, and use it as the device_id; ensure the
fetch body uses that retrieved/generated identifier instead of the static
'serviceworker'.

In
`@apps/client/src/shared/components/analyticsCardWrapper/AnalyticsCardWrapper.tsx`:
- Line 27: The wrapper div in AnalyticsCardWrapper may disrupt flex/grid
layouts; update the AnalyticsCardWrapper component to accept an optional
className prop (e.g., className?: string) and pass it through to the returned
<div> (alongside the existing ref and children) so consumers can control
layout/styling, ensuring the ref forwarding (ref) remains intact; alternatively
consider using a React.Fragment when no extra DOM node is needed, but if keeping
the div, add and forward className to it.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 567e688a-ca32-4c18-8b47-da337e4f4791

📥 Commits

Reviewing files that changed from the base of the PR and between 5437213 and 1c42161.

📒 Files selected for processing (33)
  • .vscode/settings.json
  • apps/client/public/firebase-messaging-sw.js
  • apps/client/src/pages/jobPins/JobPins.tsx
  • apps/client/src/pages/jobPins/apis/axios.ts
  • apps/client/src/pages/jobPins/apis/queries.ts
  • apps/client/src/pages/level/Level.tsx
  • apps/client/src/pages/level/components/LevelInfoCard.tsx
  • apps/client/src/pages/level/components/LevelScene.tsx
  • apps/client/src/pages/myBookmark/MyBookmark.tsx
  • apps/client/src/pages/myBookmark/apis/axios.ts
  • apps/client/src/pages/myBookmark/apis/queries.ts
  • apps/client/src/pages/myBookmark/components/myBookmarkContent/MyBookmarkContent.tsx
  • apps/client/src/pages/myBookmark/hooks/useMyBookmarkContentData.ts
  • apps/client/src/pages/onBoarding/components/funnel/MainCard.tsx
  • apps/client/src/pages/onBoarding/components/funnel/step/job/JobStep.tsx
  • apps/client/src/pages/onBoarding/components/timePicker/TimePicker.tsx
  • apps/client/src/pages/onBoarding/hooks/useOnboardingFunnel.ts
  • apps/client/src/pages/remind/Remind.tsx
  • apps/client/src/shared/apis/axios.ts
  • apps/client/src/shared/apis/queries.ts
  • apps/client/src/shared/components/analyticsCardWrapper/AnalyticsCardWrapper.tsx
  • apps/client/src/shared/components/balloon/Balloon.tsx
  • apps/client/src/shared/components/cardEditModal/CardEditModal.tsx
  • apps/client/src/shared/components/jobSelectionFunnel/step/job/JobStep.tsx
  • apps/client/src/shared/components/sidebar/AccordionItem.tsx
  • apps/client/src/shared/components/sidebar/SideItem.tsx
  • apps/client/src/shared/components/sidebar/hooks/useCategoryActions.ts
  • apps/client/src/shared/utils/fetchOgData.ts
  • apps/client/src/shared/utils/treeLevel.ts
  • apps/extension/src/pages/MainPop.tsx
  • packages/analytics/index.ts
  • packages/analytics/src/ampli/index.ts
  • packages/eslint-config/react-internal.js
💤 Files with no reviewable changes (1)
  • apps/client/src/pages/myBookmark/MyBookmark.tsx

Comment on lines +83 to +86
analytics.track('Clicked_Shared_Bookmark', {
article_id: String(article.articleId),
category_id: String(article.category.categoryId),
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

카테고리 없는 카드 클릭 시 런타임 에러 가능성이 있습니다.

Line 85는 article.category가 없을 때 예외가 발생할 수 있습니다. 이미 다른 props에서 optional 접근을 쓰고 있어 여기서도 동일하게 방어가 필요합니다.

수정 제안
                     analytics.track('Clicked_Shared_Bookmark', {
                       article_id: String(article.articleId),
-                      category_id: String(article.category.categoryId),
+                      category_id: article.category
+                        ? String(article.category.categoryId)
+                        : undefined,
                     });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
analytics.track('Clicked_Shared_Bookmark', {
article_id: String(article.articleId),
category_id: String(article.category.categoryId),
});
analytics.track('Clicked_Shared_Bookmark', {
article_id: String(article.articleId),
category_id: article.category
? String(article.category.categoryId)
: undefined,
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/client/src/pages/jobPins/JobPins.tsx` around lines 83 - 86, The
analytics.track call can throw when article.category is undefined; update the
analytics.track('Clicked_Shared_Bookmark', ...) invocation to defensively access
category by using optional chaining or a fallback (e.g.,
String(article.category?.categoryId ?? '')) so category_id is always a string
and no runtime error occurs; locate the analytics.track call in JobPins.tsx and
replace the direct article.category.categoryId access with a safe expression.

@constantly-dev constantly-dev changed the title Feat/#327/connect amplitude event Feat(project): amplitude event 연결 Apr 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feat 기능 개발하라 개발 달려라 달려

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feat] amplitude event 연결

1 participant