All files / features/staff/pages CollectorPage.tsx

77.27% Statements 51/66
73.17% Branches 30/41
61.53% Functions 8/13
84.48% Lines 49/58

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 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220                                1x 18x 18x 18x 18x 18x 18x   18x 18x         18x 18x 18x 18x 18x   18x 8x 8x 8x 8x     18x       18x             18x 13x         13x 13x           18x 3x   3x   3x             3x 3x 1x 1x     2x   2x   2x 1x 1x       1x   1x 1x 1x 1x   1x         18x 18x         18x 18x     18x                                                                                                                                                                                                            
import { useState, useEffect } from 'react'
import { SyncService } from '@features/staff/services/sync.service'
import { useStaffAuth } from '../hooks/useStaffAuth'
 
import { Keypad } from '../components/Keypad'
import { DonationTypeSelector } from '../components/DonationTypeSelector'
import type { DonationType } from '../types'
import { DonorInfoForm } from '../components/DonorInfoForm'
import { Button } from '@core/components/ui/button'
import { Check, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { useTranslation } from 'react-i18next'
import { useCurrencyFormatter } from '@core/hooks/useCurrencyFormatter'
import { useNavigate, useParams } from 'react-router-dom'
import { useEvent } from '@features/events/context/EventContext'
 
export const CollectorPage = () => {
    const { t } = useTranslation('common')
    const { slug } = useParams<{ slug: string }>()
    const navigate = useNavigate()
    const { event } = useEvent()
    const { getStaffUser, isStaffAuthenticated } = useStaffAuth()
    const { formatCurrency } = useCurrencyFormatter()
 
    useEffect(() => {
        Iif (event && !isStaffAuthenticated(event.id)) {
            navigate(`/${slug}/staff/login`)
        }
    }, [event, isStaffAuthenticated, navigate, slug])
 
    const [amount, setAmount] = useState<string>('')
    const [type, setType] = useState<DonationType>('cash')
    const [name, setName] = useState<string>('')
    const [email, setEmail] = useState<string>('')
    const [isSubmitting, setIsSubmitting] = useState(false)
 
    const handleKeyPress = (key: string) => {
        Iif (amount.length >= 8) return
        Iif (key === '0' && amount === '0') return
        Iif (key === '00' && (amount === '' || amount === '0')) return
        setAmount((prev) => prev + key)
    }
 
    const handleDelete = () => {
        setAmount((prev) => prev.slice(0, -1))
    }
 
    const handleClear = () => {
        setAmount('')
        setName('')
        setEmail('')
        setType('cash')
    }
 
    const formatAmount = (val: string) => {
        Iif (!val)
            return formatCurrency(0, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
            })
        const num = parseInt(val) / 100
        return formatCurrency(num, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        })
    }
 
    const handleSubmit = async () => {
        Iif (!amount || parseInt(amount) === 0) return
 
        setIsSubmitting(true)
 
        const donationData = {
            amount: parseInt(amount),
            type,
            name: name || undefined,
            email: email || undefined,
        }
 
        const staffUser = getStaffUser()
        if (!staffUser?.eventId) {
            toast.error(t('staff.session_invalid', 'Session invalid. Please login again.'))
            return
        }
 
        const result = await SyncService.submitDonation(donationData, staffUser.eventId)
 
        setIsSubmitting(false)
 
        if (result.success) {
            const formattedAmount = formatAmount(amount)
            const msg = result.offline
                ? t('staff.success_offline', { amount: formattedAmount })
                : t('staff.success_online', { amount: formattedAmount })
 
            toast.success(msg)
 
            setAmount('')
            setName('')
            setEmail('')
            setType('cash')
        } else {
            toast.error(result.error || t('staff.submit_error'))
        }
    }
 
    // Add Sync Effect
    useEffect(() => {
        const handleOnline = () => {
            SyncService.processQueue().then((count) => {
                if (count > 0) toast.success(t('staff.back_online', { count }))
            })
        }
        window.addEventListener('online', handleOnline)
        return () => window.removeEventListener('online', handleOnline)
    }, [t])
 
    return (
        <div className="flex flex-col min-h-[calc(100vh-4rem)] max-w-md mx-auto">
            {/* Display Area */}
            <div
                className="flex-1 flex flex-col items-center justify-center min-h-[120px] mx-4 mt-4 border shadow-inner"
                style={{
                    backgroundColor: 'var(--staff-display-bg)',
                    borderColor: 'var(--staff-display-border)',
                    borderRadius: 'var(--staff-display-radius)',
                }}
            >
                <span
                    className="text-sm font-medium uppercase tracking-widest mb-1"
                    style={{ color: 'var(--staff-label-color)' }}
                >
                    {t('staff.enter_amount')}
                </span>
                <div
                    className="font-bold tracking-tighter"
                    style={{
                        fontSize: 'var(--staff-amount-size)',
                        color: 'var(--staff-amount-color)',
                    }}
                >
                    {amount ? (
                        formatAmount(amount)
                    ) : (
                        <span
                            style={{
                                color: 'var(--staff-amount-placeholder-color)',
                                opacity: 0.4,
                            }}
                        >
                            {formatCurrency(0, {
                                minimumFractionDigits: 2,
                                maximumFractionDigits: 2,
                            })}
                        </span>
                    )}
                </div>
            </div>
 
            {/* Controls */}
            <div
                className="flex-none mt-4 shadow-[0_-4px_20px_-5px_rgba(0,0,0,0.1)] border-t pb-6"
                style={{
                    backgroundColor: 'var(--staff-keypad-bg)',
                    borderColor: 'var(--staff-display-border)',
                    borderRadius: 'var(--staff-keypad-radius)',
                    boxShadow: 'var(--staff-keypad-shadow)',
                }}
            >
                <div className="w-12 h-1.5 bg-slate-200 dark:bg-slate-700 rounded-full mx-auto my-3" />
 
                <DonationTypeSelector value={type} onChange={setType} disabled={isSubmitting} />
 
                <DonorInfoForm
                    name={name}
                    email={email}
                    onNameChange={setName}
                    onEmailChange={setEmail}
                    disabled={isSubmitting}
                />
 
                <Keypad
                    onKeyPress={handleKeyPress}
                    onDelete={handleDelete}
                    onClear={handleClear}
                    disabled={isSubmitting}
                />
 
                <div className="px-4 mt-2 w-full max-w-sm mx-auto">
                    <Button
                        size="lg"
                        className="w-full text-lg font-bold h-14"
                        onClick={handleSubmit}
                        disabled={!amount || isSubmitting}
                        style={{
                            backgroundColor: 'var(--staff-type-button-selected-bg)',
                            color: 'var(--staff-type-button-selected-text)',
                            boxShadow:
                                '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
                        }}
                    >
                        {isSubmitting ? (
                            <Loader2
                                className="mr-2 h-6 w-6 animate-spin"
                                style={{ color: 'var(--staff-type-button-selected-icon)' }}
                            />
                        ) : (
                            <Check
                                className="mr-2 h-6 w-6"
                                style={{ color: 'var(--staff-type-button-selected-icon)' }}
                            />
                        )}
                        {t('staff.collect_button')}
                    </Button>
                </div>
            </div>
        </div>
    )
}