After improving the faq fonctionality management in adding the pdf upload2

This commit is contained in:
Your Name 2026-11-07 14:18:44 +02:00
parent 1ef445f3ee
commit ce03c55378
13 changed files with 512 additions and 121 deletions

View File

@ -4,6 +4,11 @@ import { FaqCategoryRow, FaqDocumentLang } from '../models/faq.model';
export declare function parseFaqDocumentLang(raw: string): FaqDocumentLang; export declare function parseFaqDocumentLang(raw: string): FaqDocumentLang;
/** Safe download filename for Content-Disposition. */ /** Safe download filename for Content-Disposition. */
export declare function sanitizeDownloadFilename(name: string, fallback?: string): string; export declare function sanitizeDownloadFilename(name: string, fallback?: string): string;
/**
* Public download name: `guide_<category>_<lang>.pdf`
* Uses the category slug when available so users immediately see topic + language.
*/
export declare function buildFaqCategoryGuideFilename(slugOrName: string, lang: FaqDocumentLang): string;
declare function mapCategory(row: FaqCategoryRow): { declare function mapCategory(row: FaqCategoryRow): {
id: number; id: number;
slug: string; slug: string;

View File

@ -1 +1 @@
{"version":3,"file":"faqService.d.ts","sourceRoot":"","sources":["../../src/services/faqService.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAuBtE,sDAAsD;AACtD,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,eAAe,CAGjE;AAED,sDAAsD;AACtD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,SAAc,GAAG,MAAM,CAIrF;AAeD,iBAAS,WAAW,CAAC,GAAG,EAAE,cAAc;;;;;;;;;;;;;;;;;EAavC;AA8BD,wBAAgB,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAMnE;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,C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U,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;;;;;;;;;;;;;;;;;;KAGA;AAED,wBAAsB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;;;;GAuBjF;AAED,wBAAsB,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;;;;GAc7F;AAED,wBAAsB,cAAc,CAAC,EAAE,EAAE,MAAM;;GAI9C;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI3D;AAED;;;GAGG;AACH,wBAAsB,sBAAsB,CAAC,KAAK,EAAE;IAClD,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,eAAe,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;CAClB,GAAG,OAAO,CAAC,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC,CA4C1C;AAED,wBAAsB,sBAAsB,CAAC,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,eAAe;;;;;;;;;;;;;;;;;GAKrF;AAED,iEAAiE;AACjE,wBAAsB,6BAA6B,CACjD,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,eAAe,GACpB,OAAO,CAAC;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAY5D"}

View File

@ -38,6 +38,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFaqDocumentLang = parseFaqDocumentLang; exports.parseFaqDocumentLang = parseFaqDocumentLang;
exports.sanitizeDownloadFilename = sanitizeDownloadFilename; exports.sanitizeDownloadFilename = sanitizeDownloadFilename;
exports.buildFaqCategoryGuideFilename = buildFaqCategoryGuideFilename;
exports.buildVoterKey = buildVoterKey; exports.buildVoterKey = buildVoterKey;
exports.publicFaqFileUrl = publicFaqFileUrl; exports.publicFaqFileUrl = publicFaqFileUrl;
exports.resolveFaqFilePath = resolveFaqFilePath; exports.resolveFaqFilePath = resolveFaqFilePath;
@ -94,11 +95,21 @@ function sanitizeDownloadFilename(name, fallback = 'guide.pdf') {
return fallback; return fallback;
return base.toLowerCase().endsWith('.pdf') ? base : `${base}.pdf`; return base.toLowerCase().endsWith('.pdf') ? base : `${base}.pdf`;
} }
function mapPdfMeta(lang, slug, filename, originalName) { /**
* Public download name: `guide_<category>_<lang>.pdf`
* Uses the category slug when available so users immediately see topic + language.
*/
function buildFaqCategoryGuideFilename(slugOrName, lang) {
const raw = slugify(slugOrName) || 'category';
const token = raw.replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'category';
return `guide_${token}_${lang}.pdf`;
}
function mapPdfMeta(lang, slug, filename, _originalName) {
if (!filename) if (!filename)
return null; return null;
return { return {
originalName: originalName || filename, // Display / download label always reflects category + language.
originalName: buildFaqCategoryGuideFilename(slug, lang),
url: `/api/v1/faq/categories/${encodeURIComponent(slug)}/documents/${lang}`, url: `/api/v1/faq/categories/${encodeURIComponent(slug)}/documents/${lang}`,
}; };
} }
@ -347,7 +358,8 @@ async function uploadCategoryDocument(input) {
throw e; throw e;
} }
const previous = input.lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename; const previous = input.lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename;
const originalName = sanitizeDownloadFilename(input.originalName); // Prefer a clear guide name over the uploader's original filename.
const originalName = buildFaqCategoryGuideFilename(cat.slug || cat.name, input.lang);
const updated = await repo.setCategoryDocument(input.categoryId, input.lang, path_1.default.basename(input.storedFilename), originalName); const updated = await repo.setCategoryDocument(input.categoryId, input.lang, path_1.default.basename(input.storedFilename), originalName);
if (!updated) { if (!updated) {
(0, fileMagic_1.removeUploadedFile)(filePath); (0, fileMagic_1.removeUploadedFile)(filePath);
@ -372,15 +384,15 @@ async function resolvePublicCategoryDocument(slug, lang) {
if (!cat || !cat.is_active) if (!cat || !cat.is_active)
return null; return null;
const filename = lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename; const filename = lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename;
const originalName = lang === 'fr' ? cat.pdf_fr_original_name : cat.pdf_en_original_name;
if (!filename) if (!filename)
return null; return null;
const filePath = readFaqFile(filename); const filePath = readFaqFile(filename);
if (!filePath) if (!filePath)
return null; return null;
// Always derive from current category + language (survives rename / old uploads).
return { return {
filePath, filePath,
downloadName: sanitizeDownloadFilename(originalName || filename), downloadName: buildFaqCategoryGuideFilename(cat.slug || cat.name, lang),
}; };
} }
//# sourceMappingURL=faqService.js.map //# sourceMappingURL=faqService.js.map

File diff suppressed because one or more lines are too long

View File

@ -39,15 +39,29 @@ export function sanitizeDownloadFilename(name: string, fallback = 'guide.pdf'):
return base.toLowerCase().endsWith('.pdf') ? base : `${base}.pdf`; return base.toLowerCase().endsWith('.pdf') ? base : `${base}.pdf`;
} }
/**
* Public download name: `guide_<category>_<lang>.pdf`
* Uses the category slug when available so users immediately see topic + language.
*/
export function buildFaqCategoryGuideFilename(
slugOrName: string,
lang: FaqDocumentLang
): string {
const raw = slugify(slugOrName) || 'category';
const token = raw.replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'category';
return `guide_${token}_${lang}.pdf`;
}
function mapPdfMeta( function mapPdfMeta(
lang: FaqDocumentLang, lang: FaqDocumentLang,
slug: string, slug: string,
filename: string | null, filename: string | null,
originalName: string | null _originalName: string | null
) { ) {
if (!filename) return null; if (!filename) return null;
return { return {
originalName: originalName || filename, // Display / download label always reflects category + language.
originalName: buildFaqCategoryGuideFilename(slug, lang),
url: `/api/v1/faq/categories/${encodeURIComponent(slug)}/documents/${lang}`, url: `/api/v1/faq/categories/${encodeURIComponent(slug)}/documents/${lang}`,
}; };
} }
@ -320,7 +334,8 @@ export async function uploadCategoryDocument(input: {
const previous = const previous =
input.lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename; input.lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename;
const originalName = sanitizeDownloadFilename(input.originalName); // Prefer a clear guide name over the uploader's original filename.
const originalName = buildFaqCategoryGuideFilename(cat.slug || cat.name, input.lang);
const updated = await repo.setCategoryDocument( const updated = await repo.setCategoryDocument(
input.categoryId, input.categoryId,
@ -357,13 +372,12 @@ export async function resolvePublicCategoryDocument(
const cat = await repo.getCategoryBySlug(slug); const cat = await repo.getCategoryBySlug(slug);
if (!cat || !cat.is_active) return null; if (!cat || !cat.is_active) return null;
const filename = lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename; const filename = lang === 'fr' ? cat.pdf_fr_filename : cat.pdf_en_filename;
const originalName =
lang === 'fr' ? cat.pdf_fr_original_name : cat.pdf_en_original_name;
if (!filename) return null; if (!filename) return null;
const filePath = readFaqFile(filename); const filePath = readFaqFile(filename);
if (!filePath) return null; if (!filePath) return null;
// Always derive from current category + language (survives rename / old uploads).
return { return {
filePath, filePath,
downloadName: sanitizeDownloadFilename(originalName || filename), downloadName: buildFaqCategoryGuideFilename(cat.slug || cat.name, lang),
}; };
} }

View File

@ -4,6 +4,7 @@ import fs from 'fs';
import os from 'os'; import os from 'os';
import path from 'path'; import path from 'path';
import { import {
buildFaqCategoryGuideFilename,
parseFaqDocumentLang, parseFaqDocumentLang,
sanitizeDownloadFilename, sanitizeDownloadFilename,
} from '../services/faqService'; } from '../services/faqService';
@ -25,6 +26,13 @@ describe('faq category document helpers', () => {
assert.equal(sanitizeDownloadFilename(''), 'guide.pdf'); assert.equal(sanitizeDownloadFilename(''), 'guide.pdf');
}); });
test('buildFaqCategoryGuideFilename encodes category + language', () => {
assert.equal(buildFaqCategoryGuideFilename('account', 'fr'), 'guide_account_fr.pdf');
assert.equal(buildFaqCategoryGuideFilename('account', 'en'), 'guide_account_en.pdf');
assert.equal(buildFaqCategoryGuideFilename('Compte', 'fr'), 'guide_compte_fr.pdf');
assert.equal(buildFaqCategoryGuideFilename('Dépôts', 'en'), 'guide_depots_en.pdf');
});
test('PDF allowlist is PDF-only', () => { test('PDF allowlist is PDF-only', () => {
assert.equal(FAQ_PDF_ALLOWED_MIMES.size, 1); assert.equal(FAQ_PDF_ALLOWED_MIMES.size, 1);
assert.ok(FAQ_PDF_ALLOWED_MIMES.has('application/pdf')); assert.ok(FAQ_PDF_ALLOWED_MIMES.has('application/pdf'));

View File

@ -1,9 +1,70 @@
class FaqCategoryDocument {
const FaqCategoryDocument({
required this.originalName,
required this.url,
});
final String originalName;
final String url;
factory FaqCategoryDocument.fromJson(Map<String, dynamic>? json) {
if (json == null) {
return const FaqCategoryDocument(originalName: '', url: '');
}
return FaqCategoryDocument(
originalName: (json['originalName'] ?? '').toString(),
url: (json['url'] ?? '').toString(),
);
}
bool get isPresent => url.isNotEmpty;
}
class FaqCategoryModel {
const FaqCategoryModel({
required this.id,
required this.slug,
required this.name,
this.description,
this.pdfFr,
this.pdfEn,
});
final int id;
final String slug;
final String name;
final String? description;
final FaqCategoryDocument? pdfFr;
final FaqCategoryDocument? pdfEn;
bool get hasDownloads =>
(pdfFr?.isPresent ?? false) || (pdfEn?.isPresent ?? false);
factory FaqCategoryModel.fromJson(Map<String, dynamic> json) {
FaqCategoryDocument? parseDoc(dynamic raw) {
if (raw is! Map<String, dynamic>) return null;
final doc = FaqCategoryDocument.fromJson(raw);
return doc.isPresent ? doc : null;
}
return FaqCategoryModel(
id: _asInt(json['id']),
slug: (json['slug'] ?? '').toString(),
name: (json['name'] ?? '').toString(),
description: json['description']?.toString(),
pdfFr: parseDoc(json['pdfFr']),
pdfEn: parseDoc(json['pdfEn']),
);
}
}
class FaqEntryModel { class FaqEntryModel {
const FaqEntryModel({ const FaqEntryModel({
required this.id, required this.id,
required this.question, required this.question,
required this.answer, required this.answer,
required this.category, required this.category,
this.categorySlug = '',
this.viewCount = 0, this.viewCount = 0,
}); });
@ -11,6 +72,7 @@ class FaqEntryModel {
final String question; final String question;
final String answer; final String answer;
final String category; final String category;
final String categorySlug;
final int viewCount; final int viewCount;
factory FaqEntryModel.fromJson(Map<String, dynamic> json) { factory FaqEntryModel.fromJson(Map<String, dynamic> json) {
@ -27,6 +89,7 @@ class FaqEntryModel {
json['categorySlug'] ?? json['categorySlug'] ??
'') '')
.toString(), .toString(),
categorySlug: (json['categorySlug'] ?? '').toString(),
viewCount: _asInt(json['viewCount']), viewCount: _asInt(json['viewCount']),
); );
} }

View File

@ -14,6 +14,10 @@ class FaqListStore {
String? _inFlightKey; String? _inFlightKey;
int fetchStarts = 0; int fetchStarts = 0;
List<FaqCategoryModel>? categoriesCached;
DateTime? categoriesCachedAt;
Future<List<FaqCategoryModel>>? categoriesInFlight;
String keyFor({String? search, String? category}) => String keyFor({String? search, String? category}) =>
'${category ?? ''}|${search ?? ''}'; '${category ?? ''}|${search ?? ''}';
@ -23,6 +27,8 @@ class FaqListStore {
void invalidate() { void invalidate() {
_cached.clear(); _cached.clear();
_cachedAt.clear(); _cachedAt.clear();
categoriesCached = null;
categoriesCachedAt = null;
} }
Future<List<FaqEntryModel>> get( Future<List<FaqEntryModel>> get(
@ -59,6 +65,37 @@ class FaqListStore {
} }
} }
} }
Future<List<FaqCategoryModel>> getCategories(
Future<List<FaqCategoryModel>> Function() fetch, {
bool force = false,
}) async {
if (!force) {
final cached = categoriesCached;
final at = categoriesCachedAt;
if (cached != null &&
at != null &&
DateTime.now().difference(at) < ttl) {
return cached;
}
if (categoriesInFlight != null) return categoriesInFlight!;
} else if (categoriesInFlight != null) {
return categoriesInFlight!;
}
final future = fetch().then((value) {
categoriesCached = value;
categoriesCachedAt = DateTime.now();
return value;
});
categoriesInFlight = future;
try {
return await future;
} finally {
if (identical(categoriesInFlight, future)) {
categoriesInFlight = null;
}
}
}
} }
class FaqRepositoryImpl implements FaqRepository { class FaqRepositoryImpl implements FaqRepository {
@ -71,6 +108,9 @@ class FaqRepositoryImpl implements FaqRepository {
List<FaqEntryModel>? peekLast({String? search, String? category}) => List<FaqEntryModel>? peekLast({String? search, String? category}) =>
store.peekLast(search: search, category: category); store.peekLast(search: search, category: category);
@override
List<FaqCategoryModel>? peekCategories() => store.categoriesCached;
@override @override
void invalidate() => store.invalidate(); void invalidate() => store.invalidate();
@ -102,4 +142,23 @@ class FaqRepositoryImpl implements FaqRepository {
force: force, force: force,
); );
} }
@override
Future<List<FaqCategoryModel>> listCategories({bool force = false}) {
return store.getCategories(
() async {
try {
final res = await _api.dio.get<Map<String, dynamic>>(
'/api/v1/faq/categories',
);
return (res.data?['items'] as List<dynamic>? ?? [])
.map((e) => FaqCategoryModel.fromJson(e as Map<String, dynamic>))
.toList();
} on DioException catch (e) {
throw AppException.fromDio(e, fallback: 'Failed to load FAQ categories');
}
},
force: force,
);
}
} }

View File

@ -7,7 +7,11 @@ abstract class FaqRepository {
bool force = false, bool force = false,
}); });
Future<List<FaqCategoryModel>> listCategories({bool force = false});
List<FaqEntryModel>? peekLast({String? search, String? category}); List<FaqEntryModel>? peekLast({String? search, String? category});
List<FaqCategoryModel>? peekCategories();
void invalidate(); void invalidate();
} }

View File

@ -1,8 +1,12 @@
/// Help presentation: searchable FAQ list with expandable answers. /// Help presentation: searchable FAQ list with category filters + PDF guides.
library; library;
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../core/config/app_config.dart';
import '../../../core/di/injection.dart'; import '../../../core/di/injection.dart';
import '../../../core/errors/app_exception.dart'; import '../../../core/errors/app_exception.dart';
import '../../../core/theme/app_colors.dart'; import '../../../core/theme/app_colors.dart';
@ -18,7 +22,7 @@ import '../../welcome/utils/welcome_navigation.dart';
class FaqScreen extends StatefulWidget { class FaqScreen extends StatefulWidget {
const FaqScreen({super.key, this.initialCategory}); const FaqScreen({super.key, this.initialCategory});
/// Optional FAQ category slug (e.g. `game`) from `/faq?category=...`. /// Optional FAQ category slug (e.g. `predictions`) from `/faq?category=...`.
final String? initialCategory; final String? initialCategory;
@override @override
@ -28,7 +32,10 @@ class FaqScreen extends StatefulWidget {
class _FaqScreenState extends State<FaqScreen> { class _FaqScreenState extends State<FaqScreen> {
final _repo = sl<FaqRepository>(); final _repo = sl<FaqRepository>();
final _searchController = TextEditingController(); final _searchController = TextEditingController();
Timer? _searchDebounce;
List<FaqEntryModel> _entries = []; List<FaqEntryModel> _entries = [];
List<FaqCategoryModel> _categories = [];
String? _selectedCategory;
bool _loading = true; bool _loading = true;
bool _searching = false; bool _searching = false;
bool _retrying = false; bool _retrying = false;
@ -41,19 +48,62 @@ class _FaqScreenState extends State<FaqScreen> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_searchController.addListener(() { _selectedCategory = widget.initialCategory;
if (mounted) setState(() {}); _searchController.addListener(_onSearchTextChanged);
}); final cachedCats = _repo.peekCategories();
final cached = _repo.peekLast(category: widget.initialCategory); if (cachedCats != null && cachedCats.isNotEmpty) {
_categories = cachedCats;
}
final cached = _repo.peekLast(category: _selectedCategory);
if (cached != null && cached.isNotEmpty) { if (cached != null && cached.isNotEmpty) {
_entries = cached; _entries = cached;
_loading = false; _loading = false;
} }
_load(category: widget.initialCategory); _bootstrap();
}
Future<void> _bootstrap({bool force = false}) async {
try {
final cats = await _repo.listCategories(force: force);
if (!mounted) return;
setState(() => _categories = cats);
} catch (_) {
// Soft-fail categories: entries can still load.
}
await _load(
search: _normalizedSearch(_searchController.text),
category: _selectedCategory,
force: force,
);
}
String? _normalizedSearch(String raw) {
final q = raw.trim();
return q.isEmpty ? null : q;
}
void _onSearchTextChanged() {
if (!mounted) return;
setState(() {}); // refresh clear icon
_searchDebounce?.cancel();
_searchDebounce = Timer(const Duration(milliseconds: 350), () {
if (!mounted) return;
final next = _normalizedSearch(_searchController.text);
if (next == _activeSearch) return;
_load(search: next, category: _selectedCategory, force: true);
});
}
void _submitSearch([String? raw]) {
_searchDebounce?.cancel();
final next = _normalizedSearch(raw ?? _searchController.text);
_load(search: next, category: _selectedCategory, force: true);
} }
@override @override
void dispose() { void dispose() {
_searchDebounce?.cancel();
_searchController.removeListener(_onSearchTextChanged);
_searchController.dispose(); _searchController.dispose();
super.dispose(); super.dispose();
} }
@ -63,9 +113,8 @@ class _FaqScreenState extends State<FaqScreen> {
String? category, String? category,
bool force = false, bool force = false,
}) { }) {
final cat = category ?? widget.initialCategory; final cat = category;
final key = '${cat ?? ''}|${search ?? ''}'; final key = '${cat ?? ''}|${search ?? ''}';
// Coalesce only identical in-flight queries (retry spam); new searches proceed.
if (_sameKeyInFlight != null && _sameKey == key) return _sameKeyInFlight!; if (_sameKeyInFlight != null && _sameKey == key) return _sameKeyInFlight!;
final gen = ++_loadGen; final gen = ++_loadGen;
@ -119,8 +168,61 @@ class _FaqScreenState extends State<FaqScreen> {
} }
void _clearSearch() { void _clearSearch() {
_searchDebounce?.cancel();
_searchController.clear(); _searchController.clear();
_load(category: widget.initialCategory, force: true); _load(search: null, category: _selectedCategory, force: true);
}
void _selectCategory(String? slug) {
if (_selectedCategory == slug) return;
setState(() => _selectedCategory = slug);
_load(
search: _normalizedSearch(_searchController.text),
category: slug,
force: true,
);
}
FaqCategoryModel? get _activeCategoryModel {
final slug = _selectedCategory;
if (slug == null) return null;
for (final c in _categories) {
if (c.slug == slug) return c;
}
return null;
}
Future<void> _openPdf(FaqCategoryDocument doc) async {
final base = sl<AppConfig>().apiBaseUrl.replaceAll(RegExp(r'/$'), '');
final path = doc.url.startsWith('/') ? doc.url : '/${doc.url}';
final uri = Uri.parse('$base$path');
final ok = await launchUrl(uri, mode: LaunchMode.externalApplication);
if (!ok && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(context.strings.faqPdfOpenFailed)),
);
}
}
String _categoryLabel(AppStrings s, FaqCategoryModel cat) {
switch (cat.slug) {
case 'account':
return s.faqCatAccount;
case 'deposits':
return s.faqCatDeposits;
case 'withdrawals':
return s.faqCatWithdrawals;
case 'predictions':
return s.faqCatPredictions;
case 'referral':
return s.faqCatReferral;
case 'bonus':
return s.faqCatBonus;
case 'security':
return s.faqCatSecurity;
default:
return cat.name;
}
} }
@override @override
@ -141,6 +243,7 @@ class _FaqScreenState extends State<FaqScreen> {
20, 20,
24 + bottomInset + keyboardInset, 24 + bottomInset + keyboardInset,
); );
final activeCat = _activeCategoryModel;
return AnnotatedRegion<SystemUiOverlayStyle>( return AnnotatedRegion<SystemUiOverlayStyle>(
value: TlotoGradientAppBar.overlayStyle, value: TlotoGradientAppBar.overlayStyle,
@ -174,14 +277,33 @@ class _FaqScreenState extends State<FaqScreen> {
) )
: null, : null,
), ),
onSubmitted: (q) => _load( onSubmitted: _submitSearch,
search: q.trim().isEmpty ? null : q.trim(),
category: widget.initialCategory,
force: true,
),
), ),
), ),
), ),
if (_categories.isNotEmpty)
Padding(
key: const Key('faq_category_chips'),
padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
ChoiceChip(
label: Text(s.faqAllCategories),
selected: _selectedCategory == null,
onSelected: (_) => _selectCategory(null),
),
..._categories.map(
(cat) => ChoiceChip(
label: Text(_categoryLabel(s, cat)),
selected: _selectedCategory == cat.slug,
onSelected: (_) => _selectCategory(cat.slug),
),
),
],
),
),
if (_searching) if (_searching)
const LinearProgressIndicator( const LinearProgressIndicator(
minHeight: 2, minHeight: 2,
@ -189,11 +311,7 @@ class _FaqScreenState extends State<FaqScreen> {
), ),
Expanded( Expanded(
child: RefreshIndicator( child: RefreshIndicator(
onRefresh: () => _load( onRefresh: () => _bootstrap(force: true),
search: _activeSearch,
category: widget.initialCategory,
force: true,
),
child: _error != null && _entries.isEmpty child: _error != null && _entries.isEmpty
? ListView( ? ListView(
physics: physics, physics: physics,
@ -202,11 +320,7 @@ class _FaqScreenState extends State<FaqScreen> {
SectionError( SectionError(
message: _error!, message: _error!,
retrying: _retrying, retrying: _retrying,
onRetry: () => _load( onRetry: () => _bootstrap(force: true),
search: _activeSearch,
category: widget.initialCategory,
force: true,
),
), ),
], ],
) )
@ -222,97 +336,108 @@ class _FaqScreenState extends State<FaqScreen> {
PredSkeletonCard(height: 72), PredSkeletonCard(height: 72),
], ],
) )
: _entries.isEmpty : ListView(
? ListView( physics: physics,
physics: physics, padding: listPadding,
padding: EdgeInsets.fromLTRB( children: [
40, if (activeCat != null && activeCat.hasDownloads)
40, _FaqDownloadsCard(
40, category: activeCat,
40 + bottomInset, onOpenFr: activeCat.pdfFr != null
? () => _openPdf(activeCat.pdfFr!)
: null,
onOpenEn: activeCat.pdfEn != null
? () => _openPdf(activeCat.pdfEn!)
: null,
), ),
children: [ if (activeCat != null && activeCat.hasDownloads)
Icon( const SizedBox(height: 14),
Icons.help_outline_rounded, if (_entries.isEmpty)
size: 48, Padding(
color: muted, padding: const EdgeInsets.only(top: 32),
), child: Column(
const SizedBox(height: 12), children: [
Text( Icon(
s.noFaqResults, Icons.help_outline_rounded,
textAlign: TextAlign.center, size: 48,
style: Theme.of(context) color: muted,
.textTheme
.bodyMedium
?.copyWith(color: secondary),
),
],
)
: ListView.separated(
physics: physics,
padding: listPadding,
itemCount: _entries.length,
separatorBuilder: (_, __) =>
const SizedBox(height: 8),
itemBuilder: (context, index) {
final entry = _entries[index];
return PredCard(
padding: EdgeInsets.zero,
child: Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
), ),
child: ExpansionTile( const SizedBox(height: 12),
tilePadding: const EdgeInsets.symmetric( Text(
horizontal: 14, s.noFaqResults,
vertical: 2, textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(color: secondary),
),
],
),
)
else
..._entries.map(
(entry) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: PredCard(
padding: EdgeInsets.zero,
child: Theme(
data: Theme.of(context).copyWith(
dividerColor: Colors.transparent,
), ),
childrenPadding: child: ExpansionTile(
const EdgeInsets.fromLTRB( tilePadding:
14, const EdgeInsets.symmetric(
0, horizontal: 14,
14, vertical: 2,
14, ),
), childrenPadding:
title: Text( const EdgeInsets.fromLTRB(
entry.question, 14,
style: Theme.of(context) 0,
.textTheme 14,
.titleSmall 14,
?.copyWith( ),
fontWeight: FontWeight.w700, title: Text(
), entry.question,
), style: Theme.of(context)
subtitle: entry.category.isNotEmpty .textTheme
? Text( .titleSmall
entry.category, ?.copyWith(
fontWeight: FontWeight.w700,
),
),
subtitle: entry.category.isNotEmpty
? Text(
entry.category,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: muted,
),
)
: null,
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
entry.answer,
style: Theme.of(context) style: Theme.of(context)
.textTheme .textTheme
.bodySmall .bodyMedium
?.copyWith( ?.copyWith(
color: muted, color: secondary,
), ),
) ),
: null,
children: [
Align(
alignment: Alignment.centerLeft,
child: Text(
entry.answer,
style: Theme.of(context)
.textTheme
.bodyMedium
?.copyWith(
color: secondary,
),
), ),
), ],
], ),
), ),
), ),
); ),
}, ),
), ],
),
), ),
), ),
], ],
@ -321,3 +446,74 @@ class _FaqScreenState extends State<FaqScreen> {
); );
} }
} }
class _FaqDownloadsCard extends StatelessWidget {
const _FaqDownloadsCard({
required this.category,
this.onOpenFr,
this.onOpenEn,
});
final FaqCategoryModel category;
final VoidCallback? onOpenFr;
final VoidCallback? onOpenEn;
@override
Widget build(BuildContext context) {
final s = context.strings;
final isDark = Theme.of(context).brightness == Brightness.dark;
final desc = category.description?.trim();
return PredCard(
key: const Key('faq_downloads_card'),
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
s.faqDownloadsTitle,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
),
),
if (desc != null && desc.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
desc,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: isDark
? AppColors.textSecondary
: const Color(0xFF475569),
),
),
],
const SizedBox(height: 12),
if (onOpenFr != null)
SizedBox(
width: double.infinity,
child: FilledButton.icon(
key: const Key('faq_download_fr'),
onPressed: onOpenFr,
icon: const Icon(Icons.picture_as_pdf_rounded, size: 18),
label: Text(s.faqDownloadFr),
),
),
if (onOpenFr != null && onOpenEn != null) const SizedBox(height: 8),
if (onOpenEn != null)
SizedBox(
width: double.infinity,
child: FilledButton.tonalIcon(
key: const Key('faq_download_en'),
onPressed: onOpenEn,
icon: const Icon(Icons.picture_as_pdf_rounded, size: 18),
style: FilledButton.styleFrom(
foregroundColor: AppColors.primary,
backgroundColor: AppColors.primary.withValues(alpha: 0.18),
),
label: Text(s.faqDownloadEn),
),
),
],
),
);
}
}

View File

@ -776,6 +776,21 @@ class AppStrings {
String get faqTitle => t('Help & FAQ', 'Aide & FAQ'); String get faqTitle => t('Help & FAQ', 'Aide & FAQ');
String get searchFaq => t('Search FAQ…', 'Rechercher dans la FAQ…'); String get searchFaq => t('Search FAQ…', 'Rechercher dans la FAQ…');
String get noFaqResults => t('No FAQ entries found', 'Aucune entrée FAQ'); String get noFaqResults => t('No FAQ entries found', 'Aucune entrée FAQ');
String get faqAllCategories => t('All', 'Toutes');
String get faqDownloadsTitle => t('Guides to download', 'Guides à télécharger');
String get faqDownloadFr =>
t('Download the guide in French (PDF)', 'Télécharger le guide en français (PDF)');
String get faqDownloadEn =>
t('Download the guide in English (PDF)', 'Télécharger le guide en anglais (PDF)');
String get faqPdfOpenFailed =>
t('Could not open the PDF. Please try again.', 'Impossible d’ouvrir le PDF. Réessayez.');
String get faqCatAccount => t('Account', 'Compte');
String get faqCatDeposits => t('Deposits', 'Dépôts');
String get faqCatWithdrawals => t('Withdrawals', 'Retraits');
String get faqCatPredictions => t('Predictions', 'Prédictions');
String get faqCatReferral => t('Referrals', 'Parrainage');
String get faqCatBonus => t('Bonuses', 'Bonus');
String get faqCatSecurity => t('Security', 'Sécurité');
// Admin / network // Admin / network
String get networkStatus => t('Network status', 'État du réseau'); String get networkStatus => t('Network status', 'État du réseau');

View File

@ -61,6 +61,13 @@ class _ControllableFaq implements FaqRepository {
} }
return cached ?? const [_sample]; return cached ?? const [_sample];
} }
@override
List<FaqCategoryModel>? peekCategories() => const [];
@override
Future<List<FaqCategoryModel>> listCategories({bool force = false}) async =>
const [];
} }
Future<void> _boot(FaqRepository faq) async { Future<void> _boot(FaqRepository faq) async {
@ -158,11 +165,12 @@ void main() {
faq.hold = searchHold; faq.hold = searchHold;
await tester.enterText(find.byKey(const Key('faq_search')), 'wallet'); await tester.enterText(find.byKey(const Key('faq_search')), 'wallet');
await tester.testTextInput.receiveAction(TextInputAction.done); // Debounced search (~350ms) should fire without requiring the keyboard submit.
await tester.pump(); await tester.pump(const Duration(milliseconds: 400));
expect(find.text('How do predictions work?'), findsOneWidget); expect(find.text('How do predictions work?'), findsOneWidget);
expect(find.byType(LinearProgressIndicator), findsOneWidget); expect(find.byType(LinearProgressIndicator), findsOneWidget);
expect(faq.lastSearch, 'wallet');
searchHold.complete(const [ searchHold.complete(const [
FaqEntryModel( FaqEntryModel(

View File

@ -439,6 +439,9 @@ class FakeFaqRepository implements FaqRepository {
@override @override
List<FaqEntryModel>? peekLast({String? search, String? category}) => null; List<FaqEntryModel>? peekLast({String? search, String? category}) => null;
@override
List<FaqCategoryModel>? peekCategories() => null;
@override @override
void invalidate() {} void invalidate() {}
@ -456,6 +459,10 @@ class FakeFaqRepository implements FaqRepository {
category: 'game', category: 'game',
), ),
]; ];
@override
Future<List<FaqCategoryModel>> listCategories({bool force = false}) async =>
const [];
} }
class FakeAdvertisementRepository implements AdvertisementRepository { class FakeAdvertisementRepository implements AdvertisementRepository {