feat: scope articles by brand
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
import type { Brand } from '@geo/shared-types'
|
||||
|
||||
import { brandsApi } from '@/lib/api'
|
||||
import {
|
||||
clearStoredCurrentBrandId,
|
||||
readStoredCurrentBrandId,
|
||||
writeStoredCurrentBrandId,
|
||||
} from '@/lib/current-brand'
|
||||
|
||||
export const useCompanyStore = defineStore('company', () => {
|
||||
const brands = ref<Brand[]>([])
|
||||
const currentBrandId = ref<number | null>(readStoredCurrentBrandId())
|
||||
const loading = ref(false)
|
||||
const initialized = ref(false)
|
||||
|
||||
const currentBrand = computed(
|
||||
() => brands.value.find((brand) => brand.id === currentBrandId.value) ?? null,
|
||||
)
|
||||
const hasBrands = computed(() => brands.value.length > 0)
|
||||
|
||||
function setCurrentBrand(brandId: number | null): void {
|
||||
if (!brandId) {
|
||||
currentBrandId.value = null
|
||||
clearStoredCurrentBrandId()
|
||||
return
|
||||
}
|
||||
|
||||
currentBrandId.value = brandId
|
||||
writeStoredCurrentBrandId(brandId)
|
||||
}
|
||||
|
||||
function normalizeBrandList(value: Brand[] | null | undefined): Brand[] {
|
||||
return Array.isArray(value) ? value : []
|
||||
}
|
||||
|
||||
function syncCurrentBrand(value: Brand[] | null | undefined): void {
|
||||
const nextBrands = normalizeBrandList(value)
|
||||
const storedId = readStoredCurrentBrandId()
|
||||
const preferredId = currentBrandId.value ?? storedId
|
||||
const matched = preferredId
|
||||
? nextBrands.find((brand) => brand.id === preferredId)
|
||||
: undefined
|
||||
|
||||
if (matched) {
|
||||
setCurrentBrand(matched.id)
|
||||
return
|
||||
}
|
||||
|
||||
if (nextBrands.length > 0) {
|
||||
setCurrentBrand(nextBrands[0].id)
|
||||
return
|
||||
}
|
||||
|
||||
setCurrentBrand(null)
|
||||
}
|
||||
|
||||
async function refreshBrands(): Promise<Brand[]> {
|
||||
loading.value = true
|
||||
try {
|
||||
const nextBrands = normalizeBrandList(await brandsApi.list())
|
||||
brands.value = nextBrands
|
||||
syncCurrentBrand(nextBrands)
|
||||
initialized.value = true
|
||||
return nextBrands
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function reset(): void {
|
||||
brands.value = []
|
||||
currentBrandId.value = null
|
||||
initialized.value = false
|
||||
loading.value = false
|
||||
clearStoredCurrentBrandId()
|
||||
}
|
||||
|
||||
return {
|
||||
brands,
|
||||
currentBrandId,
|
||||
currentBrand,
|
||||
hasBrands,
|
||||
loading,
|
||||
initialized,
|
||||
refreshBrands,
|
||||
setCurrentBrand,
|
||||
reset,
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user