All files / app/services/articles/article-history article-history.service.ts

94.83% Statements 147/155
87.69% Branches 57/65
96.42% Functions 27/28
97.03% Lines 131/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 2774x 4x 4x 4x 4x 4x 4x                                                           4x       12x   9x 9x   9x 18x 18x 11x 11x   18x     9x     4x                       4x 43x 43x 43x 43x 43x 43x   43x 43x 43x 43x 43x 43x 43x 43x 43x       43x 43x 43x 43x   43x   43x 43x   43x 9x 9x   9x   3x 3x   4x             3x     43x 4x 4x 4x 4x 2x 2x 2x 1x     43x   5x   5x 4x         44x 44x 44x       15x 14x 14x 14x 14x 14x 14x 14x       4x 4x   3x 3x       2x         2x 1x     1x 1x           58x 18x 18x     40x     40x       61x 3x   58x     61x   61x 61x 3x 3x 3x     58x         54x 2x   52x 52x   54x 54x 54x     3x 3x 1x 1x   2x 2x             61x       61x 8x 8x 2x 2x   6x     59x 59x 5x   54x           5x     5x   49x 2x 2x 1x 1x   1x     47x      
import { AuthService } from '../../auth/auth.service';
import { InworkService } from '../../inwork/inwork.service';
import { ArticleService } from '../article.service';
import { computed, DestroyRef, inject, Injectable, Signal, signal } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { LoggerService, NotificationService } from '@drevo-web/core';
import {
    ApprovalStatus,
    ArticleHistoryItem,
    ArticleHistoryParams,
    formatDateHeader,
    InworkItem,
} from '@drevo-web/shared';
 
export type HistoryFilter =
    | 'all'
    | 'unchecked'
    | 'unfinished'
    | 'unmarked'
    | 'outside_dictionaries'
    | 'required'
    | 'my';
 
export type HistoryDisplayItem =
    | { readonly type: 'header'; readonly date: string }
    | { readonly type: 'version'; readonly data: ArticleHistoryItem }
    | { readonly type: 'inwork-header' }
    | { readonly type: 'inwork-item'; readonly data: InworkItem; readonly isOwn: boolean };
 
/**
 * Builds display items with date headers inserted between date groups.
 *
 * @param items - Flat list of history items sorted by date descending
 * @param referenceDate - Date used for relative date formatting (e.g. "Сегодня")
 * @returns Items interleaved with date group headers
 */
export function buildDisplayItems(
    items: readonly ArticleHistoryItem[],
    referenceDate: Date,
): readonly HistoryDisplayItem[] {
    if (items.length === 0) return [];
 
    const result: HistoryDisplayItem[] = [];
    let lastDateKey = '';
 
    for (const item of items) {
        const dateKey = formatDateHeader(item.date, referenceDate);
        if (dateKey !== lastDateKey) {
            result.push({ type: 'header', date: dateKey });
            lastDateKey = dateKey;
        }
        result.push({ type: 'version', data: item });
    }
 
    return result;
}
 
export const trackByFn = (_index: number, item: HistoryDisplayItem): string => {
    if (item.type === 'header') return `header-${item.date}`;
    if (item.type === 'inwork-header') return 'inwork-header';
    if (item.type === 'inwork-item') return `inwork-${item.data.title}-${item.data.author}`;
    return `version-${item.data.versionId}`;
};
 
export interface ArticleHistoryConfig {
    readonly articleId?: Signal<number | undefined>;
}
 
@Injectable()
export class ArticleHistoryService {
    private readonly destroyRef = inject(DestroyRef);
    private readonly articleService = inject(ArticleService);
    private readonly authService = inject(AuthService);
    private readonly inworkService = inject(InworkService);
    private readonly notificationService = inject(NotificationService);
    private readonly logger = inject(LoggerService).withContext('ArticleHistoryService');
 
    private readonly _historyItems = signal<readonly ArticleHistoryItem[]>([]);
    private readonly _inworkItems = signal<readonly InworkItem[]>([]);
    private readonly _isLoading = signal(false);
    private readonly _isLoadingMore = signal(false);
    private readonly _totalItems = signal(0);
    private readonly _currentPage = signal(1);
    private readonly _activeFilter = signal<HistoryFilter>('all');
    private readonly _hasError = signal(false);
    private readonly _referenceDate = signal(new Date());
 
    private articleId?: Signal<number | undefined>;
 
    readonly isLoading = this._isLoading.asReadonly();
    readonly isLoadingMore = this._isLoadingMore.asReadonly();
    readonly activeFilter = this._activeFilter.asReadonly();
    readonly hasError = this._hasError.asReadonly();
 
    private readonly currentUser = toSignal(this.authService.user$);
 
    readonly isAuthenticated = computed(() => !!this.currentUser());
    readonly hasItems = computed(() => this._historyItems().length > 0 || this._inworkItems().length > 0);
 
    readonly displayItems = computed<readonly HistoryDisplayItem[]>(() => {
        const historyItems = buildDisplayItems(this._historyItems(), this._referenceDate());
        const inworkItems = this._inworkItems();
 
        if (inworkItems.length === 0) return historyItems;
 
        const currentName = this.currentUser()?.name;
        const inworkDisplayItems: HistoryDisplayItem[] = [
            { type: 'inwork-header' },
            ...inworkItems.map(item => ({
                type: 'inwork-item' as const,
                data: item,
                isOwn: item.author === currentName,
            })),
        ];
 
        return [...inworkDisplayItems, ...historyItems];
    });
 
    readonly displayTotalItems = computed(() => {
        const inworkCount = this._inworkItems().length;
        const inworkDisplayCount = inworkCount > 0 ? inworkCount + 1 : 0;
        const total = this._totalItems();
        if (total === 0) return inworkDisplayCount;
        const loadedDisplayCount = this.displayItems().length;
        const loadedItemCount = this._historyItems().length;
        if (loadedItemCount >= total) return loadedDisplayCount;
        return loadedDisplayCount + (total - loadedItemCount);
    });
 
    readonly inworkVersionIds = computed(
        () =>
            new Set(
                this._inworkItems()
                    .filter(item => item.id > 0)
                    .map(item => item.id),
            ),
    );
 
    init(config?: ArticleHistoryConfig): void {
        this.articleId = config?.articleId;
        this.loadInworkIfNeeded();
        this.loadHistory();
    }
 
    onFilterChange(filter: HistoryFilter): void {
        if (this._activeFilter() === filter) return;
        this._activeFilter.set(filter);
        this._historyItems.set([]);
        this._currentPage.set(1);
        this._totalItems.set(0);
        this.logger.info('Filter changed', { filter });
        this.loadInworkIfNeeded();
        this.loadHistory();
    }
 
    onLoadMore(): void {
        Iif (this._isLoading() || this._isLoadingMore()) return;
        if (this._historyItems().length >= this._totalItems()) return;
 
        this._currentPage.update(p => p + 1);
        this.loadHistory(true);
    }
 
    onCancelInwork(title: string): void {
        this.inworkService
            .clearEditing(title)
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe({
                next: () => {
                    this._inworkItems.update(items => items.filter(item => item.title !== title));
                    this.logger.info('Cleared inwork editing mark', { title });
                },
                error: err => {
                    this.logger.error('Failed to clear editing mark', err);
                    this.notificationService.error('Не удалось снять метку редактирования');
                },
            });
    }
 
    private loadInworkIfNeeded(): void {
        if (this.articleId || this._activeFilter() !== 'all') {
            this._inworkItems.set([]);
            return;
        }
 
        this.inworkService
            .getInworkList()
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe(items => this._inworkItems.set(items));
    }
 
    private loadHistory(loadMore = false): void {
        if (loadMore) {
            this._isLoadingMore.set(true);
        } else {
            this._isLoading.set(true);
        }
 
        this._hasError.set(false);
 
        const params = this.buildParams();
        if (!params) {
            this._isLoading.set(false);
            this._isLoadingMore.set(false);
            return;
        }
 
        this.articleService
            .getArticlesHistory(params)
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe({
                next: response => {
                    if (loadMore) {
                        this._historyItems.update(items => [...items, ...response.items]);
                    } else {
                        this._historyItems.set(response.items);
                        this._referenceDate.set(new Date());
                    }
                    this._totalItems.set(response.total);
                    this._isLoading.set(false);
                    this._isLoadingMore.set(false);
                },
                error: error => {
                    this.logger.error('Failed to load article history', error);
                    if (loadMore) {
                        this._isLoadingMore.set(false);
                        this._currentPage.update(p => p - 1);
                    } else {
                        this._isLoading.set(false);
                        this._hasError.set(true);
                    }
                },
            });
    }
 
    private buildParams(): ArticleHistoryParams | undefined {
        let base: ArticleHistoryParams = {
            page: this._currentPage(),
        };
 
        if (this.articleId) {
            const id = this.articleId();
            if (!id) {
                this.logger.error('Cannot load history: article ID not available');
                return undefined;
            }
            base = { ...base, articleId: id };
        }
 
        const filter = this._activeFilter();
        if (filter === 'unchecked') {
            return { ...base, approved: ApprovalStatus.Pending };
        }
        if (
            filter === 'unfinished' ||
            filter === 'unmarked' ||
            filter === 'outside_dictionaries' ||
            filter === 'required'
        ) {
            this.logger.info('Filter not yet supported by backend', {
                filter,
            });
            return base;
        }
        if (filter === 'my') {
            const user = this.currentUser();
            if (!user) {
                this.logger.error('Cannot filter by author: user not loaded');
                return undefined;
            }
            return { ...base, author: user.login };
        }
 
        return base;
    }
}