1 import { Subject } from 'rxjs'
2 import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'
3 import { ComponentPagination, hasMoreItems, Notifier } from '@app/core'
4 import { UserNotificationType, AbuseState } from '@shared/models'
5 import { UserNotification } from './user-notification.model'
6 import { UserNotificationService } from './user-notification.service'
9 selector: 'my-user-notifications',
10 templateUrl: 'user-notifications.component.html',
11 styleUrls: [ 'user-notifications.component.scss' ]
13 export class UserNotificationsComponent implements OnInit {
14 @Input() ignoreLoadingBar = false
15 @Input() infiniteScroll = true
16 @Input() itemsPerPage = 20
17 @Input() markAllAsReadSubject: Subject<boolean>
19 @Output() notificationsLoaded = new EventEmitter()
21 notifications: UserNotification[] = []
22 sortField = 'createdAt'
24 // So we can access it in the template
25 UserNotificationType = UserNotificationType
27 componentPagination: ComponentPagination
29 onDataSubject = new Subject<any[]>()
32 private userNotificationService: UserNotificationService,
33 private notifier: Notifier
37 this.componentPagination = {
39 itemsPerPage: this.itemsPerPage, // Reset items per page, because of the @Input() variable
43 this.loadNotifications()
45 if (this.markAllAsReadSubject) {
46 this.markAllAsReadSubject.subscribe(() => this.markAllAsRead())
50 loadNotifications (reset?: boolean) {
51 this.userNotificationService.listMyNotifications({
52 pagination: this.componentPagination,
53 ignoreLoadingBar: this.ignoreLoadingBar,
55 field: this.sortField,
56 // if we order by creation date, we want DESC. all other fields are ASC (like unread).
57 order: this.sortField === 'createdAt' ? -1 : 1
62 this.notifications = reset ? result.data : this.notifications.concat(result.data)
63 this.componentPagination.totalItems = result.total
65 this.notificationsLoaded.emit()
67 this.onDataSubject.next(result.data)
70 err => this.notifier.error(err.message)
75 if (this.infiniteScroll === false) return
77 this.componentPagination.currentPage++
79 if (hasMoreItems(this.componentPagination)) {
80 this.loadNotifications()
84 markAsRead (notification: UserNotification) {
85 if (notification.read) return
87 this.userNotificationService.markAsRead(notification)
90 notification.read = true
93 err => this.notifier.error(err.message)
98 this.userNotificationService.markAllAsRead()
101 for (const notification of this.notifications) {
102 notification.read = true
106 err => this.notifier.error(err.message)
110 changeSortColumn (column: string) {
111 this.componentPagination = {
113 itemsPerPage: this.itemsPerPage,
116 this.sortField = column
117 this.loadNotifications(true)
120 isAccepted (notification: UserNotification) {
121 return notification.abuse.state === AbuseState.ACCEPTED