All files / src/viewmodels/admin useAdminNotificationViewModel.ts

77.46% Statements 110/142
73.17% Branches 30/41
75% Functions 6/8
77.46% Lines 110/142

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 1771x         1x 1x   1x                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         4x 4x 4x   2x 2x 2x 1x 2x     1x 1x 1x     1x 1x 1x 1x                   1x 26x 26x 26x 26x 26x   26x   26x 8x 8x 8x 8x   26x 3x 3x       3x 3x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 3x   26x               26x 2x 2x 1x 1x 1x   1x     2x 2x 2x       2x 2x 2x 2x       2x 2x 2x 2x         1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 2x     2x 1x 1x 2x   26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x  
import { useMemo, useState } from 'react';
import type {
  AdminCreateNotificationResponse,
  AdminNotificationDeliveryMode,
} from '@/models/admin';
import { ApiError } from '@/services/api';
import { createAdminNotification } from '@/services/adminService';
 
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
 
interface NotificationForm {
  targetUserInput: string;
  targetUserIds: string[];
  deliveryMode: AdminNotificationDeliveryMode;
  title: string;
  body: string;
  type: string;
  deepLink: string;
  eventId: string;
  dataText: string;
}
 
const INITIAL_FORM: NotificationForm = {
  targetUserInput: '',
  targetUserIds: [],
  deliveryMode: 'IN_APP',
  title: '',
  body: '',
  type: '',
  deepLink: '',
  eventId: '',
  dataText: '',
};
 
type NotificationField = keyof NotificationForm;
type FieldErrors = Partial<Record<NotificationField, string>>;
 
function parseUserIds(value: string): string[] {
  return Array.from(new Set(value.split(/[\s,]+/).map((item) => item.trim()).filter(Boolean)));
}
 
function parseData(value: string): Record<string, string> | undefined {
  const trimmed = value.trim();
  if (!trimmed) return undefined;
  const parsed = JSON.parse(trimmed) as unknown;
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    throw new Error('Data must be a JSON object.');
  }
  const data: Record<string, string> = {};
  Object.entries(parsed).forEach(([key, entry]) => {
    if (typeof entry !== 'string') {
      throw new Error('Data values must be strings.');
    }
    data[key] = entry;
  });
  return data;
}
 
function apiErrorMessage(err: unknown, fallback: string): string {
  if (err instanceof ApiError) {
    const details = err.details ? Object.values(err.details).filter(Boolean).join(' ') : '';
    return details ? `${err.message} ${details}` : err.message;
  }
  return fallback;
}
 
export function useAdminNotificationViewModel(token: string | null) {
  const [form, setForm] = useState<NotificationForm>(INITIAL_FORM);
  const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [result, setResult] = useState<AdminCreateNotificationResponse | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
 
  const targetUserIds = useMemo(() => form.targetUserIds, [form.targetUserIds]);
 
  function setField<K extends NotificationField>(field: K, value: NotificationForm[K]) {
    setForm((current) => ({ ...current, [field]: value }));
    setFieldErrors((current) => ({ ...current, [field]: undefined }));
    setSubmitError(null);
  }
 
  function addTargetUser() {
    const values = parseUserIds(form.targetUserInput);
    if (values.length === 0) {
      setFieldErrors((current) => ({ ...current, targetUserInput: 'Enter a user ID.' }));
      return;
    }
    const invalid = values.find((id) => !UUID_RE.test(id));
    if (invalid) {
      setFieldErrors((current) => ({ ...current, targetUserInput: 'User IDs must be valid UUIDs.' }));
      return;
    }
    setForm((current) => ({
      ...current,
      targetUserInput: '',
      targetUserIds: Array.from(new Set([...current.targetUserIds, ...values])),
    }));
    setFieldErrors((current) => ({ ...current, targetUserInput: undefined }));
    setSubmitError(null);
  }
 
  function removeTargetUser(userId: string) {
    setForm((current) => ({
      ...current,
      targetUserIds: current.targetUserIds.filter((id) => id !== userId),
    }));
    setFieldErrors((current) => ({ ...current, targetUserInput: undefined }));
  }
 
  async function submit(): Promise<boolean> {
    const errors: FieldErrors = {};
    if (targetUserIds.length === 0) {
      const pendingTargets = parseUserIds(form.targetUserInput);
      errors.targetUserInput = pendingTargets.some((id) => !UUID_RE.test(id))
        ? 'User IDs must be valid UUIDs.'
        : 'Add at least one user ID.';
    } else if (targetUserIds.some((id) => !UUID_RE.test(id))) {
      errors.targetUserInput = 'User IDs must be valid UUIDs.';
    }
    if (!form.title.trim()) errors.title = 'Title is required.';
    if (!form.body.trim()) errors.body = 'Body is required.';
    if (form.eventId.trim() && !UUID_RE.test(form.eventId.trim())) {
      errors.eventId = 'Event ID must be a valid UUID.';
    }
 
    let data: Record<string, string> | undefined;
    try {
      data = parseData(form.dataText);
    } catch (err) {
      errors.dataText = err instanceof Error ? err.message : 'Data must be valid JSON.';
    }
 
    setFieldErrors(errors);
    setResult(null);
    if (Object.keys(errors).length > 0) return false;
    if (!token) {
      setSubmitError('Admin session is not available.');
      return false;
    }
 
    setIsSubmitting(true);
    setSubmitError(null);
    try {
      const response = await createAdminNotification(token, {
        user_ids: targetUserIds,
        delivery_mode: form.deliveryMode,
        title: form.title.trim(),
        body: form.body.trim(),
        type: form.type.trim() || null,
        deep_link: form.deepLink.trim() || null,
        event_id: form.eventId.trim() || null,
        data,
      });
      setResult(response);
      return true;
    } catch (err) {
      setSubmitError(apiErrorMessage(err, 'Failed to send notification.'));
      return false;
    } finally {
      setIsSubmitting(false);
    }
  }
 
  return {
    form,
    fieldErrors,
    submitError,
    result,
    isSubmitting,
    targetUserIds,
    setField,
    addTargetUser,
    removeTargetUser,
    submit,
  };
}