]> git.ipfire.org Git - thirdparty/paperless-ngx.git/blob
e3f7153b48122f4a558689634e04ad38d75fad8f
[thirdparty/paperless-ngx.git] /
1 import { NgTemplateOutlet } from '@angular/common'
2 import {
3 Component,
4 EventEmitter,
5 inject,
6 Input,
7 Output,
8 QueryList,
9 ViewChild,
10 ViewChildren,
11 } from '@angular/core'
12 import { FormsModule, ReactiveFormsModule } from '@angular/forms'
13 import {
14 NgbDatepickerModule,
15 NgbDropdown,
16 NgbDropdownModule,
17 } from '@ng-bootstrap/ng-bootstrap'
18 import { NgSelectComponent, NgSelectModule } from '@ng-select/ng-select'
19 import { NgxBootstrapIconsModule } from 'ngx-bootstrap-icons'
20 import { first, Subject, takeUntil } from 'rxjs'
21 import { CustomField, CustomFieldDataType } from 'src/app/data/custom-field'
22 import {
23 CUSTOM_FIELD_QUERY_MAX_ATOMS,
24 CUSTOM_FIELD_QUERY_MAX_DEPTH,
25 CUSTOM_FIELD_QUERY_OPERATOR_GROUPS_BY_TYPE,
26 CUSTOM_FIELD_QUERY_OPERATOR_LABELS,
27 CUSTOM_FIELD_QUERY_OPERATORS_BY_GROUP,
28 CustomFieldQueryElementType,
29 CustomFieldQueryOperator,
30 CustomFieldQueryOperatorGroups,
31 } from 'src/app/data/custom-field-query'
32 import { CustomFieldsService } from 'src/app/services/rest/custom-fields.service'
33 import {
34 CustomFieldQueryAtom,
35 CustomFieldQueryElement,
36 CustomFieldQueryExpression,
37 } from 'src/app/utils/custom-field-query-element'
38 import { pngxPopperOptions } from 'src/app/utils/popper-options'
39 import { LoadingComponentWithPermissions } from '../../loading-component/loading.component'
40 import { ClearableBadgeComponent } from '../clearable-badge/clearable-badge.component'
41 import { DocumentLinkComponent } from '../input/document-link/document-link.component'
42
43 export class CustomFieldQueriesModel {
44 public queries: CustomFieldQueryElement[] = []
45
46 public readonly changed = new Subject<CustomFieldQueriesModel>()
47
48 public clear(fireEvent = true) {
49 this.queries = []
50 if (fireEvent) {
51 this.changed.next(this)
52 }
53 }
54
55 public isValid(): boolean {
56 return (
57 this.queries.length > 0 &&
58 this.validateExpression(this.queries[0] as CustomFieldQueryExpression)
59 )
60 }
61
62 public isEmpty(): boolean {
63 return (
64 this.queries.length === 0 ||
65 (this.queries.length === 1 && this.queries[0].value.length === 0)
66 )
67 }
68
69 private validateAtom(atom: CustomFieldQueryAtom) {
70 let valid = !!(atom.field && atom.operator && atom.value !== null)
71 if (
72 [
73 CustomFieldQueryOperator.In.valueOf(),
74 CustomFieldQueryOperator.Contains.valueOf(),
75 ].includes(atom.operator) &&
76 atom.value
77 ) {
78 valid = valid && atom.value.length > 0
79 }
80 return valid
81 }
82
83 private validateExpression(expression: CustomFieldQueryExpression) {
84 return (
85 expression.operator &&
86 expression.value.length > 0 &&
87 (expression.value as CustomFieldQueryElement[]).every((e) =>
88 e.type === CustomFieldQueryElementType.Atom
89 ? this.validateAtom(e as CustomFieldQueryAtom)
90 : this.validateExpression(e as CustomFieldQueryExpression)
91 )
92 )
93 }
94
95 public addAtom(atom: CustomFieldQueryAtom) {
96 if (this.queries.length === 0) {
97 this.addExpression()
98 }
99 ;(this.queries[0].value as CustomFieldQueryElement[]).push(atom)
100 atom.changed.subscribe(() => {
101 if (atom.field && atom.operator && atom.value) {
102 this.changed.next(this)
103 }
104 })
105 }
106
107 public addExpression(
108 expression: CustomFieldQueryExpression = new CustomFieldQueryExpression()
109 ) {
110 if (this.queries.length > 0) {
111 ;(
112 (this.queries[0] as CustomFieldQueryExpression)
113 .value as CustomFieldQueryElement[]
114 ).push(expression)
115 } else {
116 this.queries.push(expression)
117 }
118 expression.changed.subscribe(() => {
119 this.changed.next(this)
120 })
121 }
122
123 private findElement(
124 queryElement: CustomFieldQueryElement,
125 elements: any[]
126 ): CustomFieldQueryElement {
127 let foundElement
128 for (let i = 0; i < elements.length; i++) {
129 if (elements[i] === queryElement) {
130 foundElement = elements.splice(i, 1)[0]
131 } else if (elements[i].type === CustomFieldQueryElementType.Expression) {
132 foundElement = this.findElement(
133 queryElement,
134 elements[i].value as CustomFieldQueryElement[]
135 )
136 }
137 if (foundElement) {
138 break
139 }
140 }
141 return foundElement
142 }
143
144 public removeElement(queryElement: CustomFieldQueryElement) {
145 let foundComponent
146 for (let i = 0; i < this.queries.length; i++) {
147 let query = this.queries[i]
148 if (query === queryElement) {
149 foundComponent = this.queries.splice(i, 1)[0]
150 break
151 } else if (query.type === CustomFieldQueryElementType.Expression) {
152 foundComponent = this.findElement(queryElement, query.value as any[])
153 }
154 }
155 if (foundComponent) {
156 foundComponent.changed.complete()
157 if (this.isEmpty()) {
158 this.clear()
159 }
160 this.changed.next(this)
161 }
162 }
163 }
164
165 @Component({
166 selector: 'pngx-custom-fields-query-dropdown',
167 templateUrl: './custom-fields-query-dropdown.component.html',
168 styleUrls: ['./custom-fields-query-dropdown.component.scss'],
169 imports: [
170 ClearableBadgeComponent,
171 FormsModule,
172 DocumentLinkComponent,
173 ReactiveFormsModule,
174 NgbDatepickerModule,
175 NgTemplateOutlet,
176 NgSelectModule,
177 NgxBootstrapIconsModule,
178 NgbDropdownModule,
179 ],
180 })
181 export class CustomFieldsQueryDropdownComponent extends LoadingComponentWithPermissions {
182 protected customFieldsService = inject(CustomFieldsService)
183
184 public CustomFieldQueryComponentType = CustomFieldQueryElementType
185 public CustomFieldQueryOperator = CustomFieldQueryOperator
186 public CustomFieldDataType = CustomFieldDataType
187 public CUSTOM_FIELD_QUERY_MAX_DEPTH = CUSTOM_FIELD_QUERY_MAX_DEPTH
188 public CUSTOM_FIELD_QUERY_MAX_ATOMS = CUSTOM_FIELD_QUERY_MAX_ATOMS
189 public popperOptions = pngxPopperOptions
190
191 @Input()
192 title: string
193
194 @Input()
195 filterPlaceholder: string = ''
196
197 @Input()
198 icon: string
199
200 @Input()
201 allowSelectNone: boolean = false
202
203 @Input()
204 editing = false
205
206 @Input()
207 applyOnClose = false
208
209 get name(): string {
210 return this.title ? this.title.replace(/\s/g, '_').toLowerCase() : null
211 }
212
213 @Input()
214 disabled: boolean = false
215
216 @ViewChild('dropdown') dropdown: NgbDropdown
217
218 @ViewChildren(NgSelectComponent) fieldSelects!: QueryList<NgSelectComponent>
219
220 private _selectionModel: CustomFieldQueriesModel
221
222 @Input()
223 set selectionModel(model: CustomFieldQueriesModel) {
224 if (this._selectionModel) {
225 this._selectionModel.changed.complete()
226 }
227 model.changed.subscribe(() => {
228 this.onModelChange()
229 })
230 this._selectionModel = model
231 }
232
233 get selectionModel(): CustomFieldQueriesModel {
234 return this._selectionModel
235 }
236
237 private onModelChange() {
238 if (this.selectionModel.isEmpty() || this.selectionModel.isValid()) {
239 this.selectionModelChange.next(this.selectionModel)
240 this.selectionModel.isEmpty() && this.dropdown?.close()
241 }
242 }
243
244 @Output()
245 selectionModelChange = new EventEmitter<CustomFieldQueriesModel>()
246
247 customFields: CustomField[] = []
248
249 public readonly today: string = new Date().toISOString().split('T')[0]
250
251 constructor() {
252 super()
253 this.selectionModel = new CustomFieldQueriesModel()
254 this.getFields()
255 this.reset()
256 }
257
258 public onOpenChange(open: boolean) {
259 if (open) {
260 if (this.selectionModel.queries.length === 0) {
261 this.selectionModel.addAtom(
262 new CustomFieldQueryAtom([
263 null,
264 CustomFieldQueryOperator.Exists,
265 'true',
266 ])
267 )
268 }
269 if (
270 this.selectionModel.queries.length === 1 &&
271 (
272 (this.selectionModel.queries[0] as CustomFieldQueryExpression)
273 ?.value[0] as CustomFieldQueryAtom
274 )?.field === null
275 ) {
276 setTimeout(() => {
277 this.fieldSelects.first?.focus()
278 }, 0)
279 }
280 }
281 }
282
283 public get isActive(): boolean {
284 return this.selectionModel.isValid()
285 }
286
287 private getFields() {
288 this.customFieldsService
289 .listAll()
290 .pipe(first(), takeUntil(this.unsubscribeNotifier))
291 .subscribe((result) => {
292 this.customFields = result.results
293 })
294 }
295
296 public getCustomFieldByID(id: number): CustomField {
297 return this.customFields.find((field) => field.id === id)
298 }
299
300 public addAtom(expression: CustomFieldQueryExpression) {
301 expression.addAtom()
302 }
303
304 public addExpression(expression: CustomFieldQueryExpression) {
305 expression.addExpression()
306 }
307
308 public removeElement(element: CustomFieldQueryElement) {
309 this.selectionModel.removeElement(element)
310 }
311
312 public reset() {
313 this.selectionModel.clear(false)
314 this.selectionModel.changed.next(this.selectionModel)
315 }
316
317 getOperatorsForField(
318 fieldID: number
319 ): Array<{ value: string; label: string }> {
320 const field = this.customFields.find((field) => field.id === fieldID)
321 const groups: CustomFieldQueryOperatorGroups[] = field
322 ? CUSTOM_FIELD_QUERY_OPERATOR_GROUPS_BY_TYPE[field.data_type]
323 : [CustomFieldQueryOperatorGroups.Basic]
324 const operators = groups.flatMap(
325 (group) => CUSTOM_FIELD_QUERY_OPERATORS_BY_GROUP[group]
326 )
327 return operators.map((operator) => ({
328 value: operator,
329 label: CUSTOM_FIELD_QUERY_OPERATOR_LABELS[operator],
330 }))
331 }
332
333 getSelectOptionsForField(
334 fieldID: number
335 ): Array<{ label: string; id: string }> {
336 const field = this.customFields.find((field) => field.id === fieldID)
337 if (field) {
338 return field.extra_data['select_options']
339 }
340 return []
341 }
342 }