Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(app): add Operator Pass commands, holdings and events

Hampus934dd38cc0a8
diff --git a/fluxer_app/src/features/premium/commands/OperatorPassCommands.ts b/fluxer_app/src/features/premium/commands/OperatorPassCommands.ts
new file mode 100644
index 000000000..bffb347c5
--- /dev/null
+++ b/fluxer_app/src/features/premium/commands/OperatorPassCommands.ts
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Endpoints} from '@app/features/app/constants/Endpoints';
+import GeoIP from '@app/features/app/state/GeoIP';
+import {http} from '@app/features/platform/transport/RestTransport';
+import {Logger} from '@app/features/platform/utils/AppLogger';
+import OperatorPassHoldings from '@app/features/premium/state/OperatorPassHoldings';
+import * as UserProfileCommands from '@app/features/user/commands/UserProfileCommands';
+import Users from '@app/features/user/state/Users';
+import type {
+ OperatorPassCheckoutRequest,
+ OperatorPassCheckoutResponse,
+ OperatorPassListingResponse,
+ OperatorPassListingUpdateRequest,
+ OperatorPassOfferAcceptRequest,
+ OperatorPassOfferResponse,
+ OperatorPassPassesResponse,
+ OperatorPassPurchaseListResponse,
+ OperatorPassPurchaseResponse,
+ OperatorPassStateResponse,
+ OperatorPassWithdrawRequest,
+} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';
+
+const logger = new Logger('OperatorPass');
+
+export function getCountryCode(): string | undefined {
+ return GeoIP.countryCode?.toUpperCase() ?? undefined;
+}
+
+function applyHolderToCurrentUser(state: OperatorPassStateResponse): void {
+ const user = Users.currentUser;
+ if (!user) return;
+ const since = state.holder?.since ?? null;
+ const current = user.operatorPassSince ?? null;
+ if ((current?.getTime() ?? null) === (since ? new Date(since).getTime() : null)) return;
+ Users.handleUserUpdate({...user.toJSON(), operator_pass_since: since});
+ UserProfileCommands.clearCurrentUserProfiles();
+}
+
+export async function fetchState(): Promise<OperatorPassStateResponse> {
+ const countryCode = getCountryCode();
+ const response = await http.get<OperatorPassStateResponse>(Endpoints.OPERATOR_PASS_STATE, {
+ query: countryCode ? {country_code: countryCode} : {},
+ });
+ applyHolderToCurrentUser(response.body);
+ return response.body;
+}
+
+export async function createCheckout(request: OperatorPassCheckoutRequest): Promise<string> {
+ try {
+ const response = await http.post<OperatorPassCheckoutResponse>(Endpoints.OPERATOR_PASS_CHECKOUT, {
+ body: request,
+ });
+ logger.info('Operator Pass checkout created', {quantity: request.quantity});
+ return response.body.url;
+ } catch (error) {
+ logger.error('Operator Pass checkout failed', error);
+ throw error;
+ }
+}
+
+export async function fetchPurchases(): Promise<OperatorPassPurchaseListResponse> {
+ const response = await http.get<OperatorPassPurchaseListResponse>(Endpoints.OPERATOR_PASS_PURCHASES);
+ return response.body;
+}
+
+export async function withdrawPurchase(
+ purchaseId: string,
+ request: OperatorPassWithdrawRequest,
+): Promise<OperatorPassPurchaseResponse> {
+ try {
+ const response = await http.post<OperatorPassPurchaseResponse>(
+ Endpoints.OPERATOR_PASS_PURCHASE_WITHDRAW(purchaseId),
+ {
+ body: request,
+ },
+ );
+ logger.info('Operator Pass purchase withdrawn', {quantity: response.body.quantity});
+ UserProfileCommands.clearCurrentUserProfiles();
+ return response.body;
+ } catch (error) {
+ logger.error('Operator Pass withdrawal failed', error);
+ throw error;
+ }
+}
+
+export async function fetchListing(): Promise<OperatorPassListingResponse> {
+ const response = await http.get<OperatorPassListingResponse>(Endpoints.OPERATOR_PASS_LISTING);
+ return response.body;
+}
+
+export async function updateListing(request: OperatorPassListingUpdateRequest): Promise<OperatorPassListingResponse> {
+ try {
+ const response = await http.put<OperatorPassListingResponse>(Endpoints.OPERATOR_PASS_LISTING, {body: request});
+ logger.info("Operators' wall listing updated", {optOut: request.wall_opt_out});
+ return response.body;
+ } catch (error) {
+ logger.error("Operators' wall listing update failed", error);
+ throw error;
+ }
+}
+
+export async function fetchPasses(): Promise<OperatorPassPassesResponse> {
+ const response = await http.get<OperatorPassPassesResponse>(Endpoints.OPERATOR_PASS_PASSES);
+ OperatorPassHoldings.setPasses(response.body);
+ OperatorPassHoldings.markIncomingOffersSeen();
+ return response.body;
+}
+
+async function refreshPassesQuietly(): Promise<void> {
+ try {
+ await fetchPasses();
+ } catch (error) {
+ logger.warn('Operator Pass refresh failed', error);
+ }
+}
+
+export async function createOffer(
+ passId: string,
+ recipientId: string,
+ confirmLastPass: boolean,
+): Promise<OperatorPassOfferResponse> {
+ try {
+ const response = await http.post<OperatorPassOfferResponse>(Endpoints.OPERATOR_PASS_PASS_OFFERS(passId), {
+ body: {recipient_id: recipientId, confirm_last_pass: confirmLastPass},
+ });
+ logger.info('Operator Pass offer created');
+ await refreshPassesQuietly();
+ return response.body;
+ } catch (error) {
+ logger.error('Operator Pass offer failed', error);
+ throw error;
+ }
+}
+
+export async function fetchOffer(offerId: string): Promise<OperatorPassOfferResponse> {
+ const response = await http.get<OperatorPassOfferResponse>(Endpoints.OPERATOR_PASS_OFFER(offerId));
+ return response.body;
+}
+
+export async function withdrawOffer(offerId: string): Promise<OperatorPassOfferResponse> {
+ const response = await http.delete<OperatorPassOfferResponse>(Endpoints.OPERATOR_PASS_OFFER(offerId));
+ logger.info('Operator Pass offer withdrawn');
+ await refreshPassesQuietly();
+ return response.body;
+}
+
+export async function acceptOffer(
+ offerId: string,
+ request: OperatorPassOfferAcceptRequest,
+): Promise<OperatorPassOfferResponse> {
+ const response = await http.post<OperatorPassOfferResponse>(Endpoints.OPERATOR_PASS_OFFER_ACCEPT(offerId), {
+ body: request,
+ });
+ logger.info('Operator Pass offer accepted', {status: response.body.status});
+ await refreshPassesQuietly();
+ UserProfileCommands.clearCurrentUserProfiles();
+ return response.body;
+}
+
+export async function declineOffer(offerId: string): Promise<OperatorPassOfferResponse> {
+ const response = await http.post<OperatorPassOfferResponse>(Endpoints.OPERATOR_PASS_OFFER_DECLINE(offerId));
+ logger.info('Operator Pass offer declined');
+ await refreshPassesQuietly();
+ return response.body;
+}
+
+export async function withdrawPass(
+ passId: string,
+ request: OperatorPassWithdrawRequest,
+): Promise<OperatorPassPassesResponse> {
+ try {
+ const response = await http.post<OperatorPassPassesResponse>(Endpoints.OPERATOR_PASS_PASS_WITHDRAW(passId), {
+ body: request,
+ });
+ logger.info('Operator Pass withdrawn');
+ OperatorPassHoldings.setPasses(response.body);
+ UserProfileCommands.clearCurrentUserProfiles();
+ return response.body;
+ } catch (error) {
+ logger.error('Operator Pass withdrawal failed', error);
+ throw error;
+ }
+}
diff --git a/fluxer_app/src/features/premium/commands/OperatorPassModalCommands.tsx b/fluxer_app/src/features/premium/commands/OperatorPassModalCommands.tsx
new file mode 100644
index 000000000..49deb03da
--- /dev/null
+++ b/fluxer_app/src/features/premium/commands/OperatorPassModalCommands.tsx
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {OperatorPassCheckoutModal} from '@app/features/premium/components/modals/OperatorPassCheckoutModal';
+import * as ModalCommands from '@app/features/ui/commands/ModalCommands';
+import {modal} from '@app/features/ui/commands/ModalCommands';
+
+const CHECKOUT_MODAL_KEY = 'operator-pass-checkout';
+
+let checkoutModalMount = 0;
+
+export function openCheckoutModal({canceled = false}: {canceled?: boolean} = {}): void {
+ const mount = ++checkoutModalMount;
+ ModalCommands.pushWithKey(
+ modal(() => (
+ <OperatorPassCheckoutModal
+ key={mount}
+ canceled={canceled}
+ data-flx="premium.operator-pass-modal-commands.open-checkout-modal.operator-pass-checkout-modal"
+ />
+ )),
+ CHECKOUT_MODAL_KEY,
+ );
+}
+
+export function reopenCheckoutModalAfterReturn(): void {
+ const topModalKey = ModalCommands.getTopModalKey();
+ if (topModalKey !== null && topModalKey !== CHECKOUT_MODAL_KEY) return;
+ openCheckoutModal();
+}
diff --git a/fluxer_app/src/features/premium/events/OperatorPassUpdate.tsx b/fluxer_app/src/features/premium/events/OperatorPassUpdate.tsx
new file mode 100644
index 000000000..336cc6715
--- /dev/null
+++ b/fluxer_app/src/features/premium/events/OperatorPassUpdate.tsx
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {OPERATOR_PASS_NAME} from '@app/features/app/config/I18nDisplayConstants';
+import type {GatewayHandlerContext} from '@app/features/gateway/events/EventRouter';
+import {Logger} from '@app/features/platform/utils/AppLogger';
+import {loadLazyModule} from '@app/features/platform/utils/LazyModuleLoader';
+import OperatorPassHoldings from '@app/features/premium/state/OperatorPassHoldings';
+import {getOperatorPassOfferUserName} from '@app/features/premium/utils/OperatorPassUtils';
+import * as ToastCommands from '@app/features/ui/commands/ToastCommands';
+import * as UserProfileCommands from '@app/features/user/commands/UserProfileCommands';
+import type {
+ OperatorPassOfferResponse,
+ OperatorPassPassesResponse,
+} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';
+import {msg} from '@lingui/core/macro';
+import {useLingui} from '@lingui/react/macro';
+
+const OFFER_RECEIVED_DESCRIPTOR = msg({
+ message: '{senderName} is passing you an {operatorPassName}. Select to accept or decline.',
+ comment:
+ 'In-app notification when someone offers this account one of their Operator Passes. Selecting it opens the offer. {senderName} is a display name. Operator Pass is a product name.',
+});
+
+const OFFER_TOAST_TIMEOUT_MS = 15000;
+
+const logger = new Logger('OperatorPassUpdate');
+
+function OfferReceivedToast({offer}: {offer: OperatorPassOfferResponse}) {
+ const {i18n} = useLingui();
+ return (
+ <span data-flx="premium.operator-pass-update.offer-toast">
+ {i18n._(OFFER_RECEIVED_DESCRIPTOR, {
+ senderName: getOperatorPassOfferUserName(offer.sender),
+ operatorPassName: OPERATOR_PASS_NAME,
+ })}
+ </span>
+ );
+}
+
+export function handleOperatorPassUpdate(data: OperatorPassPassesResponse, _context: GatewayHandlerContext): void {
+ const previous = OperatorPassHoldings.passes;
+ OperatorPassHoldings.setPasses(data);
+ if (previous?.count !== data.count) {
+ UserProfileCommands.clearCurrentUserProfiles();
+ }
+ for (const offer of OperatorPassHoldings.takeNewIncomingOffers()) {
+ ToastCommands.createToast({
+ type: 'info',
+ timeout: OFFER_TOAST_TIMEOUT_MS,
+ children: <OfferReceivedToast offer={offer} data-flx="premium.operator-pass-update.offer-received-toast" />,
+ onClick: () => {
+ void loadLazyModule(() => import('@app/features/premium/components/operator_pass/OperatorPassOfferModal'))
+ .then(({openOperatorPassOfferModal}) => openOperatorPassOfferModal(offer.id))
+ .catch((error: unknown) => logger.error('Failed to open the Pass it on offer', error));
+ },
+ });
+ }
+}
diff --git a/fluxer_app/src/features/premium/state/OperatorPassHoldings.ts b/fluxer_app/src/features/premium/state/OperatorPassHoldings.ts
new file mode 100644
index 000000000..904d70a8a
--- /dev/null
+++ b/fluxer_app/src/features/premium/state/OperatorPassHoldings.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {AccountScopedWork} from '@app/features/platform/state/AccountScopedWork';
+import type {
+ OperatorPassOfferResponse,
+ OperatorPassPassesResponse,
+} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';
+import {makeAutoObservable} from 'mobx';
+
+class OperatorPassHoldings {
+ passes: OperatorPassPassesResponse | null = null;
+ private announcedOfferIds = new Set<string>();
+ private sessionStartedAt = Date.now();
+
+ constructor() {
+ makeAutoObservable(this, {}, {autoBind: true});
+ }
+
+ get count(): number | null {
+ return this.passes?.count ?? null;
+ }
+
+ findOffer(offerId: string): OperatorPassOfferResponse | null {
+ const passes = this.passes;
+ if (!passes) return null;
+ return (
+ passes.incoming_offers.find((offer) => offer.id === offerId) ??
+ passes.outgoing_offers.find((offer) => offer.id === offerId) ??
+ null
+ );
+ }
+
+ setPasses(passes: OperatorPassPassesResponse): void {
+ this.passes = passes;
+ }
+
+ markIncomingOffersSeen(): void {
+ for (const offer of this.passes?.incoming_offers ?? []) {
+ this.announcedOfferIds.add(offer.id);
+ }
+ }
+
+ takeNewIncomingOffers(): Array<OperatorPassOfferResponse> {
+ const fresh = (this.passes?.incoming_offers ?? []).filter(
+ (offer) =>
+ offer.status === 'pending' &&
+ !this.announcedOfferIds.has(offer.id) &&
+ Date.parse(offer.created_at) >= this.sessionStartedAt,
+ );
+ this.markIncomingOffersSeen();
+ return fresh;
+ }
+
+ clear(): void {
+ this.passes = null;
+ this.sessionStartedAt = Date.now();
+ }
+}
+
+const operatorPassHoldings = new OperatorPassHoldings();
+
+AccountScopedWork.registerCancellation(() => operatorPassHoldings.clear());
+
+export default operatorPassHoldings;
diff --git a/fluxer_app/src/features/premium/utils/OperatorPassPassRows.ts b/fluxer_app/src/features/premium/utils/OperatorPassPassRows.ts
new file mode 100644
index 000000000..d8242b241
--- /dev/null
+++ b/fluxer_app/src/features/premium/utils/OperatorPassPassRows.ts
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {
+ OperatorPassOfferResponse,
+ OperatorPassPassesResponse,
+ OperatorPassPurchaseResponse,
+ OperatorPassUnitResponse,
+} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';
+
+type HeldPassGroup = [OperatorPassUnitResponse, ...Array<OperatorPassUnitResponse>];
+
+export type OperatorPassPassRow =
+ | {kind: 'incoming'; key: string; offer: OperatorPassOfferResponse}
+ | {kind: 'undelivered'; key: string; purchase: OperatorPassPurchaseResponse}
+ | {
+ kind: 'held';
+ key: string;
+ passes: Readonly<HeldPassGroup>;
+ date: string;
+ receivedFrom: OperatorPassOfferResponse['sender'];
+ paused: boolean;
+ passOn: OperatorPassUnitResponse | null;
+ lockEndsAt: string | null;
+ cancel: OperatorPassUnitResponse | null;
+ }
+ | {kind: 'offered'; key: string; pass: OperatorPassUnitResponse; offer: OperatorPassOfferResponse}
+ | {kind: 'passed_on'; key: string; offer: OperatorPassOfferResponse};
+
+export function isOperatorPassBenefitsRemoved(holdings: Pick<OperatorPassPassesResponse, 'count' | 'passes'>): boolean {
+ return holdings.count === 0 && holdings.passes.length > 0;
+}
+
+function groupKey(pass: OperatorPassUnitResponse): string {
+ if (pass.source !== 'purchase' || !pass.purchase_id) return `${pass.source}:${pass.id}`;
+ return `purchase:${pass.purchase_id}${pass.paused ? ':paused' : ''}`;
+}
+
+function isFuture(iso: string | null, now: number): boolean {
+ return iso != null && Date.parse(iso) > now;
+}
+
+export function buildOperatorPassPassRows(
+ holdings: OperatorPassPassesResponse,
+ purchases: ReadonlyArray<OperatorPassPurchaseResponse>,
+ now: number = Date.now(),
+): Array<OperatorPassPassRow> {
+ const removed = isOperatorPassBenefitsRemoved(holdings);
+ const rows: Array<OperatorPassPassRow> = [];
+ for (const offer of holdings.incoming_offers) {
+ if (offer.status === 'pending') rows.push({kind: 'incoming', key: `incoming:${offer.id}`, offer});
+ }
+ for (const purchase of purchases) {
+ if (purchase.can_withdraw) rows.push({kind: 'undelivered', key: `undelivered:${purchase.id}`, purchase});
+ }
+ const groups = new Map<string, HeldPassGroup>();
+ const dated: Array<{date: string; row: OperatorPassPassRow}> = [];
+ for (const pass of holdings.passes) {
+ if (pass.offer) {
+ dated.push({date: pass.delivered_at, row: {kind: 'offered', key: `offered:${pass.id}`, pass, offer: pass.offer}});
+ continue;
+ }
+ const key = groupKey(pass);
+ const group = groups.get(key);
+ if (group) group.push(pass);
+ else groups.set(key, [pass]);
+ }
+ for (const [key, passes] of groups) {
+ const date = passes.reduce(
+ (earliest, pass) => (Date.parse(pass.delivered_at) < Date.parse(earliest) ? pass.delivered_at : earliest),
+ passes[0].delivered_at,
+ );
+ const passOn = removed ? null : (passes.find((pass) => pass.can_pass_on && !pass.paused) ?? null);
+ const cancel =
+ passes.find((pass) => pass.can_withdraw && pass.withdrawal_ends_on && isFuture(pass.withdrawal_ends_at, now)) ??
+ null;
+ const lockEndsAt = passOn && isFuture(passOn.transfer_lock_ends_at, now) ? passOn.transfer_lock_ends_at : null;
+ dated.push({
+ date,
+ row: {
+ kind: 'held',
+ key: `held:${key}`,
+ passes,
+ date,
+ receivedFrom: passes[0].source === 'transfer' ? (passes[0].received_from ?? null) : null,
+ paused: passes.some((pass) => pass.paused),
+ passOn,
+ lockEndsAt,
+ cancel,
+ },
+ });
+ }
+ dated.sort((left, right) => Date.parse(left.date) - Date.parse(right.date));
+ rows.push(...dated.map(({row}) => row));
+ for (const offer of holdings.passed_on ?? []) {
+ rows.push({kind: 'passed_on', key: `passed_on:${offer.id}`, offer});
+ }
+ return rows;
+}
diff --git a/fluxer_app/src/features/premium/utils/OperatorPassUtils.ts b/fluxer_app/src/features/premium/utils/OperatorPassUtils.ts
new file mode 100644
index 000000000..eef158d9f
--- /dev/null
+++ b/fluxer_app/src/features/premium/utils/OperatorPassUtils.ts
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import RuntimeConfig from '@app/features/app/state/RuntimeConfig';
+import {isolateBidi} from '@app/features/i18n/utils/BidiIsolate';
+import {HttpError} from '@app/features/platform/types/EndpointError';
+import {shouldUse12HourFormat} from '@app/features/user/utils/DateFormatting';
+import {getCurrentOrDetectedLocale} from '@app/features/user/utils/LocaleUtils';
+import {getOperatorPassEarlyBirdEndsOn} from '@fluxer/constants/src/OperatorPassEarlyBird';
+import {getDateFormatter} from '@fluxer/date_utils/src/DateFormatterCache';
+import {formatSinceMonthYear} from '@fluxer/date_utils/src/SinceMonthYear';
+import {
+ OPERATOR_PASS_WALL_NAME_MAX_LENGTH,
+ type OperatorPassOfferResponse,
+ type OperatorPassPassesResponse,
+} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';
+
+export const OPERATOR_PASS_LABS_INVITE_CODE = 'fluxer-labs';
+
+export function focusOperatorPassField(id: string): void {
+ requestAnimationFrame(() => {
+ const target = document.getElementById(id);
+ const control =
+ target instanceof HTMLInputElement ? target : target?.querySelector<HTMLElement>('[role="checkbox"]');
+ control?.focus();
+ });
+}
+
+export function focusFirstInvalidOperatorPassField(fields: ReadonlyArray<{id: string; invalid: boolean}>): boolean {
+ const field = fields.find((entry) => entry.invalid);
+ if (!field) return false;
+ focusOperatorPassField(field.id);
+ return true;
+}
+
+export function isOperatorPassAvailable(): boolean {
+ return !RuntimeConfig.isSelfHosted();
+}
+
+export function hasOperatorPassProfileBadge(user: {operatorPassSince: unknown}): boolean {
+ return isOperatorPassAvailable() && user.operatorPassSince != null;
+}
+
+export function formatOperatorPassDateTime(iso: string): string {
+ const locale = getCurrentOrDetectedLocale();
+ return getDateFormatter(locale, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ hour12: shouldUse12HourFormat(locale),
+ }).format(new Date(iso));
+}
+
+export function formatOperatorPassLongDate(iso: string): string {
+ return getDateFormatter(getCurrentOrDetectedLocale(), {dateStyle: 'long'}).format(new Date(iso));
+}
+
+export function formatOperatorPassDate(iso: string): string {
+ return getDateFormatter(getCurrentOrDetectedLocale(), {dateStyle: 'medium'}).format(new Date(iso));
+}
+
+interface OperatorPassCalendarDay {
+ year: number;
+ month: number;
+ day: number;
+}
+
+function getZonedTime(at: number, timeZone?: string): OperatorPassCalendarDay & {startOfDay: boolean} {
+ const parts = new Intl.DateTimeFormat('en-US', {
+ timeZone,
+ hourCycle: 'h23',
+ year: 'numeric',
+ month: 'numeric',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: 'numeric',
+ second: 'numeric',
+ }).formatToParts(new Date(at));
+ const value = (type: Intl.DateTimeFormatPartTypes) => Number(parts.find((part) => part.type === type)?.value ?? 0);
+ return {
+ year: value('year'),
+ month: value('month'),
+ day: value('day'),
+ startOfDay: value('hour') === 0 && value('minute') === 0 && value('second') === 0 && at % 1000 === 0,
+ };
+}
+
+function formatCalendarDay(
+ {year, month, day}: OperatorPassCalendarDay,
+ dateStyle: 'medium' | 'long' = 'medium',
+): string {
+ return getDateFormatter(getCurrentOrDetectedLocale(), {dateStyle, timeZone: 'UTC'}).format(
+ new Date(Date.UTC(year, month - 1, day)),
+ );
+}
+
+function parseCalendarDay(day: string): OperatorPassCalendarDay {
+ const [year, month, date] = day.split('-').map(Number) as [number, number, number];
+ return {year, month, day: date};
+}
+
+export function formatOperatorPassCalendarDay(day: string): string {
+ return formatCalendarDay(parseCalendarDay(day));
+}
+
+export function formatOperatorPassEarlyBirdEnd(priceRisesAt: string): string {
+ return formatCalendarDay(parseCalendarDay(getOperatorPassEarlyBirdEndsOn(priceRisesAt)), 'long');
+}
+
+export function formatOperatorPassUnlockDay(iso: string, timeZone?: string): string {
+ const zoned = getZonedTime(Date.parse(iso), timeZone);
+ if (zoned.startOfDay) return formatCalendarDay(zoned);
+ const next = new Date(Date.UTC(zoned.year, zoned.month - 1, zoned.day + 1));
+ return formatCalendarDay({year: next.getUTCFullYear(), month: next.getUTCMonth() + 1, day: next.getUTCDate()});
+}
+
+export function hasOperatorPassTimePassed(iso: string | null | undefined, now: number = Date.now()): boolean {
+ if (!iso) return true;
+ const at = Date.parse(iso);
+ return Number.isNaN(at) || at <= now;
+}
+
+export function formatOperatorPassSinceMonth(iso: string | Date): string {
+ return formatSinceMonthYear(new Date(iso), getCurrentOrDetectedLocale());
+}
+
+export type OperatorPassWallNameProblem = 'required' | 'too_long';
+
+export function getOperatorPassWallNameProblem(name: string, optOut: boolean): OperatorPassWallNameProblem | null {
+ if (optOut) return null;
+ const trimmed = normalizeOperatorPassWallName(name);
+ if (trimmed.length === 0) return 'required';
+ if (trimmed.length > OPERATOR_PASS_WALL_NAME_MAX_LENGTH) return 'too_long';
+ return null;
+}
+
+export function normalizeOperatorPassWallName(name: string): string {
+ return name.replace(/[\r\n]+/gu, ' ').trim();
+}
+
+export function getOperatorPassErrorCode(error: unknown): string | null {
+ if (!(error instanceof HttpError)) return null;
+ const body = error.body;
+ if (body && typeof body === 'object' && 'code' in body && typeof body.code === 'string') {
+ return body.code;
+ }
+ return null;
+}
+
+export function getOperatorPassOfferUserName(user: OperatorPassOfferResponse['sender']): string {
+ if (!user) return '';
+ return isolateBidi(user.global_name ?? user.username);
+}
+
+export function clampOperatorPassQuantity(value: number, max: number): number {
+ if (!Number.isFinite(value)) return 1;
+ return Math.min(Math.max(1, Math.floor(value)), Math.max(1, max));
+}
+
+export function isOperatorPassLastFreePass(
+ holdings: Pick<OperatorPassPassesResponse, 'count' | 'outgoing_offers'>,
+): boolean {
+ const offered = holdings.outgoing_offers.filter(
+ (offer) => offer.status === 'pending' || offer.status === 'accepted',
+ ).length;
+ return holdings.count - offered <= 1;
+}
diff --git a/fluxer_app/src/features/premium/utils/PremiumMessageDescriptors.ts b/fluxer_app/src/features/premium/utils/PremiumMessageDescriptors.ts
index 02c14a918..5cdbde508 100644
--- a/fluxer_app/src/features/premium/utils/PremiumMessageDescriptors.ts
+++ b/fluxer_app/src/features/premium/utils/PremiumMessageDescriptors.ts
@@ -38,3 +38,34 @@ export const CUSTOMER_PORTAL_FAILED_MESSAGE_DESCRIPTOR = msg({
comment:
'Body of the error modal shown when opening the billing customer portal from the premium-expired nagbar fails.',
});
+export const PAYMENT_DISPUTE_OPEN_DESCRIPTOR = msg({
+ message:
+ 'Purchases are paused while a payment dispute on your account is open. They come back on their own when the dispute closes.',
+ comment:
+ 'Shown wherever something can be bought while a payment dispute this account made is open. A payment dispute is a chargeback filed with a bank or card company. Every purchase is paused until the bank closes the dispute, then purchases come back without the person doing anything. Neutral tone, never suggest the person did something wrong.',
+});
+export const PURCHASES_PAUSED_TITLE_DESCRIPTOR = msg({
+ message: 'Purchases paused',
+ comment: 'Dialog title when checkout is refused because a payment dispute this account made is still open.',
+});
+export const OPERATOR_PASS_CHARACTERISTICS_DESCRIPTOR = msg({
+ message:
+ "A spot on the Operators' wall, whenever you want it, and the Operator badge, for life, as long as we run {productName}.",
+ comment:
+ "What an Operator Pass gives, shown at checkout and when someone offers you a pass. The Operators' wall is the list of Operators on the homepage. Whenever you want it means the buyer can choose not to be listed and join the wall later. Operator is the badge name. For life means for as long as the official service and website run, and the part after it says so. {productName} is the product name.",
+});
+export const OPERATOR_PASS_LISTING_UNCHANGED_DESCRIPTOR = msg({
+ message: "Your Operators' wall listing stays the same.",
+ comment:
+ "Line for someone who already has an Operator Pass and gets another one, at checkout or when accepting an offer. The Operators' wall is the list of Operators on the homepage.",
+});
+export const OPERATOR_PASS_REQUIRED_BOX_DESCRIPTOR = msg({
+ message: 'Check this box to continue.',
+ comment:
+ 'Error under a required checkbox in the Operator Pass checkout dialog or the dialog for an Operator Pass someone offered you, shown when they try to continue without checking it.',
+});
+export const OPERATOR_PASS_OPEN_LABS_DESCRIPTOR = msg({
+ message: 'Open {labsName}',
+ comment:
+ 'Button in the Operator Pass dialog and on the page after an Operator Pass purchase. It opens the invite to {labsName}, the community that has #operators and the Operator role.',
+});