EmailSettings.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import { useState } from 'react';
  2. import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { useTranslation } from 'react-i18next';
  4. import { Mail, Send, Lock, Unlock, AlertTriangle, CheckCircle, Loader2 } from 'lucide-react';
  5. import { api } from '../api/client';
  6. import type { SMTPSettings, TestSMTPRequest } from '../api/client';
  7. import { Card, CardContent, CardHeader } from './Card';
  8. import { Button } from './Button';
  9. import { useToast } from '../contexts/ToastContext';
  10. import { useEffect } from 'react';
  11. import { useAuth } from '../contexts/AuthContext';
  12. const SECURITY_PORT_MAP: Record<string, number> = {
  13. starttls: 587,
  14. ssl: 465,
  15. none: 25,
  16. };
  17. const PORT_SECURITY_MAP: Record<number, string> = {
  18. 587: 'starttls',
  19. 465: 'ssl',
  20. 25: 'none',
  21. };
  22. export function EmailSettings() {
  23. const { t } = useTranslation();
  24. const { showToast } = useToast();
  25. const queryClient = useQueryClient();
  26. const [smtpSettings, setSMTPSettings] = useState<SMTPSettings>({
  27. smtp_host: '',
  28. smtp_port: 587,
  29. smtp_username: '',
  30. smtp_password: '',
  31. smtp_security: 'starttls',
  32. smtp_auth_enabled: true,
  33. smtp_from_email: '',
  34. smtp_from_name: 'BamBuddy',
  35. });
  36. const [testEmail, setTestEmail] = useState('');
  37. // Fetch SMTP settings
  38. const { data: existingSettings, isLoading } = useQuery({
  39. queryKey: ['smtpSettings'],
  40. queryFn: () => api.getSMTPSettings(),
  41. });
  42. // Fetch global auth status
  43. const { authEnabled } = useAuth();
  44. // Fetch advanced auth status
  45. const { data: advancedAuthStatus } = useQuery({
  46. queryKey: ['advancedAuthStatus'],
  47. queryFn: () => api.getAdvancedAuthStatus(),
  48. });
  49. // Load existing settings when fetched
  50. useEffect(() => {
  51. if (existingSettings) {
  52. setSMTPSettings({
  53. ...existingSettings,
  54. smtp_password: '', // Never show password
  55. });
  56. }
  57. }, [existingSettings]);
  58. const handleSecurityChange = (security: 'starttls' | 'ssl' | 'none') => {
  59. setSMTPSettings({
  60. ...smtpSettings,
  61. smtp_security: security,
  62. smtp_port: SECURITY_PORT_MAP[security],
  63. });
  64. };
  65. const handlePortChange = (port: number) => {
  66. const matchedSecurity = PORT_SECURITY_MAP[port];
  67. setSMTPSettings({
  68. ...smtpSettings,
  69. smtp_port: port,
  70. ...(matchedSecurity ? { smtp_security: matchedSecurity as 'starttls' | 'ssl' | 'none' } : {}),
  71. });
  72. };
  73. const handleAuthChange = (enabled: boolean) => {
  74. setSMTPSettings({
  75. ...smtpSettings,
  76. smtp_auth_enabled: enabled,
  77. ...(!enabled ? { smtp_username: '', smtp_password: '' } : {}),
  78. });
  79. };
  80. // Save SMTP settings
  81. const saveMutation = useMutation({
  82. mutationFn: (settings: SMTPSettings) => api.saveSMTPSettings(settings),
  83. onSuccess: () => {
  84. queryClient.invalidateQueries({ queryKey: ['smtpSettings'] });
  85. queryClient.invalidateQueries({ queryKey: ['advancedAuthStatus'] });
  86. showToast(t('settings.email.success.settingsSaved'), 'success');
  87. },
  88. onError: (error: Error) => {
  89. showToast(error.message, 'error');
  90. },
  91. });
  92. // Test SMTP connection
  93. const testMutation = useMutation({
  94. mutationFn: (request: TestSMTPRequest) => api.testSMTP(request),
  95. onSuccess: (data) => {
  96. showToast(data.message, data.success ? 'success' : 'error');
  97. },
  98. onError: (error: Error) => {
  99. showToast(error.message, 'error');
  100. },
  101. });
  102. // Toggle advanced auth
  103. const toggleAdvancedAuthMutation = useMutation({
  104. mutationFn: (enabled: boolean) =>
  105. enabled ? api.enableAdvancedAuth() : api.disableAdvancedAuth(),
  106. onSuccess: (data) => {
  107. queryClient.invalidateQueries({ queryKey: ['advancedAuthStatus'] });
  108. showToast(data.message, 'success');
  109. },
  110. onError: (error: Error) => {
  111. showToast(error.message, 'error');
  112. },
  113. });
  114. const handleSave = () => {
  115. // Validate required fields
  116. if (!smtpSettings.smtp_host || !smtpSettings.smtp_from_email) {
  117. showToast(t('settings.email.errors.requiredFields'), 'error');
  118. return;
  119. }
  120. // Validate auth fields when authentication is enabled
  121. if (smtpSettings.smtp_auth_enabled && (!smtpSettings.smtp_username)) {
  122. showToast(t('settings.email.errors.usernameRequired'), 'error');
  123. return;
  124. }
  125. saveMutation.mutate(smtpSettings);
  126. };
  127. const handleTest = () => {
  128. if (!testEmail) {
  129. showToast(t('settings.email.errors.enterTestEmail'), 'error');
  130. return;
  131. }
  132. testMutation.mutate({
  133. test_recipient: testEmail,
  134. });
  135. };
  136. const handleToggleAdvancedAuth = () => {
  137. if (!authEnabled) {
  138. showToast(t('settings.email.errors.enableAuthFirst'), 'error');
  139. return;
  140. }
  141. if (!advancedAuthStatus?.advanced_auth_enabled && !advancedAuthStatus?.smtp_configured) {
  142. showToast(t('settings.email.errors.configureSmtpFirst'), 'error');
  143. return;
  144. }
  145. toggleAdvancedAuthMutation.mutate(!advancedAuthStatus?.advanced_auth_enabled);
  146. };
  147. if (isLoading) {
  148. return (
  149. <div className="flex items-center justify-center p-12">
  150. <Loader2 className="w-8 h-8 animate-spin text-bambu-green" />
  151. </div>
  152. );
  153. }
  154. const advancedEnabled = advancedAuthStatus?.advanced_auth_enabled ?? false;
  155. const inputClasses = "w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white placeholder-bambu-gray focus:outline-none focus:ring-2 focus:ring-bambu-green/50 focus:border-bambu-green transition-colors";
  156. const disabledInputClasses = "w-full px-3 py-2 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg text-white/40 placeholder-bambu-gray/40 cursor-not-allowed";
  157. return (
  158. <div className="space-y-3">
  159. {/* Advanced Authentication Toggle - Always visible */}
  160. <Card id="card-email-advanced-auth">
  161. <CardHeader>
  162. <div className="flex items-center justify-between">
  163. <div className="flex items-center gap-2">
  164. <Mail className="w-5 h-5 text-bambu-green" />
  165. <h2 className="text-lg font-semibold text-white">
  166. {t('settings.email.advancedAuth') || 'Advanced Authentication'}
  167. </h2>
  168. </div>
  169. <Button
  170. onClick={handleToggleAdvancedAuth}
  171. disabled={toggleAdvancedAuthMutation.isPending}
  172. variant={advancedEnabled ? 'danger' : 'primary'}
  173. >
  174. {advancedEnabled ? (
  175. <>
  176. <Unlock className="w-4 h-4" />
  177. {t('settings.email.disable') || 'Disable'}
  178. </>
  179. ) : (
  180. <>
  181. <Lock className="w-4 h-4" />
  182. {t('settings.email.enable') || 'Enable'}
  183. </>
  184. )}
  185. </Button>
  186. </div>
  187. </CardHeader>
  188. <CardContent>
  189. <div className="space-y-3">
  190. {advancedEnabled ? (
  191. <div className="bg-green-500/10 border border-green-500/30 rounded-lg p-4">
  192. <div className="flex items-start gap-3">
  193. <CheckCircle className="w-5 h-5 text-green-400 mt-0.5 flex-shrink-0" />
  194. <div className="space-y-2">
  195. <p className="text-white font-medium">
  196. {t('settings.email.advancedAuthEnabled') || 'Advanced Authentication is enabled'}
  197. </p>
  198. <ul className="text-sm text-green-300 space-y-1 list-disc list-inside">
  199. <li>{t('settings.email.feature1') || 'Passwords are auto-generated and emailed to new users'}</li>
  200. <li>{t('settings.email.feature2') || 'Users can login with username or email'}</li>
  201. <li>{t('settings.email.feature3') || 'Forgot password feature is available'}</li>
  202. <li>{t('settings.email.feature4') || 'Admins can reset user passwords via email'}</li>
  203. </ul>
  204. </div>
  205. </div>
  206. </div>
  207. ) : (
  208. <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-4">
  209. <div className="flex items-start gap-3">
  210. <AlertTriangle className="w-5 h-5 text-yellow-400 mt-0.5 flex-shrink-0" />
  211. <div className="space-y-2">
  212. <p className="text-white font-medium">
  213. {t('settings.email.advancedAuthDisabled') || 'Advanced Authentication is disabled'}
  214. </p>
  215. <p className="text-sm text-yellow-300">
  216. {t('settings.email.advancedAuthDisabledDesc') || 'Enable advanced authentication to activate email-based features for user management.'}
  217. </p>
  218. </div>
  219. </div>
  220. </div>
  221. )}
  222. </div>
  223. </CardContent>
  224. </Card>
  225. {/* SMTP Config + Test SMTP side-by-side on lg+ */}
  226. <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
  227. <div className="lg:col-span-2">
  228. <Card id="card-smtp-config">
  229. <CardHeader>
  230. <h2 className="text-lg font-semibold text-white">
  231. {t('settings.email.smtpSettings') || 'SMTP Configuration'}
  232. </h2>
  233. </CardHeader>
  234. <CardContent>
  235. <div className="space-y-3">
  236. {/* Authentication - at the top */}
  237. <div>
  238. <label className="block text-sm font-medium text-white mb-1">
  239. {t('settings.email.authentication') || 'Authentication'}
  240. </label>
  241. <select
  242. value={smtpSettings.smtp_auth_enabled ? 'true' : 'false'}
  243. onChange={(e) => handleAuthChange(e.target.value === 'true')}
  244. className={inputClasses}
  245. >
  246. <option value="true">{t('settings.email.authOptions.enabled')}</option>
  247. <option value="false">{t('settings.email.authOptions.disabled')}</option>
  248. </select>
  249. </div>
  250. {/* Username / Password - dimmed when auth disabled */}
  251. <div className={`grid grid-cols-1 md:grid-cols-2 gap-4 transition-opacity ${!smtpSettings.smtp_auth_enabled ? 'opacity-40 pointer-events-none' : ''}`}>
  252. <div>
  253. <label className="block text-sm font-medium text-white mb-1">
  254. {t('settings.email.username') || 'Username'}
  255. </label>
  256. <input
  257. type="text"
  258. value={smtpSettings.smtp_username || ''}
  259. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_username: e.target.value })}
  260. placeholder="your.email@gmail.com"
  261. disabled={!smtpSettings.smtp_auth_enabled}
  262. className={smtpSettings.smtp_auth_enabled ? inputClasses : disabledInputClasses}
  263. />
  264. </div>
  265. <div>
  266. <label className="block text-sm font-medium text-white mb-1">
  267. {t('settings.email.password') || 'Password'}
  268. </label>
  269. <input
  270. type="password"
  271. value={smtpSettings.smtp_password || ''}
  272. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_password: e.target.value })}
  273. placeholder={existingSettings ? '••••••••' : 'App password'}
  274. disabled={!smtpSettings.smtp_auth_enabled}
  275. className={smtpSettings.smtp_auth_enabled ? inputClasses : disabledInputClasses}
  276. />
  277. </div>
  278. </div>
  279. {/* SMTP Server / Port */}
  280. <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
  281. <div>
  282. <label className="block text-sm font-medium text-white mb-1">
  283. {t('settings.email.smtpHost') || 'SMTP Server'} *
  284. </label>
  285. <input
  286. type="text"
  287. value={smtpSettings.smtp_host}
  288. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_host: e.target.value })}
  289. placeholder="smtp.gmail.com"
  290. className={inputClasses}
  291. />
  292. </div>
  293. <div>
  294. <label className="block text-sm font-medium text-white mb-1">
  295. {t('settings.email.smtpPort') || 'SMTP Port'}
  296. </label>
  297. <input
  298. type="number"
  299. value={smtpSettings.smtp_port}
  300. onChange={(e) => handlePortChange(parseInt(e.target.value) || 587)}
  301. placeholder="587"
  302. className={inputClasses}
  303. />
  304. </div>
  305. </div>
  306. {/* Security */}
  307. <div>
  308. <label className="block text-sm font-medium text-white mb-1">
  309. {t('settings.email.security') || 'Security'}
  310. </label>
  311. <select
  312. value={smtpSettings.smtp_security}
  313. onChange={(e) => handleSecurityChange(e.target.value as 'starttls' | 'ssl' | 'none')}
  314. className={inputClasses}
  315. >
  316. <option value="starttls">{t('settings.email.securityOptions.starttls')}</option>
  317. <option value="ssl">{t('settings.email.securityOptions.ssl')}</option>
  318. <option value="none">{t('settings.email.securityOptions.none')}</option>
  319. </select>
  320. </div>
  321. {/* From Email / Name */}
  322. <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
  323. <div>
  324. <label className="block text-sm font-medium text-white mb-1">
  325. {t('settings.email.fromEmail') || 'From Email'} *
  326. </label>
  327. <input
  328. type="email"
  329. value={smtpSettings.smtp_from_email}
  330. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_from_email: e.target.value })}
  331. placeholder="your@email.com"
  332. className={inputClasses}
  333. />
  334. </div>
  335. <div>
  336. <label className="block text-sm font-medium text-white mb-1">
  337. {t('settings.email.fromName') || 'From Name'}
  338. </label>
  339. <input
  340. type="text"
  341. value={smtpSettings.smtp_from_name}
  342. onChange={(e) => setSMTPSettings({ ...smtpSettings, smtp_from_name: e.target.value })}
  343. placeholder="BamBuddy"
  344. className={inputClasses}
  345. />
  346. </div>
  347. </div>
  348. <div className="flex gap-2">
  349. <Button
  350. onClick={handleSave}
  351. disabled={saveMutation.isPending}
  352. className="flex-1"
  353. >
  354. {saveMutation.isPending ? (
  355. <>
  356. <Loader2 className="w-4 h-4 animate-spin" />
  357. {t('settings.email.saving') || 'Saving...'}
  358. </>
  359. ) : (
  360. t('settings.email.save') || 'Save Settings'
  361. )}
  362. </Button>
  363. </div>
  364. </div>
  365. </CardContent>
  366. </Card>
  367. </div>
  368. {/* Test SMTP */}
  369. <div>
  370. <Card id="card-email-test">
  371. <CardHeader>
  372. <h2 className="text-lg font-semibold text-white">
  373. {t('settings.email.testConnection') || 'Test SMTP Connection'}
  374. </h2>
  375. </CardHeader>
  376. <CardContent>
  377. <div className="space-y-3">
  378. <div>
  379. <label className="block text-sm font-medium text-white mb-1">
  380. {t('settings.email.testRecipient') || 'Test Recipient Email'}
  381. </label>
  382. <input
  383. type="email"
  384. value={testEmail}
  385. onChange={(e) => setTestEmail(e.target.value)}
  386. placeholder="test@example.com"
  387. className={inputClasses}
  388. />
  389. </div>
  390. <Button
  391. onClick={handleTest}
  392. disabled={testMutation.isPending}
  393. variant="secondary"
  394. >
  395. {testMutation.isPending ? (
  396. <>
  397. <Loader2 className="w-4 h-4 animate-spin" />
  398. {t('settings.email.sending') || 'Sending...'}
  399. </>
  400. ) : (
  401. <>
  402. <Send className="w-4 h-4" />
  403. {t('settings.email.sendTest') || 'Send Test Email'}
  404. </>
  405. )}
  406. </Button>
  407. </div>
  408. </CardContent>
  409. </Card>
  410. </div>
  411. </div>
  412. </div>
  413. );
  414. }