Compare commits

..
Author SHA1 Message Date
Trenton H 56ba15d2e0 Chore: remove unused test helpers
Drops the shared_samples_dir fixture, MailAttachmentMock, _SHORT_TEXT and _make_extract_text, none of which any test used.
2026-11-16 09:15:38 -08:00
Trenton H 919e6838c4 Chore: remove unused GNUPG_HOME setting
Nothing read it. The mail GPG code uses EMAIL_GNUPG_HOME.
2026-11-16 08:01:53 -08:00
Trenton H 1c6a7fe970 Chore: remove unused TASK_WORKERS setting
An alias of CELERY_WORKER_CONCURRENCY that nothing read. PAPERLESS_TASK_WORKERS is unchanged.
2026-11-16 08:01:28 -08:00
Trenton H facc8b07ff Chore: remove unused RtlLanguageException
A leftover from the old tesseract parser, nothing referenced it.
2026-11-16 07:50:51 -08:00
Trenton H 28365eb610 Chore: remove unused ColorField and DeprecatedColors
No serializer used ColorField, and DeprecatedColors was only referenced by it.
2026-11-16 07:38:37 -08:00
Trenton H 02d2da6731 Chore: remove legacy DocumentParser base class
Parsers are resolved through the parser registry and ParserProtocol now, and nothing referenced this class. Its now unused imports are removed too.
2026-11-16 07:37:07 -08:00
Trenton H 56a1ef64c3 Chore: remove unused DocumentViewSet._has_document_permissions
It duplicated has_document_operation_permissions and had no callers.
2026-11-16 07:34:36 -08:00
Trenton H 03e53fd724 Chore: remove unused SanityCheckMessages summary properties
has_global_issues was never referenced and total_issue_count was only asserted in tests. The two private issue counters that fed it are removed as well, and the tests assert on has_error and has_warning instead.
2026-11-16 07:22:22 -08:00
Trenton H e1bd11d0e4 Chore: remove unused Tag.parent_pk
It was an alias of tn_parent_id used only by two test asserts, which now use tn_parent_id directly.
2026-11-16 07:19:12 -08:00
Trenton H 1326378a90 Chore: remove unused is_file_ext_supported
Nothing in production called it, only its own test.
2026-11-16 07:18:53 -08:00
182 changed files with 13586 additions and 29862 deletions

No files matched your search

-6
View File
@@ -285,12 +285,6 @@ The API supports various bulk-editing operations which are executed asynchronous
### Documents
Document bulk operations, including the dedicated document action endpoints, return
`{"result":"OK","task_id":"…"}` when queued. Use `/api/tasks/?task_id={uuid}`
to check the task outcome. Actions that create or reprocess files may start further
consumption or reprocessing tasks and completion of the bulk task means those tasks
were scheduled, not that their file processing has finished.
For bulk operations on documents, use the endpoint `/api/documents/bulk_edit/` which accepts
a json payload of the format:
-116
View File
@@ -1,121 +1,5 @@
# Changelog
## paperless-ngx 3.5.1
### Changes
- Tweak: adjust chat timing for streaming [@shamoon](https://github.com/shamoon) ([#14805](https://github.com/paperless-ngx/paperless-ngx/pull/14805))
### Bug Fixes
- Fix: dont use set\_actor if audit log disabled in tasks [@shamoon](https://github.com/shamoon) ([#14808](https://github.com/paperless-ngx/paperless-ngx/pull/14808))
- Fix: stream AI chat answers under ASGI [@stumpylog](https://github.com/stumpylog) ([#14803](https://github.com/paperless-ngx/paperless-ngx/pull/14803))
- Tweak/fix: retain bulk edit selection after queuing operation [@shamoon](https://github.com/shamoon) ([#14797](https://github.com/paperless-ngx/paperless-ngx/pull/14797))
### All App Changes
<details>
<summary>4 changes</summary>
- Fix: dont use set\_actor if audit log disabled in tasks [@shamoon](https://github.com/shamoon) ([#14808](https://github.com/paperless-ngx/paperless-ngx/pull/14808))
- Tweak: adjust chat timing for streaming [@shamoon](https://github.com/shamoon) ([#14805](https://github.com/paperless-ngx/paperless-ngx/pull/14805))
- Fix: stream AI chat answers under ASGI [@stumpylog](https://github.com/stumpylog) ([#14803](https://github.com/paperless-ngx/paperless-ngx/pull/14803))
- Tweak/fix: retain bulk edit selection after queuing operation [@shamoon](https://github.com/shamoon) ([#14797](https://github.com/paperless-ngx/paperless-ngx/pull/14797))
</details>
## paperless-ngx 3.5.0
### Features / Enhancements
- Chorehancement: move all bulk operations to async hand-off [@shamoon](https://github.com/shamoon) ([#14773](https://github.com/paperless-ngx/paperless-ngx/pull/14773))
- Enhancement: render document notes as markdown [@zwif](https://github.com/zwif) ([#14626](https://github.com/paperless-ngx/paperless-ngx/pull/14626))
- Feature: manual workflow trigger [@shamoon](https://github.com/shamoon) ([#14704](https://github.com/paperless-ngx/paperless-ngx/pull/14704))
- Enhancement: make bulk metadata operations run async [@shamoon](https://github.com/shamoon) ([#14711](https://github.com/paperless-ngx/paperless-ngx/pull/14711))
- Fixhancement: add automatic clearing of sessions [@shamoon](https://github.com/shamoon) ([#14722](https://github.com/paperless-ngx/paperless-ngx/pull/14722))
- Tweak: chat reference tweaks [@shamoon](https://github.com/shamoon) ([#14723](https://github.com/paperless-ngx/paperless-ngx/pull/14723))
- Fixhancement: rework saved view widget queue processing to expected [@shamoon](https://github.com/shamoon) ([#14699](https://github.com/paperless-ngx/paperless-ngx/pull/14699))
### Bug Fixes
- Fix: use a constant password mask and consolidate the no-change check [@stumpylog](https://github.com/stumpylog) ([#14784](https://github.com/paperless-ngx/paperless-ngx/pull/14784))
- Fix: use a PostgreSQL-compatible regex for scheduled workflow filename filters [@stumpylog](https://github.com/stumpylog) ([#14783](https://github.com/paperless-ngx/paperless-ngx/pull/14783))
- Fix: get users for saved view create dialog [@shamoon](https://github.com/shamoon) ([#14769](https://github.com/paperless-ngx/paperless-ngx/pull/14769))
- Fix: Allow AI chat filters over more than 32700 documents [@stumpylog](https://github.com/stumpylog) ([#14754](https://github.com/paperless-ngx/paperless-ngx/pull/14754))
- Fix: Enforce CRLF when writing an email message to the file [@stumpylog](https://github.com/stumpylog) ([#14745](https://github.com/paperless-ngx/paperless-ngx/pull/14745))
- Fix: restore image without archive version thumbnail generation [@shamoon](https://github.com/shamoon) ([#14741](https://github.com/paperless-ngx/paperless-ngx/pull/14741))
- Fix: Blacklist certain OCR user arguments that paperless itself uses [@stumpylog](https://github.com/stumpylog) ([#14734](https://github.com/paperless-ngx/paperless-ngx/pull/14734))
- Fix: remove redundant ui task text filters [@shamoon](https://github.com/shamoon) ([#14736](https://github.com/paperless-ngx/paperless-ngx/pull/14736))
- Fix: fix allowed\_hosts default [@shamoon](https://github.com/shamoon) ([#14735](https://github.com/paperless-ngx/paperless-ngx/pull/14735))
- Fixhancement: add automatic clearing of sessions [@shamoon](https://github.com/shamoon) ([#14722](https://github.com/paperless-ngx/paperless-ngx/pull/14722))
- Fix: two dropdown-related UI fixes [@shamoon](https://github.com/shamoon) ([#14717](https://github.com/paperless-ngx/paperless-ngx/pull/14717))
- Fix: use filtered documents for statistics ASN max [@shamoon](https://github.com/shamoon) ([#14710](https://github.com/paperless-ngx/paperless-ngx/pull/14710))
- Fix: make config view permissions consistent [@shamoon](https://github.com/shamoon) ([#14709](https://github.com/paperless-ngx/paperless-ngx/pull/14709))
- Fix: release the LLM index read lock before streaming the chat answer [@stumpylog](https://github.com/stumpylog) ([#14674](https://github.com/paperless-ngx/paperless-ngx/pull/14674))
- Fix: retrieve once per document chat question [@stumpylog](https://github.com/stumpylog) ([#14673](https://github.com/paperless-ngx/paperless-ngx/pull/14673))
- Fixhancement: rework saved view widget queue processing to expected [@shamoon](https://github.com/shamoon) ([#14699](https://github.com/paperless-ngx/paperless-ngx/pull/14699))
- Fix: apply PDF/A conversion once for mail archives [@shamoon](https://github.com/shamoon) ([#14698](https://github.com/paperless-ngx/paperless-ngx/pull/14698))
- Fix default MFA trusted AMR setting [@shamoon](https://github.com/shamoon) ([#14693](https://github.com/paperless-ngx/paperless-ngx/pull/14693))
- Fix: check descendant tag permissions on delete [@shamoon](https://github.com/shamoon) ([#14687](https://github.com/paperless-ngx/paperless-ngx/pull/14687))
- Fix: lock rows for first-user signup [@shamoon](https://github.com/shamoon) ([#14688](https://github.com/paperless-ngx/paperless-ngx/pull/14688))
- Fix: prevent ID badge wrapping under title on mobile [@shamoon](https://github.com/shamoon) ([#14682](https://github.com/paperless-ngx/paperless-ngx/pull/14682))
### Maintenance
- Chore(deps): Bump the actions group across 1 directory with 17 updates @[dependabot[bot]](https://github.com/apps/dependabot) ([#14691](https://github.com/paperless-ngx/paperless-ngx/pull/14691))
### Dependencies
<details>
<summary>4 changes</summary>
- Chore(deps): Bump the pre-commit-dependencies group with 4 updates @[dependabot[bot]](https://github.com/apps/dependabot) ([#14636](https://github.com/paperless-ngx/paperless-ngx/pull/14636))
- Chore(deps): Bump the actions group across 1 directory with 17 updates @[dependabot[bot]](https://github.com/apps/dependabot) ([#14691](https://github.com/paperless-ngx/paperless-ngx/pull/14691))
- docker(deps): bump astral-sh/uv from 0.13.5-python3.14-trixie-slim to 0.13.7-python3.14-trixie-slim @[dependabot[bot]](https://github.com/apps/dependabot) ([#14635](https://github.com/paperless-ngx/paperless-ngx/pull/14635))
- chore(deps): bump django-allauth to 65.21.1 [@stumpylog](https://github.com/stumpylog) ([#14672](https://github.com/paperless-ngx/paperless-ngx/pull/14672))
</details>
### All App Changes
<details>
<summary>32 changes</summary>
- Chorehancement: move all bulk operations to async hand-off [@shamoon](https://github.com/shamoon) ([#14773](https://github.com/paperless-ngx/paperless-ngx/pull/14773))
- Fix: use a constant password mask and consolidate the no-change check [@stumpylog](https://github.com/stumpylog) ([#14784](https://github.com/paperless-ngx/paperless-ngx/pull/14784))
- Fix: use a PostgreSQL-compatible regex for scheduled workflow filename filters [@stumpylog](https://github.com/stumpylog) ([#14783](https://github.com/paperless-ngx/paperless-ngx/pull/14783))
- Fix: get users for saved view create dialog [@shamoon](https://github.com/shamoon) ([#14769](https://github.com/paperless-ngx/paperless-ngx/pull/14769))
- Enhancement: render document notes as markdown [@zwif](https://github.com/zwif) ([#14626](https://github.com/paperless-ngx/paperless-ngx/pull/14626))
- Feature: manual workflow trigger [@shamoon](https://github.com/shamoon) ([#14704](https://github.com/paperless-ngx/paperless-ngx/pull/14704))
- Fix: Allow AI chat filters over more than 32700 documents [@stumpylog](https://github.com/stumpylog) ([#14754](https://github.com/paperless-ngx/paperless-ngx/pull/14754))
- Fix: Enforce CRLF when writing an email message to the file [@stumpylog](https://github.com/stumpylog) ([#14745](https://github.com/paperless-ngx/paperless-ngx/pull/14745))
- Enhancement: make bulk metadata operations run async [@shamoon](https://github.com/shamoon) ([#14711](https://github.com/paperless-ngx/paperless-ngx/pull/14711))
- Performance: load a cached Hugging Face embedding model without contacting the Hub [@stumpylog](https://github.com/stumpylog) ([#14728](https://github.com/paperless-ngx/paperless-ngx/pull/14728))
- Fix: restore image without archive version thumbnail generation [@shamoon](https://github.com/shamoon) ([#14741](https://github.com/paperless-ngx/paperless-ngx/pull/14741))
- Fix: Blacklist certain OCR user arguments that paperless itself uses [@stumpylog](https://github.com/stumpylog) ([#14734](https://github.com/paperless-ngx/paperless-ngx/pull/14734))
- Fix: remove redundant ui task text filters [@shamoon](https://github.com/shamoon) ([#14736](https://github.com/paperless-ngx/paperless-ngx/pull/14736))
- Fix: fix allowed\_hosts default [@shamoon](https://github.com/shamoon) ([#14735](https://github.com/paperless-ngx/paperless-ngx/pull/14735))
- Fixhancement: add automatic clearing of sessions [@shamoon](https://github.com/shamoon) ([#14722](https://github.com/paperless-ngx/paperless-ngx/pull/14722))
- Tweak: chat reference tweaks [@shamoon](https://github.com/shamoon) ([#14723](https://github.com/paperless-ngx/paperless-ngx/pull/14723))
- Fix: two dropdown-related UI fixes [@shamoon](https://github.com/shamoon) ([#14717](https://github.com/paperless-ngx/paperless-ngx/pull/14717))
- Fix: use filtered documents for statistics ASN max [@shamoon](https://github.com/shamoon) ([#14710](https://github.com/paperless-ngx/paperless-ngx/pull/14710))
- Fix: make config view permissions consistent [@shamoon](https://github.com/shamoon) ([#14709](https://github.com/paperless-ngx/paperless-ngx/pull/14709))
- Performance: stop embedding every document ID in selection\_data queries [@stumpylog](https://github.com/stumpylog) ([#14597](https://github.com/paperless-ngx/paperless-ngx/pull/14597))
- Performance: replace django-treenode with adjacency-list tags [@shamoon](https://github.com/shamoon) ([#14612](https://github.com/paperless-ngx/paperless-ngx/pull/14612))
- Performance: use small vec0 chunks and larger pages for the LLM index [@stumpylog](https://github.com/stumpylog) ([#14678](https://github.com/paperless-ngx/paperless-ngx/pull/14678))
- Fix: release the LLM index read lock before streaming the chat answer [@stumpylog](https://github.com/stumpylog) ([#14674](https://github.com/paperless-ngx/paperless-ngx/pull/14674))
- Fix: retrieve once per document chat question [@stumpylog](https://github.com/stumpylog) ([#14673](https://github.com/paperless-ngx/paperless-ngx/pull/14673))
- Fixhancement: rework saved view widget queue processing to expected [@shamoon](https://github.com/shamoon) ([#14699](https://github.com/paperless-ngx/paperless-ngx/pull/14699))
- Fix: apply PDF/A conversion once for mail archives [@shamoon](https://github.com/shamoon) ([#14698](https://github.com/paperless-ngx/paperless-ngx/pull/14698))
- Fix default MFA trusted AMR setting [@shamoon](https://github.com/shamoon) ([#14693](https://github.com/paperless-ngx/paperless-ngx/pull/14693))
- Fix: check descendant tag permissions on delete [@shamoon](https://github.com/shamoon) ([#14687](https://github.com/paperless-ngx/paperless-ngx/pull/14687))
- Fix: lock rows for first-user signup [@shamoon](https://github.com/shamoon) ([#14688](https://github.com/paperless-ngx/paperless-ngx/pull/14688))
- Fix: prevent ID badge wrapping under title on mobile [@shamoon](https://github.com/shamoon) ([#14682](https://github.com/paperless-ngx/paperless-ngx/pull/14682))
- chore(deps): bump django-allauth to 65.21.1 [@stumpylog](https://github.com/stumpylog) ([#14672](https://github.com/paperless-ngx/paperless-ngx/pull/14672))
- chore(deps): bump dev tooling [@stumpylog](https://github.com/stumpylog) ([#14671](https://github.com/paperless-ngx/paperless-ngx/pull/14671))
</details>
## paperless-ngx 3.4.2
### Bug Fixes
+3 -4
View File
@@ -1,6 +1,6 @@
[project]
name = "paperless-ngx"
version = "3.5.1"
version = "3.4.2"
description = """\
A community-supported supercharged document management system: scan, index and archive all your physical documents\
"""
@@ -151,9 +151,8 @@ typing = [
required-version = ">=0.9.0"
prerelease = "disallow"
environments = [
"sys_platform == 'darwin' and platform_machine == 'arm64' and platform_python_implementation == 'CPython'",
"sys_platform == 'linux' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython'",
"sys_platform == 'linux' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython'",
"sys_platform == 'darwin'",
"sys_platform == 'linux'",
]
package = false
[tool.uv.sources]
+249 -490
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paperless-ngx-ui",
"version": "3.5.1",
"version": "3.4.2",
"scripts": {
"preinstall": "npx only-allow pnpm",
"ng": "ng",
@@ -175,13 +175,7 @@
</div>
</td>
<td class="overflow-auto name-col">
@let documentCount = taskDocumentCount(task);
<div>
{{ taskDisplayName(task) }}
@if (documentCount !== null && documentCount > 1) {
<small class="text-muted ms-1" i18n>({documentCount, plural, =1 {1 document} other {{{ documentCount }} documents}})</small>
}
</div>
<div>{{ taskDisplayName(task) }}</div>
<div class="small text-muted">
@if (taskShowsSeparateTypeLabel(task)) {
<span class="me-2">{{ task.task_type_display }}</span>
@@ -895,117 +895,6 @@ describe('TasksComponent', () => {
expect(sanityTaskRow.nativeElement.textContent).toContain('System')
})
it.each([
['modify_tags', 12, 'Bulk operation: Update tags', '(12 documents)'],
['run_workflow', 1, 'Run workflow', null],
['delete', 3, 'Bulk operation: Move to trash', '(3 documents)'],
['reprocess', 2, 'Bulk operation: Document reprocessing', '(2 documents)'],
])(
'shows the operation, document count and outcome for %s',
(operation, count, label, summary) => {
const task: PaperlessTask = {
...tasks[4],
task_type:
operation === 'delete'
? PaperlessTaskType.BulkDelete
: PaperlessTaskType.BulkUpdate,
task_type_display:
operation === 'delete' ? 'Bulk Delete' : 'Bulk Update',
trigger_source: PaperlessTaskTriggerSource.WebUI,
trigger_source_display: 'Web UI',
input_data: { operation, document_count: count },
result_data: { operation, document_count: count },
}
component.setSection(TaskSection.Completed)
flushTaskLists(25, 1, [task])
fixture.detectChanges()
const name = fixture.nativeElement.querySelector('tbody .name-col')
expect(name.textContent).toContain(label)
const countLabel = name.querySelector('small.text-muted')
if (summary) {
expect(countLabel.textContent).toContain(summary)
} else {
expect(countLabel).toBeNull()
expect(name.textContent).not.toContain('Bulk operation:')
}
expect(name.textContent).not.toContain('·')
expect(name.textContent).toContain('Web UI')
expect(name.textContent).not.toContain(task.task_type_display)
expect(
name.closest('tr').querySelector('.results-col').textContent
).toContain(
[
'reprocess',
'rotate',
'merge',
'split',
'delete_pages',
'edit_pdf',
'remove_password',
].includes(operation)
? 'Submitted for processing'
: 'Completed'
)
}
)
it('shows operation context while work is pending without reporting completion', () => {
const task = {
...tasks[2],
task_type: PaperlessTaskType.BulkUpdate,
task_type_display: 'Bulk Update',
input_data: { operation: 'reprocess', document_count: 1 },
}
component.setSection(TaskSection.InProgress)
flushTaskLists(25, 1, [task])
fixture.detectChanges()
const name = fixture.nativeElement.querySelector('tbody .name-col')
expect(name.textContent).toContain('Document reprocessing')
expect(name.textContent).not.toContain('Bulk operation:')
expect(name.querySelector('small')).toBeNull()
expect(component.taskResultMessage(task)).toBeNull()
})
it.each([{}, { operation: 'future_operation' }])(
'preserves the fallback for legacy or unknown operation data: %j',
(input_data) => {
const task = {
...tasks[4],
task_type: PaperlessTaskType.BulkUpdate,
task_type_display: 'Bulk Update',
input_data,
result_data: {},
}
expect(component.taskDisplayName(task)).toBe('Bulk Update')
expect(component.taskDocumentCount(task)).toBeNull()
expect(component.taskResultMessage(task)).toBeNull()
}
)
it.each([-1, 1.5, '2', null, undefined])(
'does not display an invalid document count: %s',
(document_count) => {
expect(
component.taskDocumentCount({
...tasks[4],
input_data: { operation: 'modify_tags', document_count },
})
).toBeNull()
}
)
it('retains error details for failed operation tasks', () => {
expect(
component.taskResultMessage({
...tasks[0],
input_data: { operation: 'modify_tags', document_count: 12 },
result_data: { error_message: 'Insufficient permissions' },
})
).toBe('Insufficient permissions')
})
it('should filter tasks by result', () => {
component.setSection(TaskSection.NeedsAttention)
component.filterTargetID = 1
@@ -33,10 +33,6 @@ import { IfPermissionsDirective } from 'src/app/directives/if-permissions.direct
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
import { TasksService } from 'src/app/services/tasks.service'
import { ToastService } from 'src/app/services/toast.service'
import {
documentOperationHasFollowUpTasks,
getDocumentOperationLabel,
} from 'src/app/utils/document-operation'
import { ConfirmDialogComponent } from '../../common/confirm-dialog/confirm-dialog.component'
import { PageHeaderComponent } from '../../common/page-header/page-header.component'
import { LoadingComponentWithPermissions } from '../../loading-component/loading.component'
@@ -418,30 +414,11 @@ export class TasksComponent
}
taskDisplayName(task: PaperlessTask): string {
const filename = task.input_data?.filename?.toString()
if (filename) return filename
const operation = this.taskOperationLabel(task)
const count = this.taskDocumentCount(task)
if (operation && count !== null && count > 1) {
return $localize`Bulk operation: ${operation}`
}
return operation || task.task_type_display
return task.input_data?.filename?.toString() || task.task_type_display
}
taskShowsSeparateTypeLabel(task: PaperlessTask): boolean {
return (
!this.taskOperationLabel(task) &&
this.taskDisplayName(task) !== task.task_type_display
)
}
private taskOperationLabel(task: PaperlessTask): string | null {
return getDocumentOperationLabel(task.input_data?.operation)
}
taskDocumentCount(task: PaperlessTask): number | null {
const count = task.input_data?.document_count
return Number.isInteger(count) && count >= 0 ? count : null
return this.taskDisplayName(task) !== task.task_type_display
}
taskResultMessage(task: PaperlessTask): string | null {
@@ -469,15 +446,6 @@ export class TasksComponent
return errorMessage
}
if (
task.status === PaperlessTaskStatus.Success &&
this.taskOperationLabel(task)
) {
return documentOperationHasFollowUpTasks(task.input_data?.operation)
? $localize`Submitted for processing`
: $localize`Completed`
}
return null
}
@@ -361,9 +361,8 @@
</a>
</li>
}
<li class="nav-item mt-2 position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation) && !settingsService.organizingSidebarItems()"
[class.d-md-block]="slimSidebarEnabled && settingsService.unseenReleasesSince()" tourAnchor="tour.outro">
<a class="text-muted small d-flex align-items-center flex-wrap text-decoration-none nav-anchor" [class.d-md-none]="slimSidebarEnabled && settingsService.unseenReleasesSince()" [class.opacity-50]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation)" [class.pe-5]="settingsService.organizingSidebarItems() && !slimSidebarEnabled && !slimSidebarAnimating()"
<li class="nav-item mt-2 position-relative" [class.d-none]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation) && !settingsService.organizingSidebarItems()" tourAnchor="tour.outro">
<a class="text-muted small d-flex align-items-center flex-wrap text-decoration-none nav-anchor" [class.opacity-50]="settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation)" [class.pe-5]="settingsService.organizingSidebarItems() && !slimSidebarEnabled && !slimSidebarAnimating()"
target="_blank" rel="noopener noreferrer" href="https://docs.paperless-ngx.com" ngbPopover="Documentation"
i18n-ngbPopover [disablePopover]="!slimSidebarPopoversEnabled" placement="end" container="body"
triggers="mouseenter:mouseleave" popoverClass="popover-slim">
@@ -372,26 +371,16 @@
@if (settingsService.organizingSidebarItems()) {
<pngx-input-switch class="position-absolute top-50 end-0 translate-middle-y me-1" [class.d-none]="slimSidebarEnabled || slimSidebarAnimating()" [compact]="true" title="Documentation" i18n-title [ngModel]="!settingsService.sidebarItemIsHidden(HideableSidebarItemID.Documentation)" (ngModelChange)="toggleSidebarItem(HideableSidebarItemID.Documentation, $event)"></pngx-input-switch>
}
@if (slimSidebarEnabled && settingsService.unseenReleasesSince()) {
<button type="button" class="btn btn-link border-0 w-100 text-muted small d-none d-md-flex align-items-center nav-anchor position-relative" (click)="showReleaseNotes()"
aria-label="See what's new in this version" i18n-aria-label
ngbPopover="What's new" i18n-ngbPopover placement="end" container="body"
triggers="mouseenter:mouseleave" popoverClass="popover-slim">
<pngx-bs-icon class="d-flex" name="info-circle"></pngx-bs-icon>
<div class="position-absolute top-0 start-50 ms-1 p-1 bg-success rounded-circle"></div>
</button>
}
</li>
<li class="nav-item" [class.visually-hidden]="slimSidebarEnabled">
<div class="text-muted small d-flex align-items-center flex-wrap nav-label">
<div class="me-2">
<button type="button" class="bg-transparent border-0 p-0 text-muted" (click)="showReleaseNotes()" title="See what's new in this version" i18n-title>
<a class="text-muted text-decoration-none" target="_blank" rel="noopener noreferrer"
href="https://github.com/paperless-ngx/paperless-ngx" ngbPopover="GitHub" i18n-ngbPopover
[disablePopover]="!slimSidebarPopoversEnabled" placement="end" container="body"
triggers="mouseenter:mouseleave" popoverClass="popover-slim">
{{ versionString }}
</button>
@if (settingsService.unseenReleasesSince()) {
<button type="button" class="btn btn-whats-new rounded-pill smaller ms-1 py-1 px-2 fw-bold lh-sm align-baseline" (click)="showReleaseNotes()"
title="See what's new in this version" i18n-title i18n>New</button>
}
</a>
</div>
@if (!settingsService.updateCheckingIsSet || appRemoteVersion()) {
<div class="version-check d-flex align-items-center">
@@ -700,15 +700,3 @@ main {
.smaller {
font-size: 0.75rem;
}
// From active / hover of sidebar nav links
.btn-whats-new {
--bs-btn-color: var(--bs-primary);
--bs-btn-bg: color-mix(in srgb, var(--bs-primary) 13%, transparent);
--bs-btn-border-width: 0;
--bs-btn-font-weight: 600;
--bs-btn-hover-color: var(--bs-primary);
--bs-btn-hover-bg: color-mix(in srgb, var(--bs-primary) 20%, transparent);
--bs-btn-active-color: var(--bs-primary);
--bs-btn-active-bg: color-mix(in srgb, var(--bs-primary) 20%, transparent);
}
@@ -33,7 +33,6 @@ import { RemoteVersionService } from 'src/app/services/rest/remote-version.servi
import { SavedViewService } from 'src/app/services/rest/saved-view.service'
import { SearchService } from 'src/app/services/rest/search.service'
import { SettingsService } from 'src/app/services/settings.service'
import { TaskNotificationService } from 'src/app/services/task-notification.service'
import { TasksService } from 'src/app/services/tasks.service'
import { ToastService } from 'src/app/services/toast.service'
import { UploadDocumentsService } from 'src/app/services/upload-documents.service'
@@ -42,7 +41,6 @@ import { environment } from 'src/environments/environment'
import { ProfileEditDialogComponent } from '../common/profile-edit-dialog/profile-edit-dialog.component'
import { UploadStatusTrayComponent } from '../common/upload-status-tray/upload-status-tray.component'
import { DocumentDetailComponent } from '../document-detail/document-detail.component'
import { ReleaseNotesDialogComponent } from '../common/release-notes-dialog/release-notes-dialog.component'
import { AppFrameComponent } from './app-frame.component'
import { GlobalSearchComponent } from './global-search/global-search.component'
@@ -200,14 +198,14 @@ describe('AppFrameComponent', () => {
fixture.detectChanges()
})
it('refreshes and updates the task notification on completion', () => {
it('refreshes and notifies on completion without client-side task tracking', () => {
const list = TestBed.inject(DocumentListViewService)
const reload = jest.spyOn(list, 'reload').mockImplementation(() => {})
jest.spyOn(list, 'reduceSelectionToFilter').mockImplementation(() => {})
const tasksReload = jest
.spyOn(tasksService, 'reload')
.mockImplementation(() => {})
const success = jest.spyOn(toastService, 'show')
const success = jest.spyOn(toastService, 'showSuccess')
const refresh = jest
.spyOn(openDocumentsService, 'refreshDocument')
.mockImplementation(() => {})
@@ -232,12 +230,7 @@ describe('AppFrameComponent', () => {
expect(refresh).toHaveBeenCalledWith(document.id)
expect(maybeRefreshSpy).toHaveBeenCalledTimes(1)
expect(tasksReload).toHaveBeenCalledTimes(1)
expect(success).toHaveBeenCalledWith(
expect.objectContaining({
id: 'task-bulk-task',
content: "Operation 'Set permissions' completed.",
})
)
expect(success).toHaveBeenCalledWith('Bulk operation completed.')
fixture.destroy()
bulkEvents.next({
task_id: 'bulk-task',
@@ -252,14 +245,14 @@ describe('AppFrameComponent', () => {
const reload = jest.spyOn(list, 'reload').mockImplementation(() => {})
jest.spyOn(list, 'reduceSelectionToFilter').mockImplementation(() => {})
jest.spyOn(tasksService, 'reload').mockImplementation(() => {})
const error = jest.spyOn(toastService, 'show')
const error = jest.spyOn(toastService, 'showError')
const success = jest.spyOn(toastService, 'showSuccess')
for (const status of [
PaperlessTaskStatus.Failure,
PaperlessTaskStatus.Revoked,
]) {
bulkEvents.next({
task_id: `${status}-task`,
task_id: 'bulk-task',
operation: 'set_permissions',
status,
error:
@@ -269,36 +262,11 @@ describe('AppFrameComponent', () => {
})
}
expect(reload).toHaveBeenCalledTimes(2)
expect(error).toHaveBeenCalledWith(expect.any(String), 'Could not update')
expect(error).toHaveBeenCalledWith(
expect.objectContaining({
content:
"Operation 'Set permissions' failed. Some changes may already have been applied.",
error: 'Could not update',
})
'Bulk operation revoked.',
'Task expired before execution.'
)
expect(error).toHaveBeenCalledWith(
expect.objectContaining({
content: "Operation 'Set permissions' revoked.",
error: 'Task expired before execution.',
})
)
expect(success).not.toHaveBeenCalled()
})
it('passes delete completion to the shared task notification handler', () => {
const success = jest.spyOn(toastService, 'showSuccess')
const notifications = TestBed.inject(TaskNotificationService)
const handleStatus = jest.spyOn(notifications, 'complete')
bulkEvents.next({
task_id: 'delete-1',
operation: 'delete',
status: PaperlessTaskStatus.Success,
})
expect(handleStatus).toHaveBeenCalledWith({
task_id: 'delete-1',
operation: 'delete',
status: PaperlessTaskStatus.Success,
})
expect(success).not.toHaveBeenCalled()
})
@@ -696,68 +664,6 @@ describe('AppFrameComponent', () => {
expect(maybeRefreshSpy).toHaveBeenCalled()
})
it('should show new release pill and mark releases seen on click', () => {
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
settingsService.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, '3.4.2')
fixture.detectChanges()
const pill = fixture.debugElement
.queryAll(By.css('button'))
.find((b) => b.nativeElement.textContent.trim() === 'New')
expect(pill).toBeTruthy()
pill.nativeElement.click()
const req = httpTestingController.expectOne(
`${environment.apiBaseUrl}ui_settings/`
)
expect(req.request.body.settings.whats_new.last_seen_version).toEqual(
'3.5.1'
)
req.flush({ success: true })
fixture.detectChanges()
expect(
fixture.debugElement
.queryAll(By.css('button'))
.find((b) => b.nativeElement.textContent.trim() === 'New')
).toBeUndefined()
})
it('should open current release notes from the version without marking seen', () => {
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
settingsService.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, '3.5.1')
fixture.detectChanges()
const modalSpy = jest.spyOn(modalService, 'open')
const versionButton = fixture.debugElement
.queryAll(By.css('button'))
.find((b) => b.nativeElement.textContent.includes('3.5.1'))
versionButton.nativeElement.click()
expect(modalSpy).toHaveBeenCalledWith(
ReleaseNotesDialogComponent,
expect.anything()
)
httpTestingController.expectNone(`${environment.apiBaseUrl}ui_settings/`)
})
it('should show new release dot instead of documentation in slim sidebar', () => {
settingsService.set(SETTINGS_KEYS.SLIM_SIDEBAR, true)
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
settingsService.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, '3.4.2')
fixture.detectChanges()
const whatsNew = fixture.debugElement.query(
By.css('button[aria-label="See what\'s new in this version"]')
).nativeElement
const docs = fixture.debugElement.query(
By.css('a[href="https://docs.paperless-ngx.com"].nav-anchor')
).nativeElement
expect(docs.classList).toContain('d-md-none')
// both share one li so the tour anchor points at whichever is shown
expect(whatsNew.closest('li')).toBe(docs.closest('li'))
})
it('should show tasks badge for needs-attention tasks', () => {
jest
.spyOn(tasksService, 'needsAttentionTasksCount', 'get')
@@ -57,7 +57,6 @@ import {
} from 'src/app/services/rest/remote-version.service'
import { SavedViewService } from 'src/app/services/rest/saved-view.service'
import { SettingsService } from 'src/app/services/settings.service'
import { TaskNotificationService } from 'src/app/services/task-notification.service'
import { TasksService } from 'src/app/services/tasks.service'
import { ToastService } from 'src/app/services/toast.service'
import { UploadDocumentsService } from 'src/app/services/upload-documents.service'
@@ -68,7 +67,6 @@ import { SwitchComponent } from '../common/input/switch/switch.component'
import { BrandMarkComponent } from '../common/logo/brand-mark/brand-mark.component'
import { LogoComponent } from '../common/logo/logo.component'
import { ProfileEditDialogComponent } from '../common/profile-edit-dialog/profile-edit-dialog.component'
import { ReleaseNotesDialogComponent } from '../common/release-notes-dialog/release-notes-dialog.component'
import { UploadStatusTrayComponent } from '../common/upload-status-tray/upload-status-tray.component'
import { DocumentDetailComponent } from '../document-detail/document-detail.component'
import { ComponentWithPermissions } from '../with-permissions/with-permissions.component'
@@ -117,7 +115,6 @@ export class AppFrameComponent
settingsService = inject(SettingsService)
tasksService = inject(TasksService)
private readonly toastService = inject(ToastService)
private readonly taskNotifications = inject(TaskNotificationService)
private modalService = inject(NgbModal)
permissionsService = inject(PermissionsService)
private djangoMessagesService = inject(DjangoMessagesService)
@@ -185,11 +182,9 @@ export class AppFrameComponent
),
takeUntilDestroyed(this.destroyRef)
)
.subscribe((result) => {
.subscribe(({ status, error }) => {
this.documentList.reload(null, false)
if (!this.documentList.allSelected) {
this.documentList.reduceSelectionToFilter()
}
this.documentList.reduceSelectionToFilter()
// maybe someday we can optimize to only refresh affected documents
this.openDocumentsService.getOpenDocuments().forEach((doc) => {
this.openDocumentsService.refreshDocument(doc.id)
@@ -203,7 +198,16 @@ export class AppFrameComponent
) {
this.tasksService.reload()
}
this.taskNotifications.complete(result)
if (status === PaperlessTaskStatus.Success) {
this.toastService.showSuccess($localize`Bulk operation completed.`)
} else if (status === PaperlessTaskStatus.Revoked) {
this.toastService.showError($localize`Bulk operation revoked.`, error)
} else {
this.toastService.showError(
$localize`Bulk operation failed. Some changes may already have been applied.`,
error
)
}
})
this.lastScrollY = window.scrollY
@@ -552,21 +556,6 @@ export class AppFrameComponent
})
}
showReleaseNotes() {
const since = this.settingsService.unseenReleasesSince()
const modal = this.modalService.open(ReleaseNotesDialogComponent, {
size: 'lg',
scrollable: true,
})
modal.componentInstance.load(since)
if (since) {
this.settingsService
.markReleasesSeen()
.pipe(first())
.subscribe({ error: () => {} })
}
}
setUpdateChecking(enable: boolean) {
this.settingsService.set(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED, enable)
this.settingsService
@@ -188,62 +188,6 @@ describe('ChatComponent', () => {
expect(component.loading()).toBe(false)
})
it('should reveal a complete answer within one second', () => {
component.input.set('Hello')
component.sendMessage()
const answer = 'A'.repeat(660)
mockStream$.next(answer)
mockStream$.complete()
expect(component.messages()[1].content.length).toBeGreaterThan(0)
expect(component.messages()[1].content.length).toBeLessThan(answer.length)
expect(component.loading()).toBe(true)
jest.advanceTimersByTime(800)
expect(component.messages()[1].content).toBe(answer)
expect(component.loading()).toBe(false)
})
it('should give a long answer more time to reveal', () => {
component.input.set('Hello')
component.sendMessage()
const answer = 'A'.repeat(3000)
mockStream$.next(answer)
mockStream$.complete()
jest.advanceTimersByTime(800)
expect(component.messages()[1].content.length).toBeLessThan(answer.length)
expect(component.loading()).toBe(true)
jest.advanceTimersByTime(2500)
expect(component.messages()[1].content).toBe(answer)
expect(component.loading()).toBe(false)
})
it('should reveal fast incoming chunks without making them pop in', () => {
component.input.set('Hello')
component.sendMessage()
let answer = ''
for (let i = 0; i < 20; i++) {
answer += 'A'.repeat(100)
const visibleBefore = component.messages()[1].content.length
mockStream$.next(answer)
jest.advanceTimersByTime(10)
expect(
component.messages()[1].content.length - visibleBefore
).toBeLessThan(100)
}
expect(component.messages()[1].content.length).toBeLessThan(answer.length)
mockStream$.complete()
jest.advanceTimersByTime(5200)
expect(component.messages()[1].content).toBe(answer)
expect(component.loading()).toBe(false)
})
it('should show a slow response message while waiting', () => {
component.input.set('Hello')
component.sendMessage()
@@ -21,9 +21,6 @@ import {
import { pngxPopperOptions } from 'src/app/utils/popper-options'
const SLOW_RESPONSE_DELAY_MS = 8000
const TYPEWRITER_MIN_DURATION_MS = 750
const TYPEWRITER_MAX_DURATION_MS = 3000
const TYPEWRITER_INTERVAL_MS = 16
@Component({
selector: 'pngx-chat',
@@ -76,7 +73,6 @@ export class ChatComponent implements OnInit {
private typewriterBuffer: string[] = []
private typewriterActive = false
private typewriterTimeout: ReturnType<typeof setTimeout>
private typewriterDeadline = 0
private streamSubscription: Subscription
private streamingMessage: ChatMessage
private streamFinished = false
@@ -138,7 +134,7 @@ export class ChatComponent implements OnInit {
if (nextResponse.content.length < lastVisibleContent.length) {
this.resetTypewriter(assistantMessage, nextResponse.content)
lastVisibleContent = nextResponse.content
} else if (nextResponse.content.length > lastVisibleContent.length) {
} else {
const visibleDelta = nextResponse.content.substring(
lastVisibleContent.length
)
@@ -218,12 +214,6 @@ export class ChatComponent implements OnInit {
if (!chunk) return
this.typewriterBuffer.push(...chunk.split(''))
// Longer bursts need more time to remain readable as the chat scrolls.
const revealDuration = Math.min(
TYPEWRITER_MAX_DURATION_MS,
Math.max(TYPEWRITER_MIN_DURATION_MS, this.typewriterBuffer.length)
)
this.typewriterDeadline = Date.now() + revealDuration
if (!this.typewriterActive) {
this.typewriterActive = true
@@ -232,29 +222,19 @@ export class ChatComponent implements OnInit {
}
playTypewriter(message: ChatMessage): void {
// Spread the queued text across the updates left before the deadline
const remainingUpdates = Math.max(
1,
Math.ceil((this.typewriterDeadline - Date.now()) / TYPEWRITER_INTERVAL_MS)
)
const charactersToShow = Math.ceil(
this.typewriterBuffer.length / remainingUpdates
)
message.content += this.typewriterBuffer
.splice(0, charactersToShow)
.join('')
this.notifyMessagesChanged()
this.scrollToBottom()
if (this.typewriterBuffer.length === 0) {
this.typewriterActive = false
if (this.streamFinished) this.finishStreaming(message)
} else {
this.typewriterTimeout = setTimeout(
() => this.playTypewriter(message),
TYPEWRITER_INTERVAL_MS
)
return
}
const nextChar = this.typewriterBuffer.shift()
message.content += nextChar
this.notifyMessagesChanged()
this.scrollToBottom()
// 10ms per character
this.typewriterTimeout = setTimeout(() => this.playTypewriter(message), 10)
}
private notifyMessagesChanged(): void {
@@ -87,7 +87,6 @@ import folderFill from 'bootstrap-icons/icons/folder-fill.svg'
import folder from 'bootstrap-icons/icons/folder.svg'
import funnel from 'bootstrap-icons/icons/funnel.svg'
import gear from 'bootstrap-icons/icons/gear.svg'
import github from 'bootstrap-icons/icons/github.svg'
import globe2 from 'bootstrap-icons/icons/globe2.svg'
import google from 'bootstrap-icons/icons/google.svg'
import grid from 'bootstrap-icons/icons/grid.svg'
@@ -250,7 +249,6 @@ export const icons: Record<string, string> = {
folderFill,
funnel,
gear,
github,
globe2,
google,
grid,
@@ -1,71 +0,0 @@
<div class="modal-header">
<div>
<h4 class="modal-title" i18n>What's new in Paperless-ngx</h4>
@if (since()) {
<p class="text-muted small mb-0" i18n>Updated from {{ since() }} to {{ version }}</p>
}
</div>
<div class="d-flex align-items-center gap-3 ms-auto">
<div class="btn-group btn-group-sm" role="group">
<a tabindex="-1" class="btn btn-dark border-dark-subtle d-flex align-items-center" [href]="repoUrl" target="_blank" rel="noopener noreferrer"
title="Star Paperless-ngx on GitHub" i18n-title>
<pngx-bs-icon name="github" class="me-1 d-flex" width="12" height="12"></pngx-bs-icon><span class="small" i18n>Star</span>
</a>
@if (stars() !== null) {
<a tabindex="-1" class="btn btn-dark border-dark-subtle d-flex align-items-center" [href]="repoUrl + '/stargazers'" target="_blank" rel="noopener noreferrer"
title="Stargazers" i18n-title>
<span class="small">{{ stars() | number }}</span>
</a>
}
</div>
<button type="button" class="btn-close m-0" aria-label="Close" i18n-aria-label (click)="close()"></button>
</div>
</div>
<div class="modal-body">
@if (!updateCheckingEnabled) {
<p class="mb-0" i18n>Release notes are fetched from GitHub when update checking is enabled.</p>
<ng-container *ngTemplateOutlet="githubLink"></ng-container>
} @else if (loading()) {
<div class="d-flex align-items-center gap-2 text-muted">
<output class="spinner-border spinner-border-sm"></output>
<ng-container i18n>Loading release notes...</ng-container>
</div>
} @else if (!releases()?.length) {
<p class="mb-0" i18n>Release notes could not be loaded.</p>
<ng-container *ngTemplateOutlet="githubLink"></ng-container>
} @else {
@for (release of releases(); track release.version) {
<section class="release-notes" [class.border-top]="!$first" [class.pt-3]="!$first" [class.mt-3]="!$first">
<div class="d-flex align-items-baseline gap-2 mb-2">
<h5 class="mb-0">{{ release.version }}</h5>
<a class="d-flex flex-row align-items-center text-secondary btn-link" [href]="release.html_url" target="_blank" rel="noopener noreferrer"
title="View on GitHub" i18n-title>
@if (release.published_at) {
<span class="text-muted small me-2">{{ release.published_at | customDate }}</span>
}
<pngx-bs-icon name="box-arrow-up-right" class="mt-n1" width=".7rem"></pngx-bs-icon>
</a>
</div>
<div class="release-notes-body" [innerHTML]="release.body_html"></div>
</section>
}
}
</div>
<div class="modal-footer justify-content-between">
<div class="d-flex flex-wrap gap-3 small">
<a class="link-secondary text-decoration-none d-flex align-items-center" [href]="releasesUrl" target="_blank" rel="noopener noreferrer">
<pngx-bs-icon name="clock-history" class="me-1"></pngx-bs-icon><ng-container i18n>All releases</ng-container>
</a>
<a class="link-secondary text-decoration-none d-flex align-items-center" [href]="discussionsUrl" target="_blank" rel="noopener noreferrer">
<pngx-bs-icon name="chat-left-text" class="me-1"></pngx-bs-icon><ng-container i18n>Need support? Ask in Discussions</ng-container>
</a>
</div>
<button type="button" class="btn btn-outline-secondary" (click)="close()" i18n>Close</button>
</div>
<ng-template #githubLink>
<a class="small" [href]="releaseUrl" target="_blank" rel="noopener noreferrer">
<ng-container i18n>View on GitHub</ng-container>
<pngx-bs-icon name="box-arrow-up-right" class="ms-1"></pngx-bs-icon>
</a>
</ng-template>
@@ -1,77 +0,0 @@
// Styles for GitHub-rendered release notes (body_html)
:host ::ng-deep .release-notes-body {
// Repeats the version heading
> h2:first-child {
display: none;
}
// Section labels e.g. "Bug Fixes"
> h3 {
color: var(--bs-secondary-color);
font-size: 0.875rem;
font-weight: 600;
margin-top: 1rem;
margin-bottom: 0.375rem;
}
ul {
padding-left: 1.25rem;
margin-bottom: 0.75rem;
}
li {
margin-bottom: 0.25rem;
&::marker {
color: var(--bs-secondary-color);
}
}
a {
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
a.user-mention {
color: var(--bs-secondary-color);
}
details {
margin-bottom: 0.75rem;
> summary {
color: var(--bs-secondary-color);
font-size: 0.875rem;
cursor: pointer;
margin-bottom: 0.375rem;
}
}
// Keep the link underline off code, where it hides underscores
// e.g. PAPERLESS_ALLOWED_HOSTS
a code {
display: inline-block;
}
// GitHub alerts, e.g. > [!NOTE]
.markdown-alert {
background-color: color-mix(in srgb, var(--bs-primary) 8%, transparent);
border-left: 0.25rem solid var(--bs-primary);
border-radius: var(--bs-border-radius);
padding: 0.75rem 1rem;
margin-bottom: 1rem;
> :last-child {
margin-bottom: 0;
}
}
.markdown-alert-title {
color: var(--bs-primary);
font-weight: 600;
margin-bottom: 0.25rem;
}
}
@@ -1,131 +0,0 @@
import { DatePipe } from '@angular/common'
import { provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing'
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
import { SettingsService } from 'src/app/services/settings.service'
import { environment } from 'src/environments/environment'
import {
prepareReleaseHtml,
ReleaseNotesDialogComponent,
} from './release-notes-dialog.component'
describe('ReleaseNotesDialogComponent', () => {
let component: ReleaseNotesDialogComponent
let fixture: ComponentFixture<ReleaseNotesDialogComponent>
let httpTestingController: HttpTestingController
let settingsService: SettingsService
function create(updateCheckingEnabled: boolean) {
settingsService = TestBed.inject(SettingsService)
settingsService.set(SETTINGS_KEYS.VERSION, '3.5.1')
settingsService.set(
SETTINGS_KEYS.UPDATE_CHECKING_ENABLED,
updateCheckingEnabled
)
fixture = TestBed.createComponent(ReleaseNotesDialogComponent)
component = fixture.componentInstance
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReleaseNotesDialogComponent],
providers: [
DatePipe,
NgbActiveModal,
provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(),
],
})
httpTestingController = TestBed.inject(HttpTestingController)
})
afterEach(() => {
httpTestingController.verify()
})
it('should load and render release notes since a version', () => {
create(true)
component.load('3.4.2')
const req = httpTestingController.expectOne(
`${environment.apiBaseUrl}release_notes/?since=3.4.2`
)
req.flush({
version: '3.5.1',
releases: [
{
version: '3.5.1',
name: 'Paperless-ngx v3.5.1',
body_html:
'<h2>paperless-ngx 3.5.1</h2><h3>Bug Fixes</h3><ul><li>Fix: a thing</li></ul>' +
'<h3>All App Changes</h3><details><summary>1 change</summary><ul><li>Fix: a thing</li></ul></details>',
html_url: '',
published_at: '2026-11-18T05:22:01Z',
},
],
})
fixture.detectChanges()
const text = fixture.nativeElement.textContent
expect(text).toContain('Updated from 3.4.2 to 3.5.1')
expect(text).toContain('Bug Fixes')
expect(
fixture.nativeElement.querySelector('.release-notes-body details summary')
.textContent
).toEqual('1 change')
})
it('should open release note links safely and drop svg icons', () => {
const html = prepareReleaseHtml(
'<div class="markdown-alert"><p class="markdown-alert-title"><svg><path d="M0"></path></svg>Note</p></div>' +
'<p><a href="https://github.com/paperless-ngx/paperless-ngx/pull/1" data-hovercard-type="pull_request">#1</a></p>'
)
const doc = new DOMParser().parseFromString(html, 'text/html')
expect(doc.querySelector('svg')).toBeNull()
expect(doc.querySelector('.markdown-alert-title').textContent).toEqual(
'Note'
)
const link = doc.querySelector('a')
expect(link.getAttribute('target')).toEqual('_blank')
expect(link.getAttribute('rel')).toEqual('noopener noreferrer nofollow')
expect(link.hasAttribute('data-hovercard-type')).toBe(false)
})
it('should show a message if release notes could not be loaded', () => {
create(true)
component.load(null)
httpTestingController
.expectOne(`${environment.apiBaseUrl}release_notes/`)
.flush('error', { status: 500, statusText: 'error' })
fixture.detectChanges()
expect(fixture.nativeElement.textContent).toContain(
'Release notes could not be loaded'
)
})
it('should not fetch release notes if update checking is disabled', () => {
create(false)
component.load('3.4.2')
fixture.detectChanges()
httpTestingController.expectNone(`${environment.apiBaseUrl}release_notes/`)
expect(fixture.nativeElement.textContent).toContain(
'when update checking is enabled'
)
expect(component.releaseUrl).toEqual(
'https://github.com/paperless-ngx/paperless-ngx/releases/tag/v3.5.1'
)
})
it('should support close', () => {
create(false)
const closeSpy = jest.spyOn(component.activeModal, 'close')
component.close()
expect(closeSpy).toHaveBeenCalled()
})
})
@@ -1,103 +0,0 @@
import { DecimalPipe, NgTemplateOutlet } from '@angular/common'
import { Component, inject, signal } from '@angular/core'
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'
import { first } from 'rxjs'
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
import {
AppRelease,
RemoteVersionService,
} from 'src/app/services/rest/remote-version.service'
import { SettingsService } from 'src/app/services/settings.service'
const REPO_URL = 'https://github.com/paperless-ngx/paperless-ngx'
const RELEASES_URL = `${REPO_URL}/releases`
const DISCUSSIONS_URL = `${REPO_URL}/discussions/new/choose`
/**
* Tweak GitHub release HTML: open links in a new tab, add no referrer etc,
* drop inline svgs and GH `data-*` attributes. Angular sanitizes all of this anyway.
*/
export function prepareReleaseHtml(html: string): string {
const doc = new DOMParser().parseFromString(html, 'text/html')
doc.querySelectorAll('svg').forEach((svg) => svg.remove())
doc.body.querySelectorAll('*').forEach((el) => {
for (const attr of Array.from(el.attributes)) {
if (attr.name.startsWith('data-')) el.removeAttribute(attr.name)
}
})
doc.querySelectorAll('a').forEach((a) => {
a.setAttribute('target', '_blank')
a.setAttribute('rel', 'noopener noreferrer nofollow')
})
return doc.body.innerHTML
}
@Component({
selector: 'pngx-release-notes-dialog',
templateUrl: './release-notes-dialog.component.html',
styleUrls: ['./release-notes-dialog.component.scss'],
imports: [
BootstrapIconComponent,
CustomDatePipe,
NgTemplateOutlet,
DecimalPipe,
],
})
export class ReleaseNotesDialogComponent {
readonly activeModal = inject(NgbActiveModal)
private readonly remoteVersionService = inject(RemoteVersionService)
private readonly settingsService = inject(SettingsService)
readonly since = signal<string | null>(null)
readonly releases = signal<AppRelease[] | null>(null)
readonly stars = signal<number | null>(null)
readonly loading = signal(false)
readonly version: string = this.settingsService.get(SETTINGS_KEYS.VERSION)
readonly updateCheckingEnabled: boolean = this.settingsService.get(
SETTINGS_KEYS.UPDATE_CHECKING_ENABLED
)
readonly repoUrl = REPO_URL
readonly releasesUrl = RELEASES_URL
readonly discussionsUrl = DISCUSSIONS_URL
get releaseUrl(): string {
return this.version ? `${RELEASES_URL}/tag/v${this.version}` : RELEASES_URL
}
/**
* Load notes for releases after `since`, or the running version's
* notes if `since` is null.
*/
load(since: string | null): void {
this.since.set(since)
if (!this.updateCheckingEnabled) return
this.loading.set(true)
this.remoteVersionService
.getReleaseNotes(since ?? undefined)
.pipe(first())
.subscribe({
next: (notes) => {
this.releases.set(
notes.releases.map((release) => ({
...release,
body_html: prepareReleaseHtml(release.body_html),
}))
)
this.stars.set(notes.stars ?? null)
this.loading.set(false)
},
error: () => {
this.releases.set([])
this.loading.set(false)
},
})
}
close(): void {
this.activeModal.close()
}
}
@@ -7,7 +7,6 @@
background-color: var(--pngx-toast-bg);
color: var(--bs-body-color);
overflow: hidden;
transition: background-color .18s ease, border-color .18s ease;
&.toast-success {
--pngx-toast-accent: var(--pngx-toast-success);
@@ -24,13 +23,6 @@
.toast-icon {
color: var(--pngx-toast-accent);
transition: color .18s ease;
}
@media (prefers-reduced-motion: reduce) {
.toast, .toast-icon {
transition: none;
}
}
.toast-content {
@@ -65,36 +65,6 @@ describe('ToastComponent', () => {
expect(component.delayRemaining()).toEqual(3000)
})
it('updates its color and icon in place and restarts the countdown', () => {
jest.useFakeTimers()
fixture.componentRef.setInput('toast', {
id: 'task-1',
content: 'Queued',
delay: 5000,
})
fixture.detectChanges()
component.onShown(component.toast)
jest.advanceTimersByTime(4500)
const element = fixture.nativeElement.querySelector('ngb-toast')
fixture.componentRef.setInput('toast', {
id: 'task-1',
content: 'Completed',
delay: 5000,
level: ToastLevel.Success,
})
fixture.detectChanges()
expect(fixture.nativeElement.querySelector('ngb-toast')).toBe(element)
expect(element.classList).toContain('toast-success')
expect(element.querySelector('[name="check-circle"]')).not.toBeNull()
expect(component.delayRemaining()).toBe(5000)
const hide = jest.spyOn(component.ngbToast, 'hide')
jest.advanceTimersByTime(1000)
expect(hide).not.toHaveBeenCalled()
jest.advanceTimersByTime(4200)
expect(hide).toHaveBeenCalled()
jest.useRealTimers()
})
it('should hide the toast when the countdown ends', () => {
jest.useFakeTimers()
const toast = { content: 'Info', delay: 3000 }
@@ -5,10 +5,8 @@ import {
DestroyRef,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
SimpleChanges,
ViewChild,
inject,
signal,
@@ -36,10 +34,10 @@ import { Toast, ToastLevel } from 'src/app/services/toast.service'
styleUrl: './toast.component.scss',
providers: [DatePipe, CustomDatePipe],
})
export class ToastComponent implements OnInit, OnChanges {
private readonly clipboard = inject(Clipboard)
private readonly customDatePipe = inject(CustomDatePipe)
private readonly destroyRef = inject(DestroyRef)
export class ToastComponent implements OnInit {
private clipboard = inject(Clipboard)
private customDatePipe = inject(CustomDatePipe)
private destroyRef = inject(DestroyRef)
readonly copied = signal(false)
readonly ToastLevel = ToastLevel
readonly delayRemaining = signal<number>(null)
@@ -71,12 +69,6 @@ export class ToastComponent implements OnInit, OnChanges {
if (this.autohide) this.delayRemaining.set(this.toast.delay)
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.toast && !changes.toast.firstChange && this.autohide) {
this.onShown(this.toast)
}
}
get relativeTimestamp(): string {
return this.customDatePipe.transform(this.toast.timestamp, 'relative')
}
@@ -68,9 +68,9 @@ describe('ToastsComponent', () => {
toasts.forEach((t) => toastSubject.next(t))
expect(component.toasts().map((t) => t.id)).toEqual(['3', '2', '1'])
// Updating a visible toast preserves its position without duplicating it.
// showing a visible toast again moves it to the top without duplicating
toastSubject.next(toasts[1])
expect(component.toasts().map((t) => t.id)).toEqual(['3', '2', '1'])
expect(component.toasts().map((t) => t.id)).toEqual(['1', '3', '2'])
})
it('should remove a popup when it hides without closing it', () => {
@@ -32,11 +32,10 @@ export class ToastsComponent {
return
}
this.toasts.update((toasts) =>
toasts.some((existing) => existing.id === toast.id)
? toasts.map((existing) =>
existing.id === toast.id ? toast : existing
)
: [toast, ...toasts].slice(0, MAX_VISIBLE_TOASTS)
[toast, ...toasts.filter((t) => t.id !== toast.id)].slice(
0,
MAX_VISIBLE_TOASTS
)
)
})
}
@@ -1013,45 +1013,30 @@ describe('DocumentDetailComponent', () => {
])
})
it('should queue reprocess, show the task link and close the modal', () => {
jest.useFakeTimers()
it('should support reprocess, confirm and close modal after started', () => {
initNormally()
const reprocessSpy = jest.spyOn(documentService, 'reprocessDocuments')
reprocessSpy.mockReturnValue(of({ result: 'OK', task_id: 'reprocess-1' }))
reprocessSpy.mockReturnValue(of(true))
let openModal: NgbModalRef
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
const modalSpy = jest.spyOn(modalService, 'open')
const toastSpy = jest.spyOn(toastService, 'show')
const toastSpy = jest.spyOn(toastService, 'showInfo')
component.reprocess()
const modalCloseSpy = jest.spyOn(openModal, 'close')
openModal.componentInstance.confirmClicked.next()
expect(reprocessSpy).toHaveBeenCalledWith({ documents: [doc.id] }, false)
expect(modalSpy).toHaveBeenCalled()
expect(toastSpy).not.toHaveBeenCalled()
expect(toastSpy).toHaveBeenCalled()
expect(modalCloseSpy).toHaveBeenCalled()
jest.advanceTimersByTime(400)
expect(toastSpy).toHaveBeenCalledWith(
expect.objectContaining({
content: 'Document reprocessing queued.',
actionName: 'View task',
})
)
toastSpy.mock.calls.at(-1)[0].action()
expect(router.navigate).toHaveBeenCalledWith(['/tasks'], {
queryParams: { task_id: 'reprocess-1' },
})
expect(modalCloseSpy).toHaveBeenCalled()
jest.useRealTimers()
})
it('should run a workflow on the document, confirm and close modal', () => {
jest.useFakeTimers()
initNormally()
const bulkEditSpy = jest.spyOn(documentService, 'bulkEdit')
bulkEditSpy.mockReturnValue(of({ result: 'OK', task_id: 'workflow-1' }))
bulkEditSpy.mockReturnValue(of(true))
let openModal: NgbModalRef
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
const toastSpy = jest.spyOn(toastService, 'show')
const toastSpy = jest.spyOn(toastService, 'showInfo')
component.runWorkflow()
expect(openModal.componentInstance.singleDocument).toBe(true)
expect(openModal.componentInstance.force).toBe(true)
@@ -1063,18 +1048,14 @@ describe('DocumentDetailComponent', () => {
'run_workflow',
{ workflow: 5, filter_documents: false }
)
jest.advanceTimersByTime(400)
expect(toastSpy).toHaveBeenCalledWith(
expect.objectContaining({ content: 'Workflow queued.' })
)
expect(toastSpy).toHaveBeenCalled()
expect(modalCloseSpy).toHaveBeenCalled()
jest.useRealTimers()
})
it('should apply workflow filters when the single-document checkbox is cleared', () => {
initNormally()
const bulkEditSpy = jest.spyOn(documentService, 'bulkEdit')
bulkEditSpy.mockReturnValue(of({ result: 'OK', task_id: 'workflow-2' }))
bulkEditSpy.mockReturnValue(of(true))
let openModal: NgbModalRef
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
component.runWorkflow()
@@ -1091,7 +1072,7 @@ describe('DocumentDetailComponent', () => {
it('should pass remote OCR choice when reprocessing', () => {
initNormally()
const reprocessSpy = jest.spyOn(documentService, 'reprocessDocuments')
reprocessSpy.mockReturnValue(of({ result: 'OK', task_id: 'reprocess-2' }))
reprocessSpy.mockReturnValue(of(true))
let openModal: NgbModalRef
modalService.activeInstances.subscribe((modal) => (openModal = modal[0]))
component.reprocess()
@@ -2020,12 +2001,10 @@ describe('DocumentDetailComponent', () => {
})
it('should support pdf editor, handle error', () => {
jest.useFakeTimers()
let modal: NgbModalRef
modalService.activeInstances.subscribe((m) => (modal = m[0]))
const closeSpy = jest.spyOn(openDocumentsService, 'closeDocument')
const errorSpy = jest.spyOn(toastService, 'showError')
const queuedToastSpy = jest.spyOn(toastService, 'show')
initNormally()
component.selectedVersionId.set(10)
component.editPdf()
@@ -2044,7 +2023,6 @@ describe('DocumentDetailComponent', () => {
update_document: false,
include_metadata: true,
source_mode: 'explicit_selection',
from_webui: true,
})
req.error(new ErrorEvent('failed'))
expect(errorSpy).toHaveBeenCalled()
@@ -2057,21 +2035,13 @@ describe('DocumentDetailComponent', () => {
req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/edit_pdf/`
)
req.flush({ result: 'OK', task_id: 'edit-pdf-1' })
jest.advanceTimersByTime(400)
expect(closeSpy).not.toHaveBeenCalled()
expect(queuedToastSpy).toHaveBeenCalledWith(
expect.objectContaining({ content: 'PDF edit queued.' })
)
jest.useRealTimers()
req.flush(true)
expect(closeSpy).toHaveBeenCalled()
})
it('should support removing password protection from pdfs', () => {
jest.useFakeTimers()
let modal: NgbModalRef
modalService.activeInstances.subscribe((m) => (modal = m[0]))
const closeSpy = jest.spyOn(openDocumentsService, 'closeDocument')
const queuedToastSpy = jest.spyOn(toastService, 'show')
initNormally()
component.selectedVersionId.set(10)
component.password = 'secret'
@@ -2092,15 +2062,8 @@ describe('DocumentDetailComponent', () => {
include_metadata: false,
delete_original: true,
source_mode: 'explicit_selection',
from_webui: true,
})
req.flush({ result: 'OK', task_id: 'remove-password-1' })
jest.advanceTimersByTime(400)
expect(closeSpy).not.toHaveBeenCalled()
expect(queuedToastSpy).toHaveBeenCalledWith(
expect.objectContaining({ content: 'Password removal queued.' })
)
jest.useRealTimers()
req.flush(true)
})
it('should require the current password before removing it', () => {
@@ -2152,9 +2115,9 @@ describe('DocumentDetailComponent', () => {
const req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/remove_password/`
)
req.flush({ result: 'OK', task_id: 'remove-password-2' })
req.flush(true)
expect(refreshSpy).not.toHaveBeenCalled()
expect(refreshSpy).toHaveBeenCalledWith(doc.id)
})
it('should support keyboard shortcuts', () => {
@@ -97,7 +97,6 @@ import { TagService } from 'src/app/services/rest/tag.service'
import { UserService } from 'src/app/services/rest/user.service'
import { WorkflowService } from 'src/app/services/rest/workflow.service'
import { SettingsService } from 'src/app/services/settings.service'
import { TaskNotificationService } from 'src/app/services/task-notification.service'
import { ToastService } from 'src/app/services/toast.service'
import { TrashService } from 'src/app/services/trash.service'
import { WebsocketStatusService } from 'src/app/services/websocket-status.service'
@@ -227,7 +226,6 @@ export class DocumentDetailComponent
private documentListViewService = inject(DocumentListViewService)
private documentTitlePipe = inject(DocumentTitlePipe)
private toastService = inject(ToastService)
private taskNotifications = inject(TaskNotificationService)
private trashService = inject(TrashService)
private settings = inject(SettingsService)
private storagePathService = inject(StoragePathService)
@@ -1560,11 +1558,9 @@ export class DocumentDetailComponent
modal.componentInstance.remoteOcr
)
.subscribe({
next: ({ task_id }) => {
this.taskNotifications.showQueued(
task_id,
$localize`Document reprocessing queued.`,
{ content: $localize`Document submitted for reprocessing.` }
next: () => {
this.toastService.showInfo(
$localize`Reprocess operation for "${this.document().title}" will begin in the background.`
)
if (modal) {
modal.close()
@@ -1601,13 +1597,9 @@ export class DocumentDetailComponent
filter_documents: !modal.componentInstance.force,
})
.subscribe({
next: ({ task_id }) => {
this.taskNotifications.showQueued(
task_id,
$localize`Workflow queued.`,
{
content: $localize`Workflow completed.`,
}
next: () => {
this.toastService.showInfo(
$localize`Workflow will run on "${this.document().title}" in the background.`
)
modal.close()
},
@@ -1997,15 +1989,14 @@ export class DocumentDetailComponent
})
.pipe(first(), takeUntil(this.unsubscribeNotifier))
.subscribe({
next: ({ task_id }) => {
this.taskNotifications.showQueued(
task_id,
$localize`PDF edit queued.`,
{
content: $localize`PDF edit submitted for processing.`,
}
next: () => {
this.toastService.showInfo(
$localize`PDF edit operation for "${this.document().title}" will begin in the background.`
)
modal.close()
if (modal.componentInstance.deleteOriginal) {
this.openDocumentService.closeDocument(this.document())
}
},
error: (error) => {
if (modal) {
@@ -2055,16 +2046,17 @@ export class DocumentDetailComponent
})
.pipe(first(), takeUntil(this.unsubscribeNotifier))
.subscribe({
next: ({ task_id }) => {
this.taskNotifications.showQueued(
task_id,
$localize`Password removal queued.`,
{
content: $localize`Password removal submitted for processing.`,
}
next: () => {
this.toastService.showInfo(
$localize`Password removal operation for "${this.document().title}" will begin in the background.`
)
this.networkActive.set(false)
modal.close()
if (!dialog.updateDocument && dialog.deleteOriginal) {
this.openDocumentService.closeDocument(this.document())
} else if (dialog.updateDocument) {
this.openDocumentService.refreshDocument(this.documentId())
}
},
error: (error) => {
dialog.buttonsEnabled.set(true)
@@ -2,7 +2,6 @@ import { DatePipe } from '@angular/common'
import { SimpleChange, signal } from '@angular/core'
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { By } from '@angular/platform-browser'
import { Router } from '@angular/router'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { Subject, of, throwError } from 'rxjs'
import { DocumentVersionInfo } from 'src/app/data/document'
@@ -34,7 +33,7 @@ describe('DocumentVersionDropdownComponent', () => {
>
>
let toastService: jest.Mocked<
Pick<ToastService, 'show' | 'showError' | 'showInfo' | 'showSuccess'>
Pick<ToastService, 'showError' | 'showInfo' | 'showSuccess'>
>
let finished$: Subject<{ taskId: string }>
let failed$: Subject<{ taskId: string; message?: string }>
@@ -55,7 +54,6 @@ describe('DocumentVersionDropdownComponent', () => {
}
modalService = { open: jest.fn() }
toastService = {
show: jest.fn(),
showError: jest.fn(),
showInfo: jest.fn(),
showSuccess: jest.fn(),
@@ -90,10 +88,6 @@ describe('DocumentVersionDropdownComponent', () => {
provide: PermissionsService,
useValue: permissionsService,
},
{
provide: Router,
useValue: { navigate: jest.fn() },
},
{
provide: WebsocketStatusService,
useValue: {
@@ -383,8 +377,7 @@ describe('DocumentVersionDropdownComponent', () => {
expect(component.versionLabelDraft).toEqual('')
})
it('addExistingDocumentAsVersion should queue with a label and wait to refresh versions', () => {
jest.useFakeTimers()
it('addExistingDocumentAsVersion should merge with a label and refresh versions', () => {
const confirmClicked = new Subject<number>()
const modal = {
componentInstance: {
@@ -395,9 +388,14 @@ describe('DocumentVersionDropdownComponent', () => {
close: jest.fn(),
}
modalService.open.mockReturnValue(modal as any)
documentService.mergeDocumentsAsVersions.mockReturnValue(
of({ result: 'OK', task_id: 'versions-1' })
)
documentService.mergeDocumentsAsVersions.mockReturnValue(of({} as any))
// Newest first, as the API returns them. The merged document has a lower id
// than the root, which is the whole point of merging an existing document.
const versions: DocumentVersionInfo[] = [
{ id: 2, is_root: false, checksum: 'cccc' },
{ id: 3, is_root: true, checksum: 'aaaa' },
]
documentService.getVersions.mockReturnValue(of({ id: 3, versions } as any))
component.newVersionLabel = ' Imported '
const versionsEmitSpy = jest.spyOn(component.versionsUpdated, 'emit')
const selectedEmitSpy = jest.spyOn(component.versionSelected, 'emit')
@@ -412,18 +410,11 @@ describe('DocumentVersionDropdownComponent', () => {
'Imported'
)
expect(documentService.updateVersionLabel).not.toHaveBeenCalled()
expect(documentService.getVersions).not.toHaveBeenCalled()
expect(versionsEmitSpy).not.toHaveBeenCalled()
expect(selectedEmitSpy).not.toHaveBeenCalled()
expect(documentService.getVersions).toHaveBeenCalledWith(3)
expect(versionsEmitSpy).toHaveBeenCalledWith(versions)
expect(selectedEmitSpy).toHaveBeenCalledWith(2)
expect(component.newVersionLabel).toEqual('')
expect(modal.close).toHaveBeenCalled()
jest.advanceTimersByTime(400)
expect(toastService.show).toHaveBeenCalledWith(
expect.objectContaining({
content: 'Existing document queued to be added as a version.',
actionName: 'View task',
})
)
jest.useRealTimers()
expect(toastService.showSuccess).toHaveBeenCalled()
})
})
@@ -28,7 +28,6 @@ import { DocumentVersionInfo } from 'src/app/data/document'
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
import { DocumentService } from 'src/app/services/rest/document.service'
import { TaskNotificationService } from 'src/app/services/task-notification.service'
import { ToastService } from 'src/app/services/toast.service'
import {
UploadState,
@@ -78,7 +77,6 @@ export class DocumentVersionDropdownComponent
private readonly toastService = inject(ToastService)
private readonly websocketStatusService = inject(WebsocketStatusService)
private readonly modalService = inject(NgbModal)
private readonly taskNotifications = inject(TaskNotificationService)
private readonly destroy$ = new Subject<void>()
private readonly documentChange$ = new Subject<void>()
@@ -307,19 +305,23 @@ export class DocumentVersionDropdownComponent
versionLabel
)
.pipe(
switchMap(() => this.documentsService.getVersions(this.documentId)),
first(),
finalize(() => dialog.buttonsEnabled.set(true)),
takeUntil(this.destroy$),
takeUntil(this.documentChange$)
)
.subscribe({
next: ({ task_id }) => {
next: (document) => {
if (document?.versions?.length) {
this.versionsUpdated.emit(document.versions)
// The API returns versions newest first
this.versionSelected.emit(document.versions[0].id)
}
this.newVersionLabel = ''
modal.close()
this.taskNotifications.showQueued(
task_id,
$localize`Existing document queued to be added as a version.`,
{ content: $localize`Existing document added as a version.` }
this.toastService.showSuccess(
$localize`Existing document added as a version.`
)
},
error: (error) => {
@@ -14,8 +14,7 @@ import { Correspondent } from 'src/app/data/correspondent'
import { CustomField, CustomFieldDataType } from 'src/app/data/custom-field'
import { DocumentType } from 'src/app/data/document-type'
import { FILTER_TITLE } from 'src/app/data/filter-rule-type'
import { PaperlessTaskStatus } from 'src/app/data/paperless-task'
import { Results, SelectionData } from 'src/app/data/results'
import { Results } from 'src/app/data/results'
import { StoragePath } from 'src/app/data/storage-path'
import { Tag } from 'src/app/data/tag'
import { WorkflowTriggerType } from 'src/app/data/workflow-trigger'
@@ -29,7 +28,10 @@ import {
import { CorrespondentService } from 'src/app/services/rest/correspondent.service'
import { CustomFieldsService } from 'src/app/services/rest/custom-fields.service'
import { DocumentTypeService } from 'src/app/services/rest/document-type.service'
import { DocumentService } from 'src/app/services/rest/document.service'
import {
DocumentService,
SelectionData,
} from 'src/app/services/rest/document.service'
import { GroupService } from 'src/app/services/rest/group.service'
import { ShareLinkBundleService } from 'src/app/services/rest/share-link-bundle.service'
import { StoragePathService } from 'src/app/services/rest/storage-path.service'
@@ -37,7 +39,6 @@ import { TagService } from 'src/app/services/rest/tag.service'
import { UserService } from 'src/app/services/rest/user.service'
import { WorkflowService } from 'src/app/services/rest/workflow.service'
import { SettingsService } from 'src/app/services/settings.service'
import { TaskNotificationService } from 'src/app/services/task-notification.service'
import { ToastService } from 'src/app/services/toast.service'
import { TrashService } from 'src/app/services/trash.service'
import { environment } from 'src/environments/environment'
@@ -718,6 +719,7 @@ describe('BulkEditorComponent', () => {
'Workflow will run on the selected documents in the background.'
)
expect(toast.mock.calls.at(-1)[0].actionName).toBeUndefined()
expect(documentListViewService.selected.size).toBe(0)
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
) // list reload
@@ -1265,15 +1267,14 @@ describe('BulkEditorComponent', () => {
let req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/delete/`
)
const trackSpy = jest
.spyOn(trashService, 'trackMovedToTrash')
const notifySpy = jest
.spyOn(trashService, 'notifyMovedToTrash')
.mockImplementation(() => {})
req.flush({ result: 'OK', task_id: 'delete-1' })
req.flush(true)
expect(req.request.body).toEqual({
documents: [3, 4],
from_webui: true,
})
expect(trackSpy).toHaveBeenCalledWith('delete-1', 2, [3, 4])
expect(notifySpy).toHaveBeenCalledWith(expect.any(String), [3, 4])
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
) // list reload
@@ -1290,9 +1291,9 @@ describe('BulkEditorComponent', () => {
req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/delete/`
)
req.flush({ result: 'OK', task_id: 'delete-2' })
req.flush(true)
// ids aren't known when all matching documents are selected, so no undo
expect(trackSpy).toHaveBeenLastCalledWith('delete-2', 2, null)
expect(notifySpy).toHaveBeenLastCalledWith(expect.any(String), null)
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
) // list reload
@@ -1372,11 +1373,10 @@ describe('BulkEditorComponent', () => {
let req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/reprocess/`
)
req.flush({ result: 'OK', task_id: 'reprocess-1' })
req.flush(true)
expect(req.request.body).toEqual({
documents: [3, 4],
remote_ocr: false,
from_webui: true,
})
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
@@ -1387,7 +1387,6 @@ describe('BulkEditorComponent', () => {
})
it('should support rotate', () => {
const toast = jest.spyOn(toastService, 'show')
let modal: NgbModalRef
modalService.activeInstances.subscribe((m) => (modal = m[0]))
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
@@ -1408,20 +1407,11 @@ describe('BulkEditorComponent', () => {
let req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/rotate/`
)
req.flush({ result: 'OK', task_id: 'rotate-1' })
TestBed.inject(TaskNotificationService).complete({
task_id: 'rotate-1',
operation: 'rotate',
status: PaperlessTaskStatus.Success,
})
expect(toast.mock.calls.at(-1)[0].content).toBe(
"Bulk operation 'Rotate documents' submitted for processing."
)
req.flush(true)
expect(req.request.body).toEqual({
documents: [3, 4],
degrees: 90,
source_mode: 'latest_version',
from_webui: true,
})
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
@@ -1459,11 +1449,10 @@ describe('BulkEditorComponent', () => {
let req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/merge/`
)
req.flush({ result: 'OK', task_id: 'merge-1' })
req.flush(true)
expect(req.request.body).toEqual({
documents: [3, 4],
metadata_document_id: 3,
from_webui: true,
})
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
@@ -1478,12 +1467,11 @@ describe('BulkEditorComponent', () => {
req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/merge/`
)
req.flush({ result: 'OK', task_id: 'merge-2' })
req.flush(true)
expect(req.request.body).toEqual({
documents: [3, 4],
metadata_document_id: 3,
delete_originals: true,
from_webui: true,
})
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
@@ -1491,6 +1479,7 @@ describe('BulkEditorComponent', () => {
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
) // listAllFilteredIds
expect(documentListViewService.selected.size).toEqual(0)
// Test with archiveFallback enabled
modal.componentInstance.deleteOriginals.set(false)
@@ -1499,12 +1488,11 @@ describe('BulkEditorComponent', () => {
req = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/merge/`
)
req.flush({ result: 'OK', task_id: 'merge-3' })
req.flush(true)
expect(req.request.body).toEqual({
documents: [3, 4],
metadata_document_id: 3,
archive_fallback: true,
from_webui: true,
})
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=50&ordering=-created&truncate_content=true&include_selection_data=true`
@@ -1512,10 +1500,10 @@ describe('BulkEditorComponent', () => {
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
) // listAllFilteredIds
expect(documentListViewService.selected.size).toEqual(0)
})
it('should support merging documents as versions', () => {
jest.useFakeTimers()
let modal: NgbModalRef
modalService.activeInstances.subscribe((m) => (modal = m[0]))
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(true)
@@ -1543,8 +1531,8 @@ describe('BulkEditorComponent', () => {
.mockReturnValue(true)
const mergeAsVersionsSpy = jest
.spyOn(documentService, 'mergeDocumentsAsVersions')
.mockReturnValue(of({ result: 'OK', task_id: 'versions-1' }))
const toastSpy = jest.spyOn(toastService, 'show')
.mockReturnValue(of(true))
const toastSuccessSpy = jest.spyOn(toastService, 'showSuccess')
fixture.detectChanges()
component.mergeSelectedAsVersions()
@@ -1559,21 +1547,10 @@ describe('BulkEditorComponent', () => {
httpTestingController.match(
`${environment.apiBaseUrl}documents/?page=1&page_size=100000&fields=id`
)
jest.advanceTimersByTime(400)
expect(toastSpy).toHaveBeenCalledWith(
expect.objectContaining({
content: "Bulk operation 'Merge as versions' queued.",
})
expect(documentListViewService.selected.size).toEqual(0)
expect(toastSuccessSpy).toHaveBeenCalledWith(
'Documents merged as versions.'
)
TestBed.inject(TaskNotificationService).complete({
task_id: 'versions-1',
operation: 'merge_as_versions',
status: PaperlessTaskStatus.Success,
})
expect(toastSpy.mock.calls.at(-1)[0].content).toBe(
"Bulk operation 'Merge as versions' completed."
)
jest.useRealTimers()
})
it('should not report success when merging documents as versions fails', () => {
@@ -1664,22 +1641,12 @@ describe('BulkEditorComponent', () => {
)
})
it.each<[boolean, number]>([
[true, 2],
[false, 2],
[true, 1],
])(
'names queued work and gates the task link (permission %s, documents %s)',
(canViewTasks, count) => {
jest.useFakeTimers()
it.each([true, false])(
'shows queued feedback and gates the task link on permission (%s)',
(canViewTasks) => {
jest
.spyOn(permissionsService, 'currentUserCan')
.mockReturnValue(canViewTasks)
jest
.spyOn(documentListViewService, 'selected', 'get')
.mockReturnValue(
new Set(Array.from({ length: count }, (_, index) => index + 3))
)
const queued = jest.spyOn(toastService, 'show')
let modal: NgbModalRef
modalService.activeInstances.subscribe((instances) => {
@@ -1697,11 +1664,8 @@ describe('BulkEditorComponent', () => {
)
req.flush({ result: 'OK', task_id: 'queued-operation' })
expect(close).toHaveBeenCalledTimes(1)
expect(queued).not.toHaveBeenCalled()
jest.advanceTimersByTime(400)
const notification = queued.mock.calls.at(-1)[0]
const prefix = count > 1 ? 'Bulk operation' : 'Operation'
expect(notification.content).toBe(`${prefix} \'Set permissions\' queued.`)
expect(notification.content).toBe('Bulk operation queued.')
if (canViewTasks) {
expect(notification.actionName).toBe('View task')
notification.action()
@@ -1713,16 +1677,8 @@ describe('BulkEditorComponent', () => {
expect(notification.actionName).toBeUndefined()
}
expect(reload).not.toHaveBeenCalled()
expect(documentListViewService.selected.size).toBe(0)
expect(documentListViewService.allSelected).toBe(false)
TestBed.inject(TaskNotificationService).complete({
task_id: 'queued-operation',
operation: 'set_permissions',
status: PaperlessTaskStatus.Success,
})
const completed = queued.mock.calls.at(-1)[0]
expect(completed.content).toBe(`${prefix} \'Set permissions\' completed.`)
expect(completed.action).toBeUndefined()
jest.useRealTimers()
}
)
@@ -1803,6 +1759,7 @@ describe('BulkEditorComponent', () => {
{ id: 2, name: 'Tag 2' },
],
count: 2,
all: [1, 2],
}
const modalInstance = {
@@ -1845,6 +1802,7 @@ describe('BulkEditorComponent', () => {
{ id: 2, name: 'Correspondent 2' },
],
count: 2,
all: [1, 2],
}
const modalInstance = {
@@ -1893,6 +1851,7 @@ describe('BulkEditorComponent', () => {
{ id: 2, name: 'Document Type 2' },
],
count: 2,
all: [1, 2],
}
const modalInstance = {
@@ -1938,6 +1897,7 @@ describe('BulkEditorComponent', () => {
{ id: 2, name: 'Storage Path 2' },
],
count: 2,
all: [1, 2],
}
const modalInstance = {
@@ -1991,6 +1951,7 @@ describe('BulkEditorComponent', () => {
},
],
count: 2,
all: [1, 2],
}
const modalInstance = {
@@ -19,18 +19,25 @@ import {
NgbModalRef,
} from '@ng-bootstrap/ng-bootstrap'
import { saveAs } from 'file-saver'
import { first, map, Observable, Subject, switchMap, takeUntil } from 'rxjs'
import {
first,
map,
Observable,
Subject,
switchMap,
takeUntil,
tap,
} from 'rxjs'
import { BootstrapIconComponent } from 'src/app/components/common/bootstrap-icon/bootstrap-icon.component'
import { ConfirmDialogComponent } from 'src/app/components/common/confirm-dialog/confirm-dialog.component'
import { BulkOperationResponse } from 'src/app/data/bulk-operation'
import { CustomField } from 'src/app/data/custom-field'
import { MatchingModel } from 'src/app/data/matching-model'
import { SelectionDataItem } from 'src/app/data/results'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
import { Workflow } from 'src/app/data/workflow'
import { WorkflowTriggerType } from 'src/app/data/workflow-trigger'
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
import { DocumentListViewService } from 'src/app/services/document-list-view.service'
import { OpenDocumentsService } from 'src/app/services/open-documents.service'
import {
PermissionAction,
PermissionsService,
@@ -45,18 +52,14 @@ import {
DocumentService,
MergeDocumentsRequest,
} from 'src/app/services/rest/document.service'
import { SavedViewService } from 'src/app/services/rest/saved-view.service'
import { ShareLinkBundleService } from 'src/app/services/rest/share-link-bundle.service'
import { WorkflowService } from 'src/app/services/rest/workflow.service'
import { StoragePathService } from 'src/app/services/rest/storage-path.service'
import { TagService } from 'src/app/services/rest/tag.service'
import { WorkflowService } from 'src/app/services/rest/workflow.service'
import { SettingsService } from 'src/app/services/settings.service'
import { TaskNotificationService } from 'src/app/services/task-notification.service'
import { ToastService } from 'src/app/services/toast.service'
import { TrashService } from 'src/app/services/trash.service'
import {
documentOperationHasFollowUpTasks,
getDocumentOperationLabel,
} from 'src/app/utils/document-operation'
import { flattenTags } from 'src/app/utils/flatten-tags'
import { queryParamsFromFilterRules } from 'src/app/utils/query-params'
import { MergeAsVersionsConfirmDialogComponent } from '../../common/confirm-dialog/merge-as-versions-confirm-dialog/merge-as-versions-confirm-dialog.component'
@@ -81,6 +84,7 @@ import { PermissionsDialogComponent } from '../../common/permissions-dialog/perm
import { ShareLinkBundleDialogComponent } from '../../common/share-link-bundle-dialog/share-link-bundle-dialog.component'
import { ComponentWithPermissions } from '../../with-permissions/with-permissions.component'
import { CustomFieldsBulkEditDialogComponent } from './custom-fields-bulk-edit-dialog/custom-fields-bulk-edit-dialog.component'
import { WorkflowTriggerType } from 'src/app/data/workflow-trigger'
@Component({
selector: 'pngx-bulk-editor',
@@ -106,12 +110,13 @@ export class BulkEditorComponent
private documentService = inject(DocumentService)
private trashService = inject(TrashService)
private modalService = inject(NgbModal)
private openDocumentService = inject(OpenDocumentsService)
private settings = inject(SettingsService)
private toastService = inject(ToastService)
private taskNotifications = inject(TaskNotificationService)
private storagePathService = inject(StoragePathService)
private customFieldService = inject(CustomFieldsService)
public readonly permissionService = inject(PermissionsService)
private savedViewService = inject(SavedViewService)
private readonly shareLinkBundleService = inject(ShareLinkBundleService)
private readonly workflowService = inject(WorkflowService)
private readonly router = inject(Router)
@@ -329,6 +334,7 @@ export class BulkEditorComponent
.subscribe({
next: () => {
modal.close()
this.list.selectNone()
this.toastService.showInfo(
$localize`Workflow will run on the selected documents in the background.`
)
@@ -351,61 +357,70 @@ export class BulkEditorComponent
.bulkEdit(overrideSelection ?? this.getSelectionQuery(), method, args)
.pipe(first())
.subscribe({
next: ({ task_id }) =>
this.handleOperationQueued(modal, task_id, method),
next: ({ task_id }) => this.handleOperationQueued(modal, task_id),
error: (error) => this.handleOperationError(modal, error),
})
}
private handleOperationQueued(
modal: NgbModalRef,
taskId: string,
operation: string,
onQueued?: (taskId: string) => void
) {
const bulk = this.getSelectionSize() > 1
private handleOperationQueued(modal: NgbModalRef, taskId: string) {
modal?.close()
if (onQueued) {
onQueued(taskId)
} else {
const label = getDocumentOperationLabel(operation)
const submittedMessage = bulk
? $localize`Bulk operation '${label}' submitted for processing.`
: $localize`Operation '${label}' submitted for processing.`
const completedMessage = bulk
? $localize`Bulk operation '${label}' completed.`
: $localize`Operation '${label}' completed.`
this.taskNotifications.showQueued(
taskId,
bulk
? $localize`Bulk operation '${label}' queued.`
: $localize`Operation '${label}' queued.`,
{
content: documentOperationHasFollowUpTasks(operation)
? submittedMessage
: completedMessage,
}
)
}
this.list.selectNone()
const canViewTasks = this.permissionService.currentUserCan(
PermissionAction.View,
PermissionType.PaperlessTask
)
this.toastService.show({
content: $localize`Bulk operation queued.`,
delay: 5000,
...(canViewTasks
? {
actionName: $localize`View task`,
action: () =>
this.router.navigate(['/tasks'], {
queryParams: { task_id: taskId },
}),
}
: {}),
})
}
private executeDocumentAction(
modal: NgbModalRef,
operation: string,
request: Observable<BulkOperationResponse>,
onQueued?: (taskId: string) => void
request: Observable<any>,
options: { clearSelection?: boolean; successMessage?: string } = {}
) {
if (modal) {
modal.componentInstance.buttonsEnabled.set(false)
}
request.pipe(first()).subscribe({
next: ({ task_id }) => {
this.handleOperationQueued(modal, task_id, operation, onQueued)
next: () => {
this.handleOperationSuccess(modal, options.clearSelection ?? false)
if (options.successMessage) {
this.toastService.showSuccess(options.successMessage)
}
},
error: (error) => this.handleOperationError(modal, error),
})
}
private handleOperationSuccess(
modal: NgbModalRef,
clearSelection: boolean = false
) {
if (clearSelection) {
this.list.selected.clear()
}
this.list.reload()
this.list.reduceSelectionToFilter()
this.list.selected.forEach((id) => {
this.openDocumentService.refreshDocument(id)
})
this.savedViewService.maybeRefreshDocumentCounts()
if (modal) {
modal.close()
}
}
private handleOperationError(modal: NgbModalRef, error: any) {
if (modal) {
modal.componentInstance.buttonsEnabled.set(true)
@@ -973,9 +988,16 @@ export class BulkEditorComponent
const count = this.getSelectionSize()
this.executeDocumentAction(
modal,
'delete',
this.documentService.deleteDocuments(this.getSelectionQuery()),
(taskId) => this.trashService.trackMovedToTrash(taskId, count, documents)
this.documentService
.deleteDocuments(this.getSelectionQuery())
.pipe(
tap(() =>
this.trashService.notifyMovedToTrash(
$localize`Moved ${count} document(s) to the trash`,
documents
)
)
)
)
}
@@ -1016,7 +1038,6 @@ export class BulkEditorComponent
modal.componentInstance.buttonsEnabled.set(false)
this.executeDocumentAction(
modal,
'reprocess',
this.documentService.reprocessDocuments(
this.getSelectionQuery(),
modal.componentInstance.remoteOcr
@@ -1057,7 +1078,6 @@ export class BulkEditorComponent
rotateDialog.buttonsEnabled.set(false)
this.executeDocumentAction(
modal,
'rotate',
this.documentService.rotateDocuments(
this.getSelectionQuery(),
rotateDialog.degrees
@@ -1091,8 +1111,11 @@ export class BulkEditorComponent
mergeDialog.buttonsEnabled.set(false)
this.executeDocumentAction(
modal,
'merge',
this.documentService.mergeDocuments(mergeDialog.documentIDs(), args)
this.documentService.mergeDocuments(mergeDialog.documentIDs(), args),
{ clearSelection: !!args.delete_originals }
)
this.toastService.showInfo(
$localize`Merged document will be queued for consumption.`
)
})
}
@@ -1114,11 +1137,14 @@ export class BulkEditorComponent
.subscribe(() => {
this.executeDocumentAction(
modal,
'merge_as_versions',
this.documentService.mergeDocumentsAsVersions(
mergeDialog.documentIDs(),
mergeDialog.rootDocumentID()
)
),
{
clearSelection: true,
successMessage: $localize`Documents merged as versions.`,
}
)
})
}
@@ -1143,7 +1169,7 @@ export class BulkEditorComponent
dialog.selection = this.getSelectionQuery()
dialog.selectionCount = this.getSelectionSize()
dialog.succeeded.subscribe(({ task_id }) =>
this.handleOperationQueued(null, task_id, 'modify_custom_fields')
this.handleOperationQueued(null, task_id)
)
dialog.failed.subscribe((error) => {
this.toastService.showError(
-6
View File
@@ -75,7 +75,6 @@ export const SETTINGS_KEYS = {
UPDATE_CHECKING_ENABLED: 'general-settings:update-checking:enabled',
UPDATE_CHECKING_BACKEND_SETTING:
'general-settings:update-checking:backend-setting',
WHATS_NEW_LAST_SEEN_VERSION: 'general-settings:whats-new:last-seen-version',
SAVED_VIEWS_WARN_ON_UNSAVED_CHANGE:
'general-settings:saved-views:warn-on-unsaved-change',
DASHBOARD_VIEWS_VISIBLE_IDS:
@@ -224,11 +223,6 @@ export const SETTINGS: UiSetting[] = [
type: 'string',
default: '',
},
{
key: SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION,
type: 'string',
default: '',
},
{
key: SETTINGS_KEYS.SAVED_VIEWS_WARN_ON_UNSAVED_CHANGE,
type: 'boolean',
@@ -240,7 +240,7 @@ describe('OpenDocumentsService', () => {
expect(refreshed.tags).toEqual([4])
})
it('keeps documents open after a network error during refresh', () => {
it('should handle error on refresh documents', () => {
subscriptions.push(
openDocumentsService.openDocument(documents[1]).subscribe()
)
@@ -250,63 +250,7 @@ describe('OpenDocumentsService', () => {
)
expect(req.request.method).toEqual('GET')
req.error(new ErrorEvent('timeout'))
expect(openDocumentsService.getOpenDocument(documents[1].id)).toBe(
documents[1]
)
})
it.each([500, 403])(
'keeps documents open after HTTP %s during refresh',
(status) => {
const doc = { ...documents[0] }
openDocumentsService.openDocument(doc).subscribe()
openDocumentsService.refreshDocument(doc.id)
httpTestingController
.expectOne(
`${environment.apiBaseUrl}documents/${doc.id}/?full_perms=true`
)
.flush({}, { status, statusText: 'Error' })
expect(openDocumentsService.getOpenDocument(doc.id)).toBe(doc)
}
)
it('preserves unsaved edits when a refreshed document no longer exists', () => {
const doc = { ...documents[0], title: 'Unsaved title' }
openDocumentsService.openDocument(doc).subscribe()
openDocumentsService.setDirty(doc, true, { title: doc.title })
openDocumentsService.refreshDocument(doc.id)
httpTestingController
.expectOne(
`${environment.apiBaseUrl}documents/${doc.id}/?full_perms=true`
)
.flush({}, { status: 404, statusText: 'Not Found' })
expect(openDocumentsService.getOpenDocument(doc.id)).toBe(doc)
expect(openDocumentsService.isDirty(doc)).toBe(true)
expect(
JSON.parse(sessionStorage.getItem(OPEN_DOCUMENT_SERVICE.DOCUMENTS))[0]
.title
).toBe('Unsaved title')
})
it('removes only the missing document when tab positions change during refresh', () => {
const first = { ...documents[0] }
const second = { ...documents[1] }
openDocumentsService.openDocument(first).subscribe()
openDocumentsService.openDocument(second).subscribe()
openDocumentsService.refreshDocument(first.id)
openDocumentsService.refreshDocument(second.id)
const firstRequest = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/${first.id}/?full_perms=true`
)
const secondRequest = httpTestingController.expectOne(
`${environment.apiBaseUrl}documents/${second.id}/?full_perms=true`
)
openDocumentsService.closeDocument(second).subscribe()
firstRequest.flush({}, { status: 404, statusText: 'Not Found' })
expect(openDocumentsService.getOpenDocuments()).toHaveLength(0)
openDocumentsService.openDocument(first).subscribe()
secondRequest.flush({}, { status: 404, statusText: 'Not Found' })
expect(openDocumentsService.getOpenDocuments()).toEqual([first])
})
it('should log error on sessionStorage save', () => {
@@ -1,4 +1,3 @@
import { HttpErrorResponse } from '@angular/common/http'
import { Injectable, inject, signal } from '@angular/core'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { Observable, Subject, of } from 'rxjs'
@@ -62,12 +61,7 @@ export class OpenDocumentsService {
Object.assign(openDoc, doc, unsavedEdits)
this.save()
},
error: (error: HttpErrorResponse) => {
if (error.status !== 404) return
const index = this.openDocuments.findIndex((doc) => doc.id === id)
if (index === -1 || this.isDirty(this.openDocuments[index])) return
error: () => {
this.openDocuments.splice(index, 1)
this.save()
},
@@ -290,7 +290,6 @@ describe(`DocumentService`, () => {
expect(req.request.method).toEqual('POST')
expect(req.request.body).toEqual({
documents: ids,
from_webui: true,
})
})
@@ -304,7 +303,6 @@ describe(`DocumentService`, () => {
expect(req.request.body).toEqual({
documents: ids,
remote_ocr: false,
from_webui: true,
})
})
@@ -319,7 +317,6 @@ describe(`DocumentService`, () => {
expect(req.request.body).toEqual({
documents: ids,
remote_ocr: true,
from_webui: true,
})
})
@@ -334,7 +331,6 @@ describe(`DocumentService`, () => {
documents: ids,
degrees: 90,
source_mode: 'latest_version',
from_webui: true,
})
})
@@ -350,7 +346,6 @@ describe(`DocumentService`, () => {
documents: ids,
metadata_document_id: 1,
delete_originals: true,
from_webui: true,
})
})
@@ -364,7 +359,6 @@ describe(`DocumentService`, () => {
expect(req.request.body).toEqual({
documents: ids,
root_document_id: 2,
from_webui: true,
})
})
@@ -380,7 +374,6 @@ describe(`DocumentService`, () => {
documents: ids,
root_document_id: 2,
version_label: 'Imported',
from_webui: true,
})
})
@@ -395,7 +388,6 @@ describe(`DocumentService`, () => {
expect(req.request.body).toEqual({
documents: ids,
operations: [{ page: 1, rotate: 90, doc: 0 }],
from_webui: true,
})
})
@@ -411,7 +403,6 @@ describe(`DocumentService`, () => {
documents: ids,
password: 'secret',
update_document: true,
from_webui: true,
})
})
@@ -351,24 +351,19 @@ export class DocumentService extends AbstractPaperlessService<Document> {
}
deleteDocuments(selection: DocumentSelectionQuery) {
return this.http.post<BulkOperationResponse>(
this.getResourceUrl(null, 'delete'),
{ ...selection, from_webui: true }
)
return this.http.post(this.getResourceUrl(null, 'delete'), {
...selection,
})
}
reprocessDocuments(
selection: DocumentSelectionQuery,
remoteOcr: boolean = false
) {
return this.http.post<BulkOperationResponse>(
this.getResourceUrl(null, 'reprocess'),
{
...selection,
remote_ocr: remoteOcr,
from_webui: true,
}
)
return this.http.post(this.getResourceUrl(null, 'reprocess'), {
...selection,
remote_ocr: remoteOcr,
})
}
rotateDocuments(
@@ -376,26 +371,18 @@ export class DocumentService extends AbstractPaperlessService<Document> {
degrees: number,
sourceMode: BulkEditSourceMode = BulkEditSourceMode.LATEST_VERSION
) {
return this.http.post<BulkOperationResponse>(
this.getResourceUrl(null, 'rotate'),
{
...selection,
degrees,
source_mode: sourceMode,
from_webui: true,
}
)
return this.http.post(this.getResourceUrl(null, 'rotate'), {
...selection,
degrees,
source_mode: sourceMode,
})
}
mergeDocuments(ids: number[], request: MergeDocumentsRequest = {}) {
return this.http.post<BulkOperationResponse>(
this.getResourceUrl(null, 'merge'),
{
documents: ids,
...request,
from_webui: true,
}
)
return this.http.post(this.getResourceUrl(null, 'merge'), {
documents: ids,
...request,
})
}
mergeDocumentsAsVersions(
@@ -403,40 +390,28 @@ export class DocumentService extends AbstractPaperlessService<Document> {
rootDocumentId: number,
versionLabel?: string
) {
return this.http.post<BulkOperationResponse>(
this.getResourceUrl(null, 'merge_as_versions'),
{
documents: ids,
root_document_id: rootDocumentId,
...(versionLabel ? { version_label: versionLabel } : {}),
from_webui: true,
}
)
return this.http.post(this.getResourceUrl(null, 'merge_as_versions'), {
documents: ids,
root_document_id: rootDocumentId,
...(versionLabel ? { version_label: versionLabel } : {}),
})
}
editPdfDocuments(ids: number[], request: EditPdfDocumentsRequest) {
return this.http.post<BulkOperationResponse>(
this.getResourceUrl(null, 'edit_pdf'),
{
documents: ids,
...request,
from_webui: true,
}
)
return this.http.post(this.getResourceUrl(null, 'edit_pdf'), {
documents: ids,
...request,
})
}
removePasswordDocuments(
ids: number[],
request: RemovePasswordDocumentsRequest
) {
return this.http.post<BulkOperationResponse>(
this.getResourceUrl(null, 'remove_password'),
{
documents: ids,
...request,
from_webui: true,
}
)
return this.http.post(this.getResourceUrl(null, 'remove_password'), {
documents: ids,
...request,
})
}
getSelectionData(
@@ -40,21 +40,4 @@ describe('RemoteVersionService', () => {
)
expect(req.request.method).toEqual('GET')
})
it('should call release notes endpoint without since', () => {
subscription = service.getReleaseNotes().subscribe()
const req = httpTestingController.expectOne(
`${environment.apiBaseUrl}release_notes/`
)
expect(req.request.method).toEqual('GET')
expect(req.request.params.has('since')).toBe(false)
})
it('should pass since to release notes endpoint', () => {
subscription = service.getReleaseNotes('3.4.2').subscribe()
const req = httpTestingController.expectOne(
`${environment.apiBaseUrl}release_notes/?since=3.4.2`
)
expect(req.request.method).toEqual('GET')
})
})
@@ -1,4 +1,4 @@
import { HttpClient, HttpParams } from '@angular/common/http'
import { HttpClient } from '@angular/common/http'
import { Injectable, inject } from '@angular/core'
import { Observable } from 'rxjs'
import { environment } from 'src/environments/environment'
@@ -8,20 +8,6 @@ export interface AppRemoteVersion {
update_available: boolean
}
export interface AppRelease {
version: string
name: string
body_html: string
html_url: string
published_at: string
}
export interface AppReleaseNotes {
version: string
releases: AppRelease[]
stars: number | null
}
@Injectable({
providedIn: 'root',
})
@@ -33,15 +19,4 @@ export class RemoteVersionService {
`${environment.apiBaseUrl}remote_version/`
)
}
public getReleaseNotes(since?: string): Observable<AppReleaseNotes> {
let params = new HttpParams()
if (since) {
params = params.set('since', since)
}
return this.http.get<AppReleaseNotes>(
`${environment.apiBaseUrl}release_notes/`,
{ params }
)
}
}
@@ -398,60 +398,6 @@ describe('SettingsService', () => {
expect(req.request.method).toEqual('POST')
})
it('seeds last seen version on first load', () => {
const settings = {
...ui_settings,
user: { ...ui_settings.user, is_superuser: true },
settings: {
...ui_settings.settings,
documentListSize: 50,
update_checking: { enabled: false, backend_setting: 'default' },
},
}
settings.settings['version'] = '3.5.1'
httpTestingController
.expectOne(`${environment.apiBaseUrl}ui_settings/`)
.flush(settings)
const req = httpTestingController.expectOne(
`${environment.apiBaseUrl}ui_settings/`
)
expect(req.request.method).toEqual('POST')
expect(req.request.body.settings.whats_new.last_seen_version).toEqual(
'3.5.1'
)
expect(settingsService.unseenReleasesSince()).toBeNull()
})
it('reports unseen releases and marks them seen', () => {
const settings = {
...ui_settings,
user: { ...ui_settings.user, is_superuser: true },
settings: {
...ui_settings.settings,
documentListSize: 50,
update_checking: { enabled: false, backend_setting: 'default' },
},
}
settings.settings['version'] = '3.5.1'
settings.settings['whats_new'] = { last_seen_version: '3.4.2' }
httpTestingController
.expectOne(`${environment.apiBaseUrl}ui_settings/`)
.flush(settings)
httpTestingController.expectNone(`${environment.apiBaseUrl}ui_settings/`)
expect(settingsService.unseenReleasesSince()).toEqual('3.4.2')
subscription = settingsService.markReleasesSeen().subscribe()
const req = httpTestingController.expectOne(
`${environment.apiBaseUrl}ui_settings/`
)
expect(req.request.body.settings.whats_new.last_seen_version).toEqual(
'3.5.1'
)
expect(settingsService.unseenReleasesSince()).toBeNull()
})
it('updates settings on complete tour', () => {
let req = httpTestingController.expectOne(
`${environment.apiBaseUrl}ui_settings/`
@@ -20,7 +20,6 @@ import {
hexToHsl,
} from 'src/app/utils/color'
import { DEFAULT_APP_TITLE, environment } from 'src/environments/environment'
import { compareVersions } from 'src/app/utils/version'
import { DEFAULT_DISPLAY_FIELDS, DisplayField } from '../data/document'
import { RemoteOCRModeConfig } from '../data/paperless-config'
import { SavedView } from '../data/saved-view'
@@ -328,18 +327,6 @@ export class SettingsService {
SETTINGS_KEYS.SIDEBAR_HIDDEN_ITEMS
)
/**
* The last version the user saw release notes for, if the running
* version is newer, or null.
*/
readonly unseenReleasesSince = computed<string | null>(() => {
this.settingsVersion()
const currentVersion = this.get(SETTINGS_KEYS.VERSION)
const lastSeen = this.get(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION)
if (!currentVersion || !lastSeen) return null
return compareVersions(currentVersion, lastSeen) > 0 ? lastSeen : null
})
readonly allDisplayFields = signal<Array<{ id: DisplayField; name: string }>>(
DEFAULT_DISPLAY_FIELDS
)
@@ -397,7 +384,6 @@ export class SettingsService {
uisettings.permissions,
this.currentUser()
)
this.maybeSeedLastSeenVersion()
this.initializeDisplayFields()
})
@@ -727,34 +713,6 @@ export class SettingsService {
return this.settingIsSet(SETTINGS_KEYS.UPDATE_CHECKING_ENABLED)
}
/**
* Record the baseline version for "what's new" tracking.
*/
private maybeSeedLastSeenVersion() {
const currentVersion = this.get(SETTINGS_KEYS.VERSION)
if (
!currentVersion ||
this.get(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION) ||
!this.permissionsService.currentUserCan(
PermissionAction.Change,
PermissionType.UISettings
)
)
return
this.set(SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION, currentVersion)
this.storeSettings()
.pipe(first())
.subscribe({ error: () => {} })
}
public markReleasesSeen(): Observable<any> {
this.set(
SETTINGS_KEYS.WHATS_NEW_LAST_SEEN_VERSION,
this.get(SETTINGS_KEYS.VERSION)
)
return this.storeSettings()
}
/**
* Offering remote OCR as a choice only makes sense when an engine
* is configured but is not already handling every document.
@@ -1,186 +0,0 @@
import { TestBed } from '@angular/core/testing'
import { Router } from '@angular/router'
import { BulkOperationStatus } from '../data/bulk-operation'
import { PaperlessTaskStatus } from '../data/paperless-task'
import { PermissionsService } from './permissions.service'
import { TaskNotificationService } from './task-notification.service'
import { Toast, ToastLevel, ToastService } from './toast.service'
describe('TaskNotificationService', () => {
let service: TaskNotificationService
let toastService: ToastService
let popups: Toast[]
let notifications: Toast[]
const navigate = jest.fn()
const currentUserCan = jest.fn()
const result = (
status = PaperlessTaskStatus.Success
): BulkOperationStatus => ({
task_id: 'task-1',
operation: 'run_workflow',
status,
})
beforeEach(() => {
jest.useFakeTimers()
currentUserCan.mockReturnValue(true)
TestBed.configureTestingModule({
providers: [
{ provide: Router, useValue: { navigate } },
{ provide: PermissionsService, useValue: { currentUserCan } },
],
})
service = TestBed.inject(TaskNotificationService)
toastService = TestBed.inject(ToastService)
popups = []
notifications = []
toastService.showToast.subscribe((toast) => popups.push(toast))
toastService
.getToasts()
.subscribe((toasts) => (notifications = [...toasts]))
})
afterEach(() => {
jest.clearAllTimers()
jest.useRealTimers()
})
it('replaces a queued notification with its result, removing the task link on success', () => {
service.showQueued('task-1', 'Workflow queued.', {
content: 'Workflow completed.',
})
jest.advanceTimersByTime(399)
expect(popups).toHaveLength(0)
jest.advanceTimersByTime(1)
expect(popups[0].content).toBe('Workflow queued.')
expect(popups[0].actionName).toBe('View task')
popups[0].action()
expect(navigate).toHaveBeenCalledWith(['/tasks'], {
queryParams: { task_id: 'task-1' },
})
service.complete(result())
expect(notifications).toHaveLength(1)
expect(popups[1]).toEqual(
expect.objectContaining({
id: popups[0].id,
content: 'Workflow completed.',
level: ToastLevel.Success,
})
)
expect(popups[1].action).toBeUndefined()
expect(popups[1].actionName).toBeUndefined()
})
it('shows only the result when a task completes during the grace period', () => {
service.showQueued('task-1', 'Queued')
jest.advanceTimersByTime(100)
service.complete(result())
jest.advanceTimersByTime(1000)
expect(popups.map((toast) => toast.content)).toEqual([
"Operation 'Run workflow' completed.",
])
})
it.each([
'reprocess',
'rotate',
'merge',
'split',
'delete_pages',
'edit_pdf',
'remove_password',
])('reports %s as submitted rather than completed', (operation) => {
service.showQueued('task-1', 'Queued')
service.complete({ ...result(), operation })
expect(notifications[0].content).toContain('submitted for processing.')
expect(notifications[0].content).not.toContain('completed')
expect(notifications[0].action).toBeUndefined()
})
it('does not show a stale queued state when completion beats the HTTP response', () => {
service.complete(result())
service.showQueued('task-1', 'Workflow queued.', {
content: 'Workflow completed.',
})
jest.advanceTimersByTime(1000)
expect(popups.every((toast) => toast.level === ToastLevel.Success)).toBe(
true
)
expect(notifications).toHaveLength(1)
expect(notifications[0].content).toBe('Workflow completed.')
expect(notifications[0].action).toBeUndefined()
})
it.each([PaperlessTaskStatus.Failure, PaperlessTaskStatus.Revoked])(
'replaces the queued state with an error for %s',
(status) => {
service.showQueued('task-1', 'Queued', {
content: 'Success',
actionName: 'Undo',
})
jest.advanceTimersByTime(400)
service.complete({ ...result(status), error: 'Task failed' })
expect(notifications).toHaveLength(1)
expect(notifications[0]).toEqual(
expect.objectContaining({
level: ToastLevel.Error,
error: 'Task failed',
actionName: 'View task',
})
)
}
)
it('ignores nonterminal and duplicate outcomes', () => {
service.showQueued('task-1', 'Queued')
service.complete(result(PaperlessTaskStatus.Started))
expect(popups).toHaveLength(0)
service.complete(result())
service.complete(result())
expect(popups).toHaveLength(1)
})
it('keeps concurrent task notifications separate', () => {
service.showQueued('task-1', 'First queued')
service.showQueued('task-2', 'Second queued')
jest.advanceTimersByTime(400)
service.complete(result())
expect(notifications).toHaveLength(2)
expect(notifications.map((toast) => toast.content)).toEqual([
'Second queued',
"Operation 'Run workflow' completed.",
])
})
it('omits task links without task viewing permission', () => {
currentUserCan.mockReturnValue(false)
service.showQueued('task-1', 'Queued')
jest.advanceTimersByTime(400)
service.complete(result())
expect(popups.every((toast) => !toast.action && !toast.actionName)).toBe(
true
)
})
it('identifies concurrent operations even when completion arrives before their queue responses', () => {
service.complete({
task_id: 'tags',
operation: 'modify_tags',
status: PaperlessTaskStatus.Success,
})
service.complete({
task_id: 'correspondent',
operation: 'set_correspondent',
status: PaperlessTaskStatus.Success,
})
expect(notifications.map((toast) => toast.content)).toEqual([
"Operation 'Set correspondent' completed.",
"Operation 'Update tags' completed.",
])
})
it('keeps the generic fallback for unknown operation names', () => {
service.complete({ ...result(), operation: 'future_operation' })
expect(notifications[0].content).toBe('Operation completed.')
})
})
@@ -1,128 +0,0 @@
import { inject, Injectable, OnDestroy } from '@angular/core'
import { Router } from '@angular/router'
import { BulkOperationStatus } from '../data/bulk-operation'
import { PaperlessTaskStatus } from '../data/paperless-task'
import {
documentOperationHasFollowUpTasks,
getDocumentOperationLabel,
} from '../utils/document-operation'
import {
PermissionAction,
PermissionsService,
PermissionType,
} from './permissions.service'
import { Toast, ToastLevel, ToastService } from './toast.service'
interface PendingNotification {
success: Partial<Toast>
timer: ReturnType<typeof setTimeout>
}
@Injectable({ providedIn: 'root' })
export class TaskNotificationService implements OnDestroy {
private readonly toastService = inject(ToastService)
private readonly router = inject(Router)
private readonly permissionsService = inject(PermissionsService)
private readonly pending = new Map<string, PendingNotification>()
private readonly completed = new Map<string, BulkOperationStatus>()
ngOnDestroy() {
this.pending.forEach(({ timer }) => clearTimeout(timer))
}
showQueued(taskId: string, content: string, success: Partial<Toast> = {}) {
const completed = this.completed.get(taskId)
if (completed) {
this.showResult(completed, success)
return
}
if (this.pending.has(taskId)) return
this.pending.set(taskId, {
success,
// short delay in case the task finishes super fast
timer: setTimeout(() => this.show(taskId, { content, delay: 5000 }), 400),
})
}
complete(result: BulkOperationStatus) {
if (
![
PaperlessTaskStatus.Success,
PaperlessTaskStatus.Failure,
PaperlessTaskStatus.Revoked,
].includes(result.status) ||
this.completed.has(result.task_id)
)
return
this.completed.set(result.task_id, result)
// Retain recent outcomes in case task finishes quickly
if (this.completed.size > 100) {
this.completed.delete(this.completed.keys().next().value)
}
const pending = this.pending.get(result.task_id)
if (pending) {
clearTimeout(pending.timer)
this.pending.delete(result.task_id)
}
// Trash needs the caller's document IDs to offer Undo on success.
if (
pending ||
result.operation !== 'delete' ||
result.status !== PaperlessTaskStatus.Success
) {
this.showResult(result, pending?.success)
}
}
private showResult(
result: BulkOperationStatus,
success: Partial<Toast> = {}
) {
const succeeded = result.status === PaperlessTaskStatus.Success
const operation = getDocumentOperationLabel(result.operation)
let content: string
if (succeeded) {
let operationText = $localize`Operation`
if (operation) operationText += ` '${operation}'`
const resultText = documentOperationHasFollowUpTasks(result.operation)
? $localize`submitted for processing`
: $localize`completed`
content = `${operationText} ${resultText}.`
} else if (result.status === PaperlessTaskStatus.Revoked) {
content = operation
? $localize`Operation '${operation}' revoked.`
: $localize`Operation revoked.`
} else {
content = operation
? $localize`Operation '${operation}' failed. Some changes may already have been applied.`
: $localize`Operation failed. Some changes may already have been applied.`
}
this.show(result.task_id, {
content,
delay: succeeded ? 5000 : 10000,
level: succeeded ? ToastLevel.Success : ToastLevel.Error,
...(succeeded ? success : { error: result.error }),
})
}
private show(taskId: string, toast: Toast) {
const canViewTasks = this.permissionsService.currentUserCan(
PermissionAction.View,
PermissionType.PaperlessTask
)
this.toastService.show({
id: `task-${taskId}`,
...(canViewTasks && toast.level !== ToastLevel.Success
? {
actionName: $localize`View task`,
action: () =>
this.router.navigate(['/tasks'], {
queryParams: { task_id: taskId },
}),
}
: {}),
...toast,
})
}
}
@@ -38,29 +38,6 @@ describe('ToastService', () => {
})
})
it('updates a notification by ID without duplicating or moving it', () => {
let notifications: Toast[] = []
toastService
.getToasts()
.subscribe((toasts) => (notifications = [...toasts]))
toastService.show({ id: 'task-1', content: 'Queued', delay: 5000 })
toastService.show({
id: 'other',
content: 'Another notification',
delay: 5000,
})
toastService.show({
id: 'task-1',
content: 'Completed',
delay: 5000,
level: ToastLevel.Success,
})
expect(notifications.map((toast) => toast.content)).toEqual([
'Another notification',
'Completed',
])
})
it('parses error string to object on show', () => {
const toast = {
title: 'Title',
+1 -8
View File
@@ -75,14 +75,7 @@ export class ToastService {
if (persistent) {
// the dropdown is open, so it's seen as it arrives
toast.read = !!this._suppressPopupToasts
const index = this.toasts.findIndex(
(existing) => existing.id === toast.id
)
if (index === -1) {
this.toasts.unshift(toast)
} else {
this.toasts[index] = toast
}
this.toasts.unshift(toast)
this.toastsSubject.next(this.toasts)
}
// Popups are suppressed while the dropdown is open
+1 -51
View File
@@ -5,10 +5,8 @@ import {
HttpTestingController,
} from '@angular/common/http/testing'
import { environment } from 'src/environments/environment'
import { PaperlessTaskStatus } from '../data/paperless-task'
import { DocumentListViewService } from './document-list-view.service'
import { TaskNotificationService } from './task-notification.service'
import { Toast, ToastLevel, ToastService } from './toast.service'
import { Toast, ToastService } from './toast.service'
import { TrashService } from './trash.service'
describe('TrashService', () => {
@@ -107,52 +105,4 @@ describe('TrashService', () => {
expect(toast.content).toEqual('Moved 500 document(s) to the trash')
expect(toast.action).toBeUndefined()
})
it('offers Undo only after the matching delete task succeeds', () => {
let toasts: Toast[] = []
toastService.getToasts().subscribe((t) => (toasts = [...t]))
service.trackMovedToTrash('delete-1', 2, [1, 2])
expect(toasts).toHaveLength(0)
const notifications = TestBed.inject(TaskNotificationService)
notifications.complete({
task_id: 'other-delete',
operation: 'delete',
status: PaperlessTaskStatus.Success,
})
expect(toasts).toHaveLength(0)
notifications.complete({
task_id: 'delete-1',
operation: 'delete',
status: PaperlessTaskStatus.Success,
})
expect(toasts).toHaveLength(1)
expect(toasts[0].actionName).toBe('Undo')
toasts[0].action()
const req = httpTestingController.expectOne(
`${environment.apiBaseUrl}trash/`
)
expect(req.request.body).toEqual({ action: 'restore', documents: [1, 2] })
})
it('handles completion before the queue response and does not offer Undo on failure', () => {
let toasts: Toast[] = []
toastService.getToasts().subscribe((t) => (toasts = [...t]))
const notifications = TestBed.inject(TaskNotificationService)
notifications.complete({
task_id: 'delete-1',
operation: 'delete',
status: PaperlessTaskStatus.Success,
})
service.trackMovedToTrash('delete-1', 1, [1])
expect(toasts[0].actionName).toBe('Undo')
service.trackMovedToTrash('delete-2', 1, [2])
notifications.complete({
task_id: 'delete-2',
operation: 'delete',
status: PaperlessTaskStatus.Failure,
})
expect(toasts).toHaveLength(2)
expect(toasts[0].level).toBe(ToastLevel.Error)
expect(toasts[0].actionName).not.toBe('Undo')
})
})
+5 -32
View File
@@ -5,8 +5,7 @@ import { environment } from 'src/environments/environment'
import { Document } from '../data/document'
import { Results } from '../data/results'
import { DocumentListViewService } from './document-list-view.service'
import { TaskNotificationService } from './task-notification.service'
import { Toast, ToastLevel, ToastService } from './toast.service'
import { ToastLevel, ToastService } from './toast.service'
@Injectable({
providedIn: 'root',
@@ -15,24 +14,6 @@ export class TrashService {
private http = inject(HttpClient)
private toastService = inject(ToastService)
private documentListViewService = inject(DocumentListViewService)
private taskNotifications = inject(TaskNotificationService)
public trackMovedToTrash(
taskId: string,
count: number,
documents?: number[]
) {
this.taskNotifications.showQueued(
taskId,
count > 1
? $localize`Bulk move to trash queued.`
: $localize`Move to trash queued.`,
this.movedToTrashToast(
$localize`Moved ${count} document(s) to the trash`,
documents
)
)
}
public getTrash(page: number = 1): Observable<Results<Document>> {
const httpParams = new HttpParams().set('page', page.toString())
@@ -62,22 +43,14 @@ export class TrashService {
* Shows a toast with an Undo action when possible
*/
public notifyMovedToTrash(content: string, documents?: number[]) {
this.toastService.show(this.movedToTrashToast(content, documents))
}
private movedToTrashToast(content: string, documents?: number[]): Toast {
const canUndo = documents?.length > 0
return {
this.toastService.show({
content,
delay: 10000,
level: ToastLevel.Success,
...(canUndo
? {
actionName: $localize`Undo`,
action: () => this.undoMoveToTrash(documents),
}
: {}),
}
actionName: canUndo ? $localize`Undo` : undefined,
action: canUndo ? () => this.undoMoveToTrash(documents) : undefined,
})
}
private undoMoveToTrash(documents: number[]) {
@@ -1,11 +0,0 @@
import { getDocumentOperationLabel } from './document-operation'
describe('Document Operation Utils', () => {
it('should retrieve the document operation label correctly for an existing operation, null otherwise', () => {
const result = getDocumentOperationLabel('modify_custom_fields')
expect(result).toBe('Update custom fields')
const resultNull = getDocumentOperationLabel('non_existing_operation')
expect(resultNull).toBeNull()
})
})
@@ -1,38 +0,0 @@
const OPERATION_LABELS: Record<string, string> = {
set_correspondent: $localize`Set correspondent`,
set_document_type: $localize`Set document type`,
set_storage_path: $localize`Set storage path`,
add_tag: $localize`Add tag`,
remove_tag: $localize`Remove tag`,
modify_tags: $localize`Update tags`,
modify_custom_fields: $localize`Update custom fields`,
set_permissions: $localize`Set permissions`,
delete: $localize`Move to trash`,
reprocess: $localize`Document reprocessing`,
run_workflow: $localize`Run workflow`,
rotate: $localize`Rotate documents`,
merge: $localize`Merge documents`,
merge_as_versions: $localize`Merge as versions`,
split: $localize`Split documents`,
delete_pages: $localize`Delete pages`,
edit_pdf: $localize`Edit PDF`,
remove_password: $localize`Remove password`,
}
export function getDocumentOperationLabel(operation?: string): string | null {
const label = operation ? OPERATION_LABELS[operation] : null
return label ?? null
}
// These operations queue processing in separate tasks
export function documentOperationHasFollowUpTasks(operation?: string): boolean {
return [
'reprocess',
'rotate',
'merge',
'split',
'delete_pages',
'edit_pdf',
'remove_password',
].includes(operation ?? '')
}
-11
View File
@@ -1,11 +0,0 @@
import { compareVersions } from './version'
describe('compareVersions', () => {
it('should compare versions numerically', () => {
expect(compareVersions('3.5.1', '3.5.0')).toBeGreaterThan(0)
expect(compareVersions('3.10.0', '3.9.9')).toBeGreaterThan(0)
expect(compareVersions('3.4.2', '3.5.0')).toBeLessThan(0)
expect(compareVersions('3.5.0', '3.5.0')).toEqual(0)
expect(compareVersions('3.5', '3.5.0')).toEqual(0)
})
})
-13
View File
@@ -1,13 +0,0 @@
/**
* Compare two X.Y.Z version strings numerically.
* Returns a positive number if a > b, negative if a < b, 0 if equal.
*/
export function compareVersions(a: string, b: string): number {
const partsA = a.split('.').map((p) => parseInt(p, 10) || 0)
const partsB = b.split('.').map((p) => parseInt(p, 10) || 0)
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
const diff = (partsA[i] ?? 0) - (partsB[i] ?? 0)
if (diff !== 0) return diff
}
return 0
}
+1 -1
View File
@@ -8,7 +8,7 @@ export const environment = {
apiVersion: '10', // match src/paperless/settings.py
appTitle: DEFAULT_APP_TITLE,
tag: 'prod',
version: '3.5.1',
version: '3.4.2',
webSocketHost: window.location.host,
webSocketProtocol: window.location.protocol == 'https:' ? 'wss:' : 'ws:',
webSocketBaseUrl: base_url.pathname + 'ws/',
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-3
View File
@@ -13,9 +13,6 @@ $form-file-button-hover-bg: var(--pngx-bg-alt);
@include meta.load-css("print");
// re-created bootstrap styles
.mt-n1 {
margin-top: -0.25rem;
}
.mt-n2 {
margin-top: -0.5rem;
}
-6
View File
@@ -153,12 +153,6 @@ def fake_progress_manager(
return FakeProgressManager
@pytest.fixture(scope="session")
def shared_samples_dir() -> Path:
"""Directory of sample files used by more than one app's tests."""
return samples.SHARED_SAMPLES_DIR
@pytest.fixture(scope="session")
def simple_digital_pdf_file() -> Path:
"""One-page PDF with a text layer."""
+2 -29
View File
@@ -427,7 +427,6 @@ def delete(doc_ids: list[int]) -> Literal["OK"]:
"Detected a possible incompatible database column. See https://docs.paperless-ngx.com/troubleshooting/#convert-uuid-field",
)
logger.error(f"Error deleting documents: {e!s}")
raise
return "OK"
@@ -475,9 +474,9 @@ def run_workflow(
"""
Manually run a single workflow against the given documents.
Called from the tracked bulk operation task.
Done asynchronously via a Celery task.
"""
run_workflows_for_documents(
run_workflows_for_documents.delay(
document_ids=doc_ids,
workflow_id=workflow,
filter_documents=filter_documents,
@@ -539,7 +538,6 @@ def rotate(
pair = _resolve_root_and_source_doc(doc, source_mode=source_mode)
docs_by_root_id.setdefault(pair.root_doc.id, pair)
failed_ids = []
for pair in docs_by_root_id.values():
if pair.source_doc.mime_type != "application/pdf":
logger.warning(
@@ -574,14 +572,8 @@ def rotate(
f"Queued new rotated version for document {pair.root_doc.id} by {degrees} degrees",
)
except Exception as e:
failed_ids.append(pair.root_doc.id)
logger.exception(f"Error rotating document {pair.root_doc.id}: {e}")
if failed_ids:
raise RuntimeError(
f"Rotation failed for document(s): {failed_ids}. Check logs for details.",
)
return "OK"
@@ -692,22 +684,6 @@ def merge(
return "OK"
def validate_merge_as_versions_state(
documents: list[Document],
root_document_id: int,
) -> None:
if any(document.root_document_id is not None for document in documents):
raise ValueError("Only top-level documents can be merged as versions.")
source_ids = [
document.pk for document in documents if document.pk != root_document_id
]
if Document.global_objects.filter(root_document_id__in=source_ids).exists():
raise ValueError(
"Documents with existing versions cannot be merged into another document.",
)
def merge_as_versions(
doc_ids: list[int],
*,
@@ -725,7 +701,6 @@ def merge_as_versions(
)
documents_by_id = {document.id: document for document in documents}
validate_merge_as_versions_state(documents, root_document_id)
source_ids = [doc_id for doc_id in doc_ids if doc_id != root_document_id]
root_document = documents_by_id[root_document_id]
next_version_index = (
@@ -889,7 +864,6 @@ def split(
except Exception as e:
logger.exception(f"Error splitting document {doc.id}: {e}")
raise
return "OK"
@@ -935,7 +909,6 @@ def delete_pages(
)
except Exception as e:
logger.exception(f"Error deleting pages from document {pair.root_doc.id}: {e}")
raise
return "OK"
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more