QA hardening: security RLS fixes, Flutter 3.47.5 upgrade, UI/validation fixes

Security — enforce write authorization server-side (was UI/RPC-only):
- it_service_requests RLS: block cross-office read/edit + self-approve (QA-015)
- pass_slips RLS: owner can complete but not self-approve (QA-046)
- swap_requests RLS: scope select/update to participants + admin (QA-047)
- storage: tighten it_service_attachments + task_attachments write/delete (QA-027)
- admin_user_management edge function: allow programmers to manage users (QA-016)

Fixes:
- workforce generator "uncovered shifts" false alarms (QA-043/044)
- network-map VLAN + New-location dialog validation, disabled-until-valid (QA-048)
- de-flake time-of-day-dependent dashboard metrics test (QA-045)

Toolchain:
- upgrade to Flutter 3.47.5 / Dart 3.13.4; font_awesome_flutter 11.0.0,
  flutter_quill 11.6.0, pdfrx 2.6.5; clear resulting deprecations (QA-002)

analyze clean; 139 tests pass; web build succeeds. Report + evidence in docs/qa/.

Note: also carries the in-progress Brick model cleanup already present in the
working tree. QA-001 (AI keys public in the build) is deferred by owner decision.

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
2026-09-26 11:52:16 +08:00
parent e49b52949c
commit 3cb980b629
125 changed files with 3420 additions and 2853 deletions
-144
View File
@@ -1,144 +0,0 @@
import 'dart:convert';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:google_generative_ai/google_generative_ai.dart';
import 'package:http/http.dart' as http;
class GeminiService {
static final GeminiService _instance = GeminiService._internal();
late final String _apiKey;
/// Cache of valid model IDs (flash/lite, supporting generateContent).
List<String> _validModels = [];
factory GeminiService() => _instance;
GeminiService._internal() {
final apiKey = dotenv.env['GEMINI_API_KEY'];
if (apiKey == null || apiKey.isEmpty) {
throw Exception('GEMINI_API_KEY not found in .env file');
}
_apiKey = apiKey;
}
// ---------------------------------------------------------------------------
// Model discovery
// ---------------------------------------------------------------------------
/// Queries the Gemini REST API for available models and caches those that
/// - support `generateContent`, AND
/// - contain "flash" or "lite" in their name (free-tier / fast models).
///
/// Returns a stable cached list on subsequent calls.
Future<List<String>> _getValidModels() async {
if (_validModels.isNotEmpty) return _validModels;
try {
final uri = Uri.parse(
'https://generativelanguage.googleapis.com/v1beta/models?key=$_apiKey',
);
final response = await http.get(uri);
if (response.statusCode == 200) {
final data = jsonDecode(response.body) as Map<String, dynamic>;
final rawModels = (data['models'] as List<dynamic>?) ?? [];
final discovered = <String>[];
for (final m in rawModels) {
final fullName = (m['name'] as String? ?? '');
final lower = fullName.toLowerCase();
final methods =
(m['supportedGenerationMethods'] as List<dynamic>?) ?? [];
if (methods.contains('generateContent') &&
(lower.contains('flash') || lower.contains('lite'))) {
// Strip the "models/" prefix so it can be passed directly to
// GenerativeModel(model: ...).
final id = fullName.startsWith('models/')
? fullName.substring('models/'.length)
: fullName;
discovered.add(id);
}
}
// Sort descending so newer/more-capable models are tried first.
discovered.sort((a, b) => b.compareTo(a));
_validModels = discovered;
}
} catch (_) {
// Fall back to hard-coded list of known free-tier models below.
}
// If discovery failed or returned nothing, use safe known fallbacks.
if (_validModels.isEmpty) {
_validModels = [
'gemini-2.5-flash-lite',
'gemini-2.5-flash',
'gemini-2.0-flash',
'gemini-1.5-flash',
];
}
return _validModels;
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/// Fixes spelling/grammar, improves clarity, and translates [text] to
/// professional English.
///
/// Provide a custom [promptInstruction] to give Gemini field-specific
/// context (subject, description, action-taken). If omitted a sensible
/// default is used.
///
/// Automatically retries with the next available model on 429 / quota
/// errors to minimise wasted quota calls.
Future<String> enhanceText(String text, {String? promptInstruction}) async {
if (text.trim().isEmpty) return text;
final instruction =
promptInstruction ??
'Fix spelling and grammar, improve clarity, and translate to '
'professional English. Return ONLY the improved text, no explanations:';
final prompt = '$instruction\n\n"$text"';
return _generateWithRetry(prompt, fallback: text);
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
/// Sends [prompt] to Gemini, retrying across all valid models on 429 errors.
/// Returns the model response on success, or throws if all models fail.
Future<String> _generateWithRetry(
String prompt, {
required String fallback,
}) async {
final models = await _getValidModels();
for (int i = 0; i < models.length; i++) {
try {
final model = GenerativeModel(model: models[i], apiKey: _apiKey);
final response = await model.generateContent([Content.text(prompt)]);
return response.text ?? fallback;
} catch (e) {
final msg = e.toString().toLowerCase();
final is429 =
msg.contains('429') ||
msg.contains('quota') ||
msg.contains('resource_exhausted');
if (!is429 || i == models.length - 1) {
// Non-quota error or last model — give up.
throw Exception('Gemini request failed: $e');
}
// Quota hit — try the next model.
}
}
// Should not reach here, but safety fallback.
throw Exception('All Gemini models exhausted');
}
}
+41 -26
View File
@@ -2,10 +2,28 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import '../models/notification_item.dart';
import '../models/notification_item.model.dart';
import '../providers/notifications_provider.dart';
import '../providers/notification_navigation_provider.dart';
import '../routing/app_router.dart';
import '../utils/snackbar.dart';
/// The newest unread item in [next] that wasn't in [prev], or null.
///
/// Returns null for the first snapshot ([prev] == null) so the existing inbox
/// doesn't raise a banner on startup. [next] is sorted newest-first.
@visibleForTesting
NotificationItem? newestArrival(
List<NotificationItem>? prev,
List<NotificationItem> next,
) {
if (prev == null) return null;
final seen = {for (final n in prev) n.id};
for (final n in next) {
if (n.isUnread && !seen.contains(n.id)) return n;
}
return null;
}
/// Wraps the app and installs both a Supabase realtime listener and the
/// FCM handlers described in the frontend design.
@@ -24,8 +42,8 @@ class NotificationBridge extends ConsumerStatefulWidget {
class _NotificationBridgeState extends ConsumerState<NotificationBridge>
with WidgetsBindingObserver {
// store previous notifications to diff
List<NotificationItem> _prevList = [];
// Last loaded snapshot to diff against; null until the inbox first loads.
List<NotificationItem>? _prevList;
@override
void initState() {
@@ -92,24 +110,25 @@ class _NotificationBridgeState extends ConsumerState<NotificationBridge>
};
void _showBanner(String type, NotificationItem item) {
// Use a post-frame callback so that the ScaffoldMessenger from
// MaterialApp is available in the element tree.
// This widget sits above TasqApp's MaterialApp.router, so
// ScaffoldMessenger.of(context) would resolve to a messenger with no
// Scaffold. Use the app-level messenger key instead.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
try {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(_bannerLabel(type)),
action: SnackBarAction(
label: 'View',
onPressed: () =>
_goToDetail(taskId: item.taskId, ticketId: item.ticketId),
scaffoldMessengerKey.currentState?.showSnackBar(
SnackBar(
content: Text(_bannerLabel(type)),
action: SnackBarAction(
label: 'View',
onPressed: () => _goToDetail(
route: item.announcementId != null ? '/announcements' : null,
taskId: item.taskId,
ticketId: item.ticketId,
itServiceRequestId: item.itServiceRequestId,
),
),
);
} catch (_) {
// ScaffoldMessenger not available yet (before first frame) — ignore.
}
),
);
});
}
@@ -163,16 +182,12 @@ class _NotificationBridgeState extends ConsumerState<NotificationBridge>
previous,
next,
) {
final prevList = _prevList;
final nextList = next.maybeWhen(
data: (d) => d,
orElse: () => <NotificationItem>[],
);
if (nextList.length > prevList.length) {
final newItem = nextList.last;
_showBanner(newItem.type, newItem);
}
// Loading/error emissions (e.g. invalidate on resume) keep the snapshot.
final nextList = next.valueOrNull;
if (nextList == null) return;
final item = newestArrival(_prevList, nextList);
_prevList = nextList;
if (item != null) _showBanner(item.type, item);
});
// Listen for pending navigation from local-notification taps