﻿[![Changelog](https://img.shields.io/badge/changelog-8A2BE2)](https://github.com/SAP/open-ux-tools/blob/main/packages/store/CHANGELOG.md) [![Github repo](https://img.shields.io/badge/github-repo-blue)](https://github.com/SAP/open-ux-tools/tree/main/packages/store)

# [`@sap-ux/store`](https://github.com/SAP/open-ux-tools/tree/main/packages/store)

This is a store for persistent data in Fiori tools.

# Usage
Add `@sap-ux/store` to your projects `package.json` to include it in your module.

# API

The main API to this module is `getService()`. Given an optional logger and an entity name, this function will return an instance of a class with the following methods:
```typescript
interface Service<Entity, EntityKey> {
    read(key: EntityKey): Promise<Entity | undefined>;
    write(entity: Entity): Promise<Entity | undefined>;
    delete(entity: Entity): Promise<boolean>;
    getAll(): Promise<Entity[] | []>;
}
```

Currently, `'system'`, `'telemetry'` and `'api-hub'`  are the only supported entities. Support for `'user'` may be added in the future.
Unsupported entity names will result in an error being thrown.

The store supports storing values in operating system specific secure storage, like keychain on MacOS or secure storage on Windows. To disable access to secure storage, environment variable `FIORI_TOOLS_DISABLE_SECURE_STORE` can be set.

# Recommended way to add support for a new entity

(Please read the code for the system entity starting here for a concrete example: [./src/services/backend-system.ts](./src/services/backend-system.ts))
## Add a service
This needs to needs to implement the `Service<Entity, EntityKey>` interface shown above. This is what the external clients of the API will use.

Optionally, you may need to migrate data if the underlying schema changes. You may choose to do this as a single-shot one-off procedure or do it on the fly when any of the service methods are accessed. Code for an [example](./docs/example-migration-service.md) migration service (no-op).
## Add a data provider
It is recommended that the `DataProvider` interface be used to create a data provider for the new entity. This class' concern will purely be managing the persistence of the entity. The service interface may have other concerns like the data migration step in the system store.

Recommended interfaces to implement:
```typescript
interface DataProvider<E, K extends EntityKey<E>> {
    read(key: K): Promise<E | undefined>;
    write(entity: E): Promise<E | undefined>;
    delete(entity: E): Promise<boolean>;
    getAll(): Promise<E[] | []>;
}
```

Implement the static side of the interface for the constructor:
```typescript
interface DataProviderConstructor<E, K extends EntityKey<K>> {
    new (logger: Logger): DataProvider<E, K>;
}
```

Data providers can delegate to data accessors.

### Data accessors
The following data accessors are currently available:

#### Filesystem accessor

This stores the entities on the filesystem inside the Fiori Tools directory (Uses: `getFioriToolsDirectory()` from `@sap-ux/common-utils`)

#### Hybrid accessor
This stores information on the filesystem and the system's secure store.

## Add an entity

Entity classes are simple. They don't do much other than list the properties that will be serialized. `@serializable` and `@sensitiveData` are two annotations that are understood by the hybrid store.

The system entity for example looks like this:
```typescript
class BackendSystem {
    @serializable public readonly name: string;
    @serializable public readonly url: string;
    @serializable public readonly client?: string;
    @sensitiveData public readonly serviceKeys?: unknown;
    @sensitiveData public readonly username?: string;
    @sensitiveData public readonly password?: string;
    ...
    ...
}
```
Systems that are constructed using `new BackendSystem({...})` will have the properties correctly persisted in the relevant medium by the hybrid data accessor.

Every entity needs an `EntityKey` implementing this interface:
```typescript
interface EntityKey<T> {
    getId: () => string;
}
```

#### Special handling for BackendSystem getAll()

The `BackendSystem` service supports filtering and retrieval options when calling `getAll()`. This allows you to retrieve only the backend systems that match specific criteria.

##### BackendServiceRetrievalOptions

The `getAll()` method accepts an optional `BackendServiceRetrievalOptions` parameter with the following properties:

- `includeSensitiveData?: boolean` - Whether to include sensitive data (username, password, etc.) in the returned systems
- `backendSystemFilter?: BackendSystemFilter` - Filter criteria to match specific backend systems

##### BackendSystemFilter

The `BackendSystemFilter` allows filtering by any serializable property of a `BackendSystem`. The following properties can be used for filtering:

- `name` - System name
- `url` - System URL
- `client` - SAP client number
- `systemType` - Type of system (e.g., `SystemType.AbapOnPrem`, `SystemType.AbapCloud`, `SystemType.Generic`)
- `authenticationType` - Authentication method (e.g., `AuthenticationType.Basic`, `AuthenticationType.OAuth2RefreshToken`)
- `connectionType` - Connection type (e.g., `'abap_catalog'`, `'odata_service'`, `'generic_host'`)
- `systemInfo` - Nested object with `systemId` and `client` properties

##### Filter Value Types

Each filter property supports three types of values:

1. **Single value** - Match systems where the property equals the specified value
2. **Array of values** - Match systems where the property equals any value in the array
3. **Object value** (for `systemInfo`) - Match systems where nested properties match

##### Usage Examples

**Filter by single value:**
```typescript
import { getService } from '@sap-ux/store';
import { SystemType } from '@sap-ux/store/types';

const systemService = await getService('system');

// Get only OnPrem systems
const onPremSystems = await systemService.getAll({
    backendSystemFilter: { systemType: SystemType.AbapOnPrem }
});
```

**Filter by array of values:**
```typescript
// Get systems with either 'abap_catalog' or 'odata_service' connection types
const catalogOrServiceSystems = await systemService.getAll({
    backendSystemFilter: {
        connectionType: ['abap_catalog', 'odata_service']
    }
});
```

**Filter by nested object (systemInfo):**
```typescript
// Get systems matching specific systemId and client
const specificSystems = await systemService.getAll({
    backendSystemFilter: {
        systemInfo: { systemId: 'ID123', client: '999' }
    }
});
```

**Combine multiple filters:**
```typescript
// Get OnPrem systems with abap_catalog connection and specific client
const filteredSystems = await systemService.getAll({
    backendSystemFilter: {
        systemType: SystemType.AbapOnPrem,
        connectionType: 'abap_catalog',
        client: '100'
    }
});
```

**Include sensitive data:**
```typescript
// Get all systems with sensitive data included
const systemsWithCredentials = await systemService.getAll({
    includeSensitiveData: true,
    backendSystemFilter: { systemType: SystemType.AbapCloud }
});
```

##### Default Behavior

**IMPORTANT:** If no `connectionType` filter is specified, the `getAll()` method automatically filters by `connectionType: 'abap_catalog'` for backwards compatibility. To retrieve systems with other connection types, you must explicitly specify the `connectionType` filter:

```typescript
// Returns only 'abap_catalog' systems (default behavior)
const defaultSystems = await systemService.getAll();

// Returns all systems regardless of connection type
const allSystems = await systemService.getAll({
    backendSystemFilter: {
        connectionType: ['abap_catalog', 'odata_service', 'generic_host']
    }
});
```

