diff --git a/src/api/users.api.ts b/src/api/users.api.ts index 9792119..fe954f9 100644 --- a/src/api/users.api.ts +++ b/src/api/users.api.ts @@ -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 { - const q: Record = {} - const addString = (key: string, value: string | undefined) => { - const v = value?.trim() - if (!v) return - q[key] = v - } +function addOptionalString( + q: Record, + key: string, + value: string | undefined, +) { + const v = value?.trim() + if (!v) return + q[key] = v +} + +function addOptionalNumber( + q: Record, + key: string, + value: number | undefined, +) { + if (value === undefined || !Number.isFinite(value)) return + q[key] = value +} + +function addOptionalBoolean( + q: Record, + key: string, + value: boolean | undefined, +) { + if (value === undefined) return + q[key] = value +} + +export function buildUsersListQuery(params: GetUsersParams): Record { + const q: Record = {} 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 } diff --git a/src/components/notifications/PlatformAudienceFilterPanel.tsx b/src/components/notifications/PlatformAudienceFilterPanel.tsx new file mode 100644 index 0000000..80f4a79 --- /dev/null +++ b/src/components/notifications/PlatformAudienceFilterPanel.tsx @@ -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 ( +
+ + + + + + {!disabled ? ( + + e.preventDefault()} + > + onSelect("")} + > + {allLabel} + + {options.map((opt) => { + const code = typeof opt === "string" ? opt : opt.code + const text = typeof opt === "string" ? opt : opt.label + return ( + onSelect(code)} + > + {text} + + ) + })} + + + ) : null} + +
+ ) +} + +function FilterSection({ + title, + children, +}: { + title: string + children: ReactNode +}) { + return ( +
+

{title}

+
{children}
+
+ ) +} + +function DisabledFilterHint({ label, reason }: { label: string; reason: string }) { + return ( +
+ {label} +
+ Coming soon +
+
+ ) +} + +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([]) + 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) => { + onChange({ ...filters, ...partial }) + } + + return ( + 0} + activeFilterCount={activeCount} + onClearFilters={() => onChange({ ...EMPTY_PLATFORM_AUDIENCE_FILTERS })} + clearLabel="Clear targeting" + summary={ + activeCount > 0 ? ( +

+ {activeCount} targeting filter{activeCount === 1 ? "" : "s"} applied — list shows matching users only. +

+ ) : ( +

+ Narrow the audience before selecting recipients. Leave filters empty to browse all platform users. +

+ ) + } + > +
+ + patch({ country, region: "" })} + /> + patch({ region })} + disabled={!ethiopiaSelected} + /> +
+ + patch({ createdAfterLocal: e.target.value })} + className="h-9 text-sm" + /> +
+
+ + patch({ createdBeforeLocal: e.target.value })} + className="h-9 text-sm" + /> +
+
+ + + patch({ educationLevel })} + /> + patch({ occupation })} + /> + patch({ ageGroup })} + /> + patch({ favouriteTopic })} + /> + patch({ languageGoal })} + /> + patch({ learningGoal })} + /> + patch({ knowledgeLevel })} + /> + + + + patch({ subscriptionStatus })} + /> + patch({ planId })} + /> + patch({ planCategory })} + /> + patch({ autoRenew })} + /> + patch({ hasEverPaid })} + /> +
+ + patch({ expiresWithinDays: e.target.value })} + className="h-9 text-sm" + /> +
+ +
+ + +
+ + patch({ daysSinceLastLoginMin: e.target.value })} + className="h-9 text-sm" + /> +
+
+ + patch({ daysSinceLastLoginMax: e.target.value })} + className="h-9 text-sm" + /> +
+ patch({ profileCompleted })} + /> + patch({ initialAssessmentCompleted })} + /> +
+ + patch({ minLessonsCompleted: e.target.value })} + className="h-9 text-sm" + /> +
+
+ + patch({ minModulesCompleted: e.target.value })} + className="h-9 text-sm" + /> +
+
+ + patch({ minProfileCompletionPct: e.target.value })} + className="h-9 text-sm" + /> +
+ + +
+ + + patch({ devicePlatform })} + /> + patch({ hasActiveDevice })} + /> + + + + +
+
+ ) +} diff --git a/src/lib/notificationBulk.ts b/src/lib/notificationBulk.ts index ce9075d..e8e3eef 100644 --- a/src/lib/notificationBulk.ts +++ b/src/lib/notificationBulk.ts @@ -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 { - 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 { + 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 { + return fetchAllPlatformUsersMatching(EMPTY_PLATFORM_AUDIENCE_FILTERS) } export async function fetchAllTeamMembers(): Promise { diff --git a/src/lib/platformAudienceFilters.ts b/src/lib/platformAudienceFilters.ts new file mode 100644 index 0000000..f354807 --- /dev/null +++ b/src/lib/platformAudienceFilters.ts @@ -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 = { 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), + } +} diff --git a/src/lib/userProfileFieldDisplay.ts b/src/lib/userProfileFieldDisplay.ts index 9e0ac92..35b0a99 100644 --- a/src/lib/userProfileFieldDisplay.ts +++ b/src/lib/userProfileFieldDisplay.ts @@ -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" }, diff --git a/src/pages/notifications/CreateNotificationPage.tsx b/src/pages/notifications/CreateNotificationPage.tsx index 2bec96f..2f4cb57 100644 --- a/src/pages/notifications/CreateNotificationPage.tsx +++ b/src/pages/notifications/CreateNotificationPage.tsx @@ -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("platform_selected") const [sendMode, setSendMode] = useState("now") const [users, setUsers] = useState([]) + const [platformFilters, setPlatformFilters] = useState( + EMPTY_PLATFORM_AUDIENCE_FILTERS, + ) const [teamMembers, setTeamMembers] = useState([]) 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" && ( -
+
+

Select users

- {selectedUsers.length} selected + {selectedUserIds.length} selected + {users.length > 0 ? ` · ${users.length} loaded` : ""}
@@ -901,7 +921,7 @@ export function CreateNotificationPage() { disabled={recipientsLoading} />
-
+
)} {!recipientsLoading && users.length > 0 && filteredUsers.length === 0 && (