Add platform audience targeting filters to notification send flow.
Admins can segment recipients by profile, subscription, engagement, and device fields, load the full matching user list without pagination, and treat Unsubscribed as all non-active subscription states. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
9caf9dfc30
commit
941a453592
|
|
@ -396,7 +396,7 @@ export function normalizeUserSubscriptions(raw: unknown): UserSubscriptionsData
|
|||
};
|
||||
}
|
||||
|
||||
/** Query params for GET /users (RFC3339 for created_*; subscription_status: ACTIVE | PENDING | Unsubscribed).
|
||||
/** Query params for GET /users (RFC3339 for created_* / last_login_*; subscription_status: ACTIVE | PENDING | Unsubscribed | EXPIRED).
|
||||
* status: ACTIVE | PENDING | SUSPENDED | DEACTIVATED | INACTIVE (all statuses except ACTIVE).
|
||||
*/
|
||||
export interface GetUsersParams {
|
||||
|
|
@ -410,25 +410,94 @@ export interface GetUsersParams {
|
|||
country?: string
|
||||
region?: string
|
||||
subscription_status?: string
|
||||
education_level?: string
|
||||
occupation?: string
|
||||
age_group?: string
|
||||
favourite_topic?: string
|
||||
language_goal?: string
|
||||
learning_goal?: string
|
||||
knowledge_level?: string
|
||||
plan_id?: number
|
||||
plan_category?: string
|
||||
auto_renew?: boolean
|
||||
has_ever_paid?: boolean
|
||||
expires_within_days?: number
|
||||
last_login_before?: string
|
||||
last_login_after?: string
|
||||
days_since_last_login_min?: number
|
||||
days_since_last_login_max?: number
|
||||
profile_completed?: boolean
|
||||
initial_assessment_completed?: boolean
|
||||
min_lessons_completed?: number
|
||||
min_modules_completed?: number
|
||||
min_profile_completion_pct?: number
|
||||
device_platform?: string
|
||||
has_active_device?: boolean
|
||||
}
|
||||
|
||||
export function buildUsersListQuery(params: GetUsersParams): Record<string, string | number> {
|
||||
const q: Record<string, string | number> = {}
|
||||
const addString = (key: string, value: string | undefined) => {
|
||||
const v = value?.trim()
|
||||
if (!v) return
|
||||
q[key] = v
|
||||
}
|
||||
function addOptionalString(
|
||||
q: Record<string, string | number | boolean>,
|
||||
key: string,
|
||||
value: string | undefined,
|
||||
) {
|
||||
const v = value?.trim()
|
||||
if (!v) return
|
||||
q[key] = v
|
||||
}
|
||||
|
||||
function addOptionalNumber(
|
||||
q: Record<string, string | number | boolean>,
|
||||
key: string,
|
||||
value: number | undefined,
|
||||
) {
|
||||
if (value === undefined || !Number.isFinite(value)) return
|
||||
q[key] = value
|
||||
}
|
||||
|
||||
function addOptionalBoolean(
|
||||
q: Record<string, string | number | boolean>,
|
||||
key: string,
|
||||
value: boolean | undefined,
|
||||
) {
|
||||
if (value === undefined) return
|
||||
q[key] = value
|
||||
}
|
||||
|
||||
export function buildUsersListQuery(params: GetUsersParams): Record<string, string | number | boolean> {
|
||||
const q: Record<string, string | number | boolean> = {}
|
||||
if (params.page !== undefined) q.page = params.page
|
||||
if (params.page_size !== undefined) q.page_size = params.page_size
|
||||
addString("role", params.role)
|
||||
addString("status", params.status)
|
||||
addString("query", params.query)
|
||||
addString("created_before", params.created_before)
|
||||
addString("created_after", params.created_after)
|
||||
addString("country", params.country)
|
||||
addString("region", params.region)
|
||||
addString("subscription_status", params.subscription_status)
|
||||
addOptionalString(q, "role", params.role)
|
||||
addOptionalString(q, "status", params.status)
|
||||
addOptionalString(q, "query", params.query)
|
||||
addOptionalString(q, "created_before", params.created_before)
|
||||
addOptionalString(q, "created_after", params.created_after)
|
||||
addOptionalString(q, "country", params.country)
|
||||
addOptionalString(q, "region", params.region)
|
||||
addOptionalString(q, "subscription_status", params.subscription_status)
|
||||
addOptionalString(q, "education_level", params.education_level)
|
||||
addOptionalString(q, "occupation", params.occupation)
|
||||
addOptionalString(q, "age_group", params.age_group)
|
||||
addOptionalString(q, "favourite_topic", params.favourite_topic)
|
||||
addOptionalString(q, "language_goal", params.language_goal)
|
||||
addOptionalString(q, "learning_goal", params.learning_goal)
|
||||
addOptionalString(q, "knowledge_level", params.knowledge_level)
|
||||
addOptionalString(q, "plan_category", params.plan_category)
|
||||
addOptionalString(q, "device_platform", params.device_platform)
|
||||
addOptionalString(q, "last_login_before", params.last_login_before)
|
||||
addOptionalString(q, "last_login_after", params.last_login_after)
|
||||
addOptionalNumber(q, "plan_id", params.plan_id)
|
||||
addOptionalNumber(q, "expires_within_days", params.expires_within_days)
|
||||
addOptionalNumber(q, "days_since_last_login_min", params.days_since_last_login_min)
|
||||
addOptionalNumber(q, "days_since_last_login_max", params.days_since_last_login_max)
|
||||
addOptionalNumber(q, "min_lessons_completed", params.min_lessons_completed)
|
||||
addOptionalNumber(q, "min_modules_completed", params.min_modules_completed)
|
||||
addOptionalNumber(q, "min_profile_completion_pct", params.min_profile_completion_pct)
|
||||
addOptionalBoolean(q, "auto_renew", params.auto_renew)
|
||||
addOptionalBoolean(q, "has_ever_paid", params.has_ever_paid)
|
||||
addOptionalBoolean(q, "profile_completed", params.profile_completed)
|
||||
addOptionalBoolean(q, "initial_assessment_completed", params.initial_assessment_completed)
|
||||
addOptionalBoolean(q, "has_active_device", params.has_active_device)
|
||||
return q
|
||||
}
|
||||
|
||||
|
|
|
|||
517
src/components/notifications/PlatformAudienceFilterPanel.tsx
Normal file
517
src/components/notifications/PlatformAudienceFilterPanel.tsx
Normal file
|
|
@ -0,0 +1,517 @@
|
|||
import { useEffect, useMemo, useState, type ReactNode } from "react"
|
||||
import * as DropdownMenu from "@radix-ui/react-dropdown-menu"
|
||||
import { ChevronDown } from "lucide-react"
|
||||
import { AdminFiltersPanel } from "../filters/AdminFiltersPanel"
|
||||
import { Input } from "../ui/input"
|
||||
import { cn } from "../../lib/utils"
|
||||
import { APP_TIMEZONE_LABEL } from "../../lib/datetime"
|
||||
import {
|
||||
EMPTY_PLATFORM_AUDIENCE_FILTERS,
|
||||
countPlatformAudienceActiveFilters,
|
||||
type PlatformAudienceFilters,
|
||||
} from "../../lib/platformAudienceFilters"
|
||||
import { USER_FILTER_COUNTRIES, USER_FILTER_ETHIOPIA_REGIONS } from "../../data/userFilterLocations"
|
||||
import {
|
||||
PROFILE_FILTER_AGE_GROUPS,
|
||||
PROFILE_FILTER_EDUCATION_LEVELS,
|
||||
PROFILE_FILTER_FAVOURITE_TOPICS,
|
||||
PROFILE_FILTER_KNOWLEDGE_LEVELS,
|
||||
PROFILE_FILTER_LANGUAGE_GOALS,
|
||||
PROFILE_FILTER_LEARNING_GOALS,
|
||||
PROFILE_FILTER_OCCUPATIONS,
|
||||
} from "../../lib/userProfileFieldDisplay"
|
||||
import { getSubscriptionPlans } from "../../api/subscription-plans.api"
|
||||
import type { SubscriptionPlan } from "../../types/subscription.types"
|
||||
|
||||
type CodeLabelOption = { code: string; label: string }
|
||||
|
||||
function FilterDropdown({
|
||||
id,
|
||||
label,
|
||||
value,
|
||||
allLabel,
|
||||
options,
|
||||
onSelect,
|
||||
disabled = false,
|
||||
}: {
|
||||
id: string
|
||||
label: string
|
||||
value: string
|
||||
allLabel: string
|
||||
options: readonly (string | CodeLabelOption)[]
|
||||
onSelect: (next: string) => void
|
||||
disabled?: boolean
|
||||
}) {
|
||||
const displayValue = useMemo(() => {
|
||||
if (!value) return allLabel
|
||||
const match = options.find((opt) =>
|
||||
typeof opt === "string" ? opt === value : opt.code === value,
|
||||
)
|
||||
if (typeof match === "string") return match
|
||||
if (match) return match.label
|
||||
return value
|
||||
}, [allLabel, options, value])
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col gap-1", disabled && "opacity-60")}>
|
||||
<label htmlFor={id} className="text-xs font-medium text-grayScale-500">
|
||||
{label}
|
||||
</label>
|
||||
<DropdownMenu.Root modal={false}>
|
||||
<DropdownMenu.Trigger asChild disabled={disabled}>
|
||||
<button
|
||||
type="button"
|
||||
id={id}
|
||||
disabled={disabled}
|
||||
className={cn(
|
||||
"flex h-9 w-full items-center justify-between gap-2 rounded-[6px] border border-grayScale-200 bg-white px-3 text-left text-sm text-grayScale-600",
|
||||
"outline-none focus-visible:ring-1 focus-visible:ring-brand-500",
|
||||
disabled && "cursor-not-allowed bg-grayScale-50 text-grayScale-400",
|
||||
)}
|
||||
>
|
||||
<span className="min-w-0 truncate">{displayValue}</span>
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-grayScale-400" />
|
||||
</button>
|
||||
</DropdownMenu.Trigger>
|
||||
{!disabled ? (
|
||||
<DropdownMenu.Portal>
|
||||
<DropdownMenu.Content
|
||||
side="bottom"
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
collisionPadding={12}
|
||||
className="z-[200] max-h-60 min-w-[var(--radix-dropdown-menu-trigger-width)] overflow-y-auto rounded-md border border-grayScale-200 bg-white p-1 shadow-lg"
|
||||
onCloseAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<DropdownMenu.Item
|
||||
className={cn(
|
||||
"cursor-pointer rounded px-2 py-2 text-sm text-grayScale-700 outline-none data-[highlighted]:bg-grayScale-100",
|
||||
!value && "bg-grayScale-50 font-medium",
|
||||
)}
|
||||
onSelect={() => onSelect("")}
|
||||
>
|
||||
{allLabel}
|
||||
</DropdownMenu.Item>
|
||||
{options.map((opt) => {
|
||||
const code = typeof opt === "string" ? opt : opt.code
|
||||
const text = typeof opt === "string" ? opt : opt.label
|
||||
return (
|
||||
<DropdownMenu.Item
|
||||
key={code}
|
||||
className={cn(
|
||||
"cursor-pointer rounded px-2 py-2 text-sm text-grayScale-700 outline-none data-[highlighted]:bg-grayScale-100",
|
||||
value === code && "bg-brand-50 font-medium text-brand-700",
|
||||
)}
|
||||
onSelect={() => onSelect(code)}
|
||||
>
|
||||
{text}
|
||||
</DropdownMenu.Item>
|
||||
)
|
||||
})}
|
||||
</DropdownMenu.Content>
|
||||
</DropdownMenu.Portal>
|
||||
) : null}
|
||||
</DropdownMenu.Root>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FilterSection({
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
title: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="space-y-3 rounded-lg border border-grayScale-100 bg-grayScale-50/40 p-3">
|
||||
<p className="text-xs font-semibold uppercase tracking-wide text-grayScale-500">{title}</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DisabledFilterHint({ label, reason }: { label: string; reason: string }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1 opacity-60">
|
||||
<span className="text-xs font-medium text-grayScale-500">{label}</span>
|
||||
<div
|
||||
className="flex h-9 items-center rounded-[6px] border border-dashed border-grayScale-200 bg-grayScale-50 px-3 text-xs text-grayScale-400"
|
||||
title={reason}
|
||||
>
|
||||
Coming soon
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SUBSCRIPTION_STATUS_OPTIONS = [
|
||||
{ code: "ACTIVE", label: "Active" },
|
||||
{
|
||||
code: "Unsubscribed",
|
||||
label: "Unsubscribed (pending, expired, or never subscribed)",
|
||||
},
|
||||
]
|
||||
|
||||
const PLAN_CATEGORY_OPTIONS = [
|
||||
{ code: "LEARN_ENGLISH", label: "Learn English" },
|
||||
{ code: "IELTS", label: "IELTS" },
|
||||
{ code: "DUOLINGO", label: "Duolingo" },
|
||||
]
|
||||
|
||||
const BOOL_OPTIONS = [
|
||||
{ code: "true", label: "Yes" },
|
||||
{ code: "false", label: "No" },
|
||||
]
|
||||
|
||||
const DEVICE_PLATFORM_OPTIONS = [
|
||||
{ code: "ios", label: "iOS" },
|
||||
{ code: "android", label: "Android" },
|
||||
{ code: "web", label: "Web" },
|
||||
]
|
||||
|
||||
export type PlatformAudienceFilterPanelProps = {
|
||||
filters: PlatformAudienceFilters
|
||||
onChange: (next: PlatformAudienceFilters) => void
|
||||
}
|
||||
|
||||
export function PlatformAudienceFilterPanel({
|
||||
filters,
|
||||
onChange,
|
||||
}: PlatformAudienceFilterPanelProps) {
|
||||
const [plans, setPlans] = useState<SubscriptionPlan[]>([])
|
||||
const activeCount = countPlatformAudienceActiveFilters(filters)
|
||||
const ethiopiaSelected =
|
||||
!filters.country.trim() || filters.country.trim().toLowerCase() === "ethiopia"
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
getSubscriptionPlans()
|
||||
.then((res) => {
|
||||
if (!cancelled) {
|
||||
setPlans(res.data ?? [])
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setPlans([])
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const planOptions = useMemo(
|
||||
() => plans.map((plan) => ({ code: String(plan.id), label: plan.name })),
|
||||
[plans],
|
||||
)
|
||||
|
||||
const patch = (partial: Partial<PlatformAudienceFilters>) => {
|
||||
onChange({ ...filters, ...partial })
|
||||
}
|
||||
|
||||
return (
|
||||
<AdminFiltersPanel
|
||||
defaultOpen={activeCount > 0}
|
||||
activeFilterCount={activeCount}
|
||||
onClearFilters={() => onChange({ ...EMPTY_PLATFORM_AUDIENCE_FILTERS })}
|
||||
clearLabel="Clear targeting"
|
||||
summary={
|
||||
activeCount > 0 ? (
|
||||
<p className="text-[11px] text-grayScale-500">
|
||||
{activeCount} targeting filter{activeCount === 1 ? "" : "s"} applied — list shows matching users only.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-[11px] text-grayScale-400">
|
||||
Narrow the audience before selecting recipients. Leave filters empty to browse all platform users.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<FilterSection title="User">
|
||||
<FilterDropdown
|
||||
id="audience-country"
|
||||
label="Country"
|
||||
value={filters.country}
|
||||
allLabel="Any country"
|
||||
options={USER_FILTER_COUNTRIES}
|
||||
onSelect={(country) => patch({ country, region: "" })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-region"
|
||||
label="Region"
|
||||
value={filters.region}
|
||||
allLabel="Any region"
|
||||
options={USER_FILTER_ETHIOPIA_REGIONS}
|
||||
onSelect={(region) => patch({ region })}
|
||||
disabled={!ethiopiaSelected}
|
||||
/>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="audience-created-after" className="text-xs font-medium text-grayScale-500">
|
||||
Joined after ({APP_TIMEZONE_LABEL})
|
||||
</label>
|
||||
<Input
|
||||
id="audience-created-after"
|
||||
type="datetime-local"
|
||||
value={filters.createdAfterLocal}
|
||||
onChange={(e) => patch({ createdAfterLocal: e.target.value })}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="audience-created-before" className="text-xs font-medium text-grayScale-500">
|
||||
Joined before ({APP_TIMEZONE_LABEL})
|
||||
</label>
|
||||
<Input
|
||||
id="audience-created-before"
|
||||
type="datetime-local"
|
||||
value={filters.createdBeforeLocal}
|
||||
onChange={(e) => patch({ createdBeforeLocal: e.target.value })}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
</FilterSection>
|
||||
|
||||
<FilterSection title="Profile">
|
||||
<FilterDropdown
|
||||
id="audience-education"
|
||||
label="Education level"
|
||||
value={filters.educationLevel}
|
||||
allLabel="Any level"
|
||||
options={PROFILE_FILTER_EDUCATION_LEVELS}
|
||||
onSelect={(educationLevel) => patch({ educationLevel })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-occupation"
|
||||
label="Occupation"
|
||||
value={filters.occupation}
|
||||
allLabel="Any occupation"
|
||||
options={PROFILE_FILTER_OCCUPATIONS}
|
||||
onSelect={(occupation) => patch({ occupation })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-age-group"
|
||||
label="Age group"
|
||||
value={filters.ageGroup}
|
||||
allLabel="Any age group"
|
||||
options={PROFILE_FILTER_AGE_GROUPS}
|
||||
onSelect={(ageGroup) => patch({ ageGroup })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-topic"
|
||||
label="Favorite topic"
|
||||
value={filters.favouriteTopic}
|
||||
allLabel="Any topic"
|
||||
options={PROFILE_FILTER_FAVOURITE_TOPICS}
|
||||
onSelect={(favouriteTopic) => patch({ favouriteTopic })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-language-goal"
|
||||
label="Language goal"
|
||||
value={filters.languageGoal}
|
||||
allLabel="Any language goal"
|
||||
options={PROFILE_FILTER_LANGUAGE_GOALS}
|
||||
onSelect={(languageGoal) => patch({ languageGoal })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-learning-goal"
|
||||
label="Learning goal"
|
||||
value={filters.learningGoal}
|
||||
allLabel="Any learning goal"
|
||||
options={PROFILE_FILTER_LEARNING_GOALS}
|
||||
onSelect={(learningGoal) => patch({ learningGoal })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-knowledge-level"
|
||||
label="Proficiency level"
|
||||
value={filters.knowledgeLevel}
|
||||
allLabel="Any proficiency"
|
||||
options={PROFILE_FILTER_KNOWLEDGE_LEVELS}
|
||||
onSelect={(knowledgeLevel) => patch({ knowledgeLevel })}
|
||||
/>
|
||||
</FilterSection>
|
||||
|
||||
<FilterSection title="Subscription">
|
||||
<FilterDropdown
|
||||
id="audience-subscription-status"
|
||||
label="Subscription status"
|
||||
value={filters.subscriptionStatus}
|
||||
allLabel="Any status"
|
||||
options={SUBSCRIPTION_STATUS_OPTIONS}
|
||||
onSelect={(subscriptionStatus) => patch({ subscriptionStatus })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-plan"
|
||||
label="Plan tier"
|
||||
value={filters.planId}
|
||||
allLabel="Any plan"
|
||||
options={planOptions}
|
||||
onSelect={(planId) => patch({ planId })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-plan-category"
|
||||
label="Plan category"
|
||||
value={filters.planCategory}
|
||||
allLabel="Any category"
|
||||
options={PLAN_CATEGORY_OPTIONS}
|
||||
onSelect={(planCategory) => patch({ planCategory })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-auto-renew"
|
||||
label="Auto-renew"
|
||||
value={filters.autoRenew}
|
||||
allLabel="Any"
|
||||
options={BOOL_OPTIONS}
|
||||
onSelect={(autoRenew) => patch({ autoRenew })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-has-ever-paid"
|
||||
label="Past payer vs never paid"
|
||||
value={filters.hasEverPaid}
|
||||
allLabel="Any"
|
||||
options={[
|
||||
{ code: "true", label: "Past payer" },
|
||||
{ code: "false", label: "Never paid" },
|
||||
]}
|
||||
onSelect={(hasEverPaid) => patch({ hasEverPaid })}
|
||||
/>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="audience-expires-within" className="text-xs font-medium text-grayScale-500">
|
||||
Expires within (days)
|
||||
</label>
|
||||
<Input
|
||||
id="audience-expires-within"
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder="e.g. 7"
|
||||
value={filters.expiresWithinDays}
|
||||
onChange={(e) => patch({ expiresWithinDays: e.target.value })}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<DisabledFilterHint label="In trial / trial ending soon" reason="Trial state is not tracked per user yet." />
|
||||
</FilterSection>
|
||||
|
||||
<FilterSection title="Engagement / activity">
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="audience-inactive-min" className="text-xs font-medium text-grayScale-500">
|
||||
Inactive at least (days since login)
|
||||
</label>
|
||||
<Input
|
||||
id="audience-inactive-min"
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder="e.g. 30"
|
||||
value={filters.daysSinceLastLoginMin}
|
||||
onChange={(e) => patch({ daysSinceLastLoginMin: e.target.value })}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="audience-active-within" className="text-xs font-medium text-grayScale-500">
|
||||
Active within (days since login)
|
||||
</label>
|
||||
<Input
|
||||
id="audience-active-within"
|
||||
type="number"
|
||||
min={0}
|
||||
placeholder="e.g. 7"
|
||||
value={filters.daysSinceLastLoginMax}
|
||||
onChange={(e) => patch({ daysSinceLastLoginMax: e.target.value })}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<FilterDropdown
|
||||
id="audience-profile-completed"
|
||||
label="Onboarding / profile"
|
||||
value={filters.profileCompleted}
|
||||
allLabel="Any"
|
||||
options={[
|
||||
{ code: "true", label: "Profile completed" },
|
||||
{ code: "false", label: "Profile incomplete" },
|
||||
]}
|
||||
onSelect={(profileCompleted) => patch({ profileCompleted })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-assessment"
|
||||
label="Initial assessment"
|
||||
value={filters.initialAssessmentCompleted}
|
||||
allLabel="Any"
|
||||
options={[
|
||||
{ code: "true", label: "Completed" },
|
||||
{ code: "false", label: "Not completed" },
|
||||
]}
|
||||
onSelect={(initialAssessmentCompleted) => patch({ initialAssessmentCompleted })}
|
||||
/>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="audience-min-lessons" className="text-xs font-medium text-grayScale-500">
|
||||
Min lessons completed
|
||||
</label>
|
||||
<Input
|
||||
id="audience-min-lessons"
|
||||
type="number"
|
||||
min={0}
|
||||
value={filters.minLessonsCompleted}
|
||||
onChange={(e) => patch({ minLessonsCompleted: e.target.value })}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="audience-min-modules" className="text-xs font-medium text-grayScale-500">
|
||||
Min modules completed
|
||||
</label>
|
||||
<Input
|
||||
id="audience-min-modules"
|
||||
type="number"
|
||||
min={0}
|
||||
value={filters.minModulesCompleted}
|
||||
onChange={(e) => patch({ minModulesCompleted: e.target.value })}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<label htmlFor="audience-min-profile-pct" className="text-xs font-medium text-grayScale-500">
|
||||
Min profile completion %
|
||||
</label>
|
||||
<Input
|
||||
id="audience-min-profile-pct"
|
||||
type="number"
|
||||
min={0}
|
||||
max={100}
|
||||
value={filters.minProfileCompletionPct}
|
||||
onChange={(e) => patch({ minProfileCompletionPct: e.target.value })}
|
||||
className="h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<DisabledFilterHint label="Streak status" reason="Daily streak data is not stored yet." />
|
||||
<DisabledFilterHint label="Overall LMS progress %" reason="Use min lessons/modules for now; LMS rollup filter is planned." />
|
||||
</FilterSection>
|
||||
|
||||
<FilterSection title="Technical / deliverability">
|
||||
<FilterDropdown
|
||||
id="audience-device-platform"
|
||||
label="Platform"
|
||||
value={filters.devicePlatform}
|
||||
allLabel="Any platform"
|
||||
options={DEVICE_PLATFORM_OPTIONS}
|
||||
onSelect={(devicePlatform) => patch({ devicePlatform })}
|
||||
/>
|
||||
<FilterDropdown
|
||||
id="audience-has-device"
|
||||
label="Registered push device"
|
||||
value={filters.hasActiveDevice}
|
||||
allLabel="Any"
|
||||
options={[
|
||||
{ code: "true", label: "Has active device token" },
|
||||
{ code: "false", label: "No active device token" },
|
||||
]}
|
||||
onSelect={(hasActiveDevice) => patch({ hasActiveDevice })}
|
||||
/>
|
||||
<DisabledFilterHint label="Push permission" reason="OS push permission state is not stored yet." />
|
||||
<DisabledFilterHint label="Time zone" reason="User time zone is not stored yet." />
|
||||
<DisabledFilterHint label="App version" reason="App version is not stored on user records yet." />
|
||||
</FilterSection>
|
||||
</div>
|
||||
</AdminFiltersPanel>
|
||||
)
|
||||
}
|
||||
|
|
@ -10,6 +10,11 @@ import { getUsers } from "../api/users.api"
|
|||
import { getTeamMembers } from "../api/team.api"
|
||||
import { formatAppDateTime, toRfc3339FromAppLocal } from "./datetime"
|
||||
import { TEAM_ROLE_OPTIONS } from "./teamRoles"
|
||||
import {
|
||||
platformAudienceFiltersToGetUsersParams,
|
||||
EMPTY_PLATFORM_AUDIENCE_FILTERS,
|
||||
type PlatformAudienceFilters,
|
||||
} from "./platformAudienceFilters"
|
||||
|
||||
export const PLATFORM_ROLES: { value: PlatformRole; label: string }[] = [
|
||||
{ value: "STUDENT", label: "Students" },
|
||||
|
|
@ -130,22 +135,44 @@ export function channelLabel(channel: string): string {
|
|||
}
|
||||
}
|
||||
|
||||
export async function fetchAllPlatformUsers(): Promise<UserApiDTO[]> {
|
||||
const pageSize = 50
|
||||
const firstRes = await getUsers({ page: 1, page_size: pageSize })
|
||||
const firstBatch = firstRes.data?.data?.users ?? []
|
||||
const total = firstRes.data?.data?.total ?? firstBatch.length
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize))
|
||||
export async function fetchPlatformUsersPage(
|
||||
filters: PlatformAudienceFilters,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
query?: string,
|
||||
): Promise<{ users: UserApiDTO[]; total: number }> {
|
||||
const params = platformAudienceFiltersToGetUsersParams(filters, {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
query: query?.trim() || undefined,
|
||||
})
|
||||
const res = await getUsers(params)
|
||||
return {
|
||||
users: res.data?.data?.users ?? [],
|
||||
total: res.data?.data?.total ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
if (totalPages <= 1) return firstBatch
|
||||
export async function fetchAllPlatformUsersMatching(
|
||||
filters: PlatformAudienceFilters,
|
||||
query?: string,
|
||||
): Promise<UserApiDTO[]> {
|
||||
const pageSize = 50
|
||||
const first = await fetchPlatformUsersPage(filters, 1, pageSize, query)
|
||||
const totalPages = Math.max(1, Math.ceil(first.total / pageSize))
|
||||
if (totalPages <= 1) return first.users
|
||||
|
||||
const remaining = await Promise.all(
|
||||
Array.from({ length: totalPages - 1 }, (_, i) =>
|
||||
getUsers({ page: i + 2, page_size: pageSize }),
|
||||
fetchPlatformUsersPage(filters, i + 2, pageSize, query),
|
||||
),
|
||||
)
|
||||
const rest = remaining.flatMap((r) => r.data?.data?.users ?? [])
|
||||
return [...firstBatch, ...rest]
|
||||
return [...first.users, ...remaining.flatMap((page) => page.users)]
|
||||
}
|
||||
|
||||
/** @deprecated Prefer fetchPlatformUsersPage with audience filters */
|
||||
export async function fetchAllPlatformUsers(): Promise<UserApiDTO[]> {
|
||||
return fetchAllPlatformUsersMatching(EMPTY_PLATFORM_AUDIENCE_FILTERS)
|
||||
}
|
||||
|
||||
export async function fetchAllTeamMembers(): Promise<TeamMember[]> {
|
||||
|
|
|
|||
125
src/lib/platformAudienceFilters.ts
Normal file
125
src/lib/platformAudienceFilters.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import type { GetUsersParams } from "../api/users.api"
|
||||
import { countActiveFilters } from "./adminFilterUtils"
|
||||
import { fromDatetimeLocalAppValue } from "./datetime"
|
||||
|
||||
export interface PlatformAudienceFilters {
|
||||
country: string
|
||||
region: string
|
||||
createdAfterLocal: string
|
||||
createdBeforeLocal: string
|
||||
educationLevel: string
|
||||
occupation: string
|
||||
ageGroup: string
|
||||
favouriteTopic: string
|
||||
languageGoal: string
|
||||
learningGoal: string
|
||||
knowledgeLevel: string
|
||||
subscriptionStatus: string
|
||||
planId: string
|
||||
planCategory: string
|
||||
autoRenew: string
|
||||
hasEverPaid: string
|
||||
expiresWithinDays: string
|
||||
daysSinceLastLoginMin: string
|
||||
daysSinceLastLoginMax: string
|
||||
profileCompleted: string
|
||||
initialAssessmentCompleted: string
|
||||
minLessonsCompleted: string
|
||||
minModulesCompleted: string
|
||||
minProfileCompletionPct: string
|
||||
devicePlatform: string
|
||||
hasActiveDevice: string
|
||||
}
|
||||
|
||||
export const EMPTY_PLATFORM_AUDIENCE_FILTERS: PlatformAudienceFilters = {
|
||||
country: "",
|
||||
region: "",
|
||||
createdAfterLocal: "",
|
||||
createdBeforeLocal: "",
|
||||
educationLevel: "",
|
||||
occupation: "",
|
||||
ageGroup: "",
|
||||
favouriteTopic: "",
|
||||
languageGoal: "",
|
||||
learningGoal: "",
|
||||
knowledgeLevel: "",
|
||||
subscriptionStatus: "",
|
||||
planId: "",
|
||||
planCategory: "",
|
||||
autoRenew: "",
|
||||
hasEverPaid: "",
|
||||
expiresWithinDays: "",
|
||||
daysSinceLastLoginMin: "",
|
||||
daysSinceLastLoginMax: "",
|
||||
profileCompleted: "",
|
||||
initialAssessmentCompleted: "",
|
||||
minLessonsCompleted: "",
|
||||
minModulesCompleted: "",
|
||||
minProfileCompletionPct: "",
|
||||
devicePlatform: "",
|
||||
hasActiveDevice: "",
|
||||
}
|
||||
|
||||
function optionalString(value: string): string | undefined {
|
||||
const trimmed = value.trim()
|
||||
return trimmed ? trimmed : undefined
|
||||
}
|
||||
|
||||
function optionalBool(value: string): boolean | undefined {
|
||||
if (value === "true") return true
|
||||
if (value === "false") return false
|
||||
return undefined
|
||||
}
|
||||
|
||||
function optionalInt(value: string): number | undefined {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return undefined
|
||||
const parsed = Number(trimmed)
|
||||
if (!Number.isFinite(parsed) || parsed < 0) return undefined
|
||||
return Math.trunc(parsed)
|
||||
}
|
||||
|
||||
export function countPlatformAudienceActiveFilters(filters: PlatformAudienceFilters): number {
|
||||
return countActiveFilters(Object.values(filters).map((value) => ({ value, defaultValue: "" })))
|
||||
}
|
||||
|
||||
export function platformAudienceFiltersToGetUsersParams(
|
||||
filters: PlatformAudienceFilters,
|
||||
extras: Pick<GetUsersParams, "page" | "page_size" | "query"> = { page: 1, page_size: 50 },
|
||||
): GetUsersParams {
|
||||
const country = optionalString(filters.country)
|
||||
const region =
|
||||
country && country.toLowerCase() !== "ethiopia"
|
||||
? undefined
|
||||
: optionalString(filters.region)
|
||||
|
||||
return {
|
||||
...extras,
|
||||
country,
|
||||
region,
|
||||
created_after: fromDatetimeLocalAppValue(filters.createdAfterLocal),
|
||||
created_before: fromDatetimeLocalAppValue(filters.createdBeforeLocal),
|
||||
education_level: optionalString(filters.educationLevel),
|
||||
occupation: optionalString(filters.occupation),
|
||||
age_group: optionalString(filters.ageGroup),
|
||||
favourite_topic: optionalString(filters.favouriteTopic),
|
||||
language_goal: optionalString(filters.languageGoal),
|
||||
learning_goal: optionalString(filters.learningGoal),
|
||||
knowledge_level: optionalString(filters.knowledgeLevel),
|
||||
subscription_status: optionalString(filters.subscriptionStatus),
|
||||
plan_id: optionalInt(filters.planId),
|
||||
plan_category: optionalString(filters.planCategory),
|
||||
auto_renew: optionalBool(filters.autoRenew),
|
||||
has_ever_paid: optionalBool(filters.hasEverPaid),
|
||||
expires_within_days: optionalInt(filters.expiresWithinDays),
|
||||
days_since_last_login_min: optionalInt(filters.daysSinceLastLoginMin),
|
||||
days_since_last_login_max: optionalInt(filters.daysSinceLastLoginMax),
|
||||
profile_completed: optionalBool(filters.profileCompleted),
|
||||
initial_assessment_completed: optionalBool(filters.initialAssessmentCompleted),
|
||||
min_lessons_completed: optionalInt(filters.minLessonsCompleted),
|
||||
min_modules_completed: optionalInt(filters.minModulesCompleted),
|
||||
min_profile_completion_pct: optionalInt(filters.minProfileCompletionPct),
|
||||
device_platform: optionalString(filters.devicePlatform),
|
||||
has_active_device: optionalBool(filters.hasActiveDevice),
|
||||
}
|
||||
}
|
||||
|
|
@ -99,6 +99,15 @@ const KNOWLEDGE_LEVEL_OPTIONS: ProfileFieldOption[] = [
|
|||
{ code: "ADVANCED", label: "Advanced" },
|
||||
]
|
||||
|
||||
export const PROFILE_FILTER_AGE_GROUPS = AGE_GROUP_OPTIONS
|
||||
export const PROFILE_FILTER_OCCUPATIONS = OCCUPATION_OPTIONS
|
||||
export const PROFILE_FILTER_EDUCATION_LEVELS = EDUCATION_LEVEL_OPTIONS
|
||||
export const PROFILE_FILTER_LEARNING_GOALS = LEARNING_GOAL_OPTIONS
|
||||
export const PROFILE_FILTER_LANGUAGE_GOALS = LANGUAGE_GOAL_OPTIONS
|
||||
export const PROFILE_FILTER_FAVOURITE_TOPICS = FAVOURITE_TOPIC_OPTIONS
|
||||
export const PROFILE_FILTER_KNOWLEDGE_LEVELS = KNOWLEDGE_LEVEL_OPTIONS
|
||||
export const PROFILE_FILTER_ETHIOPIA_REGIONS = ETHIOPIA_REGION_OPTIONS
|
||||
|
||||
/** ISO-style country codes from field_options seed (subset used for label lookup). */
|
||||
const COUNTRY_OPTIONS: ProfileFieldOption[] = [
|
||||
{ code: "AF", label: "Afghanistan" },
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ import {
|
|||
validateEmailComposeInput,
|
||||
} from "../../lib/notificationEmailCompose"
|
||||
import {
|
||||
fetchAllPlatformUsers,
|
||||
fetchAllPlatformUsersMatching,
|
||||
fetchAllTeamMembers,
|
||||
formatScheduledAtLabel,
|
||||
IN_APP_LEVELS,
|
||||
|
|
@ -36,6 +36,11 @@ import {
|
|||
parseDirectRecipients,
|
||||
type NotificationAudienceMode,
|
||||
} from "../../lib/notificationBulk"
|
||||
import {
|
||||
EMPTY_PLATFORM_AUDIENCE_FILTERS,
|
||||
type PlatformAudienceFilters,
|
||||
} from "../../lib/platformAudienceFilters"
|
||||
import { PlatformAudienceFilterPanel } from "../../components/notifications/PlatformAudienceFilterPanel"
|
||||
import { formatAppDateTime } from "../../lib/datetime"
|
||||
import {
|
||||
BulkSendSummaryPanel,
|
||||
|
|
@ -125,6 +130,9 @@ export function CreateNotificationPage() {
|
|||
const [audienceMode, setAudienceMode] = useState<NotificationAudienceMode>("platform_selected")
|
||||
const [sendMode, setSendMode] = useState<SendMode>("now")
|
||||
const [users, setUsers] = useState<UserApiDTO[]>([])
|
||||
const [platformFilters, setPlatformFilters] = useState<PlatformAudienceFilters>(
|
||||
EMPTY_PLATFORM_AUDIENCE_FILTERS,
|
||||
)
|
||||
const [teamMembers, setTeamMembers] = useState<TeamMember[]>([])
|
||||
const [recipientsLoading, setRecipientsLoading] = useState(false)
|
||||
const [teamRecipientsLoading, setTeamRecipientsLoading] = useState(false)
|
||||
|
|
@ -149,12 +157,23 @@ export function CreateNotificationPage() {
|
|||
const [currentStep, setCurrentStep] = useState(1)
|
||||
|
||||
useEffect(() => {
|
||||
if (audienceMode !== "platform_selected") return
|
||||
let cancelled = false
|
||||
setRecipientsLoading(true)
|
||||
fetchAllPlatformUsers()
|
||||
.then(setUsers)
|
||||
.catch(() => setUsers([]))
|
||||
.finally(() => setRecipientsLoading(false))
|
||||
}, [])
|
||||
fetchAllPlatformUsersMatching(platformFilters)
|
||||
.then((nextUsers) => {
|
||||
if (!cancelled) setUsers(nextUsers)
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setUsers([])
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setRecipientsLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [audienceMode, platformFilters])
|
||||
|
||||
useEffect(() => {
|
||||
if (channel !== "email" && channel !== "in_app") {
|
||||
|
|
@ -217,11 +236,6 @@ export function CreateNotificationPage() {
|
|||
})
|
||||
}, [users, userSearchQuery])
|
||||
|
||||
const selectedUsers = useMemo(
|
||||
() => users.filter((u) => selectedUserIds.includes(u.id)),
|
||||
[users, selectedUserIds],
|
||||
)
|
||||
|
||||
const filteredSelectedCount = useMemo(
|
||||
() => filteredUsers.filter((u) => selectedUserIds.includes(u.id)).length,
|
||||
[filteredUsers, selectedUserIds],
|
||||
|
|
@ -265,6 +279,7 @@ export function CreateNotificationPage() {
|
|||
setSelectedUserIds([])
|
||||
setSelectedTeamMemberIds([])
|
||||
setUserSearchQuery("")
|
||||
setPlatformFilters(EMPTY_PLATFORM_AUDIENCE_FILTERS)
|
||||
setTeamSearchQuery("")
|
||||
setDirectRecipients("")
|
||||
setScheduledAt("")
|
||||
|
|
@ -881,11 +896,16 @@ export function CreateNotificationPage() {
|
|||
)}
|
||||
|
||||
{audienceMode === "platform_selected" && (
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-3">
|
||||
<PlatformAudienceFilterPanel
|
||||
filters={platformFilters}
|
||||
onChange={setPlatformFilters}
|
||||
/>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<p className="text-xs font-medium text-grayScale-500">Select users</p>
|
||||
<span className="text-[10px] text-grayScale-400">
|
||||
{selectedUsers.length} selected
|
||||
{selectedUserIds.length} selected
|
||||
{users.length > 0 ? ` · ${users.length} loaded` : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-lg border border-grayScale-100 bg-grayScale-50/60">
|
||||
|
|
@ -901,7 +921,7 @@ export function CreateNotificationPage() {
|
|||
disabled={recipientsLoading}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
disabled={recipientsLoading || filteredUsers.length === 0}
|
||||
|
|
@ -941,7 +961,7 @@ export function CreateNotificationPage() {
|
|||
)}
|
||||
{!recipientsLoading && users.length === 0 && (
|
||||
<div className="py-4 text-center text-xs text-grayScale-400">
|
||||
No users available to select.
|
||||
No users match the current filters.
|
||||
</div>
|
||||
)}
|
||||
{!recipientsLoading && users.length > 0 && filteredUsers.length === 0 && (
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user