The personal finance app for everyone (by everyone)
Ruby
Expose ui_layout and ai_enabled to mobile clients and add enable_ai endpoint (#983)
Juan José Matabf0be8585974
diff --git a/app/controllers/api/v1/auth_controller.rb b/app/controllers/api/v1/auth_controller.rbindex 590b332eee..ae17448237 100644--- a/app/controllers/api/v1/auth_controller.rb+++ b/app/controllers/api/v1/auth_controller.rb@@ -6,6 +6,10 @@ module Apiskip_before_action :authenticate_request!skip_before_action :check_api_key_rate_limitskip_before_action :log_api_access+ before_action :authenticate_request!, only: :enable_ai+ before_action :ensure_write_scope, only: :enable_ai+ before_action :check_api_key_rate_limit, only: :enable_ai+ before_action :log_api_access, only: :enable_aidef signup# Check if invite code is required@@ -54,14 +58,7 @@ module Apireturnend- render json: token_response.merge(- user: {- id: user.id,- email: user.email,- first_name: user.first_name,- last_name: user.last_name- }- ), status: :created+ render json: token_response.merge(user: mobile_user_payload(user)), status: :createdelserender json: { errors: user.errors.full_messages }, status: :unprocessable_entityend@@ -97,14 +94,7 @@ module Apireturnend- render json: token_response.merge(- user: {- id: user.id,- email: user.email,- first_name: user.first_name,- last_name: user.last_name- }- )+ render json: token_response.merge(user: mobile_user_payload(user))elserender json: { error: "Invalid email or password" }, status: :unauthorizedend@@ -143,11 +133,28 @@ module Apiid: cached[:user_id],email: cached[:user_email],first_name: cached[:user_first_name],- last_name: cached[:user_last_name]+ last_name: cached[:user_last_name],+ ui_layout: cached[:user_ui_layout],+ ai_enabled: cached[:user_ai_enabled]}}end+ def enable_ai+ user = current_resource_owner++ unless user.ai_available?+ render json: { error: "AI is not available for your account" }, status: :forbidden+ return+ end++ if user.update(ai_enabled: true)+ render json: { user: mobile_user_payload(user) }+ else+ render json: { errors: user.errors.full_messages }, status: :unprocessable_entity+ end+ end+def refresh# Find the refresh tokenrefresh_token = params[:refresh_token]@@ -229,6 +236,21 @@ module Apidef sso_exchange_paramsparams.require(:code)end++ def mobile_user_payload(user)+ {+ id: user.id,+ email: user.email,+ first_name: user.first_name,+ last_name: user.last_name,+ ui_layout: user.ui_layout,+ ai_enabled: user.ai_enabled?+ }+ end++ def ensure_write_scope+ authorize_scope!(:write)+ endendendenddiff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rbindex 009a45eabe..ec53ef5f6f 100644--- a/app/controllers/sessions_controller.rb+++ b/app/controllers/sessions_controller.rb@@ -260,7 +260,9 @@ class SessionsController < ApplicationControlleruser_id: user.id,user_email: user.email,user_first_name: user.first_name,- user_last_name: user.last_name+ user_last_name: user.last_name,+ user_ui_layout: user.ui_layout,+ user_ai_enabled: user.ai_enabled?),expires_in: 5.minutes)diff --git a/config/routes.rb b/config/routes.rbindex eb1055ba60..5badb50fad 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -372,6 +372,7 @@ Rails.application.routes.draw dopost "auth/login", to: "auth#login"post "auth/refresh", to: "auth#refresh"post "auth/sso_exchange", to: "auth#sso_exchange"+ patch "auth/enable_ai", to: "auth#enable_ai"# Production API endpointsresources :accounts, only: [ :index, :show ]diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex d6fb8e2ee3..4a1515f900 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -823,10 +823,10 @@ components:format: dateqty:type: string- description: Quantity as string (JSON number or string from API)+ description: Quantity of shares heldprice:type: string- description: Price as string (JSON number or string from API)+ description: Formatted price per shareamount:type: stringcurrency:@@ -943,6 +943,365 @@ paths:application/json:schema:"$ref": "#/components/schemas/AccountCollection"+ "/api/v1/auth/signup":+ post:+ summary: Sign up a new user+ tags:+ - Auth+ parameters: []+ responses:+ '201':+ description: user created+ content:+ application/json:+ schema:+ type: object+ properties:+ access_token:+ type: string+ refresh_token:+ type: string+ token_type:+ type: string+ expires_in:+ type: integer+ created_at:+ type: integer+ user:+ type: object+ properties:+ id:+ type: string+ format: uuid+ email:+ type: string+ first_name:+ type: string+ last_name:+ type: string+ ui_layout:+ type: string+ enum:+ - dashboard+ - intro+ ai_enabled:+ type: boolean+ '422':+ description: validation error+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ '403':+ description: invite code required or invalid+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ user:+ type: object+ properties:+ email:+ type: string+ format: email+ description: User email address+ password:+ type: string+ description: Password (min 8 chars, mixed case, number, special+ char)+ first_name:+ type: string+ last_name:+ type: string+ required:+ - password+ device:+ type: object+ properties:+ device_id:+ type: string+ description: Unique device identifier+ device_name:+ type: string+ description: Human-readable device name+ device_type:+ type: string+ description: Device type (e.g. ios, android)+ os_version:+ type: string+ app_version:+ type: string+ required:+ - device_id+ - device_name+ - device_type+ - os_version+ - app_version+ invite_code:+ type: string+ nullable: true+ description: Invite code (required when invites are enforced)+ required:+ - user+ - device+ required: true+ "/api/v1/auth/login":+ post:+ summary: Log in with email and password+ tags:+ - Auth+ parameters: []+ responses:+ '200':+ description: login successful+ content:+ application/json:+ schema:+ type: object+ properties:+ access_token:+ type: string+ refresh_token:+ type: string+ token_type:+ type: string+ expires_in:+ type: integer+ created_at:+ type: integer+ user:+ type: object+ properties:+ id:+ type: string+ format: uuid+ email:+ type: string+ first_name:+ type: string+ last_name:+ type: string+ ui_layout:+ type: string+ enum:+ - dashboard+ - intro+ ai_enabled:+ type: boolean+ '401':+ description: invalid credentials or MFA required+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ email:+ type: string+ format: email+ password:+ type: string+ otp_code:+ type: string+ nullable: true+ description: TOTP code if MFA is enabled+ device:+ type: object+ properties:+ device_id:+ type: string+ device_name:+ type: string+ device_type:+ type: string+ os_version:+ type: string+ app_version:+ type: string+ required:+ - device_id+ - device_name+ - device_type+ - os_version+ - app_version+ required:+ - password+ - device+ required: true+ "/api/v1/auth/sso_exchange":+ post:+ summary: Exchange mobile SSO authorization code for tokens+ tags:+ - Auth+ description: Exchanges a one-time authorization code (received via deep link+ after mobile SSO) for OAuth tokens. The code is single-use and expires after+ 5 minutes.+ parameters: []+ responses:+ '200':+ description: tokens issued+ content:+ application/json:+ schema:+ type: object+ properties:+ access_token:+ type: string+ refresh_token:+ type: string+ token_type:+ type: string+ expires_in:+ type: integer+ created_at:+ type: integer+ user:+ type: object+ properties:+ id:+ type: string+ format: uuid+ email:+ type: string+ first_name:+ type: string+ last_name:+ type: string+ ui_layout:+ type: string+ enum:+ - dashboard+ - intro+ ai_enabled:+ type: boolean+ '401':+ description: invalid or expired code+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ code:+ type: string+ description: One-time authorization code from mobile SSO callback+ required:+ - code+ required: true+ "/api/v1/auth/refresh":+ post:+ summary: Refresh an access token+ tags:+ - Auth+ parameters: []+ responses:+ '200':+ description: token refreshed+ content:+ application/json:+ schema:+ type: object+ properties:+ access_token:+ type: string+ refresh_token:+ type: string+ token_type:+ type: string+ expires_in:+ type: integer+ created_at:+ type: integer+ '401':+ description: invalid refresh token+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ '400':+ description: missing refresh token+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse"+ requestBody:+ content:+ application/json:+ schema:+ type: object+ properties:+ refresh_token:+ type: string+ description: The refresh token from a previous login or refresh+ device:+ type: object+ properties:+ device_id:+ type: string+ required:+ - device_id+ required:+ - refresh_token+ - device+ required: true+ "/api/v1/auth/enable_ai":+ patch:+ summary: Enable AI features for the authenticated user+ tags:+ - Auth+ security:+ - apiKeyAuth: []+ responses:+ '200':+ description: ai enabled+ content:+ application/json:+ schema:+ type: object+ properties:+ user:+ type: object+ properties:+ id:+ type: string+ format: uuid+ email:+ type: string+ first_name:+ type: string+ nullable: true+ last_name:+ type: string+ nullable: true+ ui_layout:+ type: string+ enum:+ - dashboard+ - intro+ ai_enabled:+ type: boolean+ '401':+ description: unauthorized+ content:+ application/json:+ schema:+ "$ref": "#/components/schemas/ErrorResponse""/api/v1/categories":get:summary: List categories@@ -1315,8 +1674,8 @@ paths:parameters:- name: idin: path- description: Holding IDrequired: true+ description: Holding IDschema:type: stringget:@@ -1800,8 +2159,8 @@ paths:parameters:- name: idin: path- description: Trade IDrequired: true+ description: Trade IDschema:type: stringget:@@ -1835,6 +2194,7 @@ paths:- Tradessecurity:- apiKeyAuth: []+ parameters: []responses:'200':description: trade updated@@ -1848,12 +2208,6 @@ paths:application/json:schema:"$ref": "#/components/schemas/ErrorResponse"- '422':- description: validation error- content:- application/json:- schema:- "$ref": "#/components/schemas/ErrorResponse"requestBody:content:application/json:@@ -1862,34 +2216,30 @@ paths:properties:trade:type: object- description: Flat params; controller builds internal structure. When qty/price are updated, type or nature controls sign; if omitted, existing trade direction is preserved.properties:date:type: stringformat: date- name:- type: string- amount:+ qty:type: number- currency:- type: string- notes:+ price:+ type: number+ type:type: string+ enum:+ - buy+ - sellnature:type: stringenum:- inflow- outflow- type:+ name:+ type: string+ notes:+ type: string+ currency:type: string- enum:- - buy- - sell- description: Determines sign when qty/price are updated.- qty:- type: number- price:- type: numberinvestment_activity_label:type: stringcategory_id:@@ -2204,6 +2554,8 @@ paths:items:type: stringformat: uuid+ description: Array of tag IDs to assign. Omit to preserve existing+ tags; use [] to clear all tags.required: truedelete:summary: Delete a transactiondiff --git a/mobile/lib/models/user.dart b/mobile/lib/models/user.dartindex e932bcda31..1172bdfe8d 100644--- a/mobile/lib/models/user.dart+++ b/mobile/lib/models/user.dart@@ -3,23 +3,64 @@ class User {final String email;final String? firstName;final String? lastName;+ final String uiLayout;+ final bool aiEnabled;User({required this.id,required this.email,this.firstName,this.lastName,+ required this.uiLayout,+ required this.aiEnabled,});+ bool get isIntroLayout => uiLayout == 'intro';+factory User.fromJson(Map<String, dynamic> json) {return User(id: json['id'].toString(),email: json['email'] as String,firstName: json['first_name'] as String?,lastName: json['last_name'] as String?,+ uiLayout: (json['ui_layout'] as String?) ?? 'dashboard',+ // Default to true when key is absent (legacy payloads from older app versions).+ // Avoids regressing existing users who would otherwise be incorrectly gated.+ aiEnabled: json.containsKey('ai_enabled')+ ? (json['ai_enabled'] == true)+ : true,);}+ User copyWith({+ String? id,+ String? email,+ String? firstName,+ String? lastName,+ String? uiLayout,+ bool? aiEnabled,+ }) {+ return User(+ id: id ?? this.id,+ email: email ?? this.email,+ firstName: firstName ?? this.firstName,+ lastName: lastName ?? this.lastName,+ uiLayout: uiLayout ?? this.uiLayout,+ aiEnabled: aiEnabled ?? this.aiEnabled,+ );+ }++ Map<String, dynamic> toJson() {+ return {+ 'id': id,+ 'email': email,+ 'first_name': firstName,+ 'last_name': lastName,+ 'ui_layout': uiLayout,+ 'ai_enabled': aiEnabled,+ };+ }+String get displayName {if (firstName != null && lastName != null) {return '$firstName $lastName';diff --git a/mobile/lib/providers/auth_provider.dart b/mobile/lib/providers/auth_provider.dartindex 0fa47fd63b..a75826b1c0 100644--- a/mobile/lib/providers/auth_provider.dart+++ b/mobile/lib/providers/auth_provider.dart@@ -22,6 +22,8 @@ class AuthProvider with ChangeNotifier {bool _showMfaInput = false; // Track if we should show MFA input fieldUser? get user => _user;+ bool get isIntroLayout => _user?.isIntroLayout ?? false;+ bool get aiEnabled => _user?.aiEnabled ?? false;AuthTokens? get tokens => _tokens;bool get isLoading => _isLoading;bool get isInitializing => _isInitializing; // Expose initialization state@@ -321,6 +323,27 @@ class AuthProvider with ChangeNotifier {return _tokens?.accessToken;}+ Future<bool> enableAi() async {+ final accessToken = await getValidAccessToken();+ if (accessToken == null) {+ _errorMessage = 'Session expired. Please login again.';+ notifyListeners();+ return false;+ }++ final result = await _authService.enableAi(accessToken: accessToken);+ if (result['success'] == true) {+ _user = result['user'] as User?;+ _errorMessage = null;+ notifyListeners();+ return true;+ }++ _errorMessage = result['error'] as String?;+ notifyListeners();+ return false;+ }+void clearError() {_errorMessage = null;notifyListeners();diff --git a/mobile/lib/screens/main_navigation_screen.dart b/mobile/lib/screens/main_navigation_screen.dartindex 8d002851f1..7b537667e1 100644--- a/mobile/lib/screens/main_navigation_screen.dart+++ b/mobile/lib/screens/main_navigation_screen.dart@@ -1,4 +1,6 @@import 'package:flutter/material.dart';+import 'package:provider/provider.dart';+import '../providers/auth_provider.dart';import 'dashboard_screen.dart';import 'chat_list_screen.dart';import 'more_screen.dart';@@ -15,60 +17,147 @@ class _MainNavigationScreenState extends State<MainNavigationScreen> {int _currentIndex = 0;final _dashboardKey = GlobalKey<DashboardScreenState>();- late final List<Widget> _screens;+ List<Widget> _buildScreens(bool introLayout) {+ final screens = <Widget>[];- @override- void initState() {- super.initState();- _screens = [- DashboardScreen(key: _dashboardKey),- const ChatListScreen(),- const MoreScreen(),- const SettingsScreen(),- ];+ if (!introLayout) {+ screens.add(DashboardScreen(key: _dashboardKey));+ }++ screens.add(const ChatListScreen());++ if (!introLayout) {+ screens.add(const MoreScreen());+ }++ screens.add(const SettingsScreen());++ return screens;}- @override- Widget build(BuildContext context) {- return Scaffold(- body: IndexedStack(- index: _currentIndex,- children: _screens,+ List<NavigationDestination> _buildDestinations(bool introLayout) {+ final destinations = <NavigationDestination>[];++ if (!introLayout) {+ destinations.add(+ const NavigationDestination(+ icon: Icon(Icons.home_outlined),+ selectedIcon: Icon(Icons.home),+ label: 'Home',+ ),+ );+ }++ destinations.add(+ const NavigationDestination(+ icon: Icon(Icons.chat_bubble_outline),+ selectedIcon: Icon(Icons.chat_bubble),+ label: 'AI Chat',),- bottomNavigationBar: NavigationBar(- selectedIndex: _currentIndex,- onDestinationSelected: (index) {- setState(() {- _currentIndex = index;- });- // Reload preferences whenever switching back to dashboard- if (index == 0) {- _dashboardKey.currentState?.reloadPreferences();- }- },- destinations: const [- NavigationDestination(- icon: Icon(Icons.home_outlined),- selectedIcon: Icon(Icons.home),- label: 'Home',- ),- NavigationDestination(- icon: Icon(Icons.chat_bubble_outline),- selectedIcon: Icon(Icons.chat_bubble),- label: 'AI Chat',- ),- NavigationDestination(- icon: Icon(Icons.more_horiz),- selectedIcon: Icon(Icons.more_horiz),- label: 'More',+ );++ if (!introLayout) {+ destinations.add(+ const NavigationDestination(+ icon: Icon(Icons.more_horiz),+ selectedIcon: Icon(Icons.more_horiz),+ label: 'More',+ ),+ );+ }++ destinations.add(+ const NavigationDestination(+ icon: Icon(Icons.settings_outlined),+ selectedIcon: Icon(Icons.settings),+ label: 'Settings',+ ),+ );++ return destinations;+ }++ Future<bool> _showEnableAiPrompt() async {+ final authProvider = Provider.of<AuthProvider>(context, listen: false);++ final shouldEnable = await showDialog<bool>(+ context: context,+ builder: (context) => AlertDialog(+ title: const Text('Turn on AI Chat?'),+ content: const Text('AI Chat is currently disabled in your account settings. Would you like to turn it on now?'),+ actions: [+ TextButton(+ onPressed: () => Navigator.of(context).pop(false),+ child: const Text('Not now'),),- NavigationDestination(- icon: Icon(Icons.settings_outlined),- selectedIcon: Icon(Icons.settings),- label: 'Settings',+ FilledButton(+ onPressed: () => Navigator.of(context).pop(true),+ child: const Text('Turn on AI'),),],),);++ if (shouldEnable != true) {+ return false;+ }++ final enabled = await authProvider.enableAi();++ if (!enabled && mounted) {+ ScaffoldMessenger.of(context).showSnackBar(+ SnackBar(+ content: Text(authProvider.errorMessage ?? 'Unable to enable AI right now.'),+ backgroundColor: Colors.red,+ ),+ );+ }++ return enabled;+ }++ @override+ Widget build(BuildContext context) {+ return Consumer<AuthProvider>(+ builder: (context, authProvider, _) {+ final introLayout = authProvider.isIntroLayout;+ final screens = _buildScreens(introLayout);+ final destinations = _buildDestinations(introLayout);++ if (_currentIndex >= screens.length) {+ _currentIndex = 0;+ }++ final chatIndex = introLayout ? 0 : 1;+ final homeIndex = 0;++ return Scaffold(+ body: IndexedStack(+ index: _currentIndex,+ children: screens,+ ),+ bottomNavigationBar: NavigationBar(+ selectedIndex: _currentIndex,+ onDestinationSelected: (index) async {+ if (index == chatIndex && !authProvider.aiEnabled) {+ final enabled = await _showEnableAiPrompt();+ if (!enabled) {+ return;+ }+ }++ setState(() {+ _currentIndex = index;+ });++ if (!introLayout && index == homeIndex) {+ _dashboardKey.currentState?.reloadPreferences();+ }+ },+ destinations: destinations,+ ),+ );+ },+ );}}diff --git a/mobile/lib/services/auth_service.dart b/mobile/lib/services/auth_service.dartindex c6b6c88598..874b630684 100644--- a/mobile/lib/services/auth_service.dart+++ b/mobile/lib/services/auth_service.dart@@ -435,6 +435,42 @@ class AuthService {}}+ Future<Map<String, dynamic>> enableAi({+ required String accessToken,+ }) async {+ try {+ final url = Uri.parse('${ApiConfig.baseUrl}/api/v1/auth/enable_ai');+ final response = await http.patch(+ url,+ headers: {+ ...ApiConfig.getAuthHeaders(accessToken),+ 'Content-Type': 'application/json',+ },+ ).timeout(const Duration(seconds: 30));++ final responseData = jsonDecode(response.body);++ if (response.statusCode == 200) {+ final user = User.fromJson(responseData['user']);+ await _saveUser(user);+ return {+ 'success': true,+ 'user': user,+ };+ }++ return {+ 'success': false,+ 'error': responseData['error'] ?? responseData['errors']?.join(', ') ?? 'Failed to enable AI',+ };+ } catch (e) {+ return {+ 'success': false,+ 'error': 'Network error: ${e.toString()}',+ };+ }+ }+Future<void> logout() async {await _storage.delete(key: _tokenKey);await _storage.delete(key: _userKey);@@ -474,12 +510,7 @@ class AuthService {Future<void> _saveUser(User user) async {await _storage.write(key: _userKey,- value: jsonEncode({- 'id': user.id,- 'email': user.email,- 'first_name': user.firstName,- 'last_name': user.lastName,- }),+ value: jsonEncode(user.toJson()),);}diff --git a/spec/requests/api/v1/auth_spec.rb b/spec/requests/api/v1/auth_spec.rbindex 38f797bd16..f21ab79f2d 100644--- a/spec/requests/api/v1/auth_spec.rb+++ b/spec/requests/api/v1/auth_spec.rb@@ -51,7 +51,9 @@ RSpec.describe 'API V1 Auth', type: :request doid: { type: :string, format: :uuid },email: { type: :string },first_name: { type: :string },- last_name: { type: :string }+ last_name: { type: :string },+ ui_layout: { type: :string, enum: %w[dashboard intro] },+ ai_enabled: { type: :boolean }}}}@@ -110,7 +112,9 @@ RSpec.describe 'API V1 Auth', type: :request doid: { type: :string, format: :uuid },email: { type: :string },first_name: { type: :string },- last_name: { type: :string }+ last_name: { type: :string },+ ui_layout: { type: :string, enum: %w[dashboard intro] },+ ai_enabled: { type: :boolean }}}}@@ -152,7 +156,9 @@ RSpec.describe 'API V1 Auth', type: :request doid: { type: :string, format: :uuid },email: { type: :string },first_name: { type: :string },- last_name: { type: :string }+ last_name: { type: :string },+ ui_layout: { type: :string, enum: %w[dashboard intro] },+ ai_enabled: { type: :boolean }}}}@@ -209,4 +215,41 @@ RSpec.describe 'API V1 Auth', type: :request doendendend++ path '/api/v1/auth/enable_ai' do+ patch 'Enable AI features for the authenticated user' do+ tags 'Auth'+ consumes 'application/json'+ produces 'application/json'+ security [ { apiKeyAuth: [] } ]++ response '200', 'ai enabled' do+ schema type: :object,+ properties: {+ user: {+ type: :object,+ properties: {+ id: { type: :string, format: :uuid },+ email: { type: :string },+ first_name: { type: :string, nullable: true },+ last_name: { type: :string, nullable: true },+ ui_layout: { type: :string, enum: %w[dashboard intro] },+ ai_enabled: { type: :boolean }+ }+ }+ }+ run_test!+ end++ response '401', 'unauthorized' do+ schema '$ref' => '#/components/schemas/ErrorResponse'+ run_test!+ end++ response '403', 'insufficient scope' do+ schema '$ref' => '#/components/schemas/ErrorResponse'+ run_test!+ end+ end+ endenddiff --git a/test/controllers/api/v1/auth_controller_test.rb b/test/controllers/api/v1/auth_controller_test.rbindex 043f180987..06b2ed537e 100644--- a/test/controllers/api/v1/auth_controller_test.rb+++ b/test/controllers/api/v1/auth_controller_test.rb@@ -15,9 +15,10 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTest# Ensure the shared OAuth application exists@shared_app = Doorkeeper::Application.find_or_create_by!(name: "Sure Mobile") do |app|app.redirect_uri = "sureapp://oauth/callback"- app.scopes = "read_write"+ app.scopes = "read read_write"app.confidential = falseend+ @shared_app.update!(scopes: "read read_write")# Clear the memoized class variable so it picks up the test recordMobileDevice.instance_variable_set(:@shared_oauth_application, nil)@@ -49,6 +50,9 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert_equal "[email protected]", response_data["user"]["email"]assert_equal "New", response_data["user"]["first_name"]assert_equal "User", response_data["user"]["last_name"]+ new_user = User.find(response_data["user"]["id"])+ assert_equal new_user.ui_layout, response_data["user"]["ui_layout"]+ assert_equal new_user.ai_enabled?, response_data["user"]["ai_enabled"]# OAuth token assertionsassert response_data["access_token"].present?@@ -58,8 +62,8 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert response_data["created_at"].present?# Verify the device was created- new_user = User.find(response_data["user"]["id"])- device = new_user.mobile_devices.first+ created_user = User.find(response_data["user"]["id"])+ device = created_user.mobile_devices.firstassert_equal @device_info[:device_id], device.device_idassert_equal @device_info[:device_name], device.device_nameassert_equal @device_info[:device_type], device.device_type@@ -227,6 +231,8 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestassert_equal user.id.to_s, response_data["user"]["id"]assert_equal user.email, response_data["user"]["email"]+ assert_equal user.ui_layout, response_data["user"]["ui_layout"]+ assert_equal user.ai_enabled?, response_data["user"]["ai_enabled"]# OAuth token assertionsassert response_data["access_token"].present?@@ -439,4 +445,64 @@ class Api::V1::AuthControllerTest < ActionDispatch::IntegrationTestresponse_data = JSON.parse(response.body)assert_equal "Refresh token is required", response_data["error"]end++ test "should enable ai for authenticated user" do+ user = users(:family_admin)+ user.update!(ai_enabled: false)+ device = user.mobile_devices.create!(@device_info)+ token = Doorkeeper::AccessToken.create!(application: @shared_app, resource_owner_id: user.id, mobile_device_id: device.id, scopes: "read_write")++ patch "/api/v1/auth/enable_ai", headers: {+ "Authorization" => "Bearer #{token.token}",+ "Content-Type" => "application/json"+ }++ assert_response :success+ response_data = JSON.parse(response.body)+ assert_equal true, response_data.dig("user", "ai_enabled")+ assert_equal user.ui_layout, response_data.dig("user", "ui_layout")+ assert_equal true, user.reload.ai_enabled+ end++ test "should require read_write scope to enable ai" do+ user = users(:family_admin)+ user.update!(ai_enabled: false)+ device = user.mobile_devices.create!(@device_info)+ token = Doorkeeper::AccessToken.create!(application: @shared_app, resource_owner_id: user.id, mobile_device_id: device.id, scopes: "read")++ patch "/api/v1/auth/enable_ai", headers: {+ "Authorization" => "Bearer #{token.token}",+ "Content-Type" => "application/json"+ }++ assert_response :forbidden+ response_data = JSON.parse(response.body)+ assert_equal "insufficient_scope", response_data["error"]+ assert_equal "This action requires the 'write' scope", response_data["message"]+ assert_not user.reload.ai_enabled+ end++ test "should require authentication when enabling ai" do+ patch "/api/v1/auth/enable_ai", headers: { "Content-Type" => "application/json" }++ assert_response :unauthorized+ end++ test "should return forbidden when ai is not available" do+ user = users(:family_admin)+ user.update!(ai_enabled: false)+ device = user.mobile_devices.create!(@device_info)+ token = Doorkeeper::AccessToken.create!(application: @shared_app, resource_owner_id: user.id, mobile_device_id: device.id, scopes: "read_write")+ User.any_instance.stubs(:ai_available?).returns(false)++ patch "/api/v1/auth/enable_ai", headers: {+ "Authorization" => "Bearer #{token.token}",+ "Content-Type" => "application/json"+ }++ assert_response :forbidden+ response_data = JSON.parse(response.body)+ assert_equal "AI is not available for your account", response_data["error"]+ assert_not user.reload.ai_enabled+ endend