mattermost-mobile-upstream/app/actions/remote/classification.test.ts
Andre Vasconcelos e18fc6921e
MM-68208 Implementing global and channel-level banners on mobile (#9752)
* Expo-Router partial migration

* Full migration to ExpoRouter

* i18n

* add tests

* library hardware-keyboard android new arch support fix

* library rnshare android new arch support fix

* library rnutils android new arch support fix

* library secure-pdf-viewer add new arch support

* Enable new arch on iOS and Android

* update emm and network client with new-arch

* update intune to use new-arch

* performance improvements

* fix tests

* fixes post input on new-arch

* Merge branch 'main' into expo-router

* fix android emoji picker

* align package-lock.json

* i18n

* feedback review

* feedback review

* android 16kb patch

* Refactored emoji picker keyboard using a state machine

* set android launch_screen in drawables instead of layout

* no conditional hooks

* remove duplicate call in test

* address feedback

* fix tests and address more feedback

* small corrections

* small corrections

* small corrections

* fix draft test

* fix draft test 2

* remove navigateToScreen in draff test

* fix nit in draft test

* remove doc file

* remove doc

* run tests in parallel

* Feedback review

* fix snapshots

* improve test coverage

* fix i18n

* upgrade to React Native 0.83.9, Expo 55, React 19, and New Architecture

Bumps core dependencies to their latest versions:
- React Native 0.77.3 → 0.83.9 (New Architecture enabled)
- React 18.3.1 → 19.2.5
- Expo SDK 52 → 55
- TypeScript 5.8.3 → 6.0.3
- Node.js 22.16.0 → 24.15.0
- react-native-reanimated 3.17.3 → 4.3.0
- Various other dependency upgrades

Migrates iOS AppDelegate from Objective-C to Swift, updates Android
build tooling and Gradle wrapper, refreshes all patches and font
assets, and adapts app code, tests, and CI workflows throughout for
API changes introduced by these upgrades.

* remove unecessary dismissKeyboard in notifications

* feedback review

* update intune to use new-arch

* update @mattermost deps

* missing i18n string

* additional fixes

* update fastlane

* Re-implementing global classification banners on top of rn83

* Refactoring to de-couple the classification banner from the layout

* Implementing per-channel banners on mobile

* Removing custom header in favor of common component

* Making fixes for coderabbit

* Improving padding calculation

* Converting global classification banner to use portals

* Removing dead code, adding deletion check

* Addressing dryrun securit concerns

* Removing call for template field, improving consistency

* MM-68208 Storing system property values in WatermelonDB (#9781)

* Added persistence layer to system properties

* Making debounce behavior more consistent

* Cleaning up debounce logic from store persistence

* Addressing PR feedback

* Removing ephemeral store usage and employing observables

- Changing name of group to access_control

* Updating unit tests

* Refactoring to improve code consistency

- Removing any patterns introduced that weren't already established in the repo
- Removing hooks with database reads in favor of withObservables and withDatabase pattern
- Simplifying _layout.tsx by removing inset modification, now handled in the Container HoC component
- Moved some repeated hook logic into its own utils file

* Refactoring to use propertyfield and propertyvalue tables instead of system

- Simplified remote actions to purely perform API call, and call a local action to sync values
- Using local action layer to perform syncing and removal operations of property fields and values
- Observables now pre-filter for active fields / values via querying for delete_at=0

* Improving consistency of local actions

- Added unit tests for syncPropertyFieldsByGroupId, syncPropertyValuesByTargetId, clearClassificationData

* Replacing local actions with operator handlers

* Removing needless mocks from unit tests

* Consolidating operator handlers

- Leaving 1 handler for fields and 1 for values, each of them evaluating whether to delete or upsert values received in the function call

* MM-68208 Making changes based on feedback

- Removing !visible guard in global classification container
- Increasing clarity of comment for clearing of stale fields
- Updating log messages to be more clear

* Batching database operations together for fields and values

* Consolidating API call for fetching classification data

- Preparation for caching mechanism

* Updating field names to the unified classification

* Updating E2E test values to match current field names

---------

Co-authored-by: Elias Nahum <nahumhbl@gmail.com>
Co-authored-by: Mattermost Build <build@mattermost.com>
2026-07-08 12:47:01 +03:00

356 lines
14 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Q, type Database} from '@nozbe/watermelondb';
import {CLASSIFICATIONS_GROUP_NAME, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID} from '@constants/classification';
import {MM_TABLES} from '@constants/database';
import DatabaseManager from '@database/manager';
import NetworkManager from '@managers/network_manager';
import {getConfigValue} from '@queries/servers/system';
import {fetchClassificationBanner, fetchChannelClassificationValue} from './classification';
import type {PropertyFieldModel, PropertyValueModel} from '@database/models/server';
const {PROPERTY_FIELD, PROPERTY_VALUE} = MM_TABLES.SERVER;
jest.mock('@queries/servers/system', () => ({
getConfigValue: jest.fn(),
}));
const mockedGetConfigValue = jest.mocked(getConfigValue);
const serverUrl = 'classification.test.com';
const systemField: PropertyField = {
id: 'system-field-id',
group_id: CLASSIFICATIONS_GROUP_NAME,
name: 'classification',
type: 'select',
object_type: 'system',
target_type: 'system',
target_id: '',
delete_at: 0,
create_at: 1000,
update_at: 1000,
attrs: {
actions: ['display_banner_top'],
options: [
{id: 'opt-top-secret', name: 'TOP SECRET', color: '#FCE83A'},
{id: 'opt-secret', name: 'SECRET', color: '#FF0000'},
],
},
};
const channelField: PropertyField = {
id: 'channel-field-id',
group_id: CLASSIFICATIONS_GROUP_NAME,
name: 'classification',
type: 'select',
object_type: 'channel',
target_type: 'system',
target_id: '',
delete_at: 0,
create_at: 1000,
update_at: 1000,
attrs: {
options: [
{id: 'opt-top-secret', name: 'TOP SECRET', color: '#FCE83A'},
{id: 'opt-secret', name: 'SECRET', color: '#FF0000'},
],
},
};
const systemValue: PropertyValue<string> = {
id: 'val-1',
target_id: 'system',
target_type: 'system',
group_id: CLASSIFICATIONS_GROUP_NAME,
field_id: 'system-field-id',
value: 'opt-top-secret',
create_at: 1000,
update_at: 1000,
delete_at: 0,
};
const mockClient = {
getPropertyFields: jest.fn(),
getSystemPropertyValues: jest.fn(),
getPropertyValues: jest.fn(),
};
const queryFieldsByGroup = (database: Database, groupId: string) =>
database.get<PropertyFieldModel>(PROPERTY_FIELD).query(Q.where('group_id', groupId)).fetch();
const getStoredFields = async (database: Database) => {
const records = await queryFieldsByGroup(database, CLASSIFICATIONS_GROUP_NAME);
return records.map((r) => r.id).sort();
};
const getStoredValues = async (database: Database, targetId: string) => {
const records = await database.get<PropertyValueModel>(PROPERTY_VALUE).query(Q.where('target_id', targetId)).fetch();
return records;
};
beforeAll(() => {
// @ts-expect-error mock client
NetworkManager.getClient = () => mockClient;
});
beforeEach(async () => {
await DatabaseManager.init([serverUrl]);
jest.clearAllMocks();
});
afterEach(async () => {
await DatabaseManager.destroyServerDatabase(serverUrl);
});
describe('fetchClassificationBanner', () => {
it('should do nothing when feature flag is not true', async () => {
mockedGetConfigValue.mockResolvedValueOnce('false');
const result = await fetchClassificationBanner(serverUrl);
expect(result).toEqual({});
expect(mockClient.getPropertyFields).not.toHaveBeenCalled();
});
it('should clear stale classification data when feature flag is turned off', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField], prepareRecordsOnly: false});
await operator.handlePropertyValues({values: [systemValue], prepareRecordsOnly: false});
mockedGetConfigValue.mockResolvedValueOnce('false');
await fetchClassificationBanner(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
expect(await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID)).toHaveLength(0);
});
it('should clear stale classification data when API returns zero fields', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField], prepareRecordsOnly: false});
await operator.handlePropertyValues({values: [systemValue], prepareRecordsOnly: false});
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
await fetchClassificationBanner(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
expect(await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID)).toHaveLength(0);
});
it('should persist fields and values to DB on happy path', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
const result = await fetchClassificationBanner(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toEqual(['channel-field-id', 'system-field-id']);
const values = await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID);
expect(values).toHaveLength(1);
expect(values[0].value).toBe('opt-top-secret');
});
it('should persist system field when channel field is missing', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
const result = await fetchClassificationBanner(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id']);
});
it('should return early when no fields are returned by the API', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
const result = await fetchClassificationBanner(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
});
it('should exclude soft-deleted fields from the stored set', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
const deletedSystem = {...systemField, delete_at: 5000};
mockClient.getPropertyFields.mockResolvedValueOnce([deletedSystem]);
mockClient.getPropertyFields.mockResolvedValueOnce([channelField]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([]);
const result = await fetchClassificationBanner(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toEqual(['channel-field-id']);
});
it('should return early when fields have mismatched group_ids', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
const differentGroupField = {...channelField, group_id: 'other_group'};
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([differentGroupField]);
const result = await fetchClassificationBanner(serverUrl);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
});
it('should return error when network client throws', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
const networkError = new Error('network failure');
mockClient.getPropertyFields.mockRejectedValueOnce(networkError);
const result = await fetchClassificationBanner(serverUrl);
expect(result).toEqual({error: networkError});
});
it('should not write to DB when network client throws', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyFields.mockRejectedValueOnce(new Error('network failure'));
await fetchClassificationBanner(serverUrl);
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
expect(await getStoredFields(database)).toHaveLength(0);
});
it('should remove a previously persisted field the API no longer returns', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField, channelField], prepareRecordsOnly: false});
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchClassificationBanner(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id']);
});
it('should remove soft-deleted fields from DB even when they were previously persisted', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyFields({fields: [systemField, channelField], prepareRecordsOnly: false});
const deletedChannel = {...channelField, delete_at: 5000};
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([deletedChannel]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([]);
await fetchClassificationBanner(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id']);
});
it('should leave fields from other groups untouched', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const otherGroupField = {...systemField, id: 'other-field', group_id: 'other_group', name: 'some_field'};
await operator.handlePropertyFields({fields: [otherGroupField], prepareRecordsOnly: false});
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyFields.mockResolvedValueOnce([systemField]);
mockClient.getPropertyFields.mockResolvedValueOnce([]);
mockClient.getSystemPropertyValues.mockResolvedValueOnce([systemValue]);
await fetchClassificationBanner(serverUrl);
expect(await getStoredFields(database)).toEqual(['system-field-id']);
const otherGroup = await queryFieldsByGroup(database, 'other_group');
expect(otherGroup.map((f) => f.id)).toEqual(['other-field']);
});
});
describe('fetchChannelClassificationValue', () => {
const channelId = 'channel-123';
const channelValue: PropertyValue<string> = {
id: 'cv-1',
target_id: channelId,
target_type: 'channel',
group_id: CLASSIFICATIONS_GROUP_NAME,
field_id: 'channel-field-id',
value: 'opt-secret',
create_at: 1000,
update_at: 1000,
delete_at: 0,
};
it('should do nothing when feature flag is not true', async () => {
mockedGetConfigValue.mockResolvedValueOnce('false');
const result = await fetchChannelClassificationValue(serverUrl, channelId);
expect(result).toEqual({});
expect(mockClient.getPropertyValues).not.toHaveBeenCalled();
});
it('should persist channel values to DB on happy path', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyValues.mockResolvedValueOnce([channelValue]);
const result = await fetchChannelClassificationValue(serverUrl, channelId);
expect(result).toEqual({});
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const values = await getStoredValues(database, channelId);
expect(values).toHaveLength(1);
expect(values[0].value).toBe('opt-secret');
});
it('should clear existing channel values when API returns none', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyValues({values: [channelValue], prepareRecordsOnly: false});
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyValues.mockResolvedValueOnce([]);
const result = await fetchChannelClassificationValue(serverUrl, channelId);
expect(result).toEqual({});
expect(await getStoredValues(database, channelId)).toHaveLength(0);
});
it('should return error when network client throws', async () => {
mockedGetConfigValue.mockResolvedValueOnce('true');
const networkError = new Error('network failure');
mockClient.getPropertyValues.mockRejectedValueOnce(networkError);
const result = await fetchChannelClassificationValue(serverUrl, channelId);
expect(result).toEqual({error: networkError});
});
it('should isolate values across different targets', async () => {
const {operator, database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
await operator.handlePropertyValues({values: [systemValue], prepareRecordsOnly: false});
mockedGetConfigValue.mockResolvedValueOnce('true');
mockClient.getPropertyValues.mockResolvedValueOnce([channelValue]);
await fetchChannelClassificationValue(serverUrl, channelId);
expect(await getStoredValues(database, CLASSIFICATIONS_SYSTEM_VALUE_TARGET_ID)).toHaveLength(1);
expect(await getStoredValues(database, channelId)).toHaveLength(1);
});
});