Files
mail_manager/src/stores/collectionsStore.ts
T
Sebastian 7afee695c6
Build Test / test (pull_request) Successful in 26s
JS Unit Tests / test (pull_request) Failing after 27s
PHP Unit Tests / test (pull_request) Successful in 54s
fix: testing fixes
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-05-16 00:10:02 -04:00

453 lines
16 KiB
TypeScript

/**
* Collections Store
*/
import { ref, computed, readonly } from 'vue'
import { defineStore } from 'pinia'
import {
type ServiceIdentifier,
type CollectionIdentifier,
type ListFilter,
type ListSort,
collectionService,
} from '../services'
import { CollectionObject, CollectionPropertiesObject } from '../models/collection'
export const useCollectionsStore = defineStore('mailCollectionsStore', () => {
// State
const _collections = ref<Record<string, CollectionObject>>({})
const _collectionsByServiceIndex = ref<Record<string, string[]>>({})
const _collectionsByParentIndex = ref<Record<string, string[]>>({})
const transceiving = ref(false)
/**
* Get count of collections in store
*/
const count = computed(() => Object.keys(_collections.value).length)
/**
* Check if any collections are present in store
*/
const has = computed(() => count.value > 0)
/**
* Get all collections present in store
*/
const collections = computed(() => Object.values(_collections.value))
/**
* Get all collections present in store grouped by service
*/
const collectionsByService = computed(() => {
const groups: Record<string, CollectionObject[]> = {}
Object.keys(_collectionsByServiceIndex.value).forEach(serviceIndexKey => {
const collectionKeys = _collectionsByServiceIndex.value[serviceIndexKey] ?? []
const collectionsForKey = collectionKeys
.map(collectionKey => _collections.value[collectionKey])
.filter((collection): collection is CollectionObject => collection !== undefined)
if (collectionsForKey.length === 0) {
return
}
const firstCollection = collectionsForKey[0]
const serviceKey = `${firstCollection.provider}:${firstCollection.service}`
groups[serviceKey] = collectionsForKey
})
return groups
})
/**
* Get a specific collection from store, with optional retrieval
*
* @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Collection object or null
*/
function collection(target: CollectionIdentifier, retrieve: boolean = false): CollectionObject | null {
if (retrieve === true && !_collections.value[target]) {
console.debug(`[Mail Manager][Store] - Force fetching collection "${target}"`)
fetch([target])
}
return _collections.value[target] || null
}
/**
* Get all collections for a specific service
*
* @param provider - provider identifier
* @param service - service identifier
* @param retrieve - Retrieve behavior: true = fetch if missing or refresh, false = cache only
*
* @returns Array of collection objects
*/
function collectionsForService(provider: string, service: string | number, retrieve: boolean = false): CollectionObject[] {
const serviceIdentifier = `${provider}:${service}` as ServiceIdentifier
const serviceCollections = collectionObjectsForKeys(
_collectionsByServiceIndex.value[serviceIdentifier] ?? [],
)
if (retrieve === true && serviceCollections.length === 0) {
console.debug(`[Mail Manager][Store] - Force fetching collections for service "${serviceIdentifier}"`)
list([serviceIdentifier])
}
return serviceCollections
}
/**
* Get direct child collections for a parent collection, or root collections when parent is null.
*
* @param provider - provider identifier
* @param service - service identifier
* @param collectionId - parent collection identifier, or null for root-level collections
* @param retrieve - Retrieve behavior: true = fetch service collections if missing, false = cache only
*
* @returns Array of direct child collection objects
*/
function collectionsInCollection(provider: string, service: string | number, collection?: CollectionIdentifier | null, retrieve: boolean = false): CollectionObject[] {
const collectionIdentifier = collection ?? `${provider}:${service}` as CollectionIdentifier
const nestedCollections = collectionObjectsForKeys(
_collectionsByParentIndex.value[collectionIdentifier] ?? [],
)
if (retrieve === true && nestedCollections.length === 0) {
console.debug(`[Mail Manager][Store] - Force fetching collections in collection "${collectionIdentifier}"`)
list([collectionIdentifier])
}
return nestedCollections
}
function hasChildrenInCollection(provider: string, service: string | number, collection: CollectionIdentifier | null): boolean {
const collectionIdentifier = collection ?? `${provider}:${service}` as CollectionIdentifier
return (_collectionsByParentIndex.value[collectionIdentifier]?.length ?? 0) > 0
}
function collectionObjectsForKeys(collectionKeys: string[]): CollectionObject[] {
return collectionKeys
.map(collectionKey => _collections.value[collectionKey])
.filter((collection): collection is CollectionObject => collection !== undefined)
}
function indexCollection(collection: CollectionObject) {
addIndexEntry(_collectionsByServiceIndex.value, String(collection.service), String(collection.identifier))
addIndexEntry(_collectionsByParentIndex.value, String(collection.collection ?? collection.service), String(collection.identifier))
}
function deindexCollection(collection: CollectionObject) {
removeIndexEntry(_collectionsByServiceIndex.value, String(collection.service), String(collection.identifier))
removeIndexEntry(_collectionsByParentIndex.value, String(collection.collection ?? collection.service), String(collection.identifier))
}
function addIndexEntry(index: Record<string, string[]>, indexKey: string, collectionKey: string) {
const existing = index[indexKey] ?? []
if (existing.includes(collectionKey)) {
return
}
index[indexKey] = [...existing, collectionKey]
}
function removeIndexEntry(index: Record<string, string[]>, indexKey: string, collectionKey: string) {
const existing = index[indexKey]
if (!existing) {
return
}
const filtered = existing.filter(existingKey => existingKey !== collectionKey)
if (filtered.length === 0) {
delete index[indexKey]
return
}
index[indexKey] = filtered
}
// Actions
/**
* Retrieve all or specific collections, optionally filtered by source selector
*
* @param sources - optional source selector
* @param filter - optional list filter
* @param sort - optional list sort
*
* @returns Promise with collection object list keyed by provider, service, and collection identifier
*/
async function list(sources?: ServiceIdentifier[] | CollectionIdentifier[], filter?: ListFilter, sort?: ListSort): Promise<Record<string, CollectionObject>> {
transceiving.value = true
try {
const response = await collectionService.list({ sources, filter, sort })
// Flatten nested structure: provider:service:collection -> "provider:service:collection": object
const collections: Record<string, CollectionObject> = {}
Object.entries(response).forEach(([_providerId, providerServices]) => {
Object.entries(providerServices).forEach(([_serviceId, serviceCollections]) => {
Object.entries(serviceCollections).forEach(([_collectionId, collectionObj]) => {
if (_collections.value[collectionObj.identifier]) {
deindexCollection(_collections.value[collectionObj.identifier])
}
collections[collectionObj.identifier] = collectionObj
})
})
})
// Merge retrieved collections into state
_collections.value = { ..._collections.value, ...collections }
Object.values(collections).forEach(collectionObj => {
indexCollection(collectionObj)
})
console.debug('[Mail Manager][Store] - Successfully retrieved', Object.keys(collections).length, 'collections')
return collections
} catch (error: any) {
console.error('[Mail Manager][Store] - Failed to retrieve collections:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Retrieve a specific collection by provider, service, and identifier
*
* @param provider - provider identifier
* @param service - service identifier
* @param identifier - collection identifier
*
* @returns Promise with collection object
*/
async function fetch(targets: CollectionIdentifier[]): Promise<Record<string, CollectionObject>> {
transceiving.value = true
try {
const response = await collectionService.fetch({ targets })
// Merge fetched collection into state
Object.values(response).forEach(collectionObj => {
if (_collections.value[collectionObj.identifier]) {
deindexCollection(_collections.value[collectionObj.identifier])
}
_collections.value[collectionObj.identifier] = collectionObj
indexCollection(collectionObj)
})
console.debug('[Mail Manager][Store] - Successfully fetched collections:', Object.keys(response).join(', '))
return response
} catch (error: any) {
console.error('[Mail Manager][Store] - Failed to fetch collections:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Retrieve collection availability status for a given source selector
*
* @param sources - source selector to check availability for
*
* @returns Promise with collection availability status
*/
async function extant(targets: CollectionIdentifier[]): Promise<Record<string, Record<string, Record<string, boolean>>>> {
transceiving.value = true
try {
const response = await collectionService.extant({ targets })
console.debug('[Mail Manager][Store] - Successfully checked', targets ? targets.length : 0, 'collections')
return response
} catch (error: any) {
console.error('[Mail Manager][Store] - Failed to check collections:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Create a new collection with given provider, service, and data
*
* @param provider - provider identifier for the new collection
* @param service - service identifier for the new collection
* @param collection - optional parent collection identifier
* @param data - collection properties for creation
*
* @returns Promise with created collection object
*/
async function create(provider: string, service: string | number, properties: CollectionPropertiesObject, target?: CollectionIdentifier): Promise<CollectionObject> {
transceiving.value = true
try {
const response = await collectionService.create({
provider,
service,
target,
properties: properties.toJson()
})
if (response instanceof CollectionObject) {
_collections.value[response.identifier] = response
indexCollection(response)
}
console.debug('[Mail Manager][Store] - Successfully created collection:', response.identifier)
return response
} catch (error: any) {
console.error('[Mail Manager][Store] - Failed to create collection:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Update an existing collection with given target and properties
*
* @param target - collection identifier for the collection to update
* @param properties - collection properties for update
*
* @returns Promise with updated collection object
*/
async function update(target: CollectionIdentifier, properties: CollectionPropertiesObject): Promise<CollectionObject> {
transceiving.value = true
try {
const response = await collectionService.update({
target,
properties: properties.toJson()
})
if (_collections.value[target]) {
deindexCollection(_collections.value[target])
}
if (response instanceof CollectionObject) {
_collections.value[response.identifier] = response
indexCollection(response)
}
console.debug('[Mail Manager][Store] - Successfully updated collection:', response.identifier)
return response
} catch (error: any) {
console.error('[Mail Manager][Store] - Failed to update collection:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Delete a collection by identifier, with optional force delete if collection is not empty.
*
* @param target - collection identifier for the collection to delete
* @param force - optional flag to force delete if collection is not empty
*
* @returns Promise with deletion result
*/
async function remove(target: CollectionIdentifier, force?: boolean): Promise<CollectionObject | boolean> {
transceiving.value = true
try {
const response = await collectionService.delete({ target, options: { force } })
if (response !== true && !(response instanceof CollectionObject)) {
console.warn('[Mail Manager][Store] - Delete failed. Received unexpected response from delete operation:', response)
return false
}
if (_collections.value[target]) {
deindexCollection(_collections.value[target])
}
delete _collections.value[target]
if (response instanceof CollectionObject) {
_collections.value[response.identifier] = response
indexCollection(response)
console.debug('[Mail Manager][Store] - Successfully moved collection to trash', target, '->', response.identifier)
return response
}
console.debug('[Mail Manager][Store] - Successfully deleted collection:', target)
return response
} catch (error: any) {
console.error('[Mail Manager][Store] - Failed to delete collection:', error)
throw error
} finally {
transceiving.value = false
}
}
/**
* Move collections to another target collection.
*
* Updates local store keys for successfully moved collections when they are
* already present in cache.
*
* @param target - target collection identifier
* @param source - source collection identifier
*
* @returns Promise with move results keyed by source identifier
*/
async function move(target: CollectionIdentifier, source: CollectionIdentifier): Promise<CollectionObject> {
transceiving.value = true
try {
const response = await collectionService.move({ target, source })
if (!(response instanceof CollectionObject)) {
console.warn('[Mail Manager][Store] - Move failed. Received unexpected response from move operation:', response)
throw new Error('Failed to move collection: unexpected response from move operation')
}
if (_collections.value[source]) {
deindexCollection(_collections.value[source])
}
delete _collections.value[source]
_collections.value[response.identifier] = response
indexCollection(response)
console.debug('[Mail Manager][Store] - Successfully moved collection:', source, ' to ', response.identifier)
return response
} catch (error: any) {
console.error('[Mail Manager][Store] - Failed to move collection:', error)
throw error
} finally {
transceiving.value = false
}
}
// Return public API
return {
// State (readonly)
transceiving: readonly(transceiving),
// Getters
count,
has,
collections,
collectionsByService,
collectionsForService,
collectionsInCollection,
hasChildrenInCollection,
// Actions
collection,
list,
fetch,
extant,
create,
update,
delete: remove,
move,
}
})