|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useMemo, useState } from 'react'; |
| 4 | +import { Timestamp, addDoc, collection, deleteDoc, doc, limit, orderBy, query, serverTimestamp, updateDoc } from 'firebase/firestore'; |
| 5 | +import { useCollection, useFirestore, useUser } from '@/firebase'; |
| 6 | +import { Badge } from '@/components/ui/badge'; |
| 7 | +import { Button } from '@/components/ui/button'; |
| 8 | +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; |
| 9 | +import { Input } from '@/components/ui/input'; |
| 10 | +import { Label } from '@/components/ui/label'; |
| 11 | +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; |
| 12 | +import { Textarea } from '@/components/ui/textarea'; |
| 13 | +import { useToast } from '@/components/ui/use-toast'; |
| 14 | +import ZonedText from '@/components/ZonedText'; |
| 15 | +import { useNow } from '@/lib/hooks/useClientValues'; |
| 16 | +import { formatTimestamp } from '@/lib/utils'; |
| 17 | +import type { GlobalAnnouncement } from '@/lib/types'; |
| 18 | + |
| 19 | +const TYPES: { value: GlobalAnnouncement['type']; label: string }[] = [ |
| 20 | + { value: 'info', label: 'Info (blue)' }, |
| 21 | + { value: 'success', label: 'Good news (green)' }, |
| 22 | + { value: 'warning', label: 'Heads up (yellow)' }, |
| 23 | + { value: 'alert', label: 'Urgent (red)' }, |
| 24 | +]; |
| 25 | + |
| 26 | +const DAY = 24 * 60 * 60 * 1000; |
| 27 | +const DURATIONS = [ |
| 28 | + { value: '1', label: '1 day' }, |
| 29 | + { value: '3', label: '3 days' }, |
| 30 | + { value: '7', label: '1 week' }, |
| 31 | + { value: '14', label: '2 weeks' }, |
| 32 | + { value: '30', label: '1 month' }, |
| 33 | +]; |
| 34 | + |
| 35 | +const TITLE_MAX = 80; |
| 36 | +const MESSAGE_MAX = 300; |
| 37 | + |
| 38 | +/** A link the rules accept: https://... or a page on this site like /events */ |
| 39 | +function isValidLink(link: string): boolean { |
| 40 | + return /^https:\/\/\S+$/.test(link) || /^\/([^/\s]\S*)?$/.test(link); |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Admins post site-wide announcements here. The newest live one shows in the |
| 45 | + * banner at the top of every page, and recent ones are listed on /news. |
| 46 | + * firestore.rules lets only the `admin` claim write them. |
| 47 | + */ |
| 48 | +export default function AnnouncementsAdmin() { |
| 49 | + const firestore = useFirestore(); |
| 50 | + const { user } = useUser(); |
| 51 | + const { toast } = useToast(); |
| 52 | + const now = useNow(); |
| 53 | + const [title, setTitle] = useState(''); |
| 54 | + const [message, setMessage] = useState(''); |
| 55 | + const [type, setType] = useState<GlobalAnnouncement['type']>('info'); |
| 56 | + const [link, setLink] = useState(''); |
| 57 | + const [days, setDays] = useState('7'); |
| 58 | + const [busy, setBusy] = useState<string | null>(null); |
| 59 | + |
| 60 | + const recentQuery = useMemo(() => query(collection(firestore, 'announcements'), orderBy('createdAt', 'desc'), limit(20)), [firestore]); |
| 61 | + const { data: recent } = useCollection<GlobalAnnouncement>(recentQuery); |
| 62 | + |
| 63 | + const trimmedLink = link.trim(); |
| 64 | + const linkError = trimmedLink && !isValidLink(trimmedLink) ? 'Use a full https:// link, or a page here like /events.' : ''; |
| 65 | + const canPost = !!user && title.trim() && message.trim() && !linkError && busy === null; |
| 66 | + |
| 67 | + const post = async () => { |
| 68 | + if (!user || !canPost) return; |
| 69 | + setBusy('new'); |
| 70 | + try { |
| 71 | + const start = Timestamp.now(); |
| 72 | + await addDoc(collection(firestore, 'announcements'), { |
| 73 | + title: title.trim(), |
| 74 | + message: message.trim(), |
| 75 | + type, |
| 76 | + ...(trimmedLink ? { link: trimmedLink } : {}), |
| 77 | + startTime: start, |
| 78 | + endTime: Timestamp.fromMillis(start.toMillis() + Number(days) * DAY), |
| 79 | + isActive: true, |
| 80 | + createdAt: serverTimestamp(), |
| 81 | + createdBy: user.uid, |
| 82 | + }); |
| 83 | + toast({ title: 'Announcement posted', description: 'It shows at the top of every page now.' }); |
| 84 | + setTitle(''); |
| 85 | + setMessage(''); |
| 86 | + setLink(''); |
| 87 | + } catch { |
| 88 | + toast({ variant: 'destructive', title: "Couldn't post it", description: 'Only admins can post announcements.' }); |
| 89 | + } finally { |
| 90 | + setBusy(null); |
| 91 | + } |
| 92 | + }; |
| 93 | + |
| 94 | + const end = async (id: string) => { |
| 95 | + setBusy(id); |
| 96 | + try { |
| 97 | + await updateDoc(doc(firestore, 'announcements', id), { isActive: false }); |
| 98 | + toast({ title: 'Announcement ended' }); |
| 99 | + } catch { |
| 100 | + toast({ variant: 'destructive', title: "Couldn't end it" }); |
| 101 | + } finally { |
| 102 | + setBusy(null); |
| 103 | + } |
| 104 | + }; |
| 105 | + |
| 106 | + const remove = async (id: string) => { |
| 107 | + if (!window.confirm('Delete this announcement? It will also disappear from /news.')) return; |
| 108 | + setBusy(id); |
| 109 | + try { |
| 110 | + await deleteDoc(doc(firestore, 'announcements', id)); |
| 111 | + toast({ title: 'Announcement deleted' }); |
| 112 | + } catch { |
| 113 | + toast({ variant: 'destructive', title: "Couldn't delete it" }); |
| 114 | + } finally { |
| 115 | + setBusy(null); |
| 116 | + } |
| 117 | + }; |
| 118 | + |
| 119 | + return ( |
| 120 | + <div className="space-y-4"> |
| 121 | + <Card> |
| 122 | + <CardHeader className="pb-2"> |
| 123 | + <CardTitle className="text-base">Post an announcement</CardTitle> |
| 124 | + <CardDescription> |
| 125 | + It shows in a banner at the top of every page until it ends, and on the news page. Members can close the banner. |
| 126 | + </CardDescription> |
| 127 | + </CardHeader> |
| 128 | + <CardContent className="space-y-3"> |
| 129 | + <div className="space-y-1"> |
| 130 | + <Label htmlFor="announce-title">Title</Label> |
| 131 | + <Input id="announce-title" value={title} maxLength={TITLE_MAX} onChange={e => setTitle(e.target.value)} placeholder="New study groups start Monday" /> |
| 132 | + </div> |
| 133 | + <div className="space-y-1"> |
| 134 | + <Label htmlFor="announce-message">Message</Label> |
| 135 | + <Textarea id="announce-message" value={message} maxLength={MESSAGE_MAX} rows={3} onChange={e => setMessage(e.target.value)} /> |
| 136 | + <p className="text-xs text-muted-foreground text-right">{message.length}/{MESSAGE_MAX}</p> |
| 137 | + </div> |
| 138 | + <div className="space-y-1"> |
| 139 | + <Label htmlFor="announce-link">Link (optional)</Label> |
| 140 | + <Input id="announce-link" value={link} maxLength={300} onChange={e => setLink(e.target.value)} placeholder="/studygroups or https://..." /> |
| 141 | + {linkError && <p className="text-xs text-destructive">{linkError}</p>} |
| 142 | + </div> |
| 143 | + <div className="grid gap-3 sm:grid-cols-2"> |
| 144 | + <div className="space-y-1"> |
| 145 | + <Label>Style</Label> |
| 146 | + <Select value={type} onValueChange={value => setType(value as GlobalAnnouncement['type'])}> |
| 147 | + <SelectTrigger><SelectValue /></SelectTrigger> |
| 148 | + <SelectContent>{TYPES.map(t => <SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>)}</SelectContent> |
| 149 | + </Select> |
| 150 | + </div> |
| 151 | + <div className="space-y-1"> |
| 152 | + <Label>Show it for</Label> |
| 153 | + <Select value={days} onValueChange={setDays}> |
| 154 | + <SelectTrigger><SelectValue /></SelectTrigger> |
| 155 | + <SelectContent>{DURATIONS.map(d => <SelectItem key={d.value} value={d.value}>{d.label}</SelectItem>)}</SelectContent> |
| 156 | + </Select> |
| 157 | + </div> |
| 158 | + </div> |
| 159 | + <Button onClick={post} disabled={!canPost}>{busy === 'new' ? 'Posting...' : 'Post announcement'}</Button> |
| 160 | + </CardContent> |
| 161 | + </Card> |
| 162 | + |
| 163 | + <Card> |
| 164 | + <CardHeader className="pb-2"><CardTitle className="text-base">Recent announcements</CardTitle></CardHeader> |
| 165 | + <CardContent className="space-y-3"> |
| 166 | + {recent && recent.length === 0 && <p className="text-sm text-muted-foreground">None yet.</p>} |
| 167 | + {recent?.map(item => { |
| 168 | + const live = item.isActive && item.endTime && now !== null && item.endTime.toMillis() > now; |
| 169 | + return ( |
| 170 | + <div key={item.id} className="border rounded-md p-3 space-y-1"> |
| 171 | + <div className="flex items-center justify-between gap-2"> |
| 172 | + <p className="font-medium">{item.title}</p> |
| 173 | + <Badge variant={live ? 'default' : 'secondary'}>{live ? 'Live' : 'Ended'}</Badge> |
| 174 | + </div> |
| 175 | + <p className="text-sm text-muted-foreground">{item.message}</p> |
| 176 | + {item.link && <p className="text-xs break-all">{item.link}</p>} |
| 177 | + {item.endTime && ( |
| 178 | + <p className="text-xs text-muted-foreground"> |
| 179 | + {live ? 'Ends ' : 'Ended '}<ZonedText render={tz => formatTimestamp(item.endTime, true, tz)} /> |
| 180 | + </p> |
| 181 | + )} |
| 182 | + <div className="flex gap-2 pt-1"> |
| 183 | + {live && <Button size="sm" variant="outline" disabled={busy !== null} onClick={() => end(item.id)}>End now</Button>} |
| 184 | + <Button size="sm" variant="ghost" disabled={busy !== null} onClick={() => remove(item.id)}>Delete</Button> |
| 185 | + </div> |
| 186 | + </div> |
| 187 | + ); |
| 188 | + })} |
| 189 | + </CardContent> |
| 190 | + </Card> |
| 191 | + </div> |
| 192 | + ); |
| 193 | +} |
0 commit comments