|
| 1 | +import type { HttpErrorResponse } from '@angular/common/http' |
| 2 | +import { HttpClient } from '@angular/common/http' |
| 3 | +import { inject, Injectable } from '@angular/core' |
| 4 | +import { BehaviorSubject, catchError, map, take, tap } from 'rxjs' |
| 5 | +import { ErrorService } from '@seed/services' |
| 6 | +import { naturalSort } from '@seed/utils' |
| 7 | +import { UserService } from '../user' |
| 8 | +import type { FilterGroup, FilterGroupInventoryType, FilterGroupsResponse } from './filter-group.types' |
| 9 | + |
| 10 | +@Injectable({ providedIn: 'root' }) |
| 11 | +export class FilterGroupService { |
| 12 | + private _errorService = inject(ErrorService) |
| 13 | + private _filterGroups = new BehaviorSubject<FilterGroup[]>([]) |
| 14 | + private _httpClient = inject(HttpClient) |
| 15 | + private _userService = inject(UserService) |
| 16 | + |
| 17 | + filterGroups$ = this._filterGroups.asObservable() |
| 18 | + |
| 19 | + constructor() { |
| 20 | + this._userService.currentOrganizationId$ |
| 21 | + .pipe( |
| 22 | + tap((orgId) => { |
| 23 | + this.list(orgId, 'Property') |
| 24 | + }), |
| 25 | + ) |
| 26 | + .subscribe() |
| 27 | + } |
| 28 | + |
| 29 | + list(orgId: number, inventoryType: FilterGroupInventoryType = 'Property') { |
| 30 | + const url = `/api/v3/filter_groups/?organization_id=${orgId}&inventory_type=${inventoryType}` |
| 31 | + this._httpClient |
| 32 | + .get<FilterGroupsResponse>(url) |
| 33 | + .pipe( |
| 34 | + take(1), |
| 35 | + map(({ data }) => { |
| 36 | + const filterGroups = data.toSorted((a, b) => naturalSort(a.name, b.name)) |
| 37 | + this._filterGroups.next(filterGroups) |
| 38 | + return filterGroups |
| 39 | + }), |
| 40 | + catchError((error: HttpErrorResponse) => { |
| 41 | + return this._errorService.handleError(error, 'Error fetching filter groups') |
| 42 | + }), |
| 43 | + ) |
| 44 | + .subscribe() |
| 45 | + } |
| 46 | +} |
0 commit comments